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
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
//! ImportMap builder from PureUseTree
//!
//! Converts Rust `use` statements (represented as PureUseTree) into ImportMap.

use ryo_source::pure::{PureFile, PureItem, PureUseTree};
use ryo_symbol::{CrateName, ImportMap, SymbolPath};

/// Build ImportMap from a PureFile's use statements
///
/// # Arguments
/// - `file`: The PureFile to extract use statements from
/// - `crate_name`: The crate containing this file
/// - `module_path`: The module path of this file (e.g., "my_crate::handlers")
///
/// # Returns
/// An ImportMap containing all imports from the file's use statements
pub fn build_import_map(
    file: &PureFile,
    crate_name: &CrateName,
    module_path: &SymbolPath,
) -> ImportMap {
    let mut import_map = ImportMap::new();

    for item in &file.items {
        if let PureItem::Use(use_stmt) = item {
            process_use_tree(&use_stmt.tree, "", crate_name, module_path, &mut import_map);
        }
    }

    import_map
}

/// Process a PureUseTree and add imports to the ImportMap
fn process_use_tree(
    tree: &PureUseTree,
    prefix: &str,
    crate_name: &CrateName,
    module_path: &SymbolPath,
    import_map: &mut ImportMap,
) {
    match tree {
        PureUseTree::Path { path, tree: inner } => {
            // Resolve path segment (handle crate, self, super)
            let resolved = resolve_path_segment(path, prefix, crate_name, module_path);
            process_use_tree(inner, &resolved, crate_name, module_path, import_map);
        }

        PureUseTree::Name(name) => {
            // use foo::bar::Name;
            let full_path = if prefix.is_empty() {
                name.clone()
            } else {
                format!("{}::{}", prefix, name)
            };

            if let Ok(symbol_path) = SymbolPath::parse(&full_path) {
                import_map.add_import(name.clone(), symbol_path);
            }
        }

        PureUseTree::Rename { name, rename } => {
            // use foo::bar::Name as Alias;
            let full_path = if prefix.is_empty() {
                name.clone()
            } else {
                format!("{}::{}", prefix, name)
            };

            if let Ok(symbol_path) = SymbolPath::parse(&full_path) {
                import_map.add_rename(rename.clone(), symbol_path);
            }
        }

        PureUseTree::Glob => {
            // use foo::bar::*;
            if !prefix.is_empty() {
                if let Ok(symbol_path) = SymbolPath::parse(prefix) {
                    import_map.add_glob(symbol_path);
                }
            }
        }

        PureUseTree::Group(trees) => {
            // use foo::bar::{A, B, C};
            for inner_tree in trees {
                process_use_tree(inner_tree, prefix, crate_name, module_path, import_map);
            }
        }
    }
}

/// A public re-export entry: `pub use some::path::Name;` in a module.
pub struct ReExportEntry {
    /// The local name introduced by the use statement (e.g., "Mutex")
    pub local_name: String,
    /// The resolved full path of the imported symbol (e.g., "tokio::sync::mutex::Mutex")
    pub full_path: SymbolPath,
}

/// Collect public re-exports from a PureFile.
///
/// Extracts `pub use` statements and returns (local_name, resolved_full_path) pairs.
/// Only `pub` and `pub(crate)` visibility are included.
pub fn collect_public_reexports(
    file: &PureFile,
    crate_name: &CrateName,
    module_path: &SymbolPath,
) -> Vec<ReExportEntry> {
    let mut entries = Vec::new();

    for item in &file.items {
        if let PureItem::Use(use_stmt) = item {
            if matches!(
                use_stmt.vis,
                ryo_source::pure::PureVis::Public | ryo_source::pure::PureVis::Crate
            ) {
                collect_reexport_entries(&use_stmt.tree, "", crate_name, module_path, &mut entries);
            }
        }
    }

    entries
}

/// Recursively extract (local_name, full_path) pairs from a PureUseTree.
fn collect_reexport_entries(
    tree: &PureUseTree,
    prefix: &str,
    crate_name: &CrateName,
    module_path: &SymbolPath,
    entries: &mut Vec<ReExportEntry>,
) {
    match tree {
        PureUseTree::Path { path, tree: inner } => {
            let resolved = resolve_path_segment(path, prefix, crate_name, module_path);
            collect_reexport_entries(inner, &resolved, crate_name, module_path, entries);
        }
        PureUseTree::Name(name) => {
            let full_path = if prefix.is_empty() {
                name.clone()
            } else {
                format!("{}::{}", prefix, name)
            };
            if let Ok(symbol_path) = SymbolPath::parse(&full_path) {
                entries.push(ReExportEntry {
                    local_name: name.clone(),
                    full_path: symbol_path,
                });
            }
        }
        PureUseTree::Rename { name, rename } => {
            let full_path = if prefix.is_empty() {
                name.clone()
            } else {
                format!("{}::{}", prefix, name)
            };
            if let Ok(symbol_path) = SymbolPath::parse(&full_path) {
                entries.push(ReExportEntry {
                    local_name: rename.clone(),
                    full_path: symbol_path,
                });
            }
        }
        PureUseTree::Glob => {
            // Glob re-exports can't be statically enumerated without full registry scan;
            // skip for now.
        }
        PureUseTree::Group(trees) => {
            for inner_tree in trees {
                collect_reexport_entries(inner_tree, prefix, crate_name, module_path, entries);
            }
        }
    }
}

/// Resolve special path segments (crate, self, super)
fn resolve_path_segment(
    segment: &str,
    prefix: &str,
    crate_name: &CrateName,
    module_path: &SymbolPath,
) -> String {
    match segment {
        "crate" => {
            // `crate::` → current crate name
            crate_name.as_str().to_string()
        }

        "self" => {
            // `self::` → current module path
            if prefix.is_empty() {
                module_path.to_string()
            } else {
                prefix.to_string()
            }
        }

        "super" => {
            // `super::` → parent module
            if prefix.is_empty() {
                module_path
                    .parent()
                    .map(|p| p.to_string())
                    .unwrap_or_else(|| crate_name.as_str().to_string())
            } else {
                // super within an already-resolved prefix
                if let Ok(path) = SymbolPath::parse(prefix) {
                    path.parent()
                        .map(|p| p.to_string())
                        .unwrap_or_else(|| prefix.to_string())
                } else {
                    prefix.to_string()
                }
            }
        }

        _ => {
            // Normal path segment
            if prefix.is_empty() {
                segment.to_string()
            } else {
                format!("{}::{}", prefix, segment)
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use ryo_source::pure::{PureUse, PureVis};

    fn make_file_with_uses(uses: Vec<PureUse>) -> PureFile {
        PureFile {
            items: uses.into_iter().map(PureItem::Use).collect(),
            attrs: vec![],
        }
    }

    fn make_use(tree: PureUseTree) -> PureUse {
        PureUse {
            vis: PureVis::Private,
            tree,
        }
    }

    fn make_crate_name() -> CrateName {
        CrateName::new_for_test("my_crate")
    }

    fn make_module_path() -> SymbolPath {
        SymbolPath::parse("my_crate::handlers").unwrap()
    }

    #[test]
    fn test_simple_import() {
        // use std::collections::HashMap;
        let tree = PureUseTree::Path {
            path: "std".to_string(),
            tree: Box::new(PureUseTree::Path {
                path: "collections".to_string(),
                tree: Box::new(PureUseTree::Name("HashMap".to_string())),
            }),
        };

        let file = make_file_with_uses(vec![make_use(tree)]);
        let import_map = build_import_map(&file, &make_crate_name(), &make_module_path());

        let expected = SymbolPath::parse("std::collections::HashMap").unwrap();
        assert_eq!(import_map.resolve("HashMap"), Some(&expected));
    }

    #[test]
    fn test_rename_import() {
        // use std::collections::HashMap as Map;
        let tree = PureUseTree::Path {
            path: "std".to_string(),
            tree: Box::new(PureUseTree::Path {
                path: "collections".to_string(),
                tree: Box::new(PureUseTree::Rename {
                    name: "HashMap".to_string(),
                    rename: "Map".to_string(),
                }),
            }),
        };

        let file = make_file_with_uses(vec![make_use(tree)]);
        let import_map = build_import_map(&file, &make_crate_name(), &make_module_path());

        let expected = SymbolPath::parse("std::collections::HashMap").unwrap();
        assert_eq!(import_map.resolve("Map"), Some(&expected));
        assert_eq!(import_map.resolve("HashMap"), None);
    }

    #[test]
    fn test_glob_import() {
        // use std::collections::*;
        let tree = PureUseTree::Path {
            path: "std".to_string(),
            tree: Box::new(PureUseTree::Path {
                path: "collections".to_string(),
                tree: Box::new(PureUseTree::Glob),
            }),
        };

        let file = make_file_with_uses(vec![make_use(tree)]);
        let import_map = build_import_map(&file, &make_crate_name(), &make_module_path());

        let expected = SymbolPath::parse("std::collections").unwrap();
        assert!(import_map.glob_imports().contains(&expected));
    }

    #[test]
    fn test_group_import() {
        // use std::collections::{HashMap, HashSet};
        let tree = PureUseTree::Path {
            path: "std".to_string(),
            tree: Box::new(PureUseTree::Path {
                path: "collections".to_string(),
                tree: Box::new(PureUseTree::Group(vec![
                    PureUseTree::Name("HashMap".to_string()),
                    PureUseTree::Name("HashSet".to_string()),
                ])),
            }),
        };

        let file = make_file_with_uses(vec![make_use(tree)]);
        let import_map = build_import_map(&file, &make_crate_name(), &make_module_path());

        let hashmap = SymbolPath::parse("std::collections::HashMap").unwrap();
        let hashset = SymbolPath::parse("std::collections::HashSet").unwrap();
        assert_eq!(import_map.resolve("HashMap"), Some(&hashmap));
        assert_eq!(import_map.resolve("HashSet"), Some(&hashset));
    }

    #[test]
    fn test_crate_import() {
        // use crate::models::User;
        let tree = PureUseTree::Path {
            path: "crate".to_string(),
            tree: Box::new(PureUseTree::Path {
                path: "models".to_string(),
                tree: Box::new(PureUseTree::Name("User".to_string())),
            }),
        };

        let file = make_file_with_uses(vec![make_use(tree)]);
        let import_map = build_import_map(&file, &make_crate_name(), &make_module_path());

        let expected = SymbolPath::parse("my_crate::models::User").unwrap();
        assert_eq!(import_map.resolve("User"), Some(&expected));
    }

    #[test]
    fn test_super_import() {
        // use super::Config;
        // In module my_crate::handlers → resolves to my_crate::Config
        let tree = PureUseTree::Path {
            path: "super".to_string(),
            tree: Box::new(PureUseTree::Name("Config".to_string())),
        };

        let file = make_file_with_uses(vec![make_use(tree)]);
        let import_map = build_import_map(&file, &make_crate_name(), &make_module_path());

        let expected = SymbolPath::parse("my_crate::Config").unwrap();
        assert_eq!(import_map.resolve("Config"), Some(&expected));
    }

    #[test]
    fn test_self_import() {
        // use self::utils::Helper;
        // In module my_crate::handlers → resolves to my_crate::handlers::utils::Helper
        let tree = PureUseTree::Path {
            path: "self".to_string(),
            tree: Box::new(PureUseTree::Path {
                path: "utils".to_string(),
                tree: Box::new(PureUseTree::Name("Helper".to_string())),
            }),
        };

        let file = make_file_with_uses(vec![make_use(tree)]);
        let import_map = build_import_map(&file, &make_crate_name(), &make_module_path());

        let expected = SymbolPath::parse("my_crate::handlers::utils::Helper").unwrap();
        assert_eq!(import_map.resolve("Helper"), Some(&expected));
    }

    // ========== collect_public_reexports tests ==========

    fn make_pub_use(tree: PureUseTree) -> PureUse {
        PureUse {
            vis: PureVis::Public,
            tree,
        }
    }

    #[test]
    fn test_pub_reexport_collected() {
        // pub use crate::sync::mutex::Mutex;
        let tree = PureUseTree::Path {
            path: "crate".to_string(),
            tree: Box::new(PureUseTree::Path {
                path: "sync".to_string(),
                tree: Box::new(PureUseTree::Path {
                    path: "mutex".to_string(),
                    tree: Box::new(PureUseTree::Name("Mutex".to_string())),
                }),
            }),
        };

        let crate_name = CrateName::new_for_test("tokio");
        let module_path = SymbolPath::parse("tokio::sync").unwrap();
        let file = make_file_with_uses(vec![make_pub_use(tree)]);
        let reexports = collect_public_reexports(&file, &crate_name, &module_path);

        assert_eq!(reexports.len(), 1);
        assert_eq!(reexports[0].local_name, "Mutex");
        assert_eq!(
            reexports[0].full_path,
            SymbolPath::parse("tokio::sync::mutex::Mutex").unwrap()
        );
    }

    #[test]
    fn test_private_use_not_collected() {
        // use crate::sync::mutex::Mutex;  (private)
        let tree = PureUseTree::Path {
            path: "crate".to_string(),
            tree: Box::new(PureUseTree::Path {
                path: "sync".to_string(),
                tree: Box::new(PureUseTree::Name("Mutex".to_string())),
            }),
        };

        let crate_name = CrateName::new_for_test("tokio");
        let module_path = SymbolPath::parse("tokio::sync").unwrap();
        let file = make_file_with_uses(vec![make_use(tree)]); // private
        let reexports = collect_public_reexports(&file, &crate_name, &module_path);

        assert!(reexports.is_empty());
    }

    #[test]
    fn test_pub_reexport_rename() {
        // pub use parking_lot::Mutex as ParkingMutex;
        let tree = PureUseTree::Path {
            path: "parking_lot".to_string(),
            tree: Box::new(PureUseTree::Rename {
                name: "Mutex".to_string(),
                rename: "ParkingMutex".to_string(),
            }),
        };

        let crate_name = CrateName::new_for_test("my_crate");
        let module_path = SymbolPath::parse("my_crate").unwrap();
        let file = make_file_with_uses(vec![make_pub_use(tree)]);
        let reexports = collect_public_reexports(&file, &crate_name, &module_path);

        assert_eq!(reexports.len(), 1);
        assert_eq!(reexports[0].local_name, "ParkingMutex");
        assert_eq!(
            reexports[0].full_path,
            SymbolPath::parse("parking_lot::Mutex").unwrap()
        );
    }

    #[test]
    fn test_pub_reexport_group() {
        // pub use crate::types::{Config, State};
        let tree = PureUseTree::Path {
            path: "crate".to_string(),
            tree: Box::new(PureUseTree::Path {
                path: "types".to_string(),
                tree: Box::new(PureUseTree::Group(vec![
                    PureUseTree::Name("Config".to_string()),
                    PureUseTree::Name("State".to_string()),
                ])),
            }),
        };

        let crate_name = CrateName::new_for_test("my_crate");
        let module_path = SymbolPath::parse("my_crate").unwrap();
        let file = make_file_with_uses(vec![make_pub_use(tree)]);
        let reexports = collect_public_reexports(&file, &crate_name, &module_path);

        assert_eq!(reexports.len(), 2);
        let names: Vec<&str> = reexports.iter().map(|e| e.local_name.as_str()).collect();
        assert!(names.contains(&"Config"));
        assert!(names.contains(&"State"));
    }
}