nativeview-codegen 0.1.0-rc.1

Multi-language ABI, policy, flat-op codec, and hybrid Direct-FFI code generator for Native View Engine.
Documentation
//! Tests for opt-in `surface_scoped = true` Direct-FFI codegen across all targets.

use nativeview_codegen::{generate_hybrid_all, parse_hybrid_rust_spec, HybridTarget};

/// Generated direct clients forward teardown to `DirectClientCore`, which canonicalizes the token
/// and drops the null surface once for every module.
const TEARDOWN_FORWARD: &str = "fn on_surface_teardown(&self, surface: nativeview_abi::SurfaceToken) { self.0.on_surface_teardown(surface); }";

const SPEC_PLAIN: &str = r#"
#[nativeview_hybrid_macros::nativeview_hybrid_spec]
pub mod probe {
    #[nv_hybrid_module(name = "Probe", binding = "direct", impl = "host", interface_id = 0x5501)]
    pub trait Probe {
        fn ping(&self, x: u32) -> Result<u32, NvModStatus>;
        async fn fetch(&self, key: &str) -> Result<String, NvModStatus>;
    }
}
"#;

const SPEC_EXPLICIT_FALSE: &str = r#"
#[nativeview_hybrid_macros::nativeview_hybrid_spec]
pub mod probe {
    #[nv_hybrid_module(name = "Probe", binding = "direct", impl = "host", interface_id = 0x5501, surface_scoped = false)]
    pub trait Probe {
        fn ping(&self, x: u32) -> Result<u32, NvModStatus>;
        async fn fetch(&self, key: &str) -> Result<String, NvModStatus>;
    }
}
"#;

const SPEC_SURFACE_SCOPED: &str = r#"
#[nativeview_hybrid_macros::nativeview_hybrid_spec]
pub mod probe {
    #[nv_hybrid_module(name = "Probe", binding = "direct", impl = "host", interface_id = 0x5501, surface_scoped = true)]
    pub trait Probe {
        fn ping(&self, x: u32) -> Result<u32, NvModStatus>;
        async fn fetch(&self, key: &str) -> Result<String, NvModStatus>;
    }
}
"#;

#[test]
fn surface_scoped_false_has_zero_overhead_and_matches_default() {
    let default_spec = parse_hybrid_rust_spec(SPEC_PLAIN).expect("parse plain");
    let false_spec = parse_hybrid_rust_spec(SPEC_EXPLICIT_FALSE).expect("parse explicit false");
    assert!(!default_spec.modules[0].surface_scoped);
    assert!(!false_spec.modules[0].surface_scoped);
    assert_eq!(
        default_spec.modules[0].schema_hash(&default_spec),
        false_spec.modules[0].schema_hash(&false_spec)
    );

    let default_outputs =
        generate_hybrid_all(&default_spec, HybridTarget::ALL).expect("generate plain");
    let false_outputs =
        generate_hybrid_all(&false_spec, HybridTarget::ALL).expect("generate false");
    let default_files: Vec<_> = default_outputs.iter().flat_map(|o| &o.files).collect();
    let false_files: Vec<_> = false_outputs.iter().flat_map(|o| &o.files).collect();
    assert_eq!(default_files.len(), false_files.len());
    for (a, b) in default_files.iter().zip(false_files.iter()) {
        assert_eq!(a.relative_path, b.relative_path);
        assert_eq!(a.content, b.content);
        assert!(
            !a.content.contains("on_surface_teardown"),
            "non-surface_scoped target {} must not mention on_surface_teardown",
            a.relative_path
        );
        assert!(
            !a.content.contains("onSurfaceTeardown"),
            "non-surface_scoped target {} must not mention onSurfaceTeardown",
            a.relative_path
        );
        assert!(
            !a.content.contains("NV_DIRECT_OPS_FLAG_SURFACE_SCOPED"),
            "non-surface_scoped target {} must not set surface-scoped flag",
            a.relative_path
        );
    }
}

#[test]
fn surface_scoped_true_emits_teardown_and_surface_forwarding_across_targets() {
    let plain_spec = parse_hybrid_rust_spec(SPEC_PLAIN).expect("parse plain");
    let scoped_spec = parse_hybrid_rust_spec(SPEC_SURFACE_SCOPED).expect("parse surface_scoped");
    assert!(scoped_spec.modules[0].surface_scoped);
    assert_ne!(
        plain_spec.modules[0].schema_hash(&plain_spec),
        scoped_spec.modules[0].schema_hash(&scoped_spec),
        "toggling surface_scoped must change schema_hash"
    );

    let outputs =
        generate_hybrid_all(&scoped_spec, HybridTarget::ALL).expect("generate surface_scoped");
    let files: Vec<_> = outputs.iter().flat_map(|o| &o.files).collect();
    let find = |suffix: &str| -> &str {
        &files
            .iter()
            .find(|f| f.relative_path.ends_with(suffix))
            .unwrap_or_else(|| panic!("missing generated file ending in {suffix}"))
            .content
    };

    let rust = find(".generated.rs");
    assert!(rust.contains("fn ping(&self, surface: nativeview_abi::SurfaceToken, x: u32)"));
    assert!(rust.contains("fn fetch(&self, surface: nativeview_abi::SurfaceToken, key: &str,"));
    assert!(rust.contains("fn on_surface_teardown(&self, _surface: nativeview_abi::SurfaceToken) {}"));
    assert!(rust.contains(
        "pub on_surface_teardown: ::core::option::Option<nativeview_abi::NvDirectSurfaceTeardownFn>"
    ));
    assert!(rust.contains("NV_DIRECT_OPS_FLAG_SURFACE_SCOPED"));
    assert!(rust.contains("impl DirectProbeClient"));
    // The canonicalize + null-surface guard is single-sourced in `DirectClientCore::on_surface_teardown`.
    assert!(rust.contains(TEARDOWN_FORWARD));
    assert!(rust.contains("self.0.call_async_on(surface.canonicalize(), move |_nv_st, _nv_payload|"));
    // The wire dispatcher signature is emitted on a single line.
    assert!(rust.contains("pub fn dispatch_probe_wire<B: super::ProbeBackend + ?Sized>(backend: &B, surface: nativeview_abi::SurfaceToken, method_id: u32,"));

    let c_hdr = find("HybridAbi.generated.h");
    assert!(c_hdr.contains("NvDirectSurfaceTeardownFn on_surface_teardown;"));
    assert!(c_hdr.contains("NV_DIRECT_OPS_FLAG_SURFACE_SCOPED"));
    let c_wire = find("HybridWire.generated.h");
    assert!(c_wire.contains("_nv_ops->reserved = NV_DIRECT_OPS_FLAG_SURFACE_SCOPED;"));

    let cpp_hdr = find(".generated.hpp");
    assert!(cpp_hdr.contains("virtual void onSurfaceTeardown(NvSurfaceToken /*surface*/) noexcept {}"));
    assert!(cpp_hdr.contains("ops_.on_surface_teardown = &thunk_on_surface_teardown;"));

    let swift = find(".generated.swift");
    assert!(swift.contains("func onSurfaceTeardown(surface: NvSurfaceToken)"));
    assert!(swift.contains("NV_DIRECT_OPS_FLAG_SURFACE_SCOPED"));

    let kt = find(".generated.kt");
    assert!(kt.contains("fun onSurfaceTeardown(surfaceToken: Long) {}"));

    let jni = find(".generated.cpp");
    assert!(jni.contains("thunk_on_surface_teardown"));
    assert!(jni.contains("NV_DIRECT_OPS_FLAG_SURFACE_SCOPED"));

    let dart = find(".generated.dart");
    assert!(dart.contains("void onSurfaceTeardown(NvSurfaceToken surface) {}"));
    assert!(dart.contains("nvDirectOpsFlagSurfaceScoped"));
    assert!(dart.contains("if (_closed || surface.surfaceId == 0) return;"));
    assert!(dart.contains("NativeCallable.listener"));

    let ts = find(".generated.ts");
    assert!(ts.contains("onSurfaceTeardown?(surfaceToken: bigint): void;"));
}

#[test]
fn surface_scoped_true_rejected_on_rust_impl_or_vtable_binding() {
    let rust_impl = r#"
#[nativeview_hybrid_macros::nativeview_hybrid_spec]
pub mod bad_rust {
    #[nv_hybrid_module(name = "BadRust", binding = "direct", impl = "rust", surface_scoped = true)]
    pub trait BadRust {
        fn ping(&self) -> u32;
    }
}
"#;
    assert!(
        parse_hybrid_rust_spec(rust_impl).is_err(),
        "surface_scoped = true must be rejected for impl = \"rust\""
    );

    let vtable_binding = r#"
#[nativeview_hybrid_macros::nativeview_hybrid_spec]
pub mod bad_vtable {
    #[nv_hybrid_module(name = "BadVtable", binding = "vtable", impl = "host", surface_scoped = true)]
    pub trait BadVtable {
        fn ping(&self) -> u32;
    }
}
"#;
    assert!(
        parse_hybrid_rust_spec(vtable_binding).is_err(),
        "surface_scoped = true must be rejected for binding = \"vtable\""
    );
}

#[test]
fn surface_scoped_true_supports_batchable_modules_across_all_targets() {
    let spec_src = r#"
#[nativeview_hybrid_macros::nativeview_hybrid_spec]
pub mod batch_scoped {
    #[nv_hybrid_module(name = "BatchScoped", binding = "direct", impl = "host", interface_id = 0x5502, surface_scoped = true)]
    #[batchable]
    pub trait BatchScoped {
        fn set_flag(&self, id: u32, on: bool) -> Result<(), NvModStatus>;
        fn get_flag(&self, id: u32) -> Result<bool, NvModStatus>;
    }
}
"#;
    let spec = parse_hybrid_rust_spec(spec_src).expect("parse batchable surface_scoped");
    assert!(spec.modules[0].surface_scoped);
    assert!(spec.modules[0].has_batchable());

    let outputs =
        generate_hybrid_all(&spec, HybridTarget::ALL).expect("generate batchable surface_scoped");
    let files: Vec<_> = outputs.iter().flat_map(|o| &o.files).collect();
    let find = |suffix: &str| -> &str {
        &files
            .iter()
            .find(|f| f.relative_path.ends_with(suffix))
            .unwrap_or_else(|| panic!("missing generated file ending in {suffix}"))
            .content
    };

    let rust = find(".generated.rs");
    assert!(rust.contains("fn on_surface_teardown(&self, _surface: nativeview_abi::SurfaceToken) {}"));
    assert!(rust.contains("fn execute_batch(&self, surface: nativeview_abi::SurfaceToken, cmds: &[u8]"));
    assert!(rust.contains("default_execute_batch_scoped_batch(self, surface, cmds"));
    assert!(rust.contains(
        "offset_of!(NvModBatchScopedHostOps, on_surface_teardown) == 24 + ::core::mem::size_of::<*const ::core::ffi::c_void>()"
    ));
    // host_ctx (1) + on_surface_teardown (1) + 2 methods = slot index 4 for submit_batch.
    assert!(rust.contains(
        "offset_of!(NvModBatchScopedHostOps, submit_batch) == 24 + 4 * ::core::mem::size_of::<*const ::core::ffi::c_void>()"
    ));
    assert!(rust.contains("NV_DIRECT_OPS_FLAG_SURFACE_SCOPED"));

    let c_hdr = find("HybridAbi.generated.h");
    assert!(c_hdr.contains("NvDirectSurfaceTeardownFn on_surface_teardown;"));
    assert!(c_hdr.contains("submit_batch"));

    let cpp_hdr = find(".generated.hpp");
    assert!(cpp_hdr.contains("virtual void onSurfaceTeardown(NvSurfaceToken /*surface*/) noexcept {}"));
    assert!(cpp_hdr.contains("ops_.on_surface_teardown = &thunk_on_surface_teardown;"));
    assert!(cpp_hdr.contains("ops_.submit_batch = &thunk_submit_batch;"));
}

#[test]
fn surface_scoped_true_supports_async_only_modules_across_all_targets() {
    let spec_src = r#"
#[nativeview_hybrid_macros::nativeview_hybrid_spec]
pub mod async_scoped {
    #[nv_hybrid_module(name = "AsyncScoped", binding = "direct", impl = "host", interface_id = 0x5503, surface_scoped = true)]
    pub trait AsyncScoped {
        async fn open(&self, name: &str) -> Result<u32, NvModStatus>;
    }
}
"#;
    let spec = parse_hybrid_rust_spec(spec_src).expect("parse async-only surface_scoped");
    assert!(spec.modules[0].surface_scoped);

    let outputs =
        generate_hybrid_all(&spec, HybridTarget::ALL).expect("generate async-only surface_scoped");
    let files: Vec<_> = outputs.iter().flat_map(|o| &o.files).collect();
    let find = |suffix: &str| -> &str {
        &files
            .iter()
            .find(|f| f.relative_path.ends_with(suffix))
            .unwrap_or_else(|| panic!("missing generated file ending in {suffix}"))
            .content
    };

    let rust = find(".generated.rs");
    assert!(!rust.contains("pub trait AsyncScopedBackend"));
    assert!(rust.contains("pub trait AsyncScopedAsyncBackend"));
    assert!(rust.contains("fn on_surface_teardown(&self, _surface: nativeview_abi::SurfaceToken) {}"));
    assert!(rust.contains(
        "nativeview_abi::run_boxed_async_teardown::<B>(_nv_host_ctx, _nv_surface, <B as AsyncScopedAsyncBackend>::on_surface_teardown)"
    ));
    assert!(rust.contains(TEARDOWN_FORWARD));
    assert!(rust.contains("self.0.call_async_on(surface.canonicalize(), move |_nv_st, _nv_payload|"));
    assert!(rust.contains("NV_DIRECT_OPS_FLAG_SURFACE_SCOPED"));

    let dart = find(".generated.dart");
    assert!(dart.contains("void onSurfaceTeardown(NvSurfaceToken surface) {}"));
    assert!(dart.contains("if (_closed || surface.surfaceId == 0) return;"));
}