spydecy-debugger 0.3.1

Introspective debugger for Spydecy transpiler
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
//! AST visualization for debugging
//!
//! This module provides formatted visualization of ASTs for debugging purposes.

use anyhow::{Context, Result};
use colored::Colorize;
use spydecy_c::{cpython, parser::CAST};
use spydecy_python::parser::PythonAST;
use std::fs;
use std::path::Path;

/// Visualize Python source as AST
///
/// # Errors
///
/// Returns an error if the file cannot be read or parsed
pub fn visualize_python(file_path: &Path) -> Result<String> {
    // Read the source file
    let source = fs::read_to_string(file_path)
        .with_context(|| format!("Failed to read file: {}", file_path.display()))?;

    // Parse to AST
    let filename = file_path.to_string_lossy().to_string();
    let ast = spydecy_python::parser::parse(&source, &filename)
        .context("Failed to parse Python source")?;

    // Format the output
    let mut output = String::new();

    // Header
    output.push_str(&format!(
        "{}",
        "╔══════════════════════════════════════════════════════════╗\n".cyan()
    ));
    output.push_str(&format!(
        "{}",
        "║  Spydecy Debugger: Python AST Visualization             ║\n".cyan()
    ));
    output.push_str(&format!(
        "{}",
        "╚══════════════════════════════════════════════════════════╝\n".cyan()
    ));
    output.push('\n');

    // File info
    output.push_str(&format!("{} {}\n", "File:".bold(), file_path.display()));
    output.push_str(&format!(
        "{} {} lines\n",
        "Size:".bold(),
        source.lines().count()
    ));
    output.push('\n');

    // Source code preview
    output.push_str(&format!("{}\n", "═══ Source Code ═══".yellow().bold()));
    for (i, line) in source.lines().enumerate() {
        output.push_str(&format!("{:3}{}\n", (i + 1).to_string().dimmed(), line));
    }
    output.push('\n');

    // AST tree
    output.push_str(&format!(
        "{}\n",
        "═══ Abstract Syntax Tree ═══".green().bold()
    ));
    format_ast_node(&ast, 0, &mut output);
    output.push('\n');

    // Statistics
    output.push_str(&format!("{}\n", "═══ Statistics ═══".blue().bold()));
    let node_count = count_nodes(&ast);
    output.push_str(&format!("  {} {}\n", "Total AST nodes:".bold(), node_count));
    output.push_str(&format!(
        "  {} {}\n",
        "Root node type:".bold(),
        ast.node_type
    ));
    if !ast.children.is_empty() {
        output.push_str(&format!(
            "  {} {}\n",
            "Direct children:".bold(),
            ast.children.len()
        ));
    }

    Ok(output)
}

/// Format an AST node with indentation
fn format_ast_node(node: &PythonAST, depth: usize, output: &mut String) {
    let indent = "  ".repeat(depth);
    let connector = if depth > 0 { "├─ " } else { "" };

    // Node type (colored)
    let node_type_colored = match node.node_type.as_str() {
        "Module" => node.node_type.cyan().bold(),
        "FunctionDef" => node.node_type.green().bold(),
        "ClassDef" => node.node_type.yellow().bold(),
        "Call" => node.node_type.magenta(),
        "Return" => node.node_type.red(),
        "Name" => node.node_type.blue(),
        _ => node.node_type.white(),
    };

    output.push_str(&format!("{}{}{}", indent, connector, node_type_colored));

    // Node attributes
    if !node.attributes.is_empty() {
        output.push_str(" (");
        let mut first = true;
        for (key, value) in &node.attributes {
            if !first {
                output.push_str(", ");
            }
            output.push_str(&format!("{}={}", key.dimmed(), value.bright_white()));
            first = false;
        }
        output.push(')');
    }

    // Source location
    if let Some(lineno) = node.lineno {
        output.push_str(&format!(" {}", format!("@L{lineno}").dimmed()));
    }

    output.push('\n');

    // Recursively format children
    for child in &node.children {
        format_ast_node(child, depth + 1, output);
    }
}

/// Count total nodes in AST
fn count_nodes(node: &PythonAST) -> usize {
    1 + node.children.iter().map(count_nodes).sum::<usize>()
}

/// Visualize C source as AST with `CPython` API annotations
///
/// # Errors
///
/// Returns an error if the file cannot be read or parsed
pub fn visualize_c(file_path: &Path) -> Result<String> {
    // Read the source file
    let source = fs::read_to_string(file_path)
        .with_context(|| format!("Failed to read file: {}", file_path.display()))?;

    // Parse to AST
    let filename = file_path.to_string_lossy().to_string();
    let parser = spydecy_c::parser::CParser::new().context("Failed to create C parser")?;
    let ast = parser
        .parse(&source, &filename)
        .context("Failed to parse C source")?;

    // Format the output
    let mut output = String::new();

    // Header
    output.push_str(&format!(
        "{}",
        "╔══════════════════════════════════════════════════════════╗\n".cyan()
    ));
    output.push_str(&format!(
        "{}",
        "║  Spydecy Debugger: C AST Visualization                  ║\n".cyan()
    ));
    output.push_str(&format!(
        "{}",
        "╚══════════════════════════════════════════════════════════╝\n".cyan()
    ));
    output.push('\n');

    // File info
    output.push_str(&format!("{} {}\n", "File:".bold(), file_path.display()));
    output.push_str(&format!(
        "{} {} lines\n",
        "Size:".bold(),
        source.lines().count()
    ));
    output.push('\n');

    // Source code preview
    output.push_str(&format!("{}\n", "═══ Source Code ═══".yellow().bold()));
    for (i, line) in source.lines().enumerate() {
        output.push_str(&format!("{:3}{}\n", (i + 1).to_string().dimmed(), line));
    }
    output.push('\n');

    // AST tree with CPython annotations
    output.push_str(&format!(
        "{}\n",
        "═══ Abstract Syntax Tree ═══".green().bold()
    ));
    format_c_ast_node(&ast, 0, &mut output);
    output.push('\n');

    // CPython API analysis
    output.push_str(&format!(
        "{}\n",
        "═══ CPython API Analysis ═══".magenta().bold()
    ));
    let cpython_calls = collect_cpython_calls(&ast);
    if cpython_calls.is_empty() {
        output.push_str(&format!(
            "  {} No CPython API calls detected\n",
            "".dimmed()
        ));
    } else {
        for (pattern, name) in cpython_calls {
            output.push_str(&format!(
                "  {} {}{:?}\n",
                "".bright_yellow(),
                name.bright_white().bold(),
                pattern
            ));
        }
    }
    output.push('\n');

    // PyObject tracking
    output.push_str(&format!("{}\n", "═══ PyObject* Tracking ═══".blue().bold()));
    let pyobject_params = collect_pyobject_params(&ast);
    if pyobject_params.is_empty() {
        output.push_str(&format!(
            "  {} No PyObject* parameters detected\n",
            "".dimmed()
        ));
    } else {
        for (func_name, param_name, param_type) in pyobject_params {
            output.push_str(&format!(
                "  {} {}::{} ({})\n",
                "🐍".bright_cyan(),
                func_name.yellow(),
                param_name.bright_white(),
                param_type.dimmed()
            ));
        }
    }
    output.push('\n');

    // Statistics
    output.push_str(&format!("{}\n", "═══ Statistics ═══".blue().bold()));
    let node_count = count_c_nodes(&ast);
    output.push_str(&format!("  {} {}\n", "Total AST nodes:".bold(), node_count));
    output.push_str(&format!(
        "  {} {}\n",
        "Root node type:".bold(),
        ast.node_type
    ));
    if !ast.children.is_empty() {
        output.push_str(&format!(
            "  {} {}\n",
            "Direct children:".bold(),
            ast.children.len()
        ));
    }

    Ok(output)
}

/// Format a C AST node with indentation and `CPython` API highlighting
fn format_c_ast_node(node: &CAST, depth: usize, output: &mut String) {
    let indent = "  ".repeat(depth);
    let connector = if depth > 0 { "├─ " } else { "" };
    let pattern = cpython::identify_pattern(node);

    // Format node type with color
    let node_type_colored = colorize_c_node_type(&node.node_type, pattern.is_some());
    output.push_str(&format!("{indent}{connector}{node_type_colored}"));

    // Add node details
    format_c_node_details(node, pattern, output);
    output.push('\n');

    // Recursively format children
    for child in &node.children {
        format_c_ast_node(child, depth + 1, output);
    }
}

/// Colorize C node type based on type and `CPython` status
fn colorize_c_node_type(node_type: &str, is_cpython: bool) -> colored::ColoredString {
    use colored::Colorize;

    match node_type {
        "TranslationUnit" => node_type.cyan().bold(),
        "FunctionDecl" if is_cpython => node_type.magenta().bold(),
        "FunctionDecl" => node_type.green().bold(),
        "CallExpr" if is_cpython => node_type.magenta(),
        "CallExpr" => node_type.blue(),
        "ReturnStmt" => node_type.red(),
        "VarDecl" => node_type.yellow(),
        "ParmDecl" => node_type.cyan(),
        _ => node_type.white(),
    }
}

/// Format C node details (name, pattern, return type, parameters)
fn format_c_node_details(
    node: &CAST,
    pattern: Option<cpython::CPythonPattern>,
    output: &mut String,
) {
    // Node name
    if let Some(ref name) = node.name {
        output.push_str(&format!(" {}", name.bright_white().bold()));
    }

    // CPython pattern annotation
    if let Some(p) = pattern {
        output.push_str(&format!(" {} {p:?}", "".bright_yellow()));
    }

    // Return type for functions
    if let Some(ref ret_type) = node.return_type {
        output.push_str(&format!("{}", ret_type.dimmed()));
    }

    // Parameters
    if !node.params.is_empty() {
        format_c_parameters(&node.params, output);
    }
}

/// Format C function parameters with `PyObject` highlighting
fn format_c_parameters(params: &[spydecy_c::parser::CParam], output: &mut String) {
    output.push_str(" (");
    for (i, param) in params.iter().enumerate() {
        if i > 0 {
            output.push_str(", ");
        }
        format_c_parameter(param, output);
    }
    output.push(')');
}

/// Format a single C parameter with appropriate highlighting
fn format_c_parameter(param: &spydecy_c::parser::CParam, output: &mut String) {
    let is_pyobject = param.param_type.contains("PyObject") || param.param_type.contains("PyList");
    if is_pyobject {
        output.push_str(&format!(
            "{}: {}",
            param.name.bright_cyan().bold(),
            param.param_type.cyan()
        ));
    } else {
        output.push_str(&format!("{}: {}", param.name, param.param_type.dimmed()));
    }
}

/// Collect `CPython` API calls from AST
fn collect_cpython_calls(node: &CAST) -> Vec<(cpython::CPythonPattern, String)> {
    let mut calls = Vec::new();

    if let Some(pattern) = cpython::identify_pattern(node) {
        if let Some(ref name) = node.name {
            calls.push((pattern, name.clone()));
        }
    }

    for child in &node.children {
        calls.extend(collect_cpython_calls(child));
    }

    calls
}

/// Collect `PyObject*` parameters from functions
fn collect_pyobject_params(node: &CAST) -> Vec<(String, String, String)> {
    let mut params = Vec::new();

    if node.node_type == "FunctionDecl" {
        if let Some(ref func_name) = node.name {
            for param in &node.params {
                if param.param_type.contains("PyObject")
                    || param.param_type.contains("PyList")
                    || param.param_type.contains("PyDict")
                {
                    params.push((
                        func_name.clone(),
                        param.name.clone(),
                        param.param_type.clone(),
                    ));
                }
            }
        }
    }

    for child in &node.children {
        params.extend(collect_pyobject_params(child));
    }

    params
}

/// Count total nodes in C AST
fn count_c_nodes(node: &CAST) -> usize {
    1 + node.children.iter().map(count_c_nodes).sum::<usize>()
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Write;
    use tempfile::NamedTempFile;

    #[test]
    fn test_visualize_simple_function() {
        let mut temp_file = NamedTempFile::new().unwrap();
        writeln!(temp_file, "def my_len(x):\n    return len(x)").unwrap();

        let result = visualize_python(temp_file.path());
        assert!(result.is_ok());

        let output = result.unwrap();
        assert!(output.contains("Module"));
        assert!(output.contains("FunctionDef"));
        assert!(output.contains("Return"));
        assert!(output.contains("Call"));
        assert!(output.contains("my_len"));
    }

    #[test]
    fn test_count_nodes() {
        let ast = PythonAST {
            node_type: "Module".to_string(),
            lineno: None,
            col_offset: None,
            children: vec![
                PythonAST::new("FunctionDef".to_string()),
                PythonAST::new("FunctionDef".to_string()),
            ],
            attributes: std::collections::HashMap::new(),
        };

        assert_eq!(count_nodes(&ast), 3); // Module + 2 FunctionDef
    }

    #[test]
    fn test_visualize_simple_c_function() {
        use std::io::Write;
        use tempfile::Builder;

        let mut temp_file = Builder::new().suffix(".c").tempfile().unwrap();
        writeln!(temp_file, "int add(int a, int b) {{\n    return a + b;\n}}").unwrap();
        temp_file.flush().unwrap(); // Ensure content is written

        let result = visualize_c(temp_file.path());
        assert!(
            result.is_ok(),
            "Should visualize C code: {:?}",
            result.as_ref().err()
        );

        let output = result.unwrap();
        assert!(output.contains("C AST Visualization"));
        assert!(output.contains("FunctionDecl"));
        assert!(output.contains("add"));
    }

    #[test]
    fn test_visualize_cpython_function() {
        use std::io::Write;
        use tempfile::Builder;

        let mut temp_file = Builder::new().suffix(".c").tempfile().unwrap();
        writeln!(
            temp_file,
            "static Py_ssize_t list_length(PyListObject *self) {{\n    return Py_SIZE(self);\n}}"
        )
        .unwrap();
        temp_file.flush().unwrap(); // Ensure content is written

        let result = visualize_c(temp_file.path());
        assert!(
            result.is_ok(),
            "Should visualize CPython code: {:?}",
            result.as_ref().err()
        );

        let output = result.unwrap();
        assert!(output.contains("CPython API Analysis"));
        assert!(output.contains("PyObject* Tracking"));
        assert!(output.contains("list_length"));
    }

    #[test]
    fn test_collect_cpython_calls() {
        let mut ast = CAST::new("FunctionDecl".to_owned());
        ast.name = Some("list_length".to_owned());

        let mut child = CAST::new("CallExpr".to_owned());
        child.name = Some("PyList_Append".to_owned());
        ast.children.push(child);

        let calls = collect_cpython_calls(&ast);
        assert_eq!(calls.len(), 2);
        assert!(calls.iter().any(|(_, name)| name == "list_length"));
        assert!(calls.iter().any(|(_, name)| name == "PyList_Append"));
    }

    #[test]
    fn test_collect_pyobject_params() {
        let mut ast = CAST::new("FunctionDecl".to_owned());
        ast.name = Some("test_func".to_owned());
        ast.params.push(spydecy_c::parser::CParam {
            name: "obj".to_owned(),
            param_type: "PyObject*".to_owned(),
        });
        ast.params.push(spydecy_c::parser::CParam {
            name: "x".to_owned(),
            param_type: "int".to_owned(),
        });

        let params = collect_pyobject_params(&ast);
        assert_eq!(params.len(), 1);
        assert_eq!(params[0].1, "obj");
        assert_eq!(params[0].2, "PyObject*");
    }

    #[test]
    fn test_count_c_nodes() {
        let mut ast = CAST::new("TranslationUnit".to_owned());
        ast.children.push(CAST::new("FunctionDecl".to_owned()));
        ast.children.push(CAST::new("FunctionDecl".to_owned()));

        assert_eq!(count_c_nodes(&ast), 3); // TranslationUnit + 2 FunctionDecl
    }
}