raf-source 0.0.0

Workspace source index: a Tree file seam with disk and memory backends under canonical path containment.
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
// SPDX-FileCopyrightText: 2026 Blackcat InformaticsĀ® Inc. <paudley@blackcatinformatics.ca>
// SPDX-License-Identifier: MIT OR Apache-2.0 OR MulanPSL-2.0

//! The crate root of every target is a module item at its crate path.

use std::fmt::Write as _;
use std::path::Path;

use raf_source::{
    DiskTree, LoadErrorKind, LoadOptions, MemoryTree, Namespace, Origin, ResolveError, SymbolKind,
    TargetKind, TestRole, TreeError, Workspace,
};

const DEMO: &str = "[package]\nname = \"demo\"\nversion = \"0.1.0\"\n";

fn all_kinds() -> Workspace {
    let tree: MemoryTree = [
        ("Cargo.toml", DEMO),
        ("src/lib.rs", "//! The library.\npub fn go() {}\n"),
        ("src/main.rs", "fn main() {}\n"),
        ("src/bin/x.rs", "fn main() {}\n"),
        ("tests/it.rs", "#[test]\nfn case() {}\n"),
        ("benches/b.rs", "fn bench() {}\n"),
        ("examples/e.rs", "fn main() {}\n"),
        ("build.rs", "fn main() {}\n"),
    ]
    .into_iter()
    .collect();
    Workspace::load(&tree, &["."]).expect("loads")
}

#[test]
fn every_target_kind_resolves_at_its_crate_path_as_a_module_item_of_its_root_file() {
    let ws = all_kinds();
    let cases = [
        ("demo", "src/lib.rs", true),
        ("demo::bin_crate::demo", "src/main.rs", true),
        ("demo::bin_crate::x", "src/bin/x.rs", true),
        ("demo::test_crate::it", "tests/it.rs", false),
        ("demo::bench_crate::b", "benches/b.rs", false),
        ("demo::example_crate::e", "examples/e.rs", false),
        ("demo::build_script", "build.rs", true),
    ];
    for (path, file, shipping) in cases {
        let resolution = ws.resolve(path).unwrap_or_else(|e| panic!("{path}: {e}"));
        assert_eq!(resolution.namespace, Namespace::Type, "{path}");
        assert_eq!(resolution.sites.len(), 1, "{path}");
        let item = ws.item(resolution.sites[0]).expect("item");
        assert_eq!(item.kind, SymbolKind::Mod, "{path}");
        assert_eq!(item.path, path);
        assert_eq!(item.file.as_str(), file, "{path}");
        assert_eq!(item.name_line, 1, "{path}");
        assert_eq!(item.span.start_byte, 0, "{path}");
        assert_eq!(
            item.span.end_byte,
            ws.source(&item.file).expect("text").len(),
            "{path}"
        );
        assert_eq!(ws.is_shipping(item), shipping, "{path}");
        // Only the library has inner documentation.
        assert_eq!(item.documented, path == "demo", "{path}");
    }
    let roles = |path: &str| {
        ws.item(ws.resolve(path).expect("resolves").sites[0])
            .expect("item")
            .test
    };
    assert_eq!(roles("demo::test_crate::it"), TestRole::CfgTest);
    assert_eq!(roles("demo"), TestRole::None);
    // An item inside a root still resolves through it.
    assert!(ws.resolve("demo::test_crate::it::case").is_ok());
    assert!(ws.resolve("demo::go").is_ok());
}

#[test]
fn the_namespace_segments_are_not_items_and_a_first_party_module_of_that_name_collides() {
    let ws = all_kinds();
    for segment in [
        "demo::test_crate",
        "demo::bench_crate",
        "demo::example_crate",
        "demo::bin_crate",
    ] {
        assert!(
            matches!(ws.resolve(segment), Err(ResolveError::NotFound(_))),
            "{segment}: {:?}",
            ws.resolve(segment)
        );
    }
    // A target root is a type; the value namespace has nothing at its path.
    assert!(ws.resolve_in("demo", Namespace::Value).is_err());
    // A first-party module of that name is an item, and it collides with a
    // target only at a path that both define.
    let tree: MemoryTree = [
        ("Cargo.toml", DEMO),
        ("src/lib.rs", "mod test_crate;\n"),
        (
            "src/test_crate.rs",
            "pub mod it {}\npub fn first_party() {}\n",
        ),
        ("tests/it.rs", "pub fn case() {}\n"),
    ]
    .into_iter()
    .collect();
    let ws = Workspace::load(&tree, &["."]).expect("loads");
    assert!(matches!(
        ws.resolve("demo::test_crate::it"),
        Err(ResolveError::Ambiguous(_))
    ));
    assert!(ws.resolve("demo::test_crate::it::case").is_ok());
    assert!(ws.resolve("demo::test_crate").is_ok());
}

/// The file of the one definition `path` resolves to.
fn file_of(ws: &Workspace, path: &str) -> String {
    let resolution = ws.resolve(path).unwrap_or_else(|e| panic!("{path}: {e}"));
    assert_eq!(resolution.sites.len(), 1, "{path}");
    ws.item(resolution.sites[0]).expect("item").file.to_string()
}

/// The files of the items `path` is ambiguous between, sorted.
fn ambiguous_files(ws: &Workspace, path: &str) -> Vec<String> {
    match ws.resolve(path) {
        Err(ResolveError::Ambiguous(ids)) => {
            let mut files: Vec<String> = ids
                .iter()
                .map(|id| ws.item(*id).expect("item").file.to_string())
                .collect();
            files.sort();
            files
        }
        other => panic!("{path}: {other:?}"),
    }
}

#[test]
fn a_lib_module_named_bin_crate_stays_in_the_library() {
    for (segment, file) in [
        ("bin_crate", "src/bin/x.rs"),
        ("test_crate", "tests/x.rs"),
        ("bench_crate", "benches/x.rs"),
        ("example_crate", "examples/x.rs"),
    ] {
        let lib = format!("pub mod {segment} {{ pub mod x {{ pub fn lib_fn() {{}} }} }}\n");
        let tree: MemoryTree = [
            ("Cargo.toml", DEMO),
            ("src/lib.rs", lib.as_str()),
            (file, "pub fn bin_fn() {}\nfn main() {}\n"),
        ]
        .into_iter()
        .collect();
        let ws = Workspace::load(&tree, &["."]).expect("loads");
        let base = format!("demo::{segment}::x");
        assert_eq!(file_of(&ws, &format!("{base}::bin_fn")), file, "{segment}");
        assert_eq!(file_of(&ws, &format!("{base}::lib_fn")), "src/lib.rs");
        let lib_fn = ws
            .items()
            .find(|item| item.name == "lib_fn")
            .expect("indexed");
        assert_eq!(lib_fn.path, format!("{base}::lib_fn"));
        assert_eq!(
            ws.target(lib_fn.target).expect("target").kind,
            TargetKind::Lib
        );
        assert!(matches!(
            ws.resolve(&format!("{base}::main")),
            Ok(found) if found.sites.len() == 1
        ));
        // The library's module and the target's root share their path.
        let mut both = vec!["src/lib.rs".to_owned(), file.to_owned()];
        both.sort();
        assert_eq!(ambiguous_files(&ws, &base), both);
    }
    let tree: MemoryTree = [
        ("Cargo.toml", DEMO),
        (
            "src/lib.rs",
            "pub mod build_script { pub fn lib_fn() {} }\n",
        ),
        ("build.rs", "pub fn bin_fn() {}\nfn main() {}\n"),
    ]
    .into_iter()
    .collect();
    let ws = Workspace::load(&tree, &["."]).expect("loads");
    assert_eq!(file_of(&ws, "demo::build_script::bin_fn"), "build.rs");
    assert_eq!(file_of(&ws, "demo::build_script::lib_fn"), "src/lib.rs");
    assert_eq!(
        ambiguous_files(&ws, "demo::build_script"),
        ["build.rs", "src/lib.rs"]
    );
}

#[test]
fn a_build_script_main_beside_a_lib_module_build_script_is_ambiguous() {
    // `build.rs` sorts before `src/lib.rs` and `zz/build.rs` after it.
    let named = format!("{DEMO}build = \"zz/build.rs\"\n");
    for (manifest, script) in [(DEMO, "build.rs"), (named.as_str(), "zz/build.rs")] {
        let tree: MemoryTree = [
            ("Cargo.toml", manifest),
            ("src/lib.rs", "pub mod build_script { pub fn main() {} }\n"),
            (script, "fn main() {}\n"),
        ]
        .into_iter()
        .collect();
        let ws = Workspace::load(&tree, &["."]).expect("loads");
        let mut expected = vec![script.to_owned(), "src/lib.rs".to_owned()];
        expected.sort();
        assert_eq!(
            ambiguous_files(&ws, "demo::build_script::main"),
            expected,
            "{script}"
        );
    }
    // Without the library's module the build script's `main` is one symbol.
    let tree: MemoryTree = [
        ("Cargo.toml", DEMO),
        ("src/lib.rs", "pub mod tools { pub fn main() {} }\n"),
        ("build.rs", "fn main() {}\n"),
    ]
    .into_iter()
    .collect();
    let ws = Workspace::load(&tree, &["."]).expect("loads");
    assert_eq!(file_of(&ws, "demo::build_script::main"), "build.rs");
}

#[test]
fn an_explicit_path_bin_beside_a_lib_module_bin_crate_is_ambiguous_in_both_file_orders() {
    // `a/x.rs` sorts before `src/lib.rs` and `tools/x.rs` after it.
    for path in ["a/x.rs", "tools/x.rs"] {
        let manifest = format!("{DEMO}\n[[bin]]\nname = \"x\"\npath = \"{path}\"\n");
        let tree: MemoryTree = [
            ("Cargo.toml", manifest.as_str()),
            (
                "src/lib.rs",
                "pub mod bin_crate { pub mod x { pub fn main() {} } }\n",
            ),
            (path, "fn main() {}\n"),
        ]
        .into_iter()
        .collect();
        let ws = Workspace::load(&tree, &["."]).expect("loads");
        let mut expected = vec![path.to_owned(), "src/lib.rs".to_owned()];
        expected.sort();
        assert_eq!(
            ambiguous_files(&ws, "demo::bin_crate::x::main"),
            expected,
            "{path}"
        );
        // The same layout with a library module of another name is one
        // symbol in each order.
        let tree: MemoryTree = [
            ("Cargo.toml", manifest.as_str()),
            (
                "src/lib.rs",
                "pub mod tools { pub mod x { pub fn main() {} } }\n",
            ),
            (path, "fn main() {}\n"),
        ]
        .into_iter()
        .collect();
        let ws = Workspace::load(&tree, &["."]).expect("loads");
        assert_eq!(file_of(&ws, "demo::bin_crate::x::main"), path);
        assert_eq!(file_of(&ws, "demo::tools::x::main"), "src/lib.rs");
    }
}

#[test]
fn an_over_cap_inferred_lib_names_discovery_not_lib_path() {
    let mut options = LoadOptions::default();
    // Every manifest below fits the cap; the library is over it.
    options.max_file_bytes = 200;
    let big = format!("{}\n", "/".repeat(300));
    for (manifest, origin) in [
        (DEMO.to_owned(), Origin::Discovery),
        (
            format!("{DEMO}\n[lib]\nname = \"demo\"\n"),
            Origin::ManifestKey {
                key: "lib".to_owned(),
            },
        ),
        (
            format!("{DEMO}\n[lib]\npath = \"src/lib.rs\"\n"),
            Origin::ManifestKey {
                key: "lib.path".to_owned(),
            },
        ),
    ] {
        let tree: MemoryTree = [
            ("Cargo.toml", manifest.as_str()),
            ("src/lib.rs", big.as_str()),
        ]
        .into_iter()
        .collect();
        let error = Workspace::load_with(&tree, &["."], &options).expect_err("over the cap");
        assert_eq!(error.file.as_str(), "src/lib.rs");
        assert!(
            matches!(&error.kind, LoadErrorKind::Tree(inner) if matches!(**inner, TreeError::TooLarge { .. })),
            "{error}"
        );
        assert_eq!(error.origin.as_deref(), Some(&origin), "{error}");
        let text = error.to_string();
        assert_eq!(
            text.contains("lib.path"),
            origin
                == Origin::ManifestKey {
                    key: "lib.path".to_owned()
                },
            "{text}"
        );
    }
    // A library under the cap loads under each manifest.
    let tree: MemoryTree = [("Cargo.toml", DEMO), ("src/lib.rs", "pub fn go() {}\n")]
        .into_iter()
        .collect();
    assert!(Workspace::load_with(&tree, &["."], &options).is_ok());
}

#[test]
fn unreadable_target_roots_name_explicit_paths_or_table_names_and_build_discovery() {
    let mut options = LoadOptions::default();
    options.max_file_bytes = 512;
    let big = "/".repeat(513);
    for (kind, default) in [
        ("bin", "src/bin/tool.rs"),
        ("test", "tests/tool.rs"),
        ("bench", "benches/tool.rs"),
        ("example", "examples/tool.rs"),
    ] {
        for explicit in [false, true] {
            let selected = format!("selected/{kind}.rs");
            let path = if explicit { selected.as_str() } else { default };
            let mut manifest = format!("{DEMO}[[{kind}]]\nname = \"tool\"\n");
            if explicit {
                writeln!(manifest, "path = \"{path}\"").expect("writing into a String succeeds");
            }
            let tree = MemoryTree::from([("Cargo.toml", manifest.as_str()), (path, big.as_str())]);
            let error = Workspace::load_with(&tree, &["."], &options)
                .expect_err("the target exceeds its read cap");
            assert_eq!(error.file.as_str(), path);
            assert!(
                matches!(&error.kind, LoadErrorKind::Tree(inner) if matches!(**inner, TreeError::TooLarge { .. })),
                "{error}"
            );
            let key = format!("{kind}.{}", if explicit { "path" } else { "name" });
            assert_eq!(error.origin.as_deref(), Some(&Origin::ManifestKey { key }));
            let valid =
                MemoryTree::from([("Cargo.toml", manifest.as_str()), (path, "fn main() {}")]);
            assert!(Workspace::load_with(&valid, &["."], &options).is_ok());
        }
    }
    for explicit in [false, true] {
        let path = if explicit {
            "selected-build.rs"
        } else {
            "build.rs"
        };
        let manifest = if explicit {
            format!("{DEMO}build = \"{path}\"\n")
        } else {
            DEMO.to_owned()
        };
        let tree = MemoryTree::from([("Cargo.toml", manifest.as_str()), (path, big.as_str())]);
        let error = Workspace::load_with(&tree, &["."], &options)
            .expect_err("the build script exceeds its read cap");
        assert_eq!(error.file.as_str(), path);
        assert!(
            matches!(&error.kind, LoadErrorKind::Tree(inner) if matches!(**inner, TreeError::TooLarge { .. })),
            "{error}"
        );
        let origin = if explicit {
            Origin::ManifestKey {
                key: "package.build".to_owned(),
            }
        } else {
            Origin::Discovery
        };
        assert_eq!(error.origin.as_deref(), Some(&origin));
        let valid = MemoryTree::from([("Cargo.toml", manifest.as_str()), (path, "fn main() {}")]);
        assert!(Workspace::load_with(&valid, &["."], &options).is_ok());
    }
}

#[test]
fn this_repository_resolves_a_test_crate_root_and_a_library_root() {
    let repository = Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");
    let ws = Workspace::load(&DiskTree::new(repository).expect("tree"), &["crates"])
        .unwrap_or_else(|e| panic!("{e}"));
    let library = ws.resolve("raf_okf").expect("the library root");
    let item = ws.item(library.sites[0]).expect("item");
    assert_eq!(item.file.as_str(), "crates/raf-okf/src/lib.rs");
    let test = ws
        .resolve("raf_okf::test_crate::refusals")
        .expect("a test target root");
    let item = ws.item(test.sites[0]).expect("item");
    assert_eq!(item.file.as_str(), "crates/raf-okf/tests/refusals.rs");
    assert!(!ws.is_shipping(item));
}

#[test]
fn a_first_party_module_at_a_binary_crate_path_is_ambiguous_beside_a_binary_that_is_not() {
    let tree: MemoryTree = [
        ("Cargo.toml", DEMO),
        (
            "src/lib.rs",
            "pub mod bin_crate { pub mod demo { pub fn f() {} } }\n",
        ),
        ("src/main.rs", "fn main() {}\n"),
        ("src/bin/x.rs", "fn main() {}\n"),
    ]
    .into_iter()
    .collect();
    let ws = Workspace::load(&tree, &["."]).expect("loads");
    // The module and the binary root share a path.
    match ws.resolve("demo::bin_crate::demo") {
        Err(ResolveError::Ambiguous(ids)) => {
            assert_eq!(ids.len(), 2);
            let files: Vec<_> = ids
                .iter()
                .map(|id| ws.item(*id).expect("item").file.as_str())
                .collect();
            assert!(files.contains(&"src/lib.rs") && files.contains(&"src/main.rs"));
        }
        other => panic!("{other:?}"),
    }
    // The module's own item still resolves.
    assert!(ws.resolve("demo::bin_crate::demo::f").is_ok());
    // The same layout without the first-party `bin_crate` module has no collision.
    let tree: MemoryTree = [
        ("Cargo.toml", DEMO),
        ("src/lib.rs", "pub mod demo { pub fn f() {} }\n"),
        ("src/main.rs", "fn main() {}\n"),
        ("src/bin/x.rs", "fn main() {}\n"),
    ]
    .into_iter()
    .collect();
    let ws = Workspace::load(&tree, &["."]).expect("loads");
    assert_eq!(
        ws.resolve("demo::bin_crate::demo")
            .expect("the root")
            .sites
            .len(),
        1
    );
    assert_eq!(
        ws.resolve("demo::bin_crate::x")
            .expect("resolves")
            .sites
            .len(),
        1
    );
    assert!(ws.resolve("demo::demo::f").is_ok());
}