//! The header is GENERATED and COMMITTED, and this is the guard that makes the //! two unable to drift silently. //! //! It runs cbindgen over `src/ffi.rs` exactly as the committed file was //! produced, and compares BYTES. Regenerate with: //! //! ```sh //! pnpm gen:ffi //! ``` //! //! Why cbindgen is a dev-dependency and not an installed CLI: the check then //! runs wherever `cargo test` does, with no second tool to provision on a //! runner. This test IS the guard, whole; `pnpm gen:ffi:check` is how it runs. use std::path::{Path, PathBuf}; /// Where the committed header lives. fn header_path() -> PathBuf { crate_dir().join("include").join("cotton_ffi.h") } fn crate_dir() -> PathBuf { cotton_store::manifest_dir() } /// Generate the header exactly as the committed one was produced. fn generate() -> String { let dir = crate_dir(); let bindings = cbindgen::Builder::new() // `with_src`, not `with_crate`: parsing the ONE file that declares the // ABI needs no `cargo metadata`, which keeps the generator hermetic and // its output a pure function of that file plus the config. .with_src(dir.join("src").join("ffi.rs")) .with_config( cbindgen::Config::from_file(dir.join("cbindgen.toml")).expect("cbindgen.toml is read"), ) .generate() .expect("the header generates"); let mut rendered: Vec = Vec::new(); bindings.write(&mut rendered); String::from_utf8(rendered).expect("cbindgen writes UTF-8") } /// The six, in the order the design names them. const FUNCTIONS: [&str; 6] = [ "cotton_open", "cotton_close", "cotton_call", "cotton_subscribe", "cotton_version", "cotton_string_free", ]; #[test] fn the_committed_header_is_what_the_generator_writes_today() { let path = header_path(); let generated = generate(); // `COTTON_FFI_WRITE_HEADER=1 cargo test -p cotton-ffi` rewrites it; that is // what the `gen:ffi` script runs. if std::env::var("COTTON_FFI_WRITE_HEADER").is_ok() { std::fs::create_dir_all(path.parent().expect("a parent")).expect("the include directory"); std::fs::write(&path, &generated).expect("the header is written"); return; } let committed = std::fs::read_to_string(&path).unwrap_or_else(|error| { panic!( "the committed header at {} could not be read ({error}) — run `pnpm gen:ffi`", path.display() ) }); assert_eq!( committed, generated, "{} has drifted from src/ffi.rs — run `pnpm gen:ffi`", path.display() ); } #[test] fn the_header_declares_the_six_functions_and_the_opaque_handle() { let header = std::fs::read_to_string(header_path()).expect("the committed header"); for name in FUNCTIONS { assert!(header.contains(name), "{name} is missing from the header"); } assert!( header.contains("typedef struct CottonHandle CottonHandle;"), "the handle must stay opaque to C" ); } /// RULE: The bridge between the host app and the core is six functions and no seventh; every capability is a method name inside one of them. #[test] fn the_source_exports_exactly_those_six_and_no_seventh() { let source = std::fs::read_to_string(crate_dir().join("src").join("ffi.rs")) .expect("src/ffi.rs is readable"); let exported: Vec = source .lines() // Five of the six take a raw pointer and are `unsafe` for it; only // `cotton_version` is not. .filter_map(|line| { let line = line.trim(); line.strip_prefix("pub unsafe extern \"C\" fn ") .or_else(|| line.strip_prefix("pub extern \"C\" fn ")) }) .map(|rest| { rest.split('(') .next() .expect("a name before the parenthesis") .to_string() }) .collect(); assert_eq!( exported, FUNCTIONS.map(String::from).to_vec(), "the ABI is six functions and stays six (design M1) — a new capability is a method name inside cotton_call" ); } /// Read a module map that a lane other than this one owns. /// /// `None` means the file is genuinely not in this checkout — a Rust-only tree /// has no Swift app — and that is the only reason this test may pass without /// asserting anything. /// /// **Except on CI**, which always has the whole repo. There, an absent file is /// the failure this guard exists for: the module map moved and this reader went /// quiet rather than red, which is exactly what happened to the phone's /// byte-equality guard in #332. So `CI` turns the escape hatch off and the /// missing path is named in the panic. fn other_lanes_module_map(relative: &str) -> Option<(std::path::PathBuf, String)> { let path = crate_dir().join(relative); match path.canonicalize() { Ok(path) => { let text = std::fs::read_to_string(&path).expect("the module map is readable"); Some((path, text)) } Err(error) => { assert!( std::env::var_os("CI").is_none(), "{} is not in this checkout ({error}). On CI the whole repo is present, so a \ missing module map means it MOVED and this guard stopped guarding — follow it \ and fix the path here.", path.display() ); None } } } #[test] fn the_header_is_where_the_xcframework_script_stages_it_from() { // Since H2 no Swift file names this header by path: the ONE module map // says `header "cotton_ffi.h"` and `scripts/build-xcframework.sh` copies the // committed header beside it on every run. So the reader of this file BY // PATH is the script, and a guard that reads another lane's file by path // goes quiet, not red, when that file moves — the path is asserted here, // in the lane that owns the header. (Before H2 this asserted that the Mac's // own module map named the committed path; that module map is gone.) // A Rust-only checkout is not a failure, but a PRESENT script that stopped // naming the header is — and on CI an ABSENT one is a failure too. let Some((script, text)) = other_lanes_module_map("../../scripts/build-xcframework.sh") else { return; }; let header = "cotton-ffi/include/cotton_ffi.h"; assert!( text.contains(header), "{} must stage {header} into the XCFramework's headers directory", Path::new(&script).display() ); assert!( text.contains("Sources/CottonFFI/module.modulemap"), "{} must stage the ONE module map beside the header", Path::new(&script).display() ); } #[test] fn the_iphone_app_has_its_own_module_map_over_the_same_header() { // The iPhone links the SAME six functions through the SAME header (design // P1), but as an XCFramework — which takes a HEADERS DIRECTORY, so its // module map names `cotton_ffi.h` beside itself rather than the committed // path the Mac's names. `scripts/build-xcframework.sh` stages both files // from their one source on every run, which is what keeps that from being // a second declaration of the ABI. // // Asserted HERE, in the lane that owns the header, for the reason the Mac's // is: a guard that reads another package's file by path goes quiet, not // red, when that file moves. let Some((module_map, text)) = other_lanes_module_map("../../apps/cotton/Sources/CottonFFI/module.modulemap") else { return; }; assert!( text.contains("module CottonFFI") && text.contains("header \"cotton_ffi.h\""), "{} must declare `module CottonFFI` over `cotton_ffi.h` — the name the XCFramework \ carries beside it", Path::new(&module_map).display() ); }