tracerset 1.2.4__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.

Potentially problematic release.


This version of tracerset might be problematic. Click here for more details.

tracerset/__init__.py ADDED
File without changes
tracerset/tracerset.py ADDED
@@ -0,0 +1,447 @@
1
+ import ast
2
+ import sys
3
+ import tokenize
4
+ import os
5
+ import platform
6
+
7
+ # ===============================================================
8
+ # TracerSET
9
+ # Execution-Centric Program Comprehension Environment for Python
10
+ # ===============================================================
11
+
12
+ VER='TracerSET 1.2.4'
13
+ TAG='Execution-Centric Program Comprehension Environment for Python'
14
+
15
+ COLOR = "\033[93m"
16
+ ERROR = "\033[91m"
17
+ SUCCESS = "\033[92m"
18
+ RESET = "\033[0m"
19
+
20
+ MODE_BEGINNER = "beginner"
21
+ MODE_INTERMEDIATE = "intermediate"
22
+ MODE_ADVANCED = "advanced"
23
+ stdin=0
24
+ stdin_m=''
25
+
26
+ MODES = {
27
+ MODE_BEGINNER: {
28
+ "tokens": False,
29
+ "cst": False,
30
+ "ast": False,
31
+ "disassembly": False,
32
+ "execution_trace": False,
33
+ "step_trace": True,
34
+ },
35
+
36
+ MODE_INTERMEDIATE: {
37
+ "tokens": False,
38
+ "cst": False,
39
+ "ast": True,
40
+ "disassembly": False,
41
+ "execution_trace": True,
42
+ "step_trace": True,
43
+ },
44
+
45
+ MODE_ADVANCED: {
46
+ "tokens": True,
47
+ "cst": True,
48
+ "ast": True,
49
+ "disassembly": True,
50
+ "execution_trace": True,
51
+ "step_trace": True,
52
+ }
53
+ }
54
+
55
+ # ============================================================
56
+ # Utility Functions
57
+ # ============================================================
58
+
59
+ def pause(section_name):
60
+ if sys.stdin.isatty():
61
+ print(f"\n{COLOR}Press Enter key to continue to {section_name}{RESET}")
62
+ sys.stdin.read(1)
63
+ rows = os.get_terminal_size().lines
64
+ # Natural scroll
65
+ for _ in range(rows):
66
+ print()
67
+ # Reposition cursor
68
+ print("\033[H", end="", flush=True)
69
+
70
+ def get_python_cmd():
71
+ return f"python{'.'.join(platform.python_version().split('.')[:2])}"
72
+
73
+ def read_source_code(filename):
74
+ with open(filename, "r") as fp:
75
+ return fp.read()
76
+
77
+ # ============================================================
78
+ # Display Functions
79
+ # ============================================================
80
+
81
+ def show_source_code(buff):
82
+ print("[Source Code]:")
83
+ print("==============")
84
+ print(buff)
85
+
86
+ def show_tokens(filename):
87
+ pause("[Tokens]")
88
+ print("=========")
89
+
90
+ with tokenize.open(filename) as f:
91
+ tokens = tokenize.generate_tokens(f.readline)
92
+ for token in tokens:
93
+ print(token)
94
+
95
+ def resolve_import_file(module_name, current_file):
96
+ base_dir = os.path.dirname(os.path.abspath(current_file))
97
+
98
+ candidate = os.path.join(
99
+ base_dir,
100
+ module_name.replace(".", os.sep) + ".py"
101
+ )
102
+
103
+ if os.path.exists(candidate):
104
+ return os.path.abspath(candidate)
105
+ return None
106
+
107
+ def collect_all_python_files(entry_file):
108
+ base_file = os.path.abspath(entry_file)
109
+
110
+ pending = [base_file]
111
+ visited = set()
112
+
113
+ while pending:
114
+ current = pending.pop(0)
115
+ if current in visited:
116
+ continue
117
+
118
+ visited.add(current)
119
+
120
+ with open(current, "r", encoding="utf-8") as f:
121
+ source = f.read()
122
+
123
+ tree = ast.parse(source)
124
+
125
+ for node in ast.walk(tree):
126
+ if isinstance(node, ast.Import):
127
+ for alias in node.names:
128
+ imported = resolve_import_file(alias.name, current)
129
+ if imported and imported not in visited:
130
+ pending.append(imported)
131
+
132
+ elif isinstance(node, ast.ImportFrom):
133
+ if node.module:
134
+ imported = resolve_import_file(node.module, current)
135
+ if imported and imported not in visited:
136
+ pending.append(imported)
137
+
138
+ return list(visited)
139
+
140
+ def show_cognitive_complexity(filename):
141
+ pause("[Cognitive Complexity]")
142
+ print("======================")
143
+ files = collect_all_python_files(filename)
144
+ print("Analyzing files:")
145
+ for f in files:
146
+ print(" -", f)
147
+ #cmd = "complexipy -cs -C no --suggest-refactors " + " ".join(files)
148
+ cmd = "complexipy -s desc -C no --suggest-refactors " + " ".join(files)
149
+ os.system(cmd)
150
+
151
+ def show_control_flow_graph(filename):
152
+ try:
153
+ import python_ta.cfg as cfg
154
+ cfg.generate_cfg(filename)
155
+ print(filename)
156
+ except:
157
+ pycmd = get_python_cmd() #if import fails!
158
+ os.system(f"{pycmd} -m python_ta.cfg {filename}")
159
+ print(f"{pycmd} -m python_ta.cfg {filename}")
160
+
161
+ if platform.system() == 'Windows':
162
+ if '\\' in filename:
163
+ fname=filename.split('\\')[::-1][0]
164
+ else:
165
+ fname=filename.split('/')[::-1][0]
166
+ src=fname.replace(".py",".gv")
167
+ dest=filename.replace(".py",".cfg.png")
168
+ print(src,fname,dest)
169
+ os.system(f"dot -Tpng {src} > {dest}")
170
+ print(f"DOT file written to: {dest}")
171
+ #os.system(f"start {dest}")
172
+ elif platform.system() == 'Linux':
173
+ fname=filename.split('/')[::-1][0]
174
+ src=fname.replace(".py",".gv")
175
+ dest=filename.replace(".py",".cfg.dot")
176
+ os.system(f"rm -f *.svg; mv {src} {dest}")
177
+ print(f"DOT file written to: {dest}")
178
+ #os.system(f"xdot {dest} 2> /dev/null")
179
+ else:
180
+ #print("Platform not supported yet!")
181
+ #exit(-1)
182
+ pass
183
+
184
+ def cfg_iterator(filename):
185
+ pause("[Control Flow Graph (CFG)]")
186
+ print("==========================")
187
+ files = collect_all_python_files(filename)
188
+ print("Analyzing files:")
189
+ for f in files:
190
+ print(" -", f)
191
+ show_control_flow_graph(f)
192
+
193
+ def show_concrete_syntax_tree(filename):
194
+ pause("[Concrete Syntax Tree (CST)]")
195
+ print("===============================")
196
+ pycmd = get_python_cmd()
197
+ xpath = os.path.join(os.path.dirname(__file__), "utilities", "cst2dot.py")
198
+ os.system(
199
+ f"{pycmd} {xpath} {filename}"
200
+ )
201
+
202
+ def show_abstract_syntax_tree(filename):
203
+ pause("[Abstract Syntax Tree (AST)]")
204
+ print("==============================")
205
+ pycmd = get_python_cmd()
206
+ xpath = os.path.join(os.path.dirname(__file__), "utilities", "ast2dot.py")
207
+ os.system(
208
+ f"{pycmd} {xpath} {filename}"
209
+ )
210
+
211
+ def show_disassembly(filename):
212
+ pause("[Python Bytecode]")
213
+ print("==================")
214
+ pycmd = get_python_cmd()
215
+ os.system(
216
+ f"{pycmd} -m dis {filename}"
217
+ )
218
+
219
+ def show_execution_trace(filename):
220
+ pause("[Program Execution Trace]")
221
+ print("==========================")
222
+ pycmd = get_python_cmd()
223
+ if platform.system() == 'Windows':
224
+ os.system(
225
+ #f"{pycmd} -m trace --count --trace --missing --coverdir tests --summary {filename}"
226
+ f"{pycmd} -m trace --count --trace --ignore-dir=\"{os.path.dirname(os.__file__)}\" --missing --coverdir tests --summary {filename}"
227
+ )
228
+ else:
229
+ os.system(
230
+ #f"{pycmd} -m trace --count --trace --missing --coverdir tests --summary {filename}"
231
+ f"{pycmd} -m trace --count --trace --ignore-dir={os.path.dirname(os.__file__)} --missing --coverdir tests --summary {filename}"
232
+ )
233
+
234
+ def show_step_by_step_trace(filename):
235
+ pause("[Step-by-step Program Execution]")
236
+ print("=================================")
237
+ pycmd = get_python_cmd()
238
+ xpath = os.path.join(os.path.dirname(__file__), "utilities", "detailed.py")
239
+ global stdin
240
+ global stdin_m
241
+ if stdin==0:
242
+ os.system(
243
+ f"{pycmd} {xpath} {get_mode()} {filename}"
244
+ )
245
+ else:
246
+ os.system(
247
+ f"{pycmd} {xpath} {stdin_m} {filename}"
248
+ )
249
+
250
+ def show_ast_dump(parsed_ast):
251
+ pause("[AST Hierarchy]")
252
+ print("================")
253
+ print(ast.dump(parsed_ast, indent=2))
254
+
255
+ # ============================================================
256
+ # Mode Handling
257
+ # ============================================================
258
+
259
+ def get_mode():
260
+ global stdin
261
+ global stdin_m
262
+ if stdin==1:
263
+ return stdin_m
264
+
265
+ if len(sys.argv) != 3:
266
+ if len(sys.argv) == 2:
267
+ mode='beginner'
268
+ else:
269
+ print(f'''{COLOR}Usage:
270
+ tracerset [beginner] [file.py] #or stdin
271
+ tracerset intermediate [file.py] #or stdin
272
+ tracerset advanced [file.py] #or stdin{RESET}''')
273
+ sys.exit(1)
274
+ else:
275
+ mode = sys.argv[1].lower()
276
+
277
+ if mode not in MODES:
278
+ print(f"{ERROR}Invalid mode:{RESET} {mode}")
279
+ print(f"\nAvailable modes:{COLOR}")
280
+ for m in MODES:
281
+ print(f"{m}")
282
+ print(f"{RESET}")
283
+ sys.exit(1)
284
+
285
+ return mode
286
+
287
+
288
+ def show_banner(mode):
289
+ print("=" * 63)
290
+ print("TracerSET")
291
+ print("Execution-Centric Program Comprehension Environment for Python")
292
+ print("=" * 63)
293
+
294
+ print(f"\nSelected Mode : {SUCCESS}{mode.upper()}{RESET}")
295
+
296
+ if mode == MODE_BEGINNER:
297
+ print("Focus : Variables, execution flow, runtime behavior")
298
+ elif mode == MODE_INTERMEDIATE:
299
+ print("Focus : Runtime behavior + AST + execution trace")
300
+ elif mode == MODE_ADVANCED:
301
+ print("Focus : Full compiler/runtime internals")
302
+ print("=" * 63)
303
+
304
+
305
+ # ============================================================
306
+ # Main Driver
307
+ # ============================================================
308
+
309
+ def main():
310
+ mode=''
311
+ filename=''
312
+ global stdin
313
+ global stdin_m
314
+
315
+ cmd=[x.lower() for x in sys.argv]
316
+ cmd_len=len(cmd)
317
+ if cmd_len==1:
318
+ if cmd[0] in ['tracerset','tracerset.py'] or cmd[0].endswith(('tracerset','tracerset.py')):
319
+ mode=MODE_BEGINNER
320
+ stdin_m=mode
321
+ stdin=1
322
+ elif cmd_len==2:
323
+ if cmd[0] in ['tracerset','tracerset.py'] or cmd[0].endswith(('tracerset','tracerset.py')):
324
+ mode=cmd[1]
325
+ stdin_m=mode
326
+ if not mode.endswith('.py') and mode not in MODES:
327
+ if mode.lower() in ['-v','-version','--v','--version']:
328
+ print(f"{VER} - {TAG}")
329
+ return
330
+ elif mode.lower() in ['-h','-help','--help','--h']:
331
+ print(f'''{COLOR}Usage:
332
+ tracerset [beginner] [file.py] #or stdin
333
+ tracerset intermediate [file.py] #or stdin
334
+ tracerset advanced [file.py] #or stdin{RESET}''')
335
+ return
336
+ print(f"{ERROR}Invalid mode:{RESET} {mode}")
337
+ print(f"\nAvailable modes:{COLOR}")
338
+ for m in MODES:
339
+ print(f"{m}")
340
+ print(f"{RESET}")
341
+ sys.exit(1)
342
+ else:
343
+ if mode.endswith('.py'):
344
+ stdin=0
345
+ else:
346
+ stdin=1
347
+
348
+ if stdin==1:
349
+ filename="tracerset.tmp.py"
350
+ fp=open(filename,"w")
351
+ fp.write(sys.stdin.read())
352
+ fp.close()
353
+ else:
354
+ mode = get_mode()
355
+ filename = sys.argv[len(sys.argv)-1]
356
+
357
+ if filename.lower() in ['-v','-version','--v','--version']:
358
+ print(f"{VER} - {TAG}")
359
+ return
360
+ elif filename.lower() in ['-h','-help','--help','--h']:
361
+ print(f'''{COLOR}Usage:
362
+ tracerset [beginner] [file.py] #or stdin
363
+ tracerset intermediate [file.py] #or stdin
364
+ tracerset advanced [file.py] #or stdin{RESET}''')
365
+ return
366
+
367
+ config = MODES[mode]
368
+ show_banner(mode)
369
+
370
+ # --------------------------------------------------------
371
+ # Read source code
372
+ # --------------------------------------------------------
373
+ buff = read_source_code(filename)
374
+
375
+ # --------------------------------------------------------
376
+ # Parse AST
377
+ # --------------------------------------------------------
378
+ if mode != MODE_BEGINNER:
379
+ parsed = ast.parse(buff)
380
+
381
+ # --------------------------------------------------------
382
+ # Always show source code
383
+ # --------------------------------------------------------
384
+ show_source_code(buff)
385
+
386
+ # -----------------------------
387
+ # Cognitive Complexity Layer
388
+ # -----------------------------
389
+ if mode != MODE_BEGINNER:
390
+ show_cognitive_complexity(filename)
391
+
392
+ # --------------------------------------------------------
393
+ # Always show control flow graph
394
+ # --------------------------------------------------------
395
+ if mode != MODE_BEGINNER:
396
+ cfg_iterator(filename)
397
+
398
+ # --------------------------------------------------------
399
+ # ADVANCED MODE
400
+ # --------------------------------------------------------
401
+ if config["tokens"]:
402
+ show_tokens(filename)
403
+ if config["cst"]:
404
+ show_concrete_syntax_tree(filename)
405
+ if config["ast"]:
406
+ show_abstract_syntax_tree(filename)
407
+ if config["disassembly"]:
408
+ show_disassembly(filename)
409
+
410
+ # --------------------------------------------------------
411
+ # INTERMEDIATE + ADVANCED
412
+ # --------------------------------------------------------
413
+ if config["execution_trace"]:
414
+ show_execution_trace(filename)
415
+
416
+ # --------------------------------------------------------
417
+ # ALL MODES
418
+ # --------------------------------------------------------
419
+ if config["step_trace"]:
420
+ show_step_by_step_trace(filename)
421
+ if stdin==1:
422
+ os.remove('tracerset.tmp.py')
423
+
424
+ if __name__ == "__main__":
425
+ # ============================================================
426
+ # Exception Handling
427
+ # ============================================================
428
+
429
+ try:
430
+ main()
431
+
432
+ except OSError as ex:
433
+ print(f"{ERROR}File Error:{RESET}")
434
+ print(f"{ex.filename}: {ex.strerror}")
435
+
436
+ except SyntaxError as ex:
437
+ print(f"{ERROR}Syntax Error:{RESET}")
438
+ print(
439
+ f'In File "{sys.argv[1]}", line {ex.lineno}'
440
+ )
441
+ print(ex.text)
442
+ print(
443
+ f"{ex.__class__.__name__}: {ex.msg}"
444
+ )
445
+
446
+ except KeyboardInterrupt:
447
+ print(f"\n{ERROR}Execution interrupted by user.{RESET}")
File without changes
@@ -0,0 +1,148 @@
1
+ # Generating a Graphviz DOT File from a Python AST
2
+
3
+ import ast
4
+ import sys
5
+ import os
6
+ import platform
7
+
8
+ class ASTDotGenerator:
9
+ def __init__(self):
10
+ self.node_counter = 0
11
+ self.lines = []
12
+
13
+ def new_id(self):
14
+ node_id = f"node{self.node_counter}"
15
+ self.node_counter += 1
16
+ return node_id
17
+
18
+ def escape(self, text):
19
+ return str(text).replace('"', '\\"')
20
+
21
+ def resolve_import_file(self, module_name, current_file):
22
+ base_dir = os.path.dirname(
23
+ os.path.abspath(current_file)
24
+ )
25
+
26
+ candidate = os.path.join(
27
+ base_dir,
28
+ module_name.replace(".", os.sep) + ".py"
29
+ )
30
+
31
+ if os.path.exists(candidate):
32
+ return os.path.abspath(candidate)
33
+ return None
34
+
35
+ def collect_imports(self, tree, current_file):
36
+ imported_files = []
37
+
38
+ for node in ast.walk(tree):
39
+ if isinstance(node, ast.Import):
40
+ for alias in node.names:
41
+ imported = self.resolve_import_file(
42
+ alias.name,
43
+ current_file
44
+ )
45
+
46
+ if imported:
47
+ imported_files.append(imported)
48
+
49
+ elif isinstance(node, ast.ImportFrom):
50
+ if node.module:
51
+ imported = self.resolve_import_file(
52
+ node.module,
53
+ current_file
54
+ )
55
+ if imported:
56
+ imported_files.append(imported)
57
+
58
+ return imported_files
59
+
60
+ def visit(self, node, parent=None):
61
+
62
+ current_id = self.new_id()
63
+
64
+ label = type(node).__name__
65
+
66
+ # Add extra detail for important AST node types
67
+ if isinstance(node, ast.Name):
68
+ label += f"\\n{node.id}"
69
+
70
+ elif isinstance(node, ast.Constant):
71
+ label += f"\\n{repr(node.value)}"
72
+
73
+ elif isinstance(node, ast.FunctionDef):
74
+ label += f"\\n{node.name}"
75
+
76
+ elif isinstance(node, ast.arg):
77
+ label += f"\\n{node.arg}"
78
+
79
+ self.lines.append(
80
+ f'{current_id} [label="{self.escape(label)}"];'
81
+ )
82
+
83
+ if parent:
84
+ self.lines.append(f"{parent} -> {current_id};")
85
+
86
+ for child in ast.iter_child_nodes(node):
87
+ self.visit(child, current_id)
88
+
89
+ def generate(self, filename):
90
+ self.lines.append("digraph AST {")
91
+ self.lines.append(" rankdir=TB;")
92
+ self.lines.append(" node [shape=box];")
93
+
94
+ pending = [os.path.abspath(filename)]
95
+ visited = set()
96
+
97
+ while pending:
98
+ current_file = pending.pop(0)
99
+ if current_file in visited:
100
+ continue
101
+ visited.add(current_file)
102
+
103
+ with open(current_file, "r", encoding="utf-8") as f:
104
+ source = f.read()
105
+
106
+ tree = ast.parse(source)
107
+ self.visit(tree)
108
+ imported_files = self.collect_imports(
109
+ tree,
110
+ current_file
111
+ )
112
+
113
+ for imported in imported_files:
114
+ if imported not in visited:
115
+ pending.append(imported)
116
+
117
+ self.lines.append("}")
118
+ return "\n".join(self.lines)
119
+
120
+ if __name__ == "__main__":
121
+
122
+ if len(sys.argv) != 2:
123
+ print("Usage: python3 ast_to_dot.py <program.py>")
124
+ sys.exit(1)
125
+
126
+ filename = sys.argv[1]
127
+ with open(filename, "r", encoding="utf-8") as f:
128
+ source = f.read()
129
+ generator = ASTDotGenerator()
130
+ dot_output = generator.generate(filename)
131
+ output_file = filename.replace(".py", ".ast.dot")
132
+
133
+ with open(output_file, "w", encoding="utf-8") as f:
134
+ f.write(dot_output)
135
+
136
+ if platform.system() == 'Windows':
137
+ os.system(f"dot -Tpng {output_file} > {output_file}.png")
138
+ print(f"DOT file written to: {output_file}.png")
139
+ os.system(f"start {output_file}.png")
140
+ elif platform.system() == 'Linux':
141
+ print(f"DOT file written to: {output_file}")
142
+ #os.system(f"xdot {output_file} 2> /dev/null")
143
+ else:
144
+ #print("Platform not supported yet!")
145
+ #exit(-1)
146
+ pass
147
+
148
+