diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml index ae2c452b1c5..a782f4eb4ec 100644 --- a/.github/workflows/nightly.yml +++ b/.github/workflows/nightly.yml @@ -1,7 +1,7 @@ name: nightly -# Everything that boots a guest, the host checks a pull request does not run, -# and portability: on main every night, and on any branch by +# Everything that boots a guest, the host gate again to write the cache the +# merge queue restores, and portability: on main every night, and on any branch by # `gh workflow run nightly.yml --ref `. Every job's logic is # `cargo run -- --ci ` (src/ci.rs); this file says where each one runs. @@ -38,7 +38,7 @@ jobs: key: host-${{ github.run_id }} restore-keys: host- - - run: cargo run -- --ci host-full + - run: cargo run -- --ci host # The host cache's one writer. Only main's entries are readable from # every branch. diff --git a/Cargo.toml b/Cargo.toml index db9f57a57a0..a64edc2857e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -77,9 +77,8 @@ exclude = [ # The userland SDK. It compiles against the ToyOS sysroot and is a path # dependency of `rust/library/std`, so it keeps its own resolution and # cannot be a member. It is host-tested all the same — its `lib.rs` is - # `cfg_attr(not(test), no_std)` and `cargo run -- --ci host-full` runs - # `cargo test` in it against the host triple. Every crate in `exclude` that - # has host tests is named in `src/ci.rs`; nothing here reaches them. + # `cfg_attr(not(test), no_std)` and `cargo run -- --ci host` runs + # `cargo test` in it against the host triple. "toyos", # Guest programs `src/build.rs` builds for `x86_64-unknown-toyos`, each from # its own directory. The harness's own integration test lives here too diff --git a/issues/build/a-userland-test-in-a-file-no-module-reaches-runs-nowhere.md b/issues/build/a-userland-test-in-a-file-no-module-reaches-runs-nowhere.md new file mode 100644 index 00000000000..e9ded5a8245 --- /dev/null +++ b/issues/build/a-userland-test-in-a-file-no-module-reaches-runs-nowhere.md @@ -0,0 +1,22 @@ +--- +status: open +kind: tooling +opened: 2026-09-26 +--- + +# A userland test in a `src/` file no module reaches runs nowhere and still reads as gated + +`src/userlandhost.rs` gates a userland crate by reading its `src/` and `tests/` +for test attributes. A file under `src/` that no `mod` declaration reaches is +never compiled, so a test in it runs in no `cargo test`, and the survey +counts its crate as gated all the same. The merge gate is green over a test +that never ran. No such file is in the tree today, and nothing refuses one. + +The same holds for any file the survey reads that a target's module tree does +not include. A `#[path]` pointing away from the file, or a module dropped from +its parent, orphans it. + +**Exit:** every file the survey finds holding a test is shown to be compiled +into a test binary the gate runs. For example, `host` lists each gated crate's +tests (`cargo test ... -- --list`), and each such file contributes at least one +listed test. A test fixture holding an orphaned `src/` file must red. diff --git a/issues/build/soundds-host-suite-reds-a-thread-with-no-voice.md b/issues/build/soundds-host-suite-reds-a-thread-with-no-voice.md deleted file mode 100644 index 84e9ef8135c..00000000000 --- a/issues/build/soundds-host-suite-reds-a-thread-with-no-voice.md +++ /dev/null @@ -1,26 +0,0 @@ ---- -status: open -kind: defect -opened: 2026-09-26 ---- - -# soundd's host suite reds: a test's `flush` says a line from a thread with no voice - -`cargo test --manifest-path userland/soundd/Cargo.toml --target ` exits -101 on `origin/main` (checked on a `git archive` of it) as on #511. One test -fails, `mix::tests::published_totals_are_exactly_the_sum_of_every_window`: - -``` -panicked at soundd/src/say.rs:100:28: -soundd: a thread with no voice said "soundd: wakes=0 completions=0 submitted=10 underruns=1 drains=2 ..." -``` - -`mix::flush` says its window's line through `say!`, and `say::said` panics -unless the calling thread was made a voice (`say::start` or `say::speak_as`). -The test thread was made neither. soundd is in `src/ci.rs`'s -`USERLAND_HOST_CRATES`, so the nightly's `host-full` reds on this, and the PR -`host` job does not run it. - -Exit condition: the suite exits 0 with the test still reading the totals -through `flush`. Either the test gives its thread a voice, or `flush`'s line -leaves through a seam a test can hold. diff --git a/kernel-loom/tests/log_zeroed_init.rs b/kernel-loom/tests/log_zeroed_init.rs index 15f4d6f86fe..edcaeb0e284 100644 --- a/kernel-loom/tests/log_zeroed_init.rs +++ b/kernel-loom/tests/log_zeroed_init.rs @@ -8,7 +8,7 @@ //! invocations, and the other one runs nothing from this file.** That is the //! shape, not an accident — but it was silent until 2026-08-14, when CI ran //! only the default invocation and this file's `running 0 tests` looked -//! identical to a pass. `cargo run -- --ci host-full` runs both commands +//! identical to a pass. `cargo run -- --ci host` runs both commands //! now, and every other `loom::model` file is gated `cfg(feature = "loom")`, //! so a bare `--no-default-features` run at the crate root exercises none of //! them either — the second command names this target explicitly instead. diff --git a/src/build.rs b/src/build.rs index d90280966fa..21ad9c33bf5 100644 --- a/src/build.rs +++ b/src/build.rs @@ -2465,7 +2465,7 @@ mod tests { /// **A control nobody runs is a control nobody has shown can fail.** Every /// name [`declared_model_controls`] finds is a row of `crate::ci::CONTROLS`, - /// which `cargo run -- --ci host-full` runs, and every row names a declared + /// which `cargo run -- --ci host` runs, and every row names a declared /// control — or a new control can be declared and run nowhere, silently. #[test] fn every_model_control_is_run() { diff --git a/src/ci.rs b/src/ci.rs index 168ef54c412..e9558d57115 100644 --- a/src/ci.rs +++ b/src/ci.rs @@ -9,9 +9,11 @@ //! as `host`, only in the merge queue, where every branch has already been //! judged as a pull request. A required check a workflow skips on the other //! event still reports, and a skip counts as passing — that is how each half -//! enters the queue it does not itself run in. `nightly.yml` runs everything -//! that boots a guest, the rest of the host checks (`host-full`), and -//! portability. `publish.yml` puts a landing's crates on crates.io. +//! enters the queue it does not itself run in. Every test that boots no guest +//! is in [`Job::Host`], so a merge is gated on all of them. `nightly.yml` runs +//! everything that boots a guest, `host` again to write the cache the merge +//! queue restores, and portability. `publish.yml` puts a landing's crates on +//! crates.io. //! //! A host job runs every step and reds if any failed; a guest job stops at the //! first failure, because what follows a wrong instrument or a missing @@ -40,10 +42,10 @@ pub(crate) const REQUIRED_CHECKS: &[&str] = &["host", "abi-split"]; const NIGHTLY_RED: &str = "nightly is red"; const USAGE: &str = "cargo run -- --ci , where is one of: - host cargo test --lib, every host-workspace suite and clippy (ci.yml) + host every host test: the build system, the host workspace, clippy, + the model controls, userland and the SDK (ci.yml, nightly) abi-split the published crates' versions (ci.yml; the name is the required check's) gate-stage what protects main, read back from GitHub (ci.yml) - host-full host, plus the model controls, userland and the SDK (nightly) toolchain publish this tree's toolchain if nobody has (nightly) guest / one shard of the whole guest suite, nightly tier included (nightly) tcg one test on an emulated CPU (nightly) @@ -56,7 +58,6 @@ enum Job { Host, AbiSplit, GateStage, - HostFull, Toolchain, Guest(String), Tcg, @@ -75,7 +76,6 @@ fn parse(words: &[String]) -> Result { Some("host") => Job::Host, Some("abi-split") => Job::AbiSplit, Some("gate-stage") => Job::GateStage, - Some("host-full") => Job::HostFull, Some("toolchain") => Job::Toolchain, Some("guest") => Job::Guest(shard(words.get(1))?), Some("tcg") => Job::Tcg, @@ -103,7 +103,6 @@ pub fn dispatch(root: &Path, args: &[String]) { vec![step("the published crates' versions", || abi_split(root))] } Job::GateStage => vec![step("what protects main", || gate_stage(root))], - Job::HostFull => host_full(root), Job::Toolchain => vec![step("the toolchain release", || release::ensure_published(root))], Job::Guest(shard) => { guest(root, &suite_args(&["--shard", shard, "--jobs", "1", "--nightly"])) @@ -205,43 +204,6 @@ fn cargo_logged(dir: &Path, args: &[&str]) -> Result<(bool, String), String> { // --- The host jobs ------------------------------------------------------------- -/// The merge queue's whole gate: the build system's own tests, every member of -/// the host workspace, and clippy with warnings denied. None of the three -/// needs the ToyOS toolchain nightly.yml alone builds — the kernel and the -/// bootloader clippy against `x86_64-unknown-none`/`x86_64-unknown-uefi`, -/// targets any rustup installs, and `x86_64-unknown-toyos` (the one target -/// that does need the fork) is userland's alone, and userland carries no -/// clippy shape (`src/clippy.rs`). -fn host(root: &Path) -> Vec { - let mut steps = vec![ - step("the build system", || cargo(root, &["test", "--lib"])), - step("the host workspace", || { - cargo(root, &["test", "--workspace", "--exclude", "toyos-build"]) - }), - ]; - steps.push(step("clippy and the bare targets", || { - for args in [ - &["component", "add", "clippy"][..], - &["target", "add", "x86_64-unknown-none", "x86_64-unknown-uefi"], - ] { - let status = Command::new("rustup").args(args).status().map_err(|e| e.to_string())?; - if !status.success() { - return Err(format!("rustup {} exited {status}", args.join(" "))); - } - } - Ok("installed".into()) - })); - steps.push(step("clippy, warnings denied", || { - let failed = crate::clippy::run(root); - if failed.is_empty() { - Ok("clean".into()) - } else { - Err(failed.join("; ")) - } - })); - steps -} - /// What a model of the kernel's concurrency is shown able to catch: a feature /// that takes away the one edge the model's property rests on, and the verdict /// lines the model must then print. @@ -398,14 +360,46 @@ fn run_control(root: &Path, control: &Control) -> Result { judge_control(control, green, &log) } -/// The userland crates whose decisions are testable on the host. They name the -/// host triple because `userland/.cargo/config.toml` cross-compiles by default, -/// which is also why they cannot be host-workspace members. -const USERLAND_HOST_CRATES: &[&str] = &["sshd", "calc", "soundd", "logd", "pkg", "netd"]; - -fn host_full(root: &Path) -> Vec { +/// The merge queue's whole gate, and the nightly's host lane: every test that +/// runs on the host and boots no guest. The build system's own tests, every +/// member of the host workspace, clippy with warnings denied, the concurrency +/// models' negative controls, every userland crate with a host test +/// ([`crate::userlandhost`], which also reds on a userland test none of them +/// runs), and the SDK. +/// +/// Clippy needs none of the ToyOS toolchain the nightly alone builds — the +/// kernel and the bootloader lint against `x86_64-unknown-none` and +/// `x86_64-unknown-uefi`, targets any rustup installs, and userland carries no +/// clippy shape (`src/clippy.rs`). Userland and the SDK are tested against the +/// host triple for the same reason. +fn host(root: &Path) -> Vec { let host_triple = crate::toolchain::host_triple(); - let mut steps = self::host(root); + let mut steps = vec![ + step("the build system", || cargo(root, &["test", "--lib"])), + step("the host workspace", || { + cargo(root, &["test", "--workspace", "--exclude", "toyos-build"]) + }), + ]; + steps.push(step("clippy and the bare targets", || { + for args in [ + &["component", "add", "clippy"][..], + &["target", "add", "x86_64-unknown-none", "x86_64-unknown-uefi"], + ] { + let status = Command::new("rustup").args(args).status().map_err(|e| e.to_string())?; + if !status.success() { + return Err(format!("rustup {} exited {status}", args.join(" "))); + } + } + Ok("installed".into()) + })); + steps.push(step("clippy, warnings denied", || { + let failed = crate::clippy::run(root); + if failed.is_empty() { + Ok("clean".into()) + } else { + Err(failed.join("; ")) + } + })); // `log_zeroed_init` and `log_body_words` are gated `cfg(not(feature = // "loom"))`, so the default invocation runs nothing from either. steps.push(step("kernel-loom without loom", || { @@ -423,11 +417,16 @@ fn host_full(root: &Path) -> Vec { for control in CONTROLS { steps.push(step(&format!("control `{}`", control.feature), || run_control(root, control))); } - for name in USERLAND_HOST_CRATES { - let manifest = format!("userland/{name}/Cargo.toml"); - steps.push(step(&format!("userland/{name}"), || { - cargo(root, &["test", "--manifest-path", &manifest, "--target", &host_triple]) - })); + match crate::userlandhost::survey(&root.join("userland")) { + Ok(survey) => { + for name in survey.gated { + let manifest = format!("userland/{name}/Cargo.toml"); + steps.push(step(&format!("userland/{name}"), || { + cargo(root, &["test", "--manifest-path", &manifest, "--target", &host_triple]) + })); + } + } + Err(why) => steps.push(Step { label: "the userland host crates".into(), verdict: Err(why) }), } // The SDK compiles against the ToyOS sysroot everywhere but here, and this // build links no syscall. diff --git a/src/clippy.rs b/src/clippy.rs index 3294cc91855..ce35ab4beb0 100644 --- a/src/clippy.rs +++ b/src/clippy.rs @@ -1,8 +1,8 @@ //! Default clippy with warnings denied, over the three trees this host lints. //! //! `cargo run -- --clippy` runs [`SHAPES`] alone; `cargo run -- --ci -//! host-full` runs the same list as one of its steps, so the local command and -//! the nightly gate cannot verify different sets. +//! host` runs the same list as one of its steps, so the local command and +//! the merge gate cannot verify different sets. //! //! Userland is not here: `x86_64-unknown-toyos` is a custom target, and the //! fork's `toyos` toolchain ships no clippy. diff --git a/src/lib.rs b/src/lib.rs index 4dac8d4dc81..0f2025f82b3 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -46,6 +46,7 @@ pub mod sysroot; pub mod testargs; pub mod tiers; pub mod toolchain; +pub mod userlandhost; pub mod wallpaper; pub mod worktree; diff --git a/src/sourcegate.rs b/src/sourcegate.rs index b48f6dcc836..b54bae7dfda 100644 --- a/src/sourcegate.rs +++ b/src/sourcegate.rs @@ -1,8 +1,8 @@ //! Identifiers a tree may not name, and the exceptions that are named instead. //! //! **Clippy runs now, and these scans are what it cannot say.** `cargo run -- -//! --ci host-full` runs default clippy with warnings denied over three trees -//! every night — the host workspace +//! --ci host` runs default clippy with warnings denied over three trees +//! on every merge — the host workspace //! (`--workspace --all-targets`), the kernel (`--target x86_64-unknown-none`) //! and the bootloader (`--target x86_64-unknown-uefi`) — so a `clippy.toml` is //! no longer a wall with nothing behind it. diff --git a/src/userlandhost.rs b/src/userlandhost.rs new file mode 100644 index 00000000000..07049d2acbf --- /dev/null +++ b/src/userlandhost.rs @@ -0,0 +1,393 @@ +//! Which userland crates `cargo run -- --ci host` tests, and every userland test +//! it would run nowhere. +//! +//! `userland/` is a workspace of its own that cross-compiles by default +//! (`userland/.cargo/config.toml`), so none of its crates can be a member of the +//! host workspace [`crate::hostws`] holds; the gate runs `cargo test --target +//! ` in each crate [`survey`] gates instead. There is no list: a crate's +//! first test gates the merge that adds it. +//! +//! **A test is found by reading text**, because cargo's metadata knows targets +//! and not tests, and the one tool that lists tests, the test binary, needs a +//! host build most userland crates cannot make. So the reading is made to fail +//! loudly: a test is gated only in the one shape a default `cargo test` in a +//! crate directly under `userland/` is known to run. That is an attribute naming +//! `test` or `test_case`, in a file under the crate's `src/` or `tests/`, in a +//! crate whose only `cfg` is `cfg(test)`, which ignores no test, and whose +//! manifest switches off no target's tests. +//! +//! Doc-tests are not read: a library crate that leaves `doctest` on is refused, +//! because the `toyos` toolchain builds no rustdoc. +//! +//! A test in a `src/` file that no `mod` reaches is gated and never compiled. +//! That escape is not closed here. + +use std::collections::BTreeSet; +use std::path::{Path, PathBuf}; + +/// What [`survey`] found under one `userland/` directory. +#[derive(Debug, PartialEq, Eq)] +pub struct Survey { + /// The crates `host` runs, by directory name, sorted. + pub gated: Vec, + /// Every test the gate would not run, each as `: why`, + /// sorted. `host` is red while this is not empty. + pub escapes: Vec, +} + +/// Every crate directly under `userland` that holds a test, and every test that +/// no `cargo test` in one of them runs. +pub fn survey(userland: &Path) -> Result { + let mut files = Vec::new(); + rs_files(userland, &mut files)?; + files.sort(); + let mut crates = BTreeSet::new(); + let mut gated = BTreeSet::new(); + let mut escapes = BTreeSet::new(); + // Refusals that bind only once the file's crate turns out to be gated. + let mut conditional: Vec<(String, PathBuf, &'static str)> = Vec::new(); + for file in &files { + let text = std::fs::read_to_string(file).map_err(|e| format!("{}: {e}", file.display()))?; + let at = rel(userland, file); + let scan = scan(&text).map_err(|why| format!("{at}: {why}"))?; + let Some(owner) = file + .ancestors() + .skip(1) + .take_while(|dir| *dir != userland) + .find(|dir| dir.join("Cargo.toml").is_file()) + else { + if scan.test { + escapes.insert(format!("{at}: a test in no crate")); + } + continue; + }; + let crate_name = rel(userland, owner); + crates.insert(crate_name.clone()); + for why in &scan.conditions { + conditional.push((crate_name.clone(), file.clone(), *why)); + } + if !scan.test { + continue; + } + let inside = rel(owner, file); + if crate_name.contains('/') { + escapes.insert(format!( + "{at}: a test in the nested crate {crate_name}, which the gate does not discover" + )); + } else if !(inside.starts_with("src/") || inside.starts_with("tests/")) { + escapes.insert(format!( + "{at}: a test outside {crate_name}'s src/ and tests/, which cargo test does not run" + )); + } else { + gated.insert(crate_name); + } + } + for (crate_name, file, why) in conditional { + if gated.contains(&crate_name) { + escapes.insert(format!("{}: {why}", rel(userland, &file))); + } + } + for crate_name in &crates { + let manifest = userland.join(crate_name).join("Cargo.toml"); + let text = + std::fs::read_to_string(&manifest).map_err(|e| format!("{}: {e}", manifest.display()))?; + let doc: toml::Value = + text.parse().map_err(|e| format!("{}: not TOML: {e}", manifest.display()))?; + let lib = doc.get("lib"); + let has_lib = lib.is_some() || userland.join(crate_name).join("src/lib.rs").is_file(); + if has_lib && lib.and_then(|l| l.get("doctest")).and_then(toml::Value::as_bool) != Some(false) { + escapes.insert(format!( + "{crate_name}/Cargo.toml: a library without [lib] doctest = false, whose doc-tests the gate does not read" + )); + } + if gated.contains(crate_name) { + for key in switched_off(&doc) { + escapes.insert(format!("{crate_name}/Cargo.toml: {key}")); + } + } + } + Ok(Survey { gated: gated.into_iter().collect(), escapes: escapes.into_iter().collect() }) +} + +/// `path` under `base`, with forward slashes. +fn rel(base: &Path, path: &Path) -> String { + path.strip_prefix(base).unwrap_or(path).to_string_lossy().replace('\\', "/") +} + +/// Every `.rs` file under `dir`, which may not exist; `target` and dotted +/// directories are build output and history. +fn rs_files(dir: &Path, out: &mut Vec) -> Result<(), String> { + let entries = match std::fs::read_dir(dir) { + Ok(entries) => entries, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()), + Err(e) => return Err(format!("{}: {e}", dir.display())), + }; + for entry in entries { + let path = entry.map_err(|e| format!("{}: {e}", dir.display()))?.path(); + let name = path.file_name().unwrap_or_default().to_string_lossy().into_owned(); + if path.is_dir() { + if !name.starts_with('.') && name != "target" { + rs_files(&path, out)?; + } + } else if name.ends_with(".rs") { + out.push(path); + } + } + Ok(()) +} + +/// The manifest keys that stop a default `cargo test` from running a test the +/// crate holds. +fn switched_off(doc: &toml::Value) -> Vec { + let mut found = Vec::new(); + if let Some(package) = doc.get("package") { + for key in ["autolib", "autobins", "autotests"] { + if package.get(key).and_then(toml::Value::as_bool) == Some(false) { + found.push(format!("[package] {key} = false leaves a target's tests unbuilt")); + } + } + } + let tables = doc.get("lib").into_iter().map(|t| ("lib", t)).chain( + ["bin", "test"].into_iter().flat_map(|kind| { + doc.get(kind) + .and_then(toml::Value::as_array) + .into_iter() + .flatten() + .map(move |t| (kind, t)) + }), + ); + for (kind, table) in tables { + for key in ["test", "harness"] { + if table.get(key).and_then(toml::Value::as_bool) == Some(false) { + found.push(format!("[{kind}] {key} = false leaves its tests unrun")); + } + } + if table.get("required-features").is_some() { + found.push(format!("[{kind}] required-features leaves it unbuilt by default")); + } + } + found +} + +/// What one source file holds, as far as the gate is concerned. +#[derive(Debug, Default, PartialEq, Eq)] +struct Scan { + /// An attribute names `test` or `test_case` as a word. + test: bool, + /// Why a default `cargo test` might skip this crate's tests; binding only + /// if the crate is gated. + conditions: Vec<&'static str>, +} + +/// Read every attribute in `text` for a test and for what could hide one. +fn scan(text: &str) -> Result { + let mut out = Scan::default(); + let mut attribute: Option<(String, i32)> = None; + for line in text.lines() { + let mut rest = line.trim_start(); + loop { + if attribute.is_none() { + if !(rest.starts_with("#[") || rest.starts_with("#![")) { + break; + } + attribute = Some((String::new(), 0)); + } + let (body, depth) = attribute.as_mut().expect("inside an attribute"); + let mut in_string = false; + let mut escaped = false; + let mut end = None; + for (i, c) in rest.char_indices() { + if in_string { + if escaped { + escaped = false; + } else if c == '\\' { + escaped = true; + } else if c == '"' { + in_string = false; + body.push('"'); + } + continue; + } + match c { + '"' => { + in_string = true; + body.push('"'); + continue; + } + '[' => *depth += 1, + ']' => *depth -= 1, + _ => {} + } + if !c.is_whitespace() { + body.push(c); + } + if *depth == 0 && c == ']' { + end = Some(i + 1); + break; + } + } + let Some(end) = end else { + body.push(' '); + break; + }; + let (body, _) = attribute.take().expect("inside an attribute"); + judge_attribute(&body, &mut out); + rest = rest[end..].trim_start(); + } + } + match attribute { + Some(_) => Err("an attribute that never closes, which hides the rest of the file"), + None => Ok(out), + } +} + +/// One attribute, whitespace and string contents removed: `#[cfg(test)]`, +/// `#![doc=""]`. +fn judge_attribute(body: &str, out: &mut Scan) { + let inner = body.trim_start_matches('#').trim_start_matches('!'); + let inner = inner.strip_prefix('[').and_then(|s| s.strip_suffix(']')).unwrap_or(inner); + let words: Vec<&str> = + inner.split(|c: char| !(c.is_ascii_alphanumeric() || c == '_')).filter(|w| !w.is_empty()).collect(); + if words.iter().any(|w| *w == "test" || *w == "test_case") { + out.test = true; + } + if matches!(words.first(), Some(&"cfg" | &"cfg_attr")) && inner != "cfg(test)" { + out.conditions.push("a cfg other than cfg(test) can compile a test out of the host run"); + } + if words.contains(&"ignore") { + out.conditions.push("an ignored test runs nowhere"); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::fs; + + fn repo_root() -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")) + } + + /// **Every userland test gates a merge.** + #[test] + fn every_userland_test_is_in_the_gate() { + let survey = survey(&repo_root().join("userland")).expect("userland is readable"); + assert!(!survey.gated.is_empty(), "no userland crate holds a test, so this looked at nothing"); + assert!( + survey.escapes.is_empty(), + "`cargo run -- --ci host` runs none of these:\n {}", + survey.escapes.join("\n ") + ); + } + + /// The survey's judgment, on a tree built to hold each shape it has to tell + /// apart. + #[test] + fn the_survey_gates_what_cargo_test_runs_and_names_the_rest() { + let dir = std::env::temp_dir().join(format!("toyos-userlandhost-{}", std::process::id())); + let _ = fs::remove_dir_all(&dir); + let put = |path: &str, text: &str| { + let path = dir.join(path); + fs::create_dir_all(path.parent().expect("a parent")).expect("make the fixture tree"); + fs::write(path, text).expect("write a fixture file"); + }; + let bare = "[package]\nname = \"x\"\nversion = \"0.1.0\"\n"; + let manifest = &format!("{bare}\n[lib]\ndoctest = false\n"); + let test = "#[cfg(test)]\nmod tests {\n #[test]\n fn t() {}\n}\n"; + let escape = "#[test]\nfn escapes() { panic!() }\n"; + + put("loose.rs", escape); + put("gated/Cargo.toml", manifest); + put("gated/src/lib.rs", test); + put("gated/src/slow.rs", "#[test]\n#[ignore]\nfn slow() {}\n"); + put("gated/build.rs", &format!("fn main() {{}}\n{escape}")); + put("gated/examples/x.rs", &format!("fn main() {{}}\n{escape}")); + put("gated/sub/Cargo.toml", manifest); + put("gated/sub/src/lib.rs", test); + put("testsonly/Cargo.toml", manifest); + put("testsonly/src/lib.rs", "pub fn f() {}\n"); + put("testsonly/tests/t.rs", escape); + put("plain/Cargo.toml", bare); + put("plain/src/main.rs", "fn main() {}\n"); + put("plain/src/arch.rs", "#[cfg(target_arch = \"x86_64\")]\nfn a() {}\n"); + put("doctested/Cargo.toml", bare); + put("doctested/src/lib.rs", "pub fn f() {}\n"); + put("switched/Cargo.toml", &format!("{bare}\n[lib]\ndoctest = false\ntest = false\n")); + put("switched/src/lib.rs", test); + put("switched/target/debug/x.rs", escape); + + let found = survey(&dir); + fs::remove_dir_all(&dir).ok(); + assert_eq!( + found, + Ok(Survey { + gated: vec!["gated".into(), "switched".into(), "testsonly".into()], + escapes: vec![ + "doctested/Cargo.toml: a library without [lib] doctest = false, whose \ + doc-tests the gate does not read" + .into(), + "gated/build.rs: a test outside gated's src/ and tests/, which cargo test \ + does not run" + .into(), + "gated/examples/x.rs: a test outside gated's src/ and tests/, which cargo \ + test does not run" + .into(), + "gated/src/slow.rs: an ignored test runs nowhere".into(), + "gated/sub/src/lib.rs: a test in the nested crate gated/sub, which the gate \ + does not discover" + .into(), + "loose.rs: a test in no crate".into(), + "switched/Cargo.toml: [lib] test = false leaves its tests unrun".into(), + ], + }) + ); + } + + #[test] + fn a_test_attribute_is_a_word_and_not_a_substring() { + let test = |text| scan(text).expect("closes").test; + assert!(test("#[test]\nfn f() {}")); + assert!(test(" #[cfg(test)]\nmod tests;")); + assert!(test("#![cfg(test)]")); + assert!(test("#[tokio::test]")); + assert!(test("#[test_case]")); + assert!(test("#[inline] #[test] fn f() {}")); + assert!(!test("// #[test]\nlet test = 1;")); + assert!(!test("#[derive(Debug)] struct Contest;")); + // A feature is a string, and the words inside it are not attributes: + // the kernel's `test-actuators` spelling holds no test, and is a + // condition that could hide one. + let actuators = scan("#[cfg(feature = \"test-actuators\")]\nmod m;").expect("closes"); + assert!(!actuators.test); + assert!(!actuators.conditions.is_empty()); + } + + #[test] + fn what_could_hide_a_test_is_a_condition() { + let conditions = |text| scan(text).expect("closes").conditions; + assert_eq!(conditions("#[cfg(test)]\nmod tests;"), Vec::<&str>::new()); + assert_eq!(conditions("#[cfg( test )]"), Vec::<&str>::new()); + let multi = scan("#[cfg(all(\n test,\n feature = \"x\",\n))]\nmod tests;").expect("closes"); + assert!(multi.test); + assert_eq!(multi.conditions.len(), 1, "{multi:?}"); + assert!(!conditions("#[cfg(not(test))]").is_empty()); + assert!(!conditions("#[cfg(target_os = \"toyos\")]").is_empty()); + assert!(!conditions("#[test]\n#[ignore]\nfn f() {}").is_empty()); + assert!(!conditions("#[test] #[ignore]\nfn f() {}").is_empty()); + assert!(!conditions("#[cfg(test)] #[cfg(feature = \"slow\")] mod tests {").is_empty()); + assert!(conditions("#![feature(test)]").is_empty()); + assert!(scan("#[cfg(test)\nmod tests {}\n#[test]\nfn f() {}").is_err()); + } + + #[test] + fn a_manifest_that_switches_tests_off_is_named() { + let keys = |text: &str| switched_off(&text.parse().expect("TOML")).len(); + let base = "[package]\nname = \"x\"\n"; + assert_eq!(keys(base), 0); + assert_eq!(keys(&format!("{base}[lib]\ndoctest = false\n")), 0); + assert_eq!(keys(&format!("{base}autotests = false\n")), 1); + assert_eq!(keys(&format!("{base}[[bin]]\nname = \"b\"\ntest = false\n")), 1); + assert_eq!(keys(&format!("{base}[[test]]\nname = \"t\"\nharness = false\n")), 1); + assert_eq!(keys(&format!("{base}[[test]]\nname = \"t\"\nrequired-features = [\"a\"]\n")), 1); + } +} diff --git a/tests/toyos-rust-tests/Cargo.lock b/tests/toyos-rust-tests/Cargo.lock index 27fceae823d..b2c7cafc020 100644 --- a/tests/toyos-rust-tests/Cargo.lock +++ b/tests/toyos-rust-tests/Cargo.lock @@ -1469,7 +1469,7 @@ version = "0.1.0" [[package]] name = "toyos-font" -version = "0.1.0" +version = "0.2.0" [[package]] name = "toyos-i219" @@ -1518,7 +1518,7 @@ version = "0.1.0" [[package]] name = "toyos-window" -version = "0.13.0" +version = "0.14.0" dependencies = [ "toyos 0.13.0", "toyos-abi 0.12.0", diff --git a/userland/Cargo.lock b/userland/Cargo.lock index 6ef8e40441e..6c4c38cc7b0 100644 --- a/userland/Cargo.lock +++ b/userland/Cargo.lock @@ -334,7 +334,7 @@ version = "0.1.0" dependencies = [ "fontdue", "softbuffer", - "toyos-font 0.1.0", + "toyos-font 0.2.0", "winit", ] @@ -480,10 +480,10 @@ dependencies = [ "toyos 0.13.0", "toyos-abi 0.12.0", "toyos-desktop", - "toyos-font 0.1.0", + "toyos-font 0.2.0", "toyos-inspect", "toyos-manifest", - "toyos-window 0.13.0", + "toyos-window 0.14.0", ] [[package]] @@ -502,9 +502,9 @@ dependencies = [ "terminal", "toyos 0.13.0", "toyos-abi 0.12.0", - "toyos-font 0.1.0", + "toyos-font 0.2.0", "toyos-logstream", - "toyos-window 0.13.0", + "toyos-window 0.14.0", ] [[package]] @@ -988,8 +988,8 @@ name = "editor" version = "0.1.0" dependencies = [ "filepicker-api", - "toyos-font 0.1.0", - "toyos-window 0.13.0", + "toyos-font 0.2.0", + "toyos-window 0.14.0", ] [[package]] @@ -1110,8 +1110,8 @@ version = "0.1.0" dependencies = [ "filepicker-api", "toyos 0.13.0", - "toyos-font 0.1.0", - "toyos-window 0.13.0", + "toyos-font 0.2.0", + "toyos-window 0.14.0", ] [[package]] @@ -1126,8 +1126,8 @@ name = "files" version = "0.1.0" dependencies = [ "sprite", - "toyos-font 0.1.0", - "toyos-window 0.13.0", + "toyos-font 0.2.0", + "toyos-window 0.14.0", ] [[package]] @@ -2320,8 +2320,8 @@ name = "paint" version = "0.1.0" dependencies = [ "filepicker-api", - "toyos-font 0.1.0", - "toyos-window 0.13.0", + "toyos-font 0.2.0", + "toyos-window 0.14.0", ] [[package]] @@ -3397,7 +3397,7 @@ dependencies = [ "fontdue", "rand 0.8.5", "softbuffer", - "toyos-font 0.1.0", + "toyos-font 0.2.0", "winit", ] @@ -3583,8 +3583,8 @@ name = "terminal" version = "0.1.0" dependencies = [ "toyos 0.13.0", - "toyos-font 0.1.0", - "toyos-window 0.13.0", + "toyos-font 0.2.0", + "toyos-window 0.14.0", ] [[package]] @@ -3725,7 +3725,7 @@ dependencies = [ "toyos 0.13.0", "toyos-abi 0.12.0", "toyos-keymap 0.1.0", - "toyos-window 0.13.0", + "toyos-window 0.14.0", ] [[package]] @@ -3783,12 +3783,12 @@ version = "0.1.0" [[package]] name = "toyos-font" version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "812cbf2f1cfd97efddd55a1ebebc4a3cc3bffc8b449bf113410e1487b52efcc8" [[package]] name = "toyos-font" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "812cbf2f1cfd97efddd55a1ebebc4a3cc3bffc8b449bf113410e1487b52efcc8" +version = "0.2.0" [[package]] name = "toyos-hda" @@ -3861,17 +3861,17 @@ checksum = "53aa339b93997027417df5ba25e0ea1cd1a03ceb4e60a95b9ea4c9bc5f15b9dc" dependencies = [ "toyos 0.2.0", "toyos-abi 0.2.0", - "toyos-font 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "toyos-font 0.1.0", "toyos-keymap 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "toyos-window" -version = "0.13.0" +version = "0.14.0" dependencies = [ "toyos 0.13.0", "toyos-abi 0.12.0", - "toyos-font 0.1.0", + "toyos-font 0.2.0", "toyos-keymap 0.1.0", ] diff --git a/userland/filepicker-api/Cargo.toml b/userland/filepicker-api/Cargo.toml index 243bad0c1ee..593b781862d 100644 --- a/userland/filepicker-api/Cargo.toml +++ b/userland/filepicker-api/Cargo.toml @@ -6,3 +6,6 @@ license = "MIT OR Apache-2.0" [dependencies] toyos = { path = "../../toyos" } + +[lib] +doctest = false diff --git a/userland/libc/Cargo.toml b/userland/libc/Cargo.toml index 50120147c41..8a1140f4399 100644 --- a/userland/libc/Cargo.toml +++ b/userland/libc/Cargo.toml @@ -18,3 +18,6 @@ panic = "abort" [profile.release] panic = "abort" + +[lib] +doctest = false diff --git a/userland/soundd/src/mix.rs b/userland/soundd/src/mix.rs index 6a7d1bdc8b8..4281ef72d67 100644 --- a/userland/soundd/src/mix.rs +++ b/userland/soundd/src/mix.rs @@ -35,27 +35,33 @@ const STATS_INTERVAL_NANOS: u64 = 2_000_000_000; /// it detects. const IDLE_WAKES_SAID: u32 = 8; -/// One reporting window, one line. +/// One reporting window, one line, ending in the newline `say::said` takes: the +/// mix thread formats it once and hands it over as it is. /// /// The counters are `toyos_mixer::MixStats`, and what they mean is documented -/// there beside the decision that fills them; this is the emission, which is an -/// effect and stays here. `#106`'s status tool reads one shape, so the null +/// there beside the decision that fills them; this is the line's shape, which +/// is soundd's and stays here. `#106`'s status tool reads one shape, so the null /// sink prints the same line. -fn report(stats: &MixStats, clients: usize) { - say!("soundd: wakes={} completions={} submitted={} underruns={} drains={} max_wake_lat_us={} max_batch={} clients={} deferred={} starve_max={} worst_irq_late_us={} worst_pickup_us={} worst_empty={} worst_batch={} late_wakes={}", +fn report(stats: &MixStats, clients: usize) -> String { + format!("soundd: wakes={} completions={} submitted={} underruns={} drains={} max_wake_lat_us={} max_batch={} clients={} deferred={} starve_max={} worst_irq_late_us={} worst_pickup_us={} worst_empty={} worst_batch={} late_wakes={}\n", stats.wakes, stats.completions, stats.submitted, stats.underruns, stats.drains, stats.max_wake_lat_ns / 1_000, stats.max_batch, clients, stats.deferred, stats.starve_max, stats.worst.irq_late_ns / 1_000, stats.worst.pickup_ns / 1_000, - stats.worst.empty, stats.worst.batch, stats.late_wakes); + stats.worst.empty, stats.worst.batch, stats.late_wakes) } -/// Close one reporting window: say it, add it to the running totals `inspect` -/// reads, and start the next. The only place a reported window is reset, so the -/// totals are exactly the sum of what the console said. -fn flush(stats: &mut MixStats, totals: &mut Totals, clients: usize) { - report(stats, clients); +/// Close one reporting window: add it to the running totals `inspect` reads, +/// start the next, and return the line that says it. The only place a reported +/// window is reset, so the totals are exactly the sum of what the console said. +/// +/// The caller says the line because `say::said` needs a voice with a running +/// writer, which a host test's thread is not. +#[must_use = "an unsaid window leaves the totals ahead of the console"] +fn flush(stats: &mut MixStats, totals: &mut Totals, clients: usize) -> String { + let line = report(stats, clients); totals.fold(stats); *stats = MixStats::default(); + line } /// Signal every client before the wait so priority inheritance can fill their @@ -613,11 +619,11 @@ pub(crate) fn mix_thread( // shorter than two windows that tail is most of it. let now_ns = syscall::clock_nanos(); if was_streaming && streams.is_empty() { - flush(&mut stats, &mut totals, 0); + crate::say::said(flush(&mut stats, &mut totals, 0)); next_stats_ns = now_ns + STATS_INTERVAL_NANOS; } else if now_ns >= next_stats_ns { if !streams.is_empty() { - flush(&mut stats, &mut totals, streams.len()); + crate::say::said(flush(&mut stats, &mut totals, streams.len())); } next_stats_ns = now_ns + STATS_INTERVAL_NANOS; } @@ -784,12 +790,12 @@ pub(crate) fn null_sink_thread( // silent about being discarded (#106's status tool reads one shape). let now_ns = syscall::clock_nanos(); if was_streaming && streams.is_empty() { - flush(&mut stats, &mut totals, 0); + crate::say::said(flush(&mut stats, &mut totals, 0)); next_stats_ns = now_ns + STATS_INTERVAL_NANOS; say!("soundd: null sink idle"); } else if now_ns >= next_stats_ns { if !streams.is_empty() { - flush(&mut stats, &mut totals, streams.len()); + crate::say::said(flush(&mut stats, &mut totals, streams.len())); } next_stats_ns = now_ns + STATS_INTERVAL_NANOS; } @@ -814,7 +820,8 @@ mod tests { /// `flush` on two windows with known counts, then `publish` with a third, /// still-open one: what `inspect` reads back must be exactly the sum of /// all three, once each — not a window double-counted, and not one lost to - /// a window `flush` failed to reset. + /// a window `flush` failed to reset. Each line `flush` hands back says its + /// own window and no other. /// /// The same `MixStats` is reused across both `flush` calls, as the mix /// loop's own is across its wakes: a `flush` that folded the first window @@ -824,12 +831,17 @@ mod tests { let mut totals = Totals::default(); let mut stats = window(10, 1, 2, 3); - flush(&mut stats, &mut totals, 0); + let first = flush(&mut stats, &mut totals, 0); stats.submitted += 20; stats.underruns += 4; stats.drains += 5; stats.late_wakes += 6; - flush(&mut stats, &mut totals, 0); + let second = flush(&mut stats, &mut totals, 0); + assert!(first.contains(" submitted=10 underruns=1 drains=2 "), "{first}"); + assert!(second.contains(" submitted=20 underruns=4 drains=5 "), "{second}"); + // One line each, ending in the newline `say::said` is handed as it is. + assert!(first.ends_with(" late_wakes=3\n") && first.matches('\n').count() == 1, "{first:?}"); + assert!(second.ends_with(" late_wakes=6\n") && second.matches('\n').count() == 1, "{second:?}"); let open = window(7, 8, 9, 10); let published = Published::new(State::Running); diff --git a/userland/sprite/Cargo.toml b/userland/sprite/Cargo.toml index 02011654189..9aaf69cefbf 100644 --- a/userland/sprite/Cargo.toml +++ b/userland/sprite/Cargo.toml @@ -5,6 +5,7 @@ edition = "2021" license = "MIT OR Apache-2.0" [lib] +doctest = false [dependencies] resvg = { version = "0.47", default-features = false } diff --git a/userland/terminal/Cargo.toml b/userland/terminal/Cargo.toml index b10789aa1dd..13c03bd5461 100644 --- a/userland/terminal/Cargo.toml +++ b/userland/terminal/Cargo.toml @@ -8,3 +8,6 @@ license = "MIT OR Apache-2.0" toyos = { path = "../../toyos" } toyos-font = { path = "../toyos-font" } toyos-window = { path = "../toyos-window" } + +[lib] +doctest = false diff --git a/userland/toyos-font/Cargo.toml b/userland/toyos-font/Cargo.toml index d85b172f566..341fecfd144 100644 --- a/userland/toyos-font/Cargo.toml +++ b/userland/toyos-font/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "toyos-font" -version = "0.1.0" +version = "0.2.0" edition = "2021" license = "MIT OR Apache-2.0" description = "Pre-rasterized glyph bitmaps drawn into a pixel buffer, for ToyOS programs." @@ -11,3 +11,4 @@ repository = "https://github.com/ToyOSOrg/ToyOS" # citations are written in and no branch of this shape may edit. [lib] name = "font" +doctest = false diff --git a/userland/toyos-window/Cargo.toml b/userland/toyos-window/Cargo.toml index 7ba6c1b5275..0b9802d9a03 100644 --- a/userland/toyos-window/Cargo.toml +++ b/userland/toyos-window/Cargo.toml @@ -1,13 +1,13 @@ [package] name = "toyos-window" -version = "0.13.0" +version = "0.14.0" edition = "2021" license = "MIT OR Apache-2.0" description = "Client library for ToyOS windows: create one, draw into it, read its events." repository = "https://github.com/ToyOSOrg/ToyOS" [dependencies] -toyos-font = { path = "../toyos-font", version = "0.1.0" } +toyos-font = { path = "../toyos-font", version = "0.2.0" } toyos-abi = { path = "../../toyos-abi", version = "0.12.0" } toyos-keymap = { path = "../../toyos-keymap", version = "0.1.0" } toyos = { path = "../../toyos", version = "0.13.0" } @@ -16,3 +16,4 @@ toyos = { path = "../../toyos", version = "0.13.0" } # target keeps the name every caller spells, `toyos/src`'s citations included. [lib] name = "window" +doctest = false