xingbiao 0.9.0

星表 (Xingbiao) — Tianheng's shared declared-workspace-data substrate: reads `cargo metadata --no-deps` and looks up packages and their crate-root source files, the tabulated catalog every observation dimension references before it observes. serde_json-only, below all dimensions like 璇璣 — a single source of truth so the static and semantic dimensions read the workspace through one reader instead of two drifting twins.
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
use std::path::PathBuf;

use serde_json::json;

use super::*;

#[test]
fn find_package_selects_by_name() {
    let metadata = json!({ "packages": [
        { "name": "a", "targets": [] },
        { "name": "b", "targets": [] },
    ]});
    assert_eq!(find_package(&metadata, "b").unwrap()["name"], json!("b"));
    assert!(find_package(&metadata, "missing").is_none());
}

#[test]
fn crate_root_file_prefers_lib_then_proc_macro_then_bin() {
    let lib_and_bin = json!({ "targets": [
        { "kind": ["bin"], "src_path": "/w/src/main.rs" },
        { "kind": ["lib"], "src_path": "/w/src/lib.rs" },
    ]});
    assert_eq!(
        crate_root_file(&lib_and_bin),
        Some(PathBuf::from("/w/src/lib.rs")),
        "the lib target wins over bin"
    );

    let bin_only = json!({ "targets": [{ "kind": ["bin"], "src_path": "/w/src/main.rs" }] });
    assert_eq!(
        crate_root_file(&bin_only),
        Some(PathBuf::from("/w/src/main.rs"))
    );
}

#[test]
fn crate_root_file_resolves_a_proc_macro_target() {
    let package = json!({ "targets": [
        { "kind": ["proc-macro"], "src_path": "/w/src/lib.rs" }
    ]});
    assert_eq!(
        crate_root_file(&package),
        Some(PathBuf::from("/w/src/lib.rs"))
    );
}

#[test]
fn crate_root_file_skips_a_member_with_no_lib_proc_macro_or_bin() {
    let bench_only = json!({ "targets": [{ "kind": ["bench"], "src_path": "/w/benches/b.rs" }] });
    assert_eq!(crate_root_file(&bench_only), None);
    let rootless = json!({ "targets": [] });
    assert_eq!(crate_root_file(&rootless), None);
}

#[test]
fn crate_root_file_resolves_a_cdylib_staticlib_or_rlib_library() {
    for kind in [["cdylib"], ["staticlib"], ["rlib"], ["dylib"]] {
        let package = json!({ "targets": [{ "kind": kind, "src_path": "/w/src/lib.rs" }] });
        assert_eq!(
            crate_root_file(&package),
            Some(PathBuf::from("/w/src/lib.rs")),
            "a {kind:?} library must resolve its crate root"
        );
    }
    let multi = json!({ "targets": [{ "kind": ["cdylib", "rlib"], "src_path": "/w/src/lib.rs" }] });
    assert_eq!(
        crate_root_file(&multi),
        Some(PathBuf::from("/w/src/lib.rs"))
    );
    let lib_and_bin = json!({ "targets": [
        { "kind": ["bin"], "src_path": "/w/src/main.rs" },
        { "kind": ["cdylib"], "src_path": "/w/src/lib.rs" },
    ]});
    assert_eq!(
        crate_root_file(&lib_and_bin),
        Some(PathBuf::from("/w/src/lib.rs"))
    );
}

#[test]
fn member_src_dirs_resolves_from_src_path_including_a_custom_layout() {
    let metadata = json!({
        "packages": [
            { "name": "crate_a", "targets": [
                { "kind": ["lib"], "src_path": "/ws/crate_a/src/lib.rs" }
            ]},
            { "name": "crate_b", "targets": [
                { "kind": ["lib"], "src_path": "/ws/crate_b/lib.rs" }
            ]},
            { "name": "crate_c", "targets": [
                { "kind": ["bin"], "src_path": "/ws/crate_c/src/main.rs" }
            ]},
        ]
    });
    let dirs = member_src_dirs(&metadata);
    assert!(dirs.contains(&PathBuf::from("/ws/crate_a/src")), "{dirs:?}");
    assert!(
        dirs.contains(&PathBuf::from("/ws/crate_b")),
        "a custom [lib] path must resolve to its real root, not manifest_dir/src: {dirs:?}"
    );
    assert!(dirs.contains(&PathBuf::from("/ws/crate_c/src")), "{dirs:?}");
}

#[test]
fn member_src_dirs_prefers_lib_over_bin_and_skips_rootless_members() {
    let metadata = json!({
        "packages": [
            { "name": "both", "targets": [
                { "kind": ["bin"], "src_path": "/ws/both/src/main.rs" },
                { "kind": ["lib"], "src_path": "/ws/both/src/lib.rs" }
            ]},
            { "name": "rootless", "targets": [] },
        ]
    });
    let dirs = member_src_dirs(&metadata);
    assert_eq!(dirs, vec![PathBuf::from("/ws/both/src")], "{dirs:?}");
}

#[test]
fn member_root_files_preserves_exact_custom_roots_and_is_deterministic() {
    let metadata = json!({ "packages": [
        { "targets": [
            { "kind": ["lib"], "src_path": "/ws/z/src/lib.rs" },
            { "kind": ["bin"], "src_path": "/ws/z/src/main.rs" }
        ] },
        { "targets": [{ "kind": ["lib"], "src_path": "/ws/a/custom_root.rs" }] },
        { "targets": [{ "kind": ["lib"], "src_path": "/ws/a/custom_root.rs" }] },
        { "targets": [{ "kind": ["test"], "src_path": "/ws/t/test.rs" }] }
    ]});
    assert_eq!(
        member_root_files(&metadata),
        [
            PathBuf::from("/ws/a/custom_root.rs"),
            PathBuf::from("/ws/z/src/lib.rs"),
            PathBuf::from("/ws/z/src/main.rs")
        ]
    );
}

/// Ordinary paths keep their baseline labels: each listed observed-file label preserves the path's spelling.
#[test]
fn path_label_does_not_re_key_any_shape_that_occurs() {
    for path in [
        "src/lib.rs",
        "src/main.rs",
        "src/bin/conventional.rs",
        "tools/outside.rs",
        "single.rs",
        "/abs/src/lib.rs",
        "a/../b",
    ] {
        assert_eq!(
            path_label(Path::new(path)),
            path,
            "an ordinary path must label as itself, or every recorded baseline entry re-keys"
        );
    }
    assert_eq!(
        path_label(Path::new("with%pct/f.rs")),
        "with%25pct/f.rs",
        "a literal `%` escapes so no escaped label can be spelled by an unescaped one"
    );
    // The stated normalizations. Neither form is reachable from a `cargo metadata` `src_path` or a
    // walked path, both already canonical; asserted so the bound is pinned rather than implied.
    assert_eq!(path_label(Path::new("./a")), "a");
    assert_eq!(path_label(Path::new("a//b")), "a/b");
    assert_eq!(path_label(Path::new("/")), "/");
}

/// A byte that is not valid UTF-8 survives as an escape, so two paths differing only there keep two
/// labels — and a separator byte that is legal *inside* a name is not treated as a separator.
///
/// The second half is what proves the separator rule is delegated to `std::path` rather than
/// hardcoded: on unix `\` is an ordinary byte, so `a\b` is ONE component and must not label as `a/b`.
/// A `replace('\\', "/")` implementation would map two distinct paths onto one label — the exact
/// injectivity loss this labeling exists to prevent — and this is the assertion that would catch it.
#[cfg(unix)]
#[test]
fn path_label_preserves_bytes_and_does_not_invent_separators() {
    use std::os::unix::ffi::OsStrExt;

    let bad = std::ffi::OsStr::from_bytes(b"src/ba\xffd.rs");
    assert_eq!(
        path_label(Path::new(bad)),
        "src/ba%FFd.rs",
        "an undecodable byte escapes rather than collapsing to U+FFFD"
    );
    let other = std::ffi::OsStr::from_bytes(b"src/ba\xfed.rs");
    assert_ne!(
        path_label(Path::new(bad)),
        path_label(Path::new(other)),
        "two paths differing only in undecodable bytes must keep two identities"
    );

    let backslash_in_name = std::ffi::OsStr::from_bytes(b"a\\b");
    assert_eq!(
        path_label(Path::new(backslash_in_name)),
        "a\\b",
        "on unix `\\` is a byte within one component, not a separator: labeling it as `a/b` would \
         collide with the genuinely two-component path"
    );
    assert_ne!(
        path_label(Path::new(backslash_in_name)),
        path_label(Path::new("a/b")),
        "the single file `a\\b` and the file `b` inside directory `a` are distinct observations"
    );
}

/// On Windows, `Components` splits both separator forms and emits canonical labels with `/`.
/// `Components` splits on `sys::path::is_sep_byte`, generated by `path_separator_bytes!(b'\\', b'/')` in
/// `library/std/src/sys/path/windows.rs` and `path_separator_bytes!(b'/')` in
/// `library/std/src/sys/path/unix.rs` (read in rust-src for rustc 1.98.1); no runner here executes this test.
/// Its `cfg(windows)` attribute excludes it from unix test runs.
#[cfg(windows)]
#[test]
fn a_windows_separator_labels_as_the_canonical_one() {
    assert_eq!(path_label(Path::new("src\\lib.rs")), "src/lib.rs");
    assert_eq!(path_label(Path::new("src\\bin\\x.rs")), "src/bin/x.rs");
    assert_eq!(
        path_label(Path::new("src/lib.rs")),
        path_label(Path::new("src\\lib.rs")),
        "both separators are separators on Windows, so both must reach one label"
    );
}

/// No label built from ordinary components carries the platform's own separator unless that separator is
/// already `/`.
///
/// **This assertion is vacuous on unix and load-bearing on Windows**, and is written this way
/// deliberately rather than left to a platform CI runner that does not exist. On unix
/// `MAIN_SEPARATOR` is `/`, so the check cannot fail here. On Windows it is `\`, and the assertion
/// requires `path_label` output to omit it. The Windows behavior rests on the documented separator
/// parsing of `std::path::Components`, not on a measurement taken in this repository: there is no
/// Windows runner and no wine here, and claiming otherwise would be the kind of unearned confidence
/// a green unix suite invites.
///
/// **`Component::Prefix` is outside this corpus — a coverage limitation, not a bound.** A prefix is emitted
/// verbatim, as the separator rule says every component is, so a Windows UNC prefix carries `\` within one
/// component while `/` still means a boundary; a prefix is produced only on Windows, so what is missing here
/// is a run, not a verdict.
#[test]
fn a_label_never_carries_a_platform_separator() {
    for path in ["src/lib.rs", "a/b/c.rs", "/abs/x.rs"] {
        let label = path_label(Path::new(path));
        assert!(
            std::path::MAIN_SEPARATOR == '/' || !label.contains(std::path::MAIN_SEPARATOR),
            "a label must use `/` alone, so one commit yields one identity on every platform: {label:?}"
        );
    }
}

/// A root reported under two target names collapses to one, wherever the two reports sit.
///
/// `Vec::dedup` removes only CONSECUTIVE equal elements, which is total for
/// [`member_root_files`] because it sorts first — and was not total here, where Cargo's own order is
/// preserved on purpose. Two targets may legitimately name the same `path`; Cargo accepts it, builds
/// both, and reports targets sorted by NAME, so the duplicate reports are adjacent only when no third
/// target's name sorts between them. The `[x, y, x]` arrangement below is that case, and it is what
/// `dedup` alone left untouched — measured against a real three-`[[bin]]` manifest, where
/// the root reader returned `[shared.rs, between.rs, shared.rs]`.
///
/// Adjacency is asserted alongside it so the test states the whole rule rather than one arrangement of
/// it: `[x, x, y]` collapsed under `dedup` too, so a fixture using only that shape would pass against
/// the defect.
#[test]
fn crate_roots_are_unique_by_root_not_by_adjacency() {
    let non_adjacent = json!({ "targets": [
        { "kind": ["bin"], "src_path": "/p/src/shared.rs" },
        { "kind": ["bin"], "src_path": "/p/src/between.rs" },
        { "kind": ["bin"], "src_path": "/p/src/shared.rs" }
    ]});
    assert_eq!(
        crate_roots(&non_adjacent).compiled(),
        [
            PathBuf::from("/p/src/shared.rs"),
            PathBuf::from("/p/src/between.rs")
        ],
        "a root reported twice is ONE compilation unit, and Cargo's reported order is preserved"
    );

    let adjacent = json!({ "targets": [
        { "kind": ["lib"], "src_path": "/p/src/shared.rs" },
        { "kind": ["bin"], "src_path": "/p/src/shared.rs" },
        { "kind": ["bin"], "src_path": "/p/src/other.rs" }
    ]});
    assert_eq!(
        crate_roots(&adjacent).compiled(),
        [
            PathBuf::from("/p/src/shared.rs"),
            PathBuf::from("/p/src/other.rs")
        ],
        "the adjacent arrangement collapses too — this half held before the fix, and is here so the \
         test cannot be mistaken for pinning only it"
    );
}

/// No reported target and no compiled target are two answers, and a compiled root is a third.
#[test]
fn crate_roots_tell_no_target_from_no_compiled_target() {
    assert_eq!(crate_roots(&json!({})), CrateRoots::Unreported);
    assert_eq!(
        crate_roots(&json!({ "targets": [] })),
        CrateRoots::Unreported
    );
    assert_eq!(
        crate_roots(&json!({ "targets": [
            { "kind": ["example"], "src_path": "/p/examples/e.rs" },
            { "kind": ["custom-build"], "src_path": "/p/build.rs" }
        ]})),
        CrateRoots::NoneCompiled,
        "targets none of which is a library or a binary compile no root this reads"
    );
    assert_eq!(
        crate_roots(&json!({ "targets": [
            { "kind": ["example"], "src_path": "/p/examples/e.rs" },
            { "kind": ["bin"], "src_path": "/p/src/main.rs" }
        ]})),
        CrateRoots::Compiled(CompiledRoots(vec![PathBuf::from("/p/src/main.rs")]))
    );
}

/// A unique, self-cleaning fixture directory for a path-identity fixture, rooted by [`scratch_root`].
struct TempDir(ScratchRoot);

impl TempDir {
    fn new(label: &str) -> Self {
        Self(scratch_root(&format!("xingbiao-{label}")))
    }

    fn write(&self, name: &str, contents: &str) -> PathBuf {
        let path = self.0.join(name);
        std::fs::write(&path, contents).unwrap();
        path
    }

    fn path(&self, name: &str) -> PathBuf {
        self.0.join(name)
    }
}

#[test]
fn canonicalize_or_fail_resolves_a_real_file_and_errors_on_a_missing_one() {
    let dir = TempDir::new("canonicalize");
    let file = dir.write("real.rs", "");

    assert!(canonicalize_or_fail(&file).is_ok());

    let missing = dir.path("does_not_exist.rs");
    let err = canonicalize_or_fail(&missing).unwrap_err();
    assert!(
        err.contains("cannot resolve"),
        "a missing path must fail loud, not silently skip: {err}"
    );
}

#[test]
fn try_visit_reports_first_visit_then_repeat_and_fails_loud_on_an_unresolvable_path() {
    let dir = TempDir::new("try-visit");
    let file = dir.write("a.rs", "");

    let mut visited = std::collections::HashSet::new();
    assert_eq!(
        try_visit(&mut visited, &file),
        Ok(true),
        "the first visit to a real file is new"
    );
    assert_eq!(
        try_visit(&mut visited, &file),
        Ok(false),
        "a repeat visit to the same canonical file is not new"
    );
    assert!(try_visit(&mut visited, &dir.path("missing.rs")).is_err());
}

#[test]
fn claim_scratch_creates_a_fresh_root() {
    let dir = TempDir::new("claim-fresh");
    let root = dir.path("root");
    assert!(claim_scratch(&root).is_ok());
    assert!(root.is_dir());
}

#[test]
fn claim_scratch_refuses_an_existing_directory() {
    let dir = TempDir::new("claim-existing");
    let root = dir.path("root");
    std::fs::create_dir(&root).expect("the fixture directory is writable");
    assert!(
        claim_scratch(&root).is_err(),
        "a path that already exists must be refused, not silently adopted"
    );
}

#[cfg(unix)]
#[test]
fn claim_scratch_refuses_a_pre_existing_symlink_that_create_dir_all_would_adopt() {
    let dir = TempDir::new("claim-symlink");
    let target = dir.path("elsewhere");
    std::fs::create_dir(&target).expect("the symlink target is writable");
    let root = dir.path("root");
    std::os::unix::fs::symlink(&target, &root).expect("create the symlink");

    // The defect this replaces, measured directly: `create_dir_all` follows the symlink and reports success,
    // so writes meant for a freshly claimed root would land in `target` instead.
    assert!(
        std::fs::create_dir_all(&root).is_ok(),
        "control: create_dir_all silently adopts the symlink, which is exactly the defect claim_scratch exists \
         to close"
    );

    assert!(
        claim_scratch(&root).is_err(),
        "a symlink at the path must be refused — mkdir cannot follow it, so adopting it would write through \
         to whatever it points at"
    );
}

#[test]
fn scratch_base_for_places_tmp_beside_the_profile_directory() {
    for (exe, base) in [
        ("/w/target/debug/deps/t-1", "/w/target/tmp"),
        (
            "/w/target/x86_64-unknown-linux-gnu/release/deps/t-1",
            "/w/target/x86_64-unknown-linux-gnu/tmp",
        ),
    ] {
        assert_eq!(
            scratch_base_for(Path::new(exe)),
            Ok(PathBuf::from(base)),
            "{exe}"
        );
    }
}

#[test]
fn scratch_base_for_refuses_a_layout_it_cannot_recognise_naming_the_executable() {
    for exe in ["/usr/bin/t", "/w/target/debug/t", "/t", "deps/t"] {
        let why = scratch_base_for(Path::new(exe)).expect_err(exe);
        assert!(
            why.contains(exe),
            "the refusal names the executable's path: {why}"
        );
    }
}

#[test]
fn scratch_root_lives_under_the_base_and_is_removed_on_drop() {
    let root = scratch_root("xingbiao-root-probe");
    let path = root.path().to_path_buf();
    assert!(path.starts_with(scratch_base()), "{}", path.display());
    assert!(path.is_dir());
    std::fs::write(path.join("f"), "x").unwrap();
    drop(root);
    assert!(
        !path.exists(),
        "the guard removes the root with what is in it"
    );
}

#[test]
fn scratch_root_names_are_unique_per_call() {
    let (a, b) = (
        scratch_root("xingbiao-unique"),
        scratch_root("xingbiao-unique"),
    );
    assert_ne!(a.path(), b.path());
}

/// A second root built from the same label leaves the first root's files where they are.
///
/// The race this holds closed was two tests building a fixture from one label in one process: the second
/// call removed the path the first had just filled. The direction is deterministic and needs no parallel
/// schedule: it builds both in one thread, in the order that lost the first root's files, and reads the
/// first root back afterwards.
#[test]
fn a_second_root_of_the_same_label_leaves_the_first_roots_files() {
    let first = scratch_root("xingbiao-same-label");
    let written = first.path().join("f");
    std::fs::write(&written, "first").expect("write into the first root");
    let second = scratch_root("xingbiao-same-label");
    assert_eq!(
        std::fs::read_to_string(&written).as_deref().ok(),
        Some("first"),
        "building a second root of the same label removed the first root's file"
    );
    assert_ne!(first.path(), second.path());
}

/// A label the base would not contain is refused, and the refusal names it.
///
/// Three shapes, each one [`Path::join`] reads: an absolute label replaces the base outright, a leading `..`
/// names its parent, and an inner separator names a directory beneath one nothing claimed.
///
/// **A bare `.` or `..` is accepted, and the direction asserts it rather than leaving it to be inferred.** The
/// question is asked of the name, which carries the process id and counter after the label, so `..` leaves
/// `..-<pid>-<counter>` — one ordinary component, under the base. Asking it of the label instead would refuse a
/// root that is contained, which is the repair this direction exists to refuse.
#[test]
fn scratch_root_refuses_a_label_the_base_would_not_contain() {
    for label in ["/escaped", "../escaped", "nested/escaped"] {
        let refused = std::panic::catch_unwind(|| scratch_root(label));
        let why = refused.expect_err(label);
        let message = why
            .downcast_ref::<String>()
            .map(String::as_str)
            .or_else(|| why.downcast_ref::<&str>().copied())
            .unwrap_or_else(|| panic!("the refusal carries a message: {label}"));
        assert!(
            message.contains(label),
            "the refusal names the label it will not build a root from: {message}"
        );
    }
    for label in [".", ".."] {
        let root = scratch_root(label);
        assert!(
            root.path().starts_with(scratch_base()),
            "a label the name contains is built, not refused: {}",
            root.path().display()
        );
    }
}

/// An absent path is removed; a path that is not a directory is an error rather than a silent success.
///
/// The distinction is the whole of [`remove_if_present`]: a root left by a previous process under a recycled
/// id is the expected absence, and every other failure leaves something standing where the caller is about to
/// claim a directory.
#[test]
fn remove_if_present_tells_absence_from_a_failure() {
    let root = scratch_root("xingbiao-remove-if-present");
    let absent = root.path().join("never-created");
    assert!(remove_if_present(&absent).is_ok(), "{}", absent.display());
    let file = root.path().join("f");
    std::fs::write(&file, "x").expect("write the file to remove as a directory");
    let err = remove_if_present(&file).expect_err("a file is not a directory tree to remove");
    assert_ne!(
        err.kind(),
        std::io::ErrorKind::NotFound,
        "the error a caller must hear is not absence: {err}"
    );
}