grapha 0.2.1

Blazingly fast code intelligence CLI and MCP server for Swift and 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
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
pub mod complexity;
pub mod context;
pub mod dataflow;
pub mod entries;
pub mod file_symbols;
pub(crate) mod flow;
pub mod impact;
pub(crate) mod l10n;
pub mod localize;
pub mod map;
pub mod module_summary;
pub mod origin;
pub mod reverse;
pub mod smells;
pub mod trace;
pub mod usages;

use serde::Serialize;
use thiserror::Error;

use grapha_core::graph::{Graph, Node, NodeKind, NodeRole, Visibility};

use crate::symbol_locator::{SymbolLocatorIndex, locator_matches_suffix};

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct QueryCandidate {
    pub id: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub locator: Option<String>,
    pub name: String,
    pub kind: NodeKind,
    pub file: String,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Error)]
#[serde(tag = "error", rename_all = "snake_case")]
pub enum QueryResolveError {
    #[error("not found")]
    NotFound { query: String },
    #[error("ambiguous query")]
    Ambiguous {
        query: String,
        candidates: Vec<QueryCandidate>,
    },
    #[error("{hint}")]
    NotFunction { hint: String },
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
enum MatchTier {
    ExactLocator,
    LocatorSuffix,
    ExactNormalizedName,
    NormalizedPrefix,
    IdSuffix,
    CaseInsensitiveNormalizedExact,
}

pub(crate) fn strip_accessor_prefix(name: &str) -> &str {
    name.strip_prefix("getter:")
        .or_else(|| name.strip_prefix("setter:"))
        .unwrap_or(name)
}

pub(crate) fn normalize_symbol_name(name: &str) -> &str {
    let without_accessor = strip_accessor_prefix(name);
    without_accessor
        .split_once('(')
        .map(|(head, _)| head)
        .unwrap_or(without_accessor)
}

pub(crate) fn file_matches_query_path(node_file: &std::path::Path, file_query: &str) -> bool {
    let normalize = |value: &str| value.replace('\\', "/");

    let file = normalize(&node_file.to_string_lossy());
    let query = normalize(file_query);

    if file == query || file.ends_with(&query) || file.contains(&query) || query.ends_with(&file) {
        return true;
    }

    let file_name = file.rsplit('/').next().unwrap_or(file.as_str());
    let query_name = query.rsplit('/').next().unwrap_or(query.as_str());
    file_name == query_name
}

pub(crate) fn file_matches_path_or_suffix(node_file: &std::path::Path, file_query: &str) -> bool {
    let normalize = |value: &str| value.replace('\\', "/");

    let file = normalize(&node_file.to_string_lossy());
    let query = normalize(file_query);

    if file == query || file.ends_with(&query) || query.ends_with(&file) {
        return true;
    }

    let file_name = file.rsplit('/').next().unwrap_or(file.as_str());
    let query_name = query.rsplit('/').next().unwrap_or(query.as_str());
    file_name == query_name
}

pub(crate) fn is_swiftui_invalidation_source(node: &Node) -> bool {
    node.metadata
        .get("swiftui.invalidation_source")
        .is_some_and(|value| value == "true")
}

fn kind_preference(kind: NodeKind) -> usize {
    match kind {
        NodeKind::Function => 0,
        NodeKind::Property => 1,
        NodeKind::Variant | NodeKind::Field => 2,
        NodeKind::Class
        | NodeKind::Struct
        | NodeKind::Enum
        | NodeKind::Trait
        | NodeKind::Module
        | NodeKind::Constant
        | NodeKind::TypeAlias
        | NodeKind::Protocol => 3,
        NodeKind::Impl | NodeKind::Extension => 4,
        NodeKind::View | NodeKind::Branch => 5,
    }
}

fn split_file_symbol_query(query: &str) -> Option<(&str, &str)> {
    let (file_part, symbol_part) = query.rsplit_once("::")?;
    if file_part.is_empty() || symbol_part.is_empty() {
        return None;
    }
    let looks_like_file = file_part.contains('/')
        || file_part.contains('\\')
        || file_part.ends_with(".swift")
        || file_part.ends_with(".rs");
    if !looks_like_file {
        return None;
    }
    Some((file_part, symbol_part))
}

fn match_tier(node: &Node, locator: &str, query: &str) -> Option<MatchTier> {
    if locator == query {
        return Some(MatchTier::ExactLocator);
    }
    if query.contains("::") && locator_matches_suffix(locator, query) {
        return Some(MatchTier::LocatorSuffix);
    }

    let normalized_query = normalize_symbol_name(query);
    let normalized_name = normalize_symbol_name(&node.name);

    if normalized_name == normalized_query {
        Some(MatchTier::ExactNormalizedName)
    } else if normalized_name.starts_with(normalized_query) {
        Some(MatchTier::NormalizedPrefix)
    } else if node.id.ends_with(query) {
        Some(MatchTier::IdSuffix)
    } else if normalized_name.eq_ignore_ascii_case(normalized_query) {
        Some(MatchTier::CaseInsensitiveNormalizedExact)
    } else {
        None
    }
}

fn to_candidate(node: &Node, locators: &SymbolLocatorIndex) -> QueryCandidate {
    QueryCandidate {
        id: node.id.clone(),
        locator: Some(locators.locator_for_node(node)),
        name: node.name.clone(),
        kind: node.kind,
        file: node.file.to_string_lossy().to_string(),
    }
}

pub fn ambiguity_hint() -> &'static str {
    "Retry with Module::File.swift::Type::symbol, file.swift::symbol, or the full symbol id."
}

/// Resolve a node by query using scored matching and explicit ambiguity
/// reporting.
pub fn resolve_node<'a>(graph: &'a Graph, query: &str) -> Result<&'a Node, QueryResolveError> {
    if let Some(node) = graph.nodes.iter().find(|node| node.id == query) {
        return Ok(node);
    }

    let locators = SymbolLocatorIndex::new(graph);

    let path_matches: Vec<_> = if query.contains("::") {
        graph
            .nodes
            .iter()
            .filter_map(|node| {
                let locator = locators.locator_for_id(&node.id)?;
                let tier = match_tier(node, locator, query)?;
                Some((node, tier, kind_preference(node.kind)))
            })
            .collect()
    } else {
        Vec::new()
    };

    if !path_matches.is_empty() {
        let best_tier = path_matches
            .iter()
            .map(|(_, tier, _)| *tier)
            .min()
            .expect("path_matches is not empty");
        let best_kind = path_matches
            .iter()
            .filter(|(_, tier, _)| *tier == best_tier)
            .map(|(_, _, kind)| *kind)
            .min()
            .expect("path_matches is not empty");
        let best_matches: Vec<&Node> = path_matches
            .iter()
            .filter(|(_, tier, kind)| *tier == best_tier && *kind == best_kind)
            .map(|(node, _, _)| *node)
            .collect();
        if best_matches.len() == 1 {
            return Ok(best_matches[0]);
        }
        return Err(QueryResolveError::Ambiguous {
            query: query.to_string(),
            candidates: best_matches
                .into_iter()
                .map(|node| to_candidate(node, &locators))
                .collect(),
        });
    }

    let (candidate_nodes, match_query): (Vec<&Node>, &str) = match split_file_symbol_query(query) {
        Some((file_part, symbol_part)) => (
            graph
                .nodes
                .iter()
                .filter(|node| node.file.to_string_lossy().ends_with(file_part))
                .collect(),
            symbol_part,
        ),
        None => (graph.nodes.iter().collect(), query),
    };

    let matches: Vec<_> = candidate_nodes
        .into_iter()
        .filter_map(|node| {
            let locator = locators.locator_for_id(&node.id)?;
            let tier = match_tier(node, locator, match_query)?;
            Some((node, tier, kind_preference(node.kind)))
        })
        .collect();

    if matches.is_empty() {
        return Err(QueryResolveError::NotFound {
            query: query.to_string(),
        });
    }

    let best_tier = matches
        .iter()
        .map(|(_, tier, _)| *tier)
        .min()
        .expect("matches is not empty");
    let best_kind = matches
        .iter()
        .filter(|(_, tier, _)| *tier == best_tier)
        .map(|(_, _, kind)| *kind)
        .min()
        .expect("matches is not empty");

    let best_matches: Vec<&Node> = matches
        .iter()
        .filter(|(_, tier, kind)| *tier == best_tier && *kind == best_kind)
        .map(|(node, _, _)| *node)
        .collect();

    if best_matches.len() == 1 {
        return Ok(best_matches[0]);
    }

    Err(QueryResolveError::Ambiguous {
        query: query.to_string(),
        candidates: best_matches
            .into_iter()
            .map(|node| to_candidate(node, &locators))
            .collect(),
    })
}

#[derive(Debug, Serialize)]
pub struct ContextResult {
    pub symbol: SymbolInfo,
    pub callers: Vec<SymbolRef>,
    pub callees: Vec<SymbolRef>,
    pub reads: Vec<SymbolRef>,
    pub read_by: Vec<SymbolRef>,
    pub invalidation_sources: Vec<SymbolRef>,
    pub contains: Vec<SymbolRef>,
    pub contains_tree: Vec<SymbolTreeRef>,
    pub contained_by: Vec<SymbolRef>,
    pub implementors: Vec<SymbolRef>,
    pub implements: Vec<SymbolRef>,
    pub type_refs: Vec<SymbolRef>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct SymbolInfo {
    pub id: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub locator: Option<String>,
    pub name: String,
    pub kind: NodeKind,
    pub file: String,
    pub span: [usize; 2],
    #[serde(skip_serializing_if = "Option::is_none")]
    pub visibility: Option<Visibility>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub role: Option<NodeRole>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub signature: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub module: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub snippet: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct SymbolRef {
    pub id: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub locator: Option<String>,
    pub name: String,
    pub kind: NodeKind,
    pub file: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub span: Option<[usize; 2]>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub visibility: Option<Visibility>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub role: Option<NodeRole>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub signature: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub module: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub snippet: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct SymbolTreeRef {
    pub id: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub locator: Option<String>,
    pub name: String,
    pub kind: NodeKind,
    pub file: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub span: Option<[usize; 2]>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub visibility: Option<Visibility>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub role: Option<NodeRole>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub signature: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub module: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub snippet: Option<String>,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub contains: Vec<SymbolTreeRef>,
}

fn node_span_lines(node: &Node) -> [usize; 2] {
    [node.span.start[0], node.span.end[0]]
}

impl SymbolInfo {
    pub(crate) fn from_node(node: &Node) -> Self {
        Self {
            id: node.id.clone(),
            locator: Some(crate::symbol_locator::fallback_locator(node)),
            name: node.name.clone(),
            kind: node.kind,
            file: node.file.to_string_lossy().to_string(),
            span: node_span_lines(node),
            visibility: Some(node.visibility),
            role: node.role.clone(),
            signature: node.signature.clone(),
            module: node.module.clone(),
            snippet: node.snippet.clone(),
        }
    }

    pub(crate) fn with_locator(mut self, locator: String) -> Self {
        self.locator = Some(locator);
        self
    }
}

impl SymbolRef {
    pub(crate) fn from_node(node: &Node) -> Self {
        Self {
            id: node.id.clone(),
            locator: Some(crate::symbol_locator::fallback_locator(node)),
            name: node.name.clone(),
            kind: node.kind,
            file: node.file.to_string_lossy().to_string(),
            span: Some(node_span_lines(node)),
            visibility: Some(node.visibility),
            role: node.role.clone(),
            signature: node.signature.clone(),
            module: node.module.clone(),
            snippet: node.snippet.clone(),
        }
    }

    pub(crate) fn with_locator(mut self, locator: String) -> Self {
        self.locator = Some(locator);
        self
    }
}

impl SymbolTreeRef {
    pub(crate) fn from_node(node: &Node, contains: Vec<SymbolTreeRef>) -> Self {
        Self {
            id: node.id.clone(),
            locator: Some(crate::symbol_locator::fallback_locator(node)),
            name: node.name.clone(),
            kind: node.kind,
            file: node.file.to_string_lossy().to_string(),
            span: Some(node_span_lines(node)),
            visibility: Some(node.visibility),
            role: node.role.clone(),
            signature: node.signature.clone(),
            module: node.module.clone(),
            snippet: node.snippet.clone(),
            contains,
        }
    }

    pub(crate) fn with_locator(mut self, locator: String) -> Self {
        self.locator = Some(locator);
        self
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use grapha_core::graph::{NodeRole, Span, Visibility};
    use std::collections::HashMap;
    use std::path::PathBuf;

    fn make_node(id: &str, name: &str, kind: NodeKind, file: &str) -> Node {
        Node {
            id: id.into(),
            kind,
            name: name.into(),
            file: PathBuf::from(file),
            span: Span {
                start: [0, 0],
                end: [1, 0],
            },
            visibility: Visibility::Public,
            metadata: HashMap::new(),
            role: None::<NodeRole>,
            signature: None,
            doc_comment: None,
            module: None,
            snippet: None,
        }
    }

    #[test]
    fn bare_send_gift_prefers_functions_over_variants_and_properties() {
        let graph = Graph {
            version: "0.1.0".to_string(),
            nodes: vec![
                make_node(
                    "variant-id",
                    "sendGift",
                    NodeKind::Variant,
                    "FamilyServiceCore.swift",
                ),
                make_node(
                    "property-id",
                    "sendGift",
                    NodeKind::Property,
                    "GiftView.swift",
                ),
                make_node(
                    "function-id",
                    "sendGift(req:)",
                    NodeKind::Function,
                    "GiftServiceCore.swift",
                ),
            ],
            edges: vec![],
        };

        let resolved = resolve_node(&graph, "sendGift").unwrap();
        assert_eq!(resolved.id, "function-id");
    }

    #[test]
    fn bare_send_gift_returns_ambiguous_when_functions_share_top_rank() {
        let graph = Graph {
            version: "0.1.0".to_string(),
            nodes: vec![
                make_node(
                    "function-1",
                    "sendGift(req:)",
                    NodeKind::Function,
                    "GiftServiceCore.swift",
                ),
                make_node(
                    "function-2",
                    "sendGift(goods:targetId:)",
                    NodeKind::Function,
                    "StoreModule.swift",
                ),
                make_node(
                    "variant-id",
                    "sendGift",
                    NodeKind::Variant,
                    "HeadlineData.swift",
                ),
            ],
            edges: vec![],
        };

        let err = resolve_node(&graph, "sendGift").unwrap_err();
        match err {
            QueryResolveError::Ambiguous { query, candidates } => {
                assert_eq!(query, "sendGift");
                assert_eq!(candidates.len(), 2);
                assert!(
                    candidates
                        .iter()
                        .all(|candidate| candidate.kind == NodeKind::Function)
                );
            }
            other => panic!("expected ambiguity, got {other:?}"),
        }
    }

    #[test]
    fn swift_file_symbol_query_matches_against_node_file_suffix() {
        let graph = Graph {
            version: "0.1.0".to_string(),
            nodes: vec![
                make_node(
                    "s:12ModuleExport15GiftServiceCoreC04sendC03reqy...",
                    "sendGift(req:)",
                    NodeKind::Function,
                    "GiftServiceCore.swift",
                ),
                make_node(
                    "s:5Store0A6ModuleC8sendGift5goods8targetIdy...",
                    "sendGift(goods:targetId:)",
                    NodeKind::Function,
                    "StoreModule.swift",
                ),
            ],
            edges: vec![],
        };

        let resolved = resolve_node(&graph, "GiftServiceCore.swift::sendGift").unwrap();
        assert_eq!(resolved.file, PathBuf::from("GiftServiceCore.swift"));
    }

    #[test]
    fn bare_symbol_prefers_real_declarations_over_swiftui_synthetic_nodes() {
        let graph = Graph {
            version: "0.1.0".to_string(),
            nodes: vec![
                make_node(
                    "ContentView.swift::ContentView::body::view:Row@10:12",
                    "Row",
                    NodeKind::View,
                    "ContentView.swift",
                ),
                make_node(
                    "ContentView.swift::Row",
                    "Row",
                    NodeKind::Struct,
                    "ContentView.swift",
                ),
            ],
            edges: vec![],
        };

        let resolved = resolve_node(&graph, "Row").unwrap();
        assert_eq!(resolved.kind, NodeKind::Struct);
        assert_eq!(resolved.id, "ContentView.swift::Row");
    }

    #[test]
    fn rust_style_locator_resolves_member() {
        let graph = Graph {
            version: "0.1.0".to_string(),
            nodes: vec![
                make_node("type-id", "Test", NodeKind::Struct, "Hello.swift"),
                make_node(
                    "method-id",
                    "hello(name:)",
                    NodeKind::Function,
                    "Hello.swift",
                ),
            ],
            edges: vec![grapha_core::graph::Edge {
                source: "type-id".to_string(),
                target: "method-id".to_string(),
                kind: grapha_core::graph::EdgeKind::Contains,
                confidence: 1.0,
                direction: None,
                operation: None,
                condition: None,
                async_boundary: None,
                provenance: Vec::new(),
            }],
        };
        let mut graph = graph;
        graph.nodes[0].module = Some("ModuleExport".to_string());
        graph.nodes[1].module = Some("ModuleExport".to_string());

        let resolved = resolve_node(&graph, "ModuleExport::Hello.swift::Test::hello(name:)")
            .expect("locator should resolve");
        assert_eq!(resolved.id, "method-id");
    }

    #[test]
    fn strict_file_match_requires_full_path_or_suffix() {
        let node_file = PathBuf::from("Modules/Room/Sources/Room/View/RoomPage.swift");

        assert!(file_matches_path_or_suffix(&node_file, "RoomPage.swift"));
        assert!(file_matches_path_or_suffix(
            &node_file,
            "Modules/Room/Sources/Room/View/RoomPage.swift"
        ));
        assert!(!file_matches_path_or_suffix(&node_file, "Page"));
    }
}