geographdb-core 0.3.1

Geometric graph database core - 3D spatial indexing for code analysis
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
//! Program Slicing - Backward and Forward Slicing
//!
//! Program slicing extracts all statements that affect or are affected by
//! a particular program point (the slicing criterion).
//!
//! # Types
//!
//! - **Backward Slice**: All statements that affect the criterion
//! - **Forward Slice**: All statements affected by the criterion
//! - **Full Slice**: Union of backward and forward slices
//!
//! # Applications
//!
//! - Impact analysis (what breaks if I change this?)
//! - Debugging (what code affects this variable?)
//! - Dead code detection (unreachable from entry)
//! - Optimization (remove unused code)

use crate::algorithms::astar::CfgGraphNode;
use std::collections::{HashMap, HashSet, VecDeque};

/// Result of program slicing
#[derive(Debug, Clone)]
pub struct SliceResult {
    /// Nodes in the slice
    pub nodes: HashSet<u64>,
    /// Edges within the slice (source, target)
    pub edges: Vec<(u64, u64)>,
    /// Slice direction
    pub direction: SliceDirection,
    /// Slicing criterion (target node)
    pub criterion: u64,
}

/// Direction of program slice
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SliceDirection {
    /// Backward slice (what affects criterion)
    Backward,
    /// Forward slice (what is affected by criterion)
    Forward,
}

/// Compute backward slice from a criterion node
///
/// The backward slice contains all nodes that can reach the criterion.
/// This answers: "What code affects this point?"
///
/// # Arguments
/// * `nodes` - CFG nodes
/// * `criterion` - Slicing criterion (target node)
///
/// # Returns
/// SliceResult with all nodes and edges in the backward slice
pub fn backward_slice(nodes: &[CfgGraphNode], criterion: u64) -> SliceResult {
    // Build predecessor map
    let mut predecessors: HashMap<u64, Vec<u64>> = HashMap::new();
    let mut all_nodes: HashSet<u64> = HashSet::new();

    for node in nodes {
        all_nodes.insert(node.id);
        for &succ in &node.successors {
            predecessors.entry(succ).or_default().push(node.id);
        }
    }

    // BFS backward from criterion
    let mut slice_nodes: HashSet<u64> = HashSet::new();
    let mut worklist: VecDeque<u64> = VecDeque::new();

    if all_nodes.contains(&criterion) {
        slice_nodes.insert(criterion);
        worklist.push_back(criterion);
    }

    while let Some(node_id) = worklist.pop_front() {
        if let Some(preds) = predecessors.get(&node_id) {
            for &pred in preds {
                if !slice_nodes.contains(&pred) {
                    slice_nodes.insert(pred);
                    worklist.push_back(pred);
                }
            }
        }
    }

    // Collect edges within slice
    let mut edges = Vec::new();
    for node in nodes {
        if slice_nodes.contains(&node.id) {
            for &succ in &node.successors {
                if slice_nodes.contains(&succ) {
                    edges.push((node.id, succ));
                }
            }
        }
    }

    SliceResult {
        nodes: slice_nodes,
        edges,
        direction: SliceDirection::Backward,
        criterion,
    }
}

/// Compute forward slice from a criterion node
///
/// The forward slice contains all nodes reachable from the criterion.
/// This answers: "What code is affected by this point?"
///
/// # Arguments
/// * `nodes` - CFG nodes
/// * `criterion` - Slicing criterion (source node)
///
/// # Returns
/// SliceResult with all nodes and edges in the forward slice
pub fn forward_slice(nodes: &[CfgGraphNode], criterion: u64) -> SliceResult {
    let node_map: HashMap<u64, &CfgGraphNode> = nodes.iter().map(|n| (n.id, n)).collect();

    // BFS forward from criterion
    let mut slice_nodes: HashSet<u64> = HashSet::new();
    let mut worklist: VecDeque<u64> = VecDeque::new();

    if node_map.contains_key(&criterion) {
        slice_nodes.insert(criterion);
        worklist.push_back(criterion);
    }

    while let Some(node_id) = worklist.pop_front() {
        if let Some(node) = node_map.get(&node_id) {
            for &succ in &node.successors {
                if !slice_nodes.contains(&succ) {
                    slice_nodes.insert(succ);
                    worklist.push_back(succ);
                }
            }
        }
    }

    // Collect edges within slice
    let mut edges = Vec::new();
    for node in nodes {
        if slice_nodes.contains(&node.id) {
            for &succ in &node.successors {
                if slice_nodes.contains(&succ) {
                    edges.push((node.id, succ));
                }
            }
        }
    }

    SliceResult {
        nodes: slice_nodes,
        edges,
        direction: SliceDirection::Forward,
        criterion,
    }
}

/// Compute full slice (backward + forward) from a criterion
pub fn full_slice(nodes: &[CfgGraphNode], criterion: u64) -> SliceResult {
    let backward = backward_slice(nodes, criterion);
    let forward = forward_slice(nodes, criterion);

    let mut nodes = backward.nodes;
    nodes.extend(forward.nodes);

    let mut edges = backward.edges;
    edges.extend(forward.edges);

    SliceResult {
        nodes,
        edges,
        direction: SliceDirection::Backward, // Default
        criterion,
    }
}

/// Get slice size (number of nodes)
pub fn slice_size(slice: &SliceResult) -> usize {
    slice.nodes.len()
}

/// Check if a node is in the slice
pub fn node_in_slice(node_id: u64, slice: &SliceResult) -> bool {
    slice.nodes.contains(&node_id)
}

/// Compute slice coverage (percentage of nodes in slice)
pub fn slice_coverage(slice: &SliceResult, total_nodes: usize) -> f32 {
    if total_nodes == 0 {
        return 0.0;
    }
    (slice.nodes.len() as f32) / (total_nodes as f32) * 100.0
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_backward_slice_linear() {
        // Linear: 0 -> 1 -> 2 -> 3
        let nodes = vec![
            CfgGraphNode {
                id: 0,
                x: 0.0,
                y: 0.0,
                z: 0.0,
                successors: vec![1],
            },
            CfgGraphNode {
                id: 1,
                x: 1.0,
                y: 0.0,
                z: 0.0,
                successors: vec![2],
            },
            CfgGraphNode {
                id: 2,
                x: 2.0,
                y: 0.0,
                z: 0.0,
                successors: vec![3],
            },
            CfgGraphNode {
                id: 3,
                x: 3.0,
                y: 0.0,
                z: 0.0,
                successors: vec![],
            },
        ];

        // Backward slice from node 3 should include all nodes
        let slice = backward_slice(&nodes, 3);
        assert_eq!(slice.nodes.len(), 4);
        assert!(slice.nodes.contains(&0));
        assert!(slice.nodes.contains(&3));
        assert_eq!(slice.direction, SliceDirection::Backward);
    }

    #[test]
    fn test_backward_slice_partial() {
        // Linear: 0 -> 1 -> 2 -> 3
        let nodes = vec![
            CfgGraphNode {
                id: 0,
                x: 0.0,
                y: 0.0,
                z: 0.0,
                successors: vec![1],
            },
            CfgGraphNode {
                id: 1,
                x: 1.0,
                y: 0.0,
                z: 0.0,
                successors: vec![2],
            },
            CfgGraphNode {
                id: 2,
                x: 2.0,
                y: 0.0,
                z: 0.0,
                successors: vec![3],
            },
            CfgGraphNode {
                id: 3,
                x: 3.0,
                y: 0.0,
                z: 0.0,
                successors: vec![],
            },
        ];

        // Backward slice from node 1 should include 0 and 1
        let slice = backward_slice(&nodes, 1);
        assert_eq!(slice.nodes.len(), 2);
        assert!(slice.nodes.contains(&0));
        assert!(slice.nodes.contains(&1));
    }

    #[test]
    fn test_forward_slice_linear() {
        // Linear: 0 -> 1 -> 2 -> 3
        let nodes = vec![
            CfgGraphNode {
                id: 0,
                x: 0.0,
                y: 0.0,
                z: 0.0,
                successors: vec![1],
            },
            CfgGraphNode {
                id: 1,
                x: 1.0,
                y: 0.0,
                z: 0.0,
                successors: vec![2],
            },
            CfgGraphNode {
                id: 2,
                x: 2.0,
                y: 0.0,
                z: 0.0,
                successors: vec![3],
            },
            CfgGraphNode {
                id: 3,
                x: 3.0,
                y: 0.0,
                z: 0.0,
                successors: vec![],
            },
        ];

        // Forward slice from node 0 should include all nodes
        let slice = forward_slice(&nodes, 0);
        assert_eq!(slice.nodes.len(), 4);
        assert!(slice.nodes.contains(&0));
        assert!(slice.nodes.contains(&3));
        assert_eq!(slice.direction, SliceDirection::Forward);
    }

    #[test]
    fn test_forward_slice_partial() {
        // Linear: 0 -> 1 -> 2 -> 3
        let nodes = vec![
            CfgGraphNode {
                id: 0,
                x: 0.0,
                y: 0.0,
                z: 0.0,
                successors: vec![1],
            },
            CfgGraphNode {
                id: 1,
                x: 1.0,
                y: 0.0,
                z: 0.0,
                successors: vec![2],
            },
            CfgGraphNode {
                id: 2,
                x: 2.0,
                y: 0.0,
                z: 0.0,
                successors: vec![3],
            },
            CfgGraphNode {
                id: 3,
                x: 3.0,
                y: 0.0,
                z: 0.0,
                successors: vec![],
            },
        ];

        // Forward slice from node 2 should include 2 and 3
        let slice = forward_slice(&nodes, 2);
        assert_eq!(slice.nodes.len(), 2);
        assert!(slice.nodes.contains(&2));
        assert!(slice.nodes.contains(&3));
    }

    #[test]
    fn test_slice_coverage() {
        let nodes = vec![
            CfgGraphNode {
                id: 0,
                x: 0.0,
                y: 0.0,
                z: 0.0,
                successors: vec![1],
            },
            CfgGraphNode {
                id: 1,
                x: 1.0,
                y: 0.0,
                z: 0.0,
                successors: vec![],
            },
        ];

        let slice = backward_slice(&nodes, 1);
        let coverage = slice_coverage(&slice, 2);
        assert!((coverage - 100.0).abs() < 0.001);
    }

    #[test]
    fn test_node_in_slice() {
        let nodes = vec![
            CfgGraphNode {
                id: 0,
                x: 0.0,
                y: 0.0,
                z: 0.0,
                successors: vec![1],
            },
            CfgGraphNode {
                id: 1,
                x: 1.0,
                y: 0.0,
                z: 0.0,
                successors: vec![],
            },
        ];

        let slice = backward_slice(&nodes, 1);
        assert!(node_in_slice(0, &slice));
        assert!(node_in_slice(1, &slice));
    }

    #[test]
    fn test_backward_slice_branching() {
        // Diamond: 0 -> 1 -> 3, 0 -> 2 -> 3
        let nodes = vec![
            CfgGraphNode {
                id: 0,
                x: 0.0,
                y: 0.0,
                z: 0.0,
                successors: vec![1, 2],
            },
            CfgGraphNode {
                id: 1,
                x: 1.0,
                y: 0.0,
                z: 0.0,
                successors: vec![3],
            },
            CfgGraphNode {
                id: 2,
                x: 2.0,
                y: 0.0,
                z: 0.0,
                successors: vec![3],
            },
            CfgGraphNode {
                id: 3,
                x: 3.0,
                y: 0.0,
                z: 0.0,
                successors: vec![],
            },
        ];

        // Backward slice from node 3 should include all nodes
        let slice = backward_slice(&nodes, 3);
        assert_eq!(slice.nodes.len(), 4);
    }

    #[test]
    fn test_slice_edges() {
        let nodes = vec![
            CfgGraphNode {
                id: 0,
                x: 0.0,
                y: 0.0,
                z: 0.0,
                successors: vec![1],
            },
            CfgGraphNode {
                id: 1,
                x: 1.0,
                y: 0.0,
                z: 0.0,
                successors: vec![2],
            },
            CfgGraphNode {
                id: 2,
                x: 2.0,
                y: 0.0,
                z: 0.0,
                successors: vec![],
            },
        ];

        let slice = backward_slice(&nodes, 2);
        assert_eq!(slice.edges.len(), 2);
        assert!(slice.edges.contains(&(0, 1)));
        assert!(slice.edges.contains(&(1, 2)));
    }
}