tldr-cli 0.1.5

CLI binary for TLDR code analysis tool
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
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
//! SSA CLI Integration Tests
//!
//! Tests for the `tldr ssa` command.
//! These tests define expected CLI behavior BEFORE implementation.
//!
//! Reference: session10-spec.md Section 4.1

use assert_cmd::prelude::*;
use predicates::prelude::*;
use std::fs;
use std::process::Command;
use tempfile::TempDir;

/// Get the path to the test binary
fn tldr_cmd() -> Command {
    Command::new(assert_cmd::cargo::cargo_bin!("tldr"))
}

// =============================================================================
// Test Fixtures
// =============================================================================

mod fixtures {
    pub const PYTHON_SIMPLE: &str = r#"
def simple(x):
    y = x + 1
    return y
"#;

    pub const PYTHON_DIAMOND: &str = r#"
def branch(x):
    if x > 0:
        y = 1
    else:
        y = 2
    return y
"#;

    pub const PYTHON_LOOP: &str = r#"
def loop(n):
    total = 0
    i = 0
    while i < n:
        total = total + i
        i = i + 1
    return total
"#;

    pub const PYTHON_NESTED: &str = r#"
def nested(x, y):
    if x > 0:
        if y > 0:
            z = 1
        else:
            z = 2
    else:
        z = 3
    return z
"#;

    pub const PYTHON_MULTI_VAR: &str = r#"
def multi(a, b):
    x = a
    y = b
    if a > b:
        x = a + 1
        y = b - 1
    return x + y
"#;

    pub const PYTHON_MEMORY: &str = r#"
class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

def modify_point(p, cond):
    if cond:
        p.x = 10
    else:
        p.x = 20
    return p.x
"#;

    pub const TYPESCRIPT_SIMPLE: &str = r#"
function simple(x: number): number {
    const y = x + 1;
    return y;
}
"#;

    pub const GO_SIMPLE: &str = r#"
func simple(x int) int {
    y := x + 1
    return y
}
"#;

    pub const RUST_SIMPLE: &str = r#"
fn simple(x: i32) -> i32 {
    let y = x + 1;
    y
}
"#;
}

// =============================================================================
// Help and Basic Command Tests
// =============================================================================

#[test]
fn test_ssa_help() {
    let mut cmd = tldr_cmd();
    cmd.args(["ssa", "--help"])
        .assert()
        .success()
        .stdout(predicate::str::contains("SSA"))
        .stdout(predicate::str::contains("--format"))
        .stdout(predicate::str::contains("--type"))
        .stdout(predicate::str::contains("--var"));
}

#[test]
fn test_ssa_missing_args() {
    let mut cmd = tldr_cmd();
    cmd.arg("ssa")
        .assert()
        .failure()
        .stderr(predicate::str::contains("required"));
}

#[test]
fn test_ssa_file_not_found() {
    let mut cmd = tldr_cmd();
    cmd.args(["ssa", "nonexistent.py", "func"])
        .assert()
        .failure()
        .stderr(predicate::str::contains("not found").or(predicate::str::contains("No such file")));
}

#[test]
fn test_ssa_function_not_found() {
    let temp = TempDir::new().unwrap();
    let file = temp.path().join("test.py");
    fs::write(&file, fixtures::PYTHON_SIMPLE).unwrap();

    let mut cmd = tldr_cmd();
    cmd.args(["ssa", file.to_str().unwrap(), "nonexistent_function"])
        .assert()
        .failure()
        .stderr(predicate::str::contains("not found").or(predicate::str::contains("Function")));
}

// =============================================================================
// JSON Output Tests (SSA-19)
// =============================================================================

#[test]
fn test_ssa_json_output_simple() {
    let temp = TempDir::new().unwrap();
    let file = temp.path().join("test.py");
    fs::write(&file, fixtures::PYTHON_SIMPLE).unwrap();

    let mut cmd = tldr_cmd();
    let output = cmd
        .args(["ssa", file.to_str().unwrap(), "simple", "--format", "json"])
        .output()
        .unwrap();

    assert!(output.status.success());

    // Parse as JSON
    let json: serde_json::Value =
        serde_json::from_slice(&output.stdout).expect("Output should be valid JSON");

    // Verify schema
    assert!(json.get("function").is_some());
    assert!(json.get("ssa_type").is_some());
    assert!(json.get("blocks").is_some());
    assert!(json.get("ssa_names").is_some());
    assert!(json.get("stats").is_some());

    // Verify function name
    assert_eq!(json["function"].as_str().unwrap(), "simple");
}

#[test]
fn test_ssa_json_output_with_phi() {
    let temp = TempDir::new().unwrap();
    let file = temp.path().join("test.py");
    fs::write(&file, fixtures::PYTHON_DIAMOND).unwrap();

    let mut cmd = tldr_cmd();
    let output = cmd
        .args(["ssa", file.to_str().unwrap(), "branch", "--format", "json"])
        .output()
        .unwrap();

    assert!(output.status.success());

    let json: serde_json::Value =
        serde_json::from_slice(&output.stdout).expect("Output should be valid JSON");

    // Should have phi functions
    let blocks = json["blocks"].as_array().unwrap();
    let has_phi = blocks.iter().any(|b| {
        b.get("phi_functions")
            .and_then(|p| p.as_array())
            .is_some_and(|arr| !arr.is_empty())
    });
    assert!(has_phi, "Diamond pattern should have phi functions");

    // Stats should show phi count
    assert!(json["stats"]["phi_count"].as_u64().unwrap() >= 1);
}

#[test]
fn test_ssa_json_output_loop() {
    let temp = TempDir::new().unwrap();
    let file = temp.path().join("test.py");
    fs::write(&file, fixtures::PYTHON_LOOP).unwrap();

    let mut cmd = tldr_cmd();
    let output = cmd
        .args(["ssa", file.to_str().unwrap(), "loop", "--format", "json"])
        .output()
        .unwrap();

    assert!(output.status.success());

    let json: serde_json::Value =
        serde_json::from_slice(&output.stdout).expect("Output should be valid JSON");

    // Loop should have at least 2 phis (for total and i)
    assert!(json["stats"]["phi_count"].as_u64().unwrap() >= 2);
}

// =============================================================================
// Text Output Tests (SSA-18)
// =============================================================================

#[test]
fn test_ssa_text_output() {
    let temp = TempDir::new().unwrap();
    let file = temp.path().join("test.py");
    fs::write(&file, fixtures::PYTHON_DIAMOND).unwrap();

    let mut cmd = tldr_cmd();
    cmd.args(["ssa", file.to_str().unwrap(), "branch", "--format", "text"])
        .assert()
        .success()
        .stdout(predicate::str::contains("SSA Form"))
        .stdout(predicate::str::contains("branch"))
        .stdout(predicate::str::contains("Block"))
        .stdout(predicate::str::contains("phi("));
}

#[test]
fn test_ssa_text_shows_versions() {
    let temp = TempDir::new().unwrap();
    let file = temp.path().join("test.py");
    fs::write(&file, fixtures::PYTHON_DIAMOND).unwrap();

    let mut cmd = tldr_cmd();
    cmd.args(["ssa", file.to_str().unwrap(), "branch", "--format", "text"])
        .assert()
        .success()
        // Should show versioned variables like y_1, y_2
        .stdout(predicate::str::contains("y_").or(predicate::str::contains("y₁")));
}

// =============================================================================
// DOT Output Tests (SSA-20)
// =============================================================================

#[test]
fn test_ssa_dot_output() {
    let temp = TempDir::new().unwrap();
    let file = temp.path().join("test.py");
    fs::write(&file, fixtures::PYTHON_DIAMOND).unwrap();

    let mut cmd = tldr_cmd();
    cmd.args(["ssa", file.to_str().unwrap(), "branch", "--format", "dot"])
        .assert()
        .success()
        .stdout(predicate::str::contains("digraph"))
        .stdout(predicate::str::contains("->"));
}

#[test]
fn test_ssa_dot_has_phi_nodes() {
    let temp = TempDir::new().unwrap();
    let file = temp.path().join("test.py");
    fs::write(&file, fixtures::PYTHON_DIAMOND).unwrap();

    let mut cmd = tldr_cmd();
    cmd.args(["ssa", file.to_str().unwrap(), "branch", "--format", "dot"])
        .assert()
        .success()
        // DOT should show phi in node labels
        .stdout(predicate::str::contains("phi").or(predicate::str::contains("φ")));
}

// =============================================================================
// Variable Filter Tests
// =============================================================================

#[test]
fn test_ssa_filter_by_variable() {
    let temp = TempDir::new().unwrap();
    let file = temp.path().join("test.py");
    fs::write(&file, fixtures::PYTHON_MULTI_VAR).unwrap();

    let mut cmd = tldr_cmd();
    let output = cmd
        .args([
            "ssa",
            file.to_str().unwrap(),
            "multi",
            "--format",
            "json",
            "--var",
            "x",
        ])
        .output()
        .unwrap();

    assert!(output.status.success());

    let json: serde_json::Value =
        serde_json::from_slice(&output.stdout).expect("Output should be valid JSON");

    // All SSA names should be for variable x
    let ssa_names = json["ssa_names"].as_array().unwrap();
    for name in ssa_names {
        assert_eq!(name["variable"].as_str().unwrap(), "x");
    }
}

#[test]
fn test_ssa_filter_nonexistent_variable() {
    let temp = TempDir::new().unwrap();
    let file = temp.path().join("test.py");
    fs::write(&file, fixtures::PYTHON_SIMPLE).unwrap();

    let mut cmd = tldr_cmd();
    let output = cmd
        .args([
            "ssa",
            file.to_str().unwrap(),
            "simple",
            "--format",
            "json",
            "--var",
            "nonexistent",
        ])
        .output()
        .unwrap();

    // Should succeed but return empty/filtered result
    assert!(output.status.success());

    let json: serde_json::Value =
        serde_json::from_slice(&output.stdout).expect("Output should be valid JSON");

    // SSA names should be empty (no matching variable)
    let ssa_names = json["ssa_names"].as_array().unwrap();
    assert!(ssa_names.is_empty());
}

// =============================================================================
// SSA Type Tests
// =============================================================================

#[test]
fn test_ssa_minimal_type() {
    let temp = TempDir::new().unwrap();
    let file = temp.path().join("test.py");
    fs::write(&file, fixtures::PYTHON_DIAMOND).unwrap();

    let mut cmd = tldr_cmd();
    let output = cmd
        .args([
            "ssa",
            file.to_str().unwrap(),
            "branch",
            "--format",
            "json",
            "--type",
            "minimal",
        ])
        .output()
        .unwrap();

    assert!(output.status.success());

    let json: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
    assert_eq!(json["ssa_type"].as_str().unwrap(), "minimal");
}

#[test]
fn test_ssa_semi_pruned_type() {
    let temp = TempDir::new().unwrap();
    let file = temp.path().join("test.py");
    fs::write(&file, fixtures::PYTHON_DIAMOND).unwrap();

    let mut cmd = tldr_cmd();
    let output = cmd
        .args([
            "ssa",
            file.to_str().unwrap(),
            "branch",
            "--format",
            "json",
            "--type",
            "semi-pruned",
        ])
        .output()
        .unwrap();

    assert!(output.status.success());

    let json: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
    assert_eq!(json["ssa_type"].as_str().unwrap(), "semi_pruned");
}

#[test]
fn test_ssa_pruned_type() {
    let temp = TempDir::new().unwrap();
    let file = temp.path().join("test.py");
    fs::write(&file, fixtures::PYTHON_DIAMOND).unwrap();

    let mut cmd = tldr_cmd();
    let output = cmd
        .args([
            "ssa",
            file.to_str().unwrap(),
            "branch",
            "--format",
            "json",
            "--type",
            "pruned",
        ])
        .output()
        .unwrap();

    assert!(output.status.success());

    let json: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
    assert_eq!(json["ssa_type"].as_str().unwrap(), "pruned");

    // Pruned should have fewer or equal phi functions than minimal
    let phi_count = json["stats"]["phi_count"].as_u64().unwrap();
    // This is a sanity check - actual comparison would need both runs
    let _ = phi_count;
}

// =============================================================================
// Memory SSA Tests
// =============================================================================

#[test]
fn test_ssa_memory_flag() {
    let temp = TempDir::new().unwrap();
    let file = temp.path().join("test.py");
    fs::write(&file, fixtures::PYTHON_MEMORY).unwrap();

    let mut cmd = tldr_cmd();
    let output = cmd
        .args([
            "ssa",
            file.to_str().unwrap(),
            "modify_point",
            "--format",
            "json",
            "--memory",
        ])
        .output()
        .unwrap();

    assert!(output.status.success());

    let json: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();

    // Should have memory SSA information
    assert!(
        json.get("memory_ssa").is_some(),
        "Memory SSA should be included with --memory flag"
    );
}

#[test]
fn test_ssa_without_memory_flag() {
    let temp = TempDir::new().unwrap();
    let file = temp.path().join("test.py");
    fs::write(&file, fixtures::PYTHON_MEMORY).unwrap();

    let mut cmd = tldr_cmd();
    let output = cmd
        .args([
            "ssa",
            file.to_str().unwrap(),
            "modify_point",
            "--format",
            "json",
        ])
        .output()
        .unwrap();

    assert!(output.status.success());

    let json: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();

    // Should NOT have memory SSA by default
    assert!(
        json.get("memory_ssa").is_none() || json["memory_ssa"].is_null(),
        "Memory SSA should not be included by default"
    );
}

// =============================================================================
// Multi-Language Tests
// =============================================================================

#[test]
fn test_ssa_typescript() {
    let temp = TempDir::new().unwrap();
    let file = temp.path().join("test.ts");
    fs::write(&file, fixtures::TYPESCRIPT_SIMPLE).unwrap();

    let mut cmd = tldr_cmd();
    cmd.args(["ssa", file.to_str().unwrap(), "simple", "--format", "json"])
        .assert()
        .success();
}

#[test]
fn test_ssa_go() {
    let temp = TempDir::new().unwrap();
    let file = temp.path().join("test.go");
    fs::write(&file, fixtures::GO_SIMPLE).unwrap();

    let mut cmd = tldr_cmd();
    cmd.args(["ssa", file.to_str().unwrap(), "simple", "--format", "json"])
        .assert()
        .success();
}

#[test]
fn test_ssa_rust() {
    let temp = TempDir::new().unwrap();
    let file = temp.path().join("test.rs");
    fs::write(&file, fixtures::RUST_SIMPLE).unwrap();

    let mut cmd = tldr_cmd();
    cmd.args(["ssa", file.to_str().unwrap(), "simple", "--format", "json"])
        .assert()
        .success();
}

#[test]
fn test_ssa_explicit_language() {
    let temp = TempDir::new().unwrap();
    let file = temp.path().join("test.txt"); // No extension
    fs::write(&file, fixtures::PYTHON_SIMPLE).unwrap();

    let mut cmd = tldr_cmd();
    cmd.args([
        "ssa",
        file.to_str().unwrap(),
        "simple",
        "--format",
        "json",
        "--lang",
        "python",
    ])
    .assert()
    .success();
}

// =============================================================================
// Edge Cases
// =============================================================================

#[test]
fn test_ssa_empty_function() {
    let temp = TempDir::new().unwrap();
    let file = temp.path().join("test.py");
    fs::write(&file, "def empty():\n    pass\n").unwrap();

    let mut cmd = tldr_cmd();
    let output = cmd
        .args(["ssa", file.to_str().unwrap(), "empty", "--format", "json"])
        .output()
        .unwrap();

    assert!(output.status.success());

    let json: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
    assert_eq!(json["stats"]["phi_count"].as_u64().unwrap(), 0);
}

#[test]
fn test_ssa_single_block() {
    let temp = TempDir::new().unwrap();
    let file = temp.path().join("test.py");
    fs::write(&file, "def single(x):\n    return x + 1\n").unwrap();

    let mut cmd = tldr_cmd();
    let output = cmd
        .args(["ssa", file.to_str().unwrap(), "single", "--format", "json"])
        .output()
        .unwrap();

    assert!(output.status.success());

    let json: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
    // Single block should have no phi functions
    assert_eq!(json["stats"]["phi_count"].as_u64().unwrap(), 0);
}

#[test]
fn test_ssa_deeply_nested() {
    let temp = TempDir::new().unwrap();
    let file = temp.path().join("test.py");
    fs::write(&file, fixtures::PYTHON_NESTED).unwrap();

    let mut cmd = tldr_cmd();
    cmd.args(["ssa", file.to_str().unwrap(), "nested", "--format", "json"])
        .assert()
        .success();
}

// =============================================================================
// Performance Tests
// =============================================================================

#[test]
fn test_ssa_reasonable_time() {
    use std::time::Instant;

    let temp = TempDir::new().unwrap();
    let file = temp.path().join("test.py");
    fs::write(&file, fixtures::PYTHON_LOOP).unwrap();

    let start = Instant::now();

    let mut cmd = tldr_cmd();
    cmd.args(["ssa", file.to_str().unwrap(), "loop", "--format", "json"])
        .assert()
        .success();

    let elapsed = start.elapsed();
    // Should complete in under 5 seconds (generous for CI)
    assert!(
        elapsed.as_secs() < 5,
        "SSA construction took too long: {}s",
        elapsed.as_secs()
    );
}