grapha-core 0.3.0

Shared graph types and extraction traits for Grapha
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
use std::collections::HashMap;

use crate::graph::{Edge, EdgeKind, FlowDirection, Graph, Node, NodeKind, Visibility};

pub fn normalize_graph(mut graph: Graph) -> Graph {
    fn visibility_rank(visibility: &Visibility) -> u8 {
        match visibility {
            Visibility::Private => 0,
            Visibility::Crate => 1,
            Visibility::Public => 2,
        }
    }

    fn merged_kind(existing: NodeKind, incoming: NodeKind) -> NodeKind {
        match (existing, incoming) {
            (NodeKind::Struct, NodeKind::Class) => NodeKind::Class,
            _ => existing,
        }
    }

    fn merge_node(existing: &mut Node, incoming: Node) {
        existing.kind = merged_kind(existing.kind, incoming.kind);
        if visibility_rank(&incoming.visibility) > visibility_rank(&existing.visibility) {
            existing.visibility = incoming.visibility;
        }
        if existing.role.is_none() {
            existing.role = incoming.role;
        }
        if existing.signature.is_none() {
            existing.signature = incoming.signature;
        }
        if existing.doc_comment.is_none() {
            existing.doc_comment = incoming.doc_comment;
        }
        if existing.module.is_none() {
            existing.module = incoming.module;
        }
        for (key, value) in incoming.metadata {
            existing.metadata.entry(key).or_insert(value);
        }
    }

    let mut node_index = HashMap::new();
    let mut normalized_nodes = Vec::with_capacity(graph.nodes.len());
    for node in graph.nodes {
        if let Some(existing_index) = node_index.get(&node.id).copied() {
            merge_node(&mut normalized_nodes[existing_index], node);
        } else {
            node_index.insert(node.id.clone(), normalized_nodes.len());
            normalized_nodes.push(node);
        }
    }

    let mut edge_index = HashMap::new();
    let mut normalized_edges = Vec::with_capacity(graph.edges.len());
    for edge in graph.edges {
        let fingerprint = edge_fingerprint(&edge);
        if let Some(existing_index) = edge_index.get(&fingerprint).copied() {
            let existing: &mut Edge = &mut normalized_edges[existing_index];
            existing.confidence = existing.confidence.max(edge.confidence);
            for provenance in edge.provenance {
                if !existing
                    .provenance
                    .iter()
                    .any(|current| current == &provenance)
                {
                    existing.provenance.push(provenance);
                }
            }
        } else {
            edge_index.insert(fingerprint, normalized_edges.len());
            normalized_edges.push(edge);
        }
    }

    graph.nodes = normalized_nodes;
    graph.edges = normalized_edges;
    graph
}

pub fn edge_fingerprint(edge: &Edge) -> String {
    let mut hasher = Fnv1a64::default();
    hasher.write_component(&edge.source);
    hasher.write_component(&edge.target);
    hasher.write_component(edge_kind_tag(edge.kind));
    hasher.write_component(direction_tag(edge.direction.as_ref()));
    hasher.write_component(edge.operation.as_deref().unwrap_or(""));
    hasher.write_component(edge.condition.as_deref().unwrap_or(""));
    hasher.write_component(bool_tag(edge.async_boundary));
    // Fast hex encoding without format! allocation overhead
    let hash = hasher.finish();
    let mut buf = [0u8; 16];
    let bytes = hash.to_be_bytes();
    const HEX: &[u8; 16] = b"0123456789abcdef";
    for (i, &b) in bytes.iter().enumerate() {
        buf[i * 2] = HEX[(b >> 4) as usize];
        buf[i * 2 + 1] = HEX[(b & 0xf) as usize];
    }
    // SAFETY: buf only contains ASCII hex chars
    unsafe { String::from_utf8_unchecked(buf.to_vec()) }
}

fn edge_kind_tag(kind: EdgeKind) -> &'static str {
    match kind {
        EdgeKind::Calls => "calls",
        EdgeKind::Uses => "uses",
        EdgeKind::Implements => "implements",
        EdgeKind::Contains => "contains",
        EdgeKind::TypeRef => "type_ref",
        EdgeKind::Inherits => "inherits",
        EdgeKind::Reads => "reads",
        EdgeKind::Writes => "writes",
        EdgeKind::Publishes => "publishes",
        EdgeKind::Subscribes => "subscribes",
    }
}

fn direction_tag(direction: Option<&FlowDirection>) -> &'static str {
    match direction {
        Some(FlowDirection::Read) => "read",
        Some(FlowDirection::Write) => "write",
        Some(FlowDirection::ReadWrite) => "read_write",
        Some(FlowDirection::Pure) => "pure",
        None => "",
    }
}

fn bool_tag(value: Option<bool>) -> &'static str {
    match value {
        Some(true) => "1",
        Some(false) => "0",
        None => "",
    }
}

#[derive(Default)]
struct Fnv1a64 {
    state: u64,
}

impl Fnv1a64 {
    const OFFSET_BASIS: u64 = 0xcbf29ce484222325;
    const PRIME: u64 = 0x100000001b3;

    fn write_component(&mut self, value: &str) {
        if self.state == 0 {
            self.state = Self::OFFSET_BASIS;
        }
        for byte in value.as_bytes() {
            self.state ^= u64::from(*byte);
            self.state = self.state.wrapping_mul(Self::PRIME);
        }
        self.state ^= u64::from(0xff_u8);
        self.state = self.state.wrapping_mul(Self::PRIME);
    }

    fn finish(self) -> u64 {
        if self.state == 0 {
            Self::OFFSET_BASIS
        } else {
            self.state
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::graph::{EdgeKind, EdgeProvenance, NodeKind, NodeRole, Span, TerminalKind};
    use std::collections::HashMap;
    use std::path::PathBuf;

    #[test]
    fn normalize_graph_merges_duplicate_edges_and_provenance() {
        let graph = Graph {
            version: "0.1.0".to_string(),
            nodes: vec![],
            edges: vec![
                Edge {
                    source: "a".to_string(),
                    target: "b".to_string(),
                    kind: EdgeKind::Calls,
                    confidence: 0.4,
                    direction: None,
                    operation: None,
                    condition: None,
                    async_boundary: None,
                    provenance: vec![EdgeProvenance {
                        file: PathBuf::from("a.swift"),
                        span: Span {
                            start: [1, 0],
                            end: [1, 4],
                        },
                        symbol_id: "a".to_string(),
                    }],
                },
                Edge {
                    source: "a".to_string(),
                    target: "b".to_string(),
                    kind: EdgeKind::Calls,
                    confidence: 0.9,
                    direction: None,
                    operation: None,
                    condition: None,
                    async_boundary: None,
                    provenance: vec![EdgeProvenance {
                        file: PathBuf::from("a.swift"),
                        span: Span {
                            start: [2, 0],
                            end: [2, 4],
                        },
                        symbol_id: "a".to_string(),
                    }],
                },
            ],
        };

        let normalized = normalize_graph(graph);
        assert_eq!(normalized.edges.len(), 1);
        assert_eq!(normalized.edges[0].confidence, 0.9);
        assert_eq!(normalized.edges[0].provenance.len(), 2);
    }

    #[test]
    fn normalize_graph_merges_duplicate_nodes_by_id() {
        let graph = Graph {
            version: "0.1.0".to_string(),
            nodes: vec![
                Node {
                    id: "s:RoomPage.centerContentView".to_string(),
                    kind: NodeKind::Property,
                    name: "centerContentView".to_string(),
                    file: PathBuf::from("RoomPage.swift"),
                    span: Span {
                        start: [0, 0],
                        end: [0, 0],
                    },
                    visibility: Visibility::Private,
                    metadata: HashMap::new(),
                    role: None,
                    signature: None,
                    doc_comment: None,
                    module: None,
                    snippet: None,
                },
                Node {
                    id: "s:RoomPage.centerContentView".to_string(),
                    kind: NodeKind::Property,
                    name: "centerContentView".to_string(),
                    file: PathBuf::from("RoomPage.swift"),
                    span: Span {
                        start: [10, 4],
                        end: [10, 20],
                    },
                    visibility: Visibility::Public,
                    metadata: HashMap::new(),
                    role: Some(NodeRole::EntryPoint),
                    signature: Some("var centerContentView: some View".to_string()),
                    doc_comment: Some("helper".to_string()),
                    module: Some("Room".to_string()),
                    snippet: None,
                },
            ],
            edges: vec![],
        };

        let normalized = normalize_graph(graph);
        assert_eq!(normalized.nodes.len(), 1);
        assert_eq!(normalized.nodes[0].visibility, Visibility::Public);
        assert_eq!(normalized.nodes[0].role, Some(NodeRole::EntryPoint));
        assert_eq!(
            normalized.nodes[0].signature.as_deref(),
            Some("var centerContentView: some View")
        );
        assert_eq!(normalized.nodes[0].doc_comment.as_deref(), Some("helper"));
        assert_eq!(normalized.nodes[0].module.as_deref(), Some("Room"));
    }

    #[test]
    fn normalize_graph_prefers_class_over_struct_for_same_symbol() {
        let graph = Graph {
            version: "0.1.0".to_string(),
            nodes: vec![
                Node {
                    id: "AppDelegate".to_string(),
                    kind: NodeKind::Struct,
                    name: "AppDelegate".to_string(),
                    file: PathBuf::from("AppDelegate.swift"),
                    span: Span {
                        start: [0, 0],
                        end: [1, 0],
                    },
                    visibility: Visibility::Crate,
                    metadata: HashMap::new(),
                    role: None,
                    signature: None,
                    doc_comment: None,
                    module: None,
                    snippet: None,
                },
                Node {
                    id: "AppDelegate".to_string(),
                    kind: NodeKind::Class,
                    name: "AppDelegate".to_string(),
                    file: PathBuf::from("AppDelegate.swift"),
                    span: Span {
                        start: [0, 0],
                        end: [1, 0],
                    },
                    visibility: Visibility::Crate,
                    metadata: HashMap::new(),
                    role: None,
                    signature: None,
                    doc_comment: None,
                    module: None,
                    snippet: None,
                },
            ],
            edges: vec![],
        };

        let normalized = normalize_graph(graph);
        assert_eq!(normalized.nodes.len(), 1);
        assert_eq!(normalized.nodes[0].kind, NodeKind::Class);
    }

    #[test]
    fn fingerprint_changes_when_effect_shape_changes() {
        let base = Edge {
            source: "a".to_string(),
            target: "b".to_string(),
            kind: EdgeKind::Calls,
            confidence: 1.0,
            direction: None,
            operation: None,
            condition: None,
            async_boundary: None,
            provenance: Vec::new(),
        };
        let mut changed = base.clone();
        changed.direction = Some(FlowDirection::Read);

        assert_ne!(edge_fingerprint(&base), edge_fingerprint(&changed));
    }

    #[test]
    fn fingerprint_ignores_confidence_and_provenance() {
        let base = Edge {
            source: "a".to_string(),
            target: "b".to_string(),
            kind: EdgeKind::Calls,
            confidence: 0.2,
            direction: Some(FlowDirection::Read),
            operation: Some("HTTP".to_string()),
            condition: None,
            async_boundary: None,
            provenance: Vec::new(),
        };
        let mut changed = base.clone();
        changed.confidence = 0.9;
        changed.provenance = vec![EdgeProvenance {
            file: PathBuf::from("a.swift"),
            span: Span {
                start: [1, 0],
                end: [1, 2],
            },
            symbol_id: "a".to_string(),
        }];

        assert_eq!(edge_fingerprint(&base), edge_fingerprint(&changed));
    }

    #[test]
    fn terminal_role_is_preserved_by_normalization() {
        let graph = Graph {
            version: "0.1.0".to_string(),
            nodes: vec![Node {
                id: "terminal".to_string(),
                kind: NodeKind::Function,
                name: "terminal".to_string(),
                file: PathBuf::from("main.rs"),
                span: Span {
                    start: [0, 0],
                    end: [1, 0],
                },
                visibility: Visibility::Public,
                metadata: HashMap::new(),
                role: Some(NodeRole::Terminal {
                    kind: TerminalKind::Network,
                }),
                signature: None,
                doc_comment: None,
                module: None,
                snippet: None,
            }],
            edges: vec![],
        };

        let normalized = normalize_graph(graph);
        assert_eq!(
            normalized.nodes[0].role,
            Some(NodeRole::Terminal {
                kind: TerminalKind::Network,
            })
        );
    }
}