mod common;
use nativeview_abi::table::{FieldKind, TableDesc};
use nativeview_codegen::{
CodegenError, GeneratedFile, generate_abi_files, generate_all_abi_files, generate_c_abi_header,
generate_hash_vector_files, generate_table_files,
};
use nativeview_tables::tables::CORE_TABLE_DESCS;
use common::table_desc::{field, table};
fn all_files() -> Vec<GeneratedFile> {
generate_all_abi_files(CORE_TABLE_DESCS).expect("generate every host ABI file")
}
#[test]
fn generation_is_deterministic_lf_only_and_lands_in_the_host_packages() {
let first = all_files();
let second = all_files();
assert_eq!(
first, second,
"ABI codegen must be byte-for-byte deterministic"
);
assert_eq!(first.len(), 27);
for f in &first {
assert!(
!f.content.contains('\r'),
"{} contains a carriage return",
f.relative_path
);
assert!(
f.content.ends_with('\n'),
"{} must end with a newline",
f.relative_path
);
assert!(
!f.content.contains(" \n"),
"{} has trailing spaces",
f.relative_path
);
assert!(
["cxx", "swift", "java", "dart", "ts"].iter().any(|h| f
.relative_path
.starts_with(&format!("packages/core/host-{h}/"))),
"{} must land next to its static runtime",
f.relative_path
);
}
let update = std::env::var("NV_UPDATE_ABI").is_ok();
common::assert_generated_file_naming_and_optional_disk_parity(
&first,
&common::workspace_root(),
update,
);
}
fn collect_template_files(dir: &std::path::Path, out: &mut Vec<std::path::PathBuf>) {
for entry in std::fs::read_dir(dir).expect("read template dir").flatten() {
let name = entry.file_name();
if name.to_string_lossy().starts_with('.') {
continue;
}
let path = entry.path();
if path.is_dir() {
collect_template_files(&path, out);
} else {
out.push(path);
}
}
}
#[test]
fn templates_are_lf_only_and_under_650_lines() {
let dir = common::workspace_root().join("packages/core/codegen/templates");
let mut files = Vec::new();
collect_template_files(&dir, &mut files);
for path in &files {
let text = std::fs::read_to_string(path).expect("read template");
assert!(
!text.contains('\r'),
"{} contains a carriage return",
path.display()
);
assert!(
text.lines().count() < 650,
"{} has 650+ lines",
path.display()
);
}
assert_eq!(files.len(), 60, "one template per generated file");
}
#[test]
fn golden_hash_vectors_come_from_nv_hash() {
let c = generate_hash_vector_files().expect("vectors").remove(0);
assert!(c.relative_path.ends_with("hash_vectors.generated.h"));
let expected = nativeview_hash::xxh64(b"nv.visual", 0);
assert!(c.content.contains(&format!("\"nv.visual\", \"6e762e76697375616c\", UINT64_C(0x0000000000000000), UINT64_C(0x{expected:016X})")));
assert_eq!(c.content.matches("UINT64_C(").count(), 2 * 19);
let empty = nativeview_hash::xxh64(b"", 0);
assert!(c.content.contains(&format!(
"{{\"empty\", \"\", UINT64_C(0x0000000000000000), UINT64_C(0x{empty:016X})}}"
)));
}
#[test]
fn c_headers_carry_their_schema_hashes_and_no_hand_written_layout_cases() {
let h = generate_c_abi_header().expect("C header");
assert!(h.contains(&format!(
"#define NV_CORE_ABI_SCHEMA_HASH 0x{:016X}ULL",
nativeview_abi::NV_CORE_ABI_SCHEMA_HASH
)));
assert!(h.contains("sizeof(NvEvent) == 64u"));
assert!(h.contains("offsetof(NvEvent, bytes) == 56u"));
assert!(h.contains("sizeof(NvEventBatch) == (sizeof(void*) == 8u ? 24u : 16u)"));
assert!(h.contains(&format!(
"#define NV_TABLE_CUSTOM 0x{:016X}ULL",
nativeview_abi::NV_TABLE_CUSTOM.0
)));
assert!(!h.contains("struct NvDirectEvent {"));
assert!(h.contains("NvDirectOpsHeader"));
assert!(h.contains("NvDirectEventSink"));
assert!(h.contains("NvDirectHostEnv"));
assert!(h.contains("sizeof(NvValue) == (sizeof(void*) == 8u ? 24u : (NV_ABI_U64_FIELD_ALIGN == 8u ? 16u : 12u))"));
assert!(h.contains("offsetof(NvTableView, row_index_pages) == (sizeof(void*) == 8u ? 80u : 60u)"));
assert!(h.contains("#include \"../host/api.h\""));
let files = generate_abi_files().expect("abi");
assert_eq!(files[0].content, h);
let rt = &files[1].content;
assert!(rt.contains(&format!(
"#define NV_RUNTIME_SCHEMA_HASH 0x{:016X}ULL",
nativeview_abi::NV_RUNTIME_SCHEMA_HASH
)));
assert!(!rt.contains("NvTableCommand"));
assert!(rt.contains("offsetof(NvSceneView, rows) == 72u"));
assert!(rt.contains("offsetof(NvSceneView, tables) == (sizeof(void*) == 8u ? 120u : 96u)"));
}
fn try_table_error(t: &TableDesc) -> Result<String, String> {
match generate_table_files(&[t]) {
Err(CodegenError::Validation(msg)) => Ok(msg),
other => Err(format!("expected a validation error, got {other:?}")),
}
}
#[test]
fn table_specs_are_validated_before_any_host_sees_them() {
let table_error = |t: &TableDesc| try_table_error(t).expect("validation error");
static OK: TableDesc = table(
"nv.test",
&[0, 0, 0],
&[
field("title", FieldKind::Str, 0, 0, 64),
field("flag", FieldKind::Bool, 2, 31, 1),
],
);
let files = generate_table_files(&[&OK]).expect("valid table");
assert!(
files[0]
.content
.contains("NV_TABLE_TEST_TITLE = { 0u, 0u, 32u, NV_FIELD_STR, NV_OPT_REQUIRED, 0xFFu, 0xFFu, 0u }")
);
assert!(
files[0]
.content
.contains("NV_TABLE_TEST_FLAG = { 2u, 31u, 1u, NV_FIELD_BOOL, NV_OPT_REQUIRED, 0xFFu, 0xFFu, 0u }")
);
static STR_PAST_END: TableDesc = table(
"nv.test",
&[0, 0, 0],
&[field("s", FieldKind::Str, 2, 0, 64)],
);
assert!(table_error(&STR_PAST_END).contains("field `s` does not fit its row"));
static BITS_PAST_WORD: TableDesc = table(
"nv.test",
&[0, 0, 0],
&[field("b", FieldKind::U32, 0, 30, 4)],
);
assert!(table_error(&BITS_PAST_WORD).contains("field `b` does not fit its row"));
static ZERO_BITS: TableDesc = table(
"nv.test",
&[0, 0, 0],
&[field("z", FieldKind::Enum, 0, 0, 0)],
);
assert!(table_error(&ZERO_BITS).contains("field `z`"));
static SHIFTED_STR: TableDesc = table(
"nv.test",
&[0, 0, 0],
&[field("s", FieldKind::Str, 0, 8, 64)],
);
assert!(table_error(&SHIFTED_STR).contains("field `s`"));
let mut wrong_key = table("nv.test", &[0, 0, 0], &[]);
wrong_key.key = nativeview_hash::Key64::of("nv.other");
assert!(table_error(&wrong_key).contains("key is not `xxh64(name)`"));
let mut bad_effects = table("nv.test", &[0, 0, 0], &[]);
bad_effects.word_effects = &[0];
assert!(table_error(&bad_effects).contains("word count"));
assert!(
matches!(generate_table_files(&[&OK, &OK]), Err(CodegenError::Validation(m)) if m.contains("duplicate"))
);
let dart_mod = nativeview_codegen::generate_dart_module_table_file(
"NvTestTables",
"nvTestTables",
&[&OK],
&[],
&[],
"packages/modules/test/dart/lib/src/nv_test_tables.generated.dart".into(),
)
.expect("dart per-module tables");
assert_eq!(
dart_mod.relative_path,
"packages/modules/test/dart/lib/src/nv_test_tables.generated.dart"
);
assert!(!dart_mod.content.contains('\r'));
assert!(dart_mod.content.ends_with('\n'));
assert!(dart_mod.content.contains("import 'package:nativeview_host/nativeview_host.dart' show FieldKind, FieldSpec, Key64, NvTableInfo, OptEncoding;"));
assert!(dart_mod.content.contains("final List<NvTableInfo> nvTestTables ="));
assert!(dart_mod.content.contains("abstract final class NvTestTables {"));
assert!(dart_mod.content.contains("abstract final class TestTable {"));
assert!(!dart_mod.content.contains("final class NvTableInfo {"));
}
#[test]
fn top_layer_vectors_spell_every_float_and_reject_unescapable_text() {
use nativeview_codegen::abi::top_layer_vectors::F;
use nativeview_codegen::{PressVector, TopLayerVectors, generate_top_layer_vector_files};
assert_eq!(F(50.0).c(), "50.0f");
assert_eq!(F(f32::NAN).java(), "Float.NaN");
assert_eq!(F(f32::NEG_INFINITY).swift(), "-Float.infinity");
assert_eq!(F(f32::INFINITY).dart(), "double.infinity");
assert_eq!(F(f32::NAN).ts(), "NaN");
let case = |name: &'static str| PressVector {
name,
tree: 0,
overlays: vec![nativeview_abi::NvOverlayItem { node_id: nativeview_abi::NodeId::new(3, 0), width: 1.0, height: 1.0, backdrop_color: 0xFF00_0000, ..Default::default() }],
x: f32::NAN,
y: 0.0,
hit: nativeview_abi::NodeId::NULL,
topmost_modal: nativeview_abi::NodeId::NULL,
outcome: "LightDismiss".into(),
modal_barrier: false,
until: nativeview_abi::NodeId::new(3, 0),
dismissed: vec![nativeview_abi::NodeId::new(3, 0)],
};
let ok = TopLayerVectors { trees: vec![vec![(nativeview_abi::NodeId::new(1, 0), nativeview_abi::NodeId::NULL), (nativeview_abi::NodeId::new(3, 0), nativeview_abi::NodeId::new(1, 0))]], press: vec![case("outside")], close_keys: vec![("Escape", true)] };
let files = generate_top_layer_vector_files(&ok).expect("renders");
assert_eq!(files.len(), 5);
assert!(files.iter().all(|f| f.relative_path.contains("top_layer_vectors.generated.") || f.relative_path.ends_with("TopLayerVectors.generated.swift") || f.relative_path.ends_with("generated/TopLayerVectors.java")));
assert!(files[2].content.contains("OverlaySlab.PRESS_LIGHT_DISMISS") && files[2].content.contains("0xFF000000"));
assert!(files[1].content.contains("outcome: .lightDismiss") && files[0].content.contains("PressOutcome::LightDismiss"));
let quoted = TopLayerVectors { press: vec![case("it's")], ..ok.clone() };
assert!(generate_top_layer_vector_files("ed).is_err(), "a quote would break the string literals");
let dangling = TopLayerVectors { trees: vec![], ..ok.clone() };
assert!(generate_top_layer_vector_files(&dangling).is_err(), "a case naming a missing tree");
let key = TopLayerVectors { close_keys: vec![("Esc\\", false)], ..ok };
assert!(generate_top_layer_vector_files(&key).is_err(), "a backslash key needs escaping");
}
#[test]
fn direct_spec_java_package_propagates_and_policy_java_fails_closed() {
use nativeview_abi::policy::{PolicyConsumer, PolicyHome, PolicyLang};
use nativeview_codegen::direct_specs::{
discover_direct_specs, discover_module_layouts_in, ModuleLeaf,
};
use nativeview_codegen::generate_policy_files;
let root = std::env::temp_dir().join(format!("nv_direct_spec_java_pkg_{}", std::process::id()));
let _ = std::fs::remove_dir_all(&root);
let spec_src = "\
#[nativeview_hybrid_macros::nativeview_hybrid_spec(namespace = \"linking\")]\n\
pub mod ffi {\n\
#[nv_hybrid_module(name = \"Linking\", binding = \"direct\", impl = \"host\", interface_id = 0x2010)]\n\
pub trait LinkingSpec {\n\
fn ping(&self) -> Result<bool, NvModStatus>;\n\
}\n\
}\n\
pub use ffi::*;\n";
let mod_dir = root.join("packages/modules/linking");
std::fs::create_dir_all(mod_dir.join("src")).expect("mkdir");
std::fs::write(mod_dir.join("src/spec.rs"), spec_src).expect("spec");
std::fs::write(
mod_dir.join("Cargo.toml"),
"[package]\nname = \"nativeview-linking\"\n\n[package.metadata.nativeview]\nswift_target = \"NativeViewLinkingApple\"\njava_package = \"io.github.nativeview.linking\"\n",
)
.expect("manifest");
let specs = discover_direct_specs(&root).expect("discover with java_package");
assert_eq!(specs.len(), 1);
assert_eq!(specs[0].java_package.as_deref(), Some("io.github.nativeview.linking"));
assert_eq!(specs[0].layout().java_package.as_deref(), Some("io.github.nativeview.linking"));
assert_eq!(
specs[0].leaf_dir(ModuleLeaf::JavaGenerated).unwrap(),
"packages/modules/linking/android/src/main/java/io/github/nativeview/linking/generated"
);
assert_eq!(
specs[0].leaf_dir(ModuleLeaf::JavaGenerated).unwrap(),
specs[0].layout().leaf_dir(ModuleLeaf::JavaGenerated).unwrap()
);
nativeview_abi::nv_policy! {
pub policy LINK_JAVA = "link-java" in PolicyHome::Module("linking"), consumers [
PolicyConsumer { lang: PolicyLang::Java, path: "packages/modules/linking/android/src/main/java/" },
];
pub const MAX_LINKS: usize = 16;
}
let layouts = discover_module_layouts_in(&[root.as_path()], &specs).expect("layouts");
let files = generate_policy_files(&[&LINK_JAVA], &layouts).expect("render module Java policy");
assert_eq!(files.len(), 1);
assert_eq!(
files[0].relative_path,
"packages/modules/linking/android/src/main/java/io/github/nativeview/linking/generated/NvLinkJavaPolicy.java"
);
assert!(files[0].content.contains("package io.github.nativeview.linking.generated;\n"));
std::fs::write(
mod_dir.join("Cargo.toml"),
"[package]\nname = \"nativeview-linking\"\n\n[package.metadata.nativeview]\nswift_target = \"NativeViewLinkingApple\"\n",
)
.expect("manifest without java_package");
let specs_no_pkg = discover_direct_specs(&root).expect("discover without java_package");
assert_eq!(specs_no_pkg[0].java_package, None);
assert!(specs_no_pkg[0].leaf_dir(ModuleLeaf::JavaGenerated).is_err());
let layouts_no_pkg = discover_module_layouts_in(&[root.as_path()], &specs_no_pkg).expect("layouts");
let err = generate_policy_files(&[&LINK_JAVA], &layouts_no_pkg)
.expect_err("module Java policy without java_package must fail closed")
.to_string();
assert!(err.contains("java_package"), "{err}");
std::fs::write(
mod_dir.join("Cargo.toml"),
"[package]\nname = \"nativeview-linking\"\n\n[package.metadata.nativeview]\nswift_target = \"NativeViewLinkingApple\"\njava_package = \"io.github.nativeview..bad\"\n",
)
.expect("manifest with invalid java_package");
let bad_err = discover_direct_specs(&root).expect_err("invalid java_package").to_string();
assert!(bad_err.contains("java_package"), "{bad_err}");
let _ = std::fs::remove_dir_all(&root);
}