mirage-analyzer 1.6.0

Path-Aware Code Intelligence Engine for Rust
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
// ============================================================================

use crate::cfg::reachability::find_unreachable;
use crate::cfg::{BasicBlock, BlockKind, Cfg, EdgeType, Terminator};
use crate::cli::responses::*;
use crate::cli::*;
use petgraph::graph::DiGraph;

/// Helper to create a test CFG with an unreachable block
fn create_cfg_with_unreachable() -> Cfg {
    let mut g = DiGraph::new();

    // Block 0: entry, goes to 1
    let b0 = g.add_node(BasicBlock {
        id: 0,
        db_id: None,
        kind: BlockKind::Entry,
        statements: vec!["let x = 1".to_string()],
        terminator: Terminator::Goto { target: 1 },
        source_location: None,
        coord_x: 0,
        coord_y: 0,
        coord_z: 0,
    });

    // Block 1: normal, goes to 2
    let b1 = g.add_node(BasicBlock {
        id: 1,
        db_id: None,
        kind: BlockKind::Normal,
        statements: vec!["if x > 0".to_string()],
        terminator: Terminator::SwitchInt {
            targets: vec![2],
            otherwise: 3,
        },
        source_location: None,
        coord_x: 0,
        coord_y: 0,
        coord_z: 0,
    });

    // Block 2: exit (reachable)
    let b2 = g.add_node(BasicBlock {
        id: 2,
        db_id: None,
        kind: BlockKind::Exit,
        statements: vec!["return true".to_string()],
        terminator: Terminator::Return,
        source_location: None,
        coord_x: 0,
        coord_y: 0,
        coord_z: 0,
    });

    // Block 3: exit (reachable)
    let b3 = g.add_node(BasicBlock {
        id: 3,
        db_id: None,
        kind: BlockKind::Exit,
        statements: vec!["return false".to_string()],
        terminator: Terminator::Return,
        source_location: None,
        coord_x: 0,
        coord_y: 0,
        coord_z: 0,
    });

    // Block 4: unreachable (no edges to it)
    let _b4 = g.add_node(BasicBlock {
        id: 4,
        db_id: None,
        kind: BlockKind::Exit,
        statements: vec!["unreachable code".to_string()],
        terminator: Terminator::Unreachable,
        source_location: None,
        coord_x: 0,
        coord_y: 0,
        coord_z: 0,
    });

    g.add_edge(b0, b1, EdgeType::Fallthrough);
    g.add_edge(b1, b2, EdgeType::TrueBranch);
    g.add_edge(b1, b3, EdgeType::FalseBranch);

    g
}

/// Test that unreachable blocks are detected
#[test]
fn test_unreachable_detects_dead_code() {
    let cfg = create_cfg_with_unreachable();
    let unreachable_indices = find_unreachable(&cfg);

    // Should find exactly 1 unreachable block (block 4)
    assert_eq!(
        unreachable_indices.len(),
        1,
        "Should find exactly 1 unreachable block"
    );

    // Verify it's block 4
    let block_id = cfg.node_weight(unreachable_indices[0]).unwrap().id;
    assert_eq!(block_id, 4, "Unreachable block should be block 4");
}

/// Test that UnreachableResponse struct serializes correctly
#[test]
fn test_unreachable_response_serialization() {
    use crate::output::JsonResponse;

    let response = UnreachableResponse {
        uncalled_functions: None,
        function: "test_func".to_string(),
        total_functions: 1,
        functions_with_unreachable: 1,
        unreachable_count: 1,
        blocks: vec![UnreachableBlock {
            block_id: 4,
            kind: "Exit".to_string(),
            statements: vec!["unreachable code".to_string()],
            terminator: "Unreachable".to_string(),
            incoming_edges: vec![],
        }],
    };

    let wrapper = JsonResponse::new(response);
    let json = wrapper.to_json();

    assert!(json.contains("\"function\":\"test_func\""));
    assert!(json.contains("\"unreachable_count\":1"));
    assert!(json.contains("\"block_id\":4"));
    assert!(json.contains("\"kind\":\"Exit\""));
}

/// Test that empty unreachable response is handled correctly
#[test]
fn test_unreachable_empty_response() {
    use crate::output::JsonResponse;

    let response = UnreachableResponse {
        uncalled_functions: None,
        function: "test_func".to_string(),
        total_functions: 1,
        functions_with_unreachable: 0,
        unreachable_count: 0,
        blocks: vec![],
    };

    let wrapper = JsonResponse::new(response);
    let json = wrapper.to_json();

    assert!(json.contains("\"unreachable_count\":0"));
    assert!(json.contains("\"functions_with_unreachable\":0"));
}

/// Test that UnreachableBlock struct contains expected fields
#[test]
fn test_unreachable_block_fields() {
    let block = UnreachableBlock {
        block_id: 5,
        kind: "Normal".to_string(),
        statements: vec!["stmt1".to_string(), "stmt2".to_string()],
        terminator: "Return".to_string(),
        incoming_edges: vec![],
    };

    assert_eq!(block.block_id, 5);
    assert_eq!(block.kind, "Normal");
    assert_eq!(block.statements.len(), 2);
    assert_eq!(block.terminator, "Return");
}

/// Test UnreachableArgs flags
#[test]
fn test_unreachable_args_flags() {
    let args_with = UnreachableArgs {
        include_uncalled: false,
        within_functions: true,
        show_branches: true,
    };

    let args_without = UnreachableArgs {
        include_uncalled: false,
        within_functions: false,
        show_branches: false,
    };

    assert!(args_with.within_functions);
    assert!(args_with.show_branches);
    assert!(!args_without.within_functions);
    assert!(!args_without.show_branches);
}

/// Test that create_test_cfg has no unreachable blocks
#[test]
fn test_test_cfg_fully_reachable() {
    let cfg = cmds::create_test_cfg();
    let unreachable_indices = find_unreachable(&cfg);

    // Test CFG should have no unreachable blocks
    assert_eq!(
        unreachable_indices.len(),
        0,
        "Test CFG should have no unreachable blocks"
    );
}

/// Test that --show-branches includes incoming edge details
#[test]
fn test_unreachable_show_branches_with_edges() {
    use crate::cfg::reachability::find_unreachable;
    use petgraph::visit::EdgeRef;

    // Create a CFG with an unreachable block that HAS incoming edges
    // This simulates a block that's only reachable from an unreachable source
    let mut g = DiGraph::new();

    let b0 = g.add_node(BasicBlock {
        id: 0,
        db_id: None,
        kind: BlockKind::Entry,
        statements: vec!["let x = 1".to_string()],
        terminator: Terminator::Goto { target: 1 },
        source_location: None,
        coord_x: 0,
        coord_y: 0,
        coord_z: 0,
    });

    let b1 = g.add_node(BasicBlock {
        id: 1,
        db_id: None,
        kind: BlockKind::Normal,
        statements: vec!["if x > 0".to_string()],
        terminator: Terminator::SwitchInt {
            targets: vec![2],
            otherwise: 3,
        },
        source_location: None,
        coord_x: 0,
        coord_y: 0,
        coord_z: 0,
    });

    let b2 = g.add_node(BasicBlock {
        id: 2,
        db_id: None,
        kind: BlockKind::Exit,
        statements: vec!["return true".to_string()],
        terminator: Terminator::Return,
        source_location: None,
        coord_x: 0,
        coord_y: 0,
        coord_z: 0,
    });

    // b3 and b4 are both unreachable, but b4 has an incoming edge from b3
    let b3 = g.add_node(BasicBlock {
        id: 3,
        db_id: None,
        kind: BlockKind::Normal,
        statements: vec!["unreachable branch".to_string()],
        terminator: Terminator::Goto { target: 4 },
        source_location: None,
        coord_x: 0,
        coord_y: 0,
        coord_z: 0,
    });

    let b4 = g.add_node(BasicBlock {
        id: 4,
        db_id: None,
        kind: BlockKind::Exit,
        statements: vec!["unreachable code".to_string()],
        terminator: Terminator::Unreachable,
        source_location: None,
        coord_x: 0,
        coord_y: 0,
        coord_z: 0,
    });

    // Only connect entry to b1, making b3 and b4 unreachable
    g.add_edge(b0, b1, EdgeType::Fallthrough);
    g.add_edge(b1, b2, EdgeType::TrueBranch);
    // b3 -> b4 edge exists, but both blocks are unreachable
    g.add_edge(b3, b4, EdgeType::Fallthrough);

    // Build UnreachableBlock structs with show_branches=true
    let unreachable_indices = find_unreachable(&g);
    let blocks: Vec<UnreachableBlock> = unreachable_indices
        .iter()
        .map(|&idx| {
            let block = &g[idx];
            let kind_str = format!("{:?}", block.kind);
            let terminator_str = format!("{:?}", block.terminator);

            // Collect incoming edges
            let incoming_edges: Vec<IncomingEdge> = g
                .edge_references()
                .filter(|edge| edge.target() == idx)
                .map(|edge| {
                    let source_block = &g[edge.source()];
                    let edge_type = g.edge_weight(edge.id()).unwrap();
                    IncomingEdge {
                        from_block: source_block.id,
                        edge_type: format!("{:?}", edge_type),
                    }
                })
                .collect();

            UnreachableBlock {
                block_id: block.id,
                kind: kind_str,
                statements: block.statements.clone(),
                terminator: terminator_str,
                incoming_edges,
            }
        })
        .collect();

    // Should find 2 unreachable blocks (3 and 4)
    assert_eq!(blocks.len(), 2);

    // Block 3 should have no incoming edges (isolated unreachable code)
    let block3 = blocks.iter().find(|b| b.block_id == 3).unwrap();
    assert_eq!(block3.incoming_edges.len(), 0);

    // Block 4 should have 1 incoming edge from block 3
    let block4 = blocks.iter().find(|b| b.block_id == 4).unwrap();
    assert_eq!(block4.incoming_edges.len(), 1);
    assert_eq!(block4.incoming_edges[0].from_block, 3);
    assert_eq!(block4.incoming_edges[0].edge_type, "Fallthrough");
}

/// Test that --show-branches JSON output includes incoming_edges field
#[test]
fn test_unreachable_show_branches_json_output() {
    use crate::cfg::reachability::find_unreachable;
    use crate::output::JsonResponse;
    use petgraph::visit::EdgeRef;

    // Create the same CFG as above
    let mut g = DiGraph::new();

    let b0 = g.add_node(BasicBlock {
        id: 0,
        db_id: None,
        kind: BlockKind::Entry,
        statements: vec!["let x = 1".to_string()],
        terminator: Terminator::Goto { target: 1 },
        source_location: None,
        coord_x: 0,
        coord_y: 0,
        coord_z: 0,
    });

    let b1 = g.add_node(BasicBlock {
        id: 1,
        db_id: None,
        kind: BlockKind::Normal,
        statements: vec!["if x > 0".to_string()],
        terminator: Terminator::SwitchInt {
            targets: vec![2],
            otherwise: 3,
        },
        source_location: None,
        coord_x: 0,
        coord_y: 0,
        coord_z: 0,
    });

    let b2 = g.add_node(BasicBlock {
        id: 2,
        db_id: None,
        kind: BlockKind::Exit,
        statements: vec!["return true".to_string()],
        terminator: Terminator::Return,
        source_location: None,
        coord_x: 0,
        coord_y: 0,
        coord_z: 0,
    });

    let b3 = g.add_node(BasicBlock {
        id: 3,
        db_id: None,
        kind: BlockKind::Normal,
        statements: vec!["unreachable branch".to_string()],
        terminator: Terminator::Goto { target: 4 },
        source_location: None,
        coord_x: 0,
        coord_y: 0,
        coord_z: 0,
    });

    let b4 = g.add_node(BasicBlock {
        id: 4,
        db_id: None,
        kind: BlockKind::Exit,
        statements: vec!["unreachable code".to_string()],
        terminator: Terminator::Unreachable,
        source_location: None,
        coord_x: 0,
        coord_y: 0,
        coord_z: 0,
    });

    g.add_edge(b0, b1, EdgeType::Fallthrough);
    g.add_edge(b1, b2, EdgeType::TrueBranch);
    g.add_edge(b3, b4, EdgeType::Fallthrough);

    // Build UnreachableBlock structs with incoming edges
    let unreachable_indices = find_unreachable(&g);
    let blocks: Vec<UnreachableBlock> = unreachable_indices
        .iter()
        .map(|&idx| {
            let block = &g[idx];
            UnreachableBlock {
                block_id: block.id,
                kind: format!("{:?}", block.kind),
                statements: block.statements.clone(),
                terminator: format!("{:?}", block.terminator),
                incoming_edges: g
                    .edge_references()
                    .filter(|edge| edge.target() == idx)
                    .map(|edge| {
                        let source_block = &g[edge.source()];
                        let edge_type = g.edge_weight(edge.id()).unwrap();
                        IncomingEdge {
                            from_block: source_block.id,
                            edge_type: format!("{:?}", edge_type),
                        }
                    })
                    .collect(),
            }
        })
        .collect();

    let response = UnreachableResponse {
        function: "test".to_string(),
        total_functions: 1,
        functions_with_unreachable: 1,
        unreachable_count: 2,
        blocks,
        uncalled_functions: None,
    };

    let wrapper = JsonResponse::new(response);
    let json = wrapper.to_json();

    // Verify JSON contains incoming_edges field
    assert!(json.contains("\"incoming_edges\""));
    // Verify block 4 has an incoming edge from block 3
    assert!(json.contains("\"from_block\":3"));
    assert!(json.contains("\"edge_type\":\"Fallthrough\""));
}

/// Test that IncomingEdge struct serializes correctly
#[test]
fn test_incoming_edge_serialization() {
    let edge = IncomingEdge {
        from_block: 5,
        edge_type: "TrueBranch".to_string(),
    };

    let serialized = serde_json::to_string(&edge).unwrap();
    assert!(serialized.contains("\"from_block\":5"));
    assert!(serialized.contains("\"edge_type\":\"TrueBranch\""));
}