ryo-analysis 0.1.0

Code graph and discovery engine for the RYO project
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
//! QueryBuilder - Fluent query DSL for CodeGraphV2.
//!
//! # Example
//! ```rust,ignore
//! let results = graph.query()
//!     .functions()
//!     .public()
//!     .is_async()
//!     .in_module("handlers")
//!     .collect();
//! ```

use super::{CodeGraphV2, TypeFlowGraphV2};
use crate::symbol::{SymbolId, SymbolPath, SymbolRegistry};
use crate::Pattern;
use crate::SymbolKind;

/// Fluent query builder for CodeGraphV2.
pub struct QueryBuilder<'a> {
    graph: &'a CodeGraphV2,
    typeflow: &'a TypeFlowGraphV2,
    registry: &'a SymbolRegistry,
    filters: Vec<Filter>,
}

/// Filter conditions for queries.
enum Filter {
    Kind(SymbolKind),
    KindOneOf(Vec<SymbolKind>),
    Public,
    CrateVisible,
    Private,
    InModule(String),
    InCrate(String),
    NamePattern(Pattern),
    HasCallers,
    HasNoCallers,
    Implements(SymbolId),
    UsedBy(SymbolId),
}

impl<'a> QueryBuilder<'a> {
    /// Create a new query builder.
    pub fn new(
        graph: &'a CodeGraphV2,
        typeflow: &'a TypeFlowGraphV2,
        registry: &'a SymbolRegistry,
    ) -> Self {
        Self {
            graph,
            typeflow,
            registry,
            filters: Vec::new(),
        }
    }

    // === Kind Filters ===

    /// Filter by functions.
    pub fn functions(mut self) -> Self {
        self.filters.push(Filter::Kind(SymbolKind::Function));
        self
    }

    /// Filter by structs.
    pub fn structs(mut self) -> Self {
        self.filters.push(Filter::Kind(SymbolKind::Struct));
        self
    }

    /// Filter by enums.
    pub fn enums(mut self) -> Self {
        self.filters.push(Filter::Kind(SymbolKind::Enum));
        self
    }

    /// Filter by traits.
    pub fn traits(mut self) -> Self {
        self.filters.push(Filter::Kind(SymbolKind::Trait));
        self
    }

    /// Filter by modules.
    pub fn modules(mut self) -> Self {
        self.filters.push(Filter::Kind(SymbolKind::Mod));
        self
    }

    /// Filter by impl blocks.
    pub fn impls(mut self) -> Self {
        self.filters.push(Filter::Kind(SymbolKind::Impl));
        self
    }

    /// Filter by methods.
    pub fn methods(mut self) -> Self {
        self.filters.push(Filter::Kind(SymbolKind::Method));
        self
    }

    /// Filter by a specific kind.
    pub fn kind(mut self, kind: SymbolKind) -> Self {
        self.filters.push(Filter::Kind(kind));
        self
    }

    /// Filter by one of several kinds.
    pub fn kinds(mut self, kinds: Vec<SymbolKind>) -> Self {
        self.filters.push(Filter::KindOneOf(kinds));
        self
    }

    // === Visibility Filters ===

    /// Filter by public visibility.
    pub fn public(mut self) -> Self {
        self.filters.push(Filter::Public);
        self
    }

    /// Filter by crate visibility (pub or pub(crate)).
    pub fn crate_visible(mut self) -> Self {
        self.filters.push(Filter::CrateVisible);
        self
    }

    /// Filter by private visibility.
    pub fn private(mut self) -> Self {
        self.filters.push(Filter::Private);
        self
    }

    // === Location Filters ===

    /// Filter by module path (partial match).
    pub fn in_module(mut self, module: impl Into<String>) -> Self {
        self.filters.push(Filter::InModule(module.into()));
        self
    }

    /// Filter by crate name.
    pub fn in_crate(mut self, crate_name: impl Into<String>) -> Self {
        self.filters.push(Filter::InCrate(crate_name.into()));
        self
    }

    // === Name Filters ===

    /// Filter by name pattern.
    pub fn name_matches(mut self, pattern: Pattern) -> Self {
        self.filters.push(Filter::NamePattern(pattern));
        self
    }

    /// Filter by exact name.
    pub fn name(self, name: impl Into<String>) -> Self {
        self.name_matches(Pattern::exact(name.into()))
    }

    /// Filter by glob pattern on name.
    pub fn name_glob(self, pattern: impl Into<String>) -> Self {
        self.name_matches(Pattern::glob(pattern.into()))
    }

    // === Relationship Filters ===

    /// Filter symbols that have callers.
    pub fn has_callers(mut self) -> Self {
        self.filters.push(Filter::HasCallers);
        self
    }

    /// Filter symbols that have no callers (dead code candidates).
    pub fn has_no_callers(mut self) -> Self {
        self.filters.push(Filter::HasNoCallers);
        self
    }

    /// Filter symbols that implement a trait.
    pub fn implements_trait(mut self, trait_id: SymbolId) -> Self {
        self.filters.push(Filter::Implements(trait_id));
        self
    }

    /// Filter symbols used by a specific symbol.
    pub fn used_by(mut self, user_id: SymbolId) -> Self {
        self.filters.push(Filter::UsedBy(user_id));
        self
    }

    // === Execution ===

    /// Execute the query and collect results.
    pub fn collect(self) -> Vec<SymbolId> {
        self.registry
            .iter()
            .map(|(id, _)| id)
            .filter(|&id| self.matches(id))
            .collect()
    }

    /// Execute the query and return the first result.
    pub fn first(self) -> Option<SymbolId> {
        self.registry
            .iter()
            .map(|(id, _)| id)
            .find(|&id| self.matches(id))
    }

    /// Execute the query and count results.
    pub fn count(self) -> usize {
        self.registry
            .iter()
            .map(|(id, _)| id)
            .filter(|&id| self.matches(id))
            .count()
    }

    /// Execute the query and check if any results exist.
    pub fn exists(self) -> bool {
        self.registry
            .iter()
            .map(|(id, _)| id)
            .any(|id| self.matches(id))
    }

    /// Check if a symbol matches all filters.
    fn matches(&self, id: SymbolId) -> bool {
        let path = match self.registry.resolve(id) {
            Some(p) => p,
            None => return false,
        };

        for filter in &self.filters {
            if !self.matches_filter(id, path, filter) {
                return false;
            }
        }

        true
    }

    /// Check if a symbol matches a single filter.
    fn matches_filter(&self, id: SymbolId, path: &SymbolPath, filter: &Filter) -> bool {
        match filter {
            Filter::Kind(kind) => self
                .registry
                .kind(id)
                .is_some_and(|k| k == *kind || k.matches(kind)),
            Filter::KindOneOf(kinds) => self
                .registry
                .kind(id)
                .is_some_and(|k| kinds.iter().any(|kind| k.matches(kind))),
            Filter::Public => self.registry.visibility(id).is_some_and(|v| v.is_public()),
            Filter::CrateVisible => self
                .registry
                .visibility(id)
                .is_some_and(|v| v.is_crate_visible()),
            Filter::Private => self.registry.visibility(id).is_none_or(|v| v.is_private()),
            Filter::InModule(module) => path.to_string().contains(module),
            Filter::InCrate(crate_name) => path.crate_name() == crate_name,
            Filter::NamePattern(pattern) => pattern.matches(path.name()),
            Filter::HasCallers => self.graph.callers_of(id).next().is_some(),
            Filter::HasNoCallers => self.graph.callers_of(id).next().is_none(),
            Filter::Implements(trait_id) => self.graph.implementors_of(*trait_id).any(|x| x == id),
            Filter::UsedBy(user_id) => self.typeflow.types_used_by(*user_id).any(|x| x == id),
        }
    }
}

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

    trait QueryExt {
        fn query<'a>(
            &'a self,
            typeflow: &'a TypeFlowGraphV2,
            registry: &'a SymbolRegistry,
        ) -> QueryBuilder<'a>;
    }

    impl QueryExt for CodeGraphV2 {
        fn query<'a>(
            &'a self,
            typeflow: &'a TypeFlowGraphV2,
            registry: &'a SymbolRegistry,
        ) -> QueryBuilder<'a> {
            QueryBuilder::new(self, typeflow, registry)
        }
    }

    fn setup() -> (SymbolRegistry, CodeGraphV2, TypeFlowGraphV2) {
        let mut registry = SymbolRegistry::new();

        let func1 = registry
            .register_with_metadata(
                SymbolPath::parse("mylib::handlers::handle").unwrap(),
                SymbolKind::Function,
                None,
                Some(Visibility::Public),
            )
            .unwrap();
        let func2 = registry
            .register_with_metadata(
                SymbolPath::parse("mylib::handlers::process").unwrap(),
                SymbolKind::Function,
                None,
                Some(Visibility::Private),
            )
            .unwrap();
        let struct1 = registry
            .register_with_metadata(
                SymbolPath::parse("mylib::models::User").unwrap(),
                SymbolKind::Struct,
                None,
                Some(Visibility::Public),
            )
            .unwrap();

        let mut graph = CodeGraphV2::new();
        graph.add_node(func1);
        graph.add_node(func2);
        graph.add_node(struct1);
        graph.add_to_kind_index(func1, SymbolKind::Function);
        graph.add_to_kind_index(func2, SymbolKind::Function);
        graph.add_to_kind_index(struct1, SymbolKind::Struct);
        graph.add_edge(func1, func2, super::super::CodeEdgeV2::Calls);

        let typeflow = TypeFlowGraphV2::new();
        (registry, graph, typeflow)
    }

    #[test]
    fn test_query_functions() {
        let (registry, graph, typeflow) = setup();
        let results = graph.query(&typeflow, &registry).functions().collect();
        assert_eq!(results.len(), 2);
    }

    #[test]
    fn test_query_structs() {
        let (registry, graph, typeflow) = setup();
        let results = graph.query(&typeflow, &registry).structs().collect();
        assert_eq!(results.len(), 1);
    }

    #[test]
    fn test_query_public() {
        let (registry, graph, typeflow) = setup();
        let results = graph.query(&typeflow, &registry).public().collect();
        assert_eq!(results.len(), 2); // handle and User
    }

    #[test]
    fn test_query_in_module() {
        let (registry, graph, typeflow) = setup();
        let results = graph
            .query(&typeflow, &registry)
            .in_module("handlers")
            .collect();
        assert_eq!(results.len(), 2);
    }

    #[test]
    fn test_query_combined() {
        let (registry, graph, typeflow) = setup();
        let results = graph
            .query(&typeflow, &registry)
            .functions()
            .public()
            .in_module("handlers")
            .collect();
        assert_eq!(results.len(), 1);
    }

    #[test]
    fn test_query_name_glob() {
        let (registry, graph, typeflow) = setup();
        let results = graph.query(&typeflow, &registry).name_glob("*er").collect();
        // "User" matches "*er"
        assert_eq!(results.len(), 1);
    }

    #[test]
    fn test_query_has_callers() {
        let (registry, graph, typeflow) = setup();
        let results = graph
            .query(&typeflow, &registry)
            .functions()
            .has_callers()
            .collect();
        // Only process has callers (called by handle)
        assert_eq!(results.len(), 1);
    }

    #[test]
    fn test_query_count() {
        let (registry, graph, typeflow) = setup();
        let count = graph.query(&typeflow, &registry).functions().count();
        assert_eq!(count, 2);
    }

    #[test]
    fn test_query_exists() {
        let (registry, graph, typeflow) = setup();
        assert!(graph.query(&typeflow, &registry).structs().exists());
        assert!(!graph.query(&typeflow, &registry).traits().exists());
    }
}