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
//! Shared helpers for exporting `#[nv_hybrid_view]` specs across all 6 target frameworks.

use crate::error::CodegenError;
use crate::naming::{
    kotlin_package_segment, strip_on_prefix, to_camel_case, to_pascal_case, to_snake_case,
};

/// Crate-level snake_case library stem shared by all views in `file` (`lib<stem>.so`,
/// `<stem>_web.js`), ensuring multi-view specs load from one compiled crate binary while
/// differentiating views by `vtable_symbol` / `componentName`.
pub fn export_lib_stem(file: &HybridFileSpec) -> String {
    file.stem_snake()
}

/// Canonical React Native `codegenConfig.name` and `<react/renderer/components/<name>/*.h>`
/// header directory shared across `package.json` and generated ObjC++ Fabric ComponentViews.
pub fn rn_codegen_spec_name(file: &HybridFileSpec) -> String {
    format!("{}Spec", file.stem_pascal())
}

/// C anchor function exported by `<Mod>Anchor`'s `NvExportAnchor.m` in `nitro-ui-pkg` that
/// resolves each view's `<vtable_symbol>` from its isolated `<Mod>Core.framework` via
/// `dlopen(RTLD_LOCAL)` + `dlsym`.
pub fn nitro_ios_anchor_fn(view_name: &str) -> String {
    format!("nv_export_interface_{}", to_snake_case(view_name))
}

/// Default Apple module name derived from `file.stem_pascal()`, avoiding double `NvNv` prefixes.
pub(crate) fn default_ios_module_name(file: &HybridFileSpec) -> String {
    let stem_pascal = file.stem_pascal();
    if stem_pascal.is_empty() {
        "NvComponent".to_owned()
    } else if stem_pascal.starts_with("Nv") {
        stem_pascal
    } else {
        format!("Nv{stem_pascal}")
    }
}

/// Dynamic iOS `.framework` / `.xcframework` bundle name for an exported component (`<Mod>Core`),
/// keeping the dynamic Rust binary distinct from the CocoaPods/SwiftPM wrapper module `<Mod>`.
pub fn ios_core_framework_name(ios_module_name: &str) -> String {
    format!("{ios_module_name}Core")
}

/// Kotlin-safe `package` header name preserving segment underscores/casing while backtick-escaping
/// reserved Kotlin keywords.
pub(crate) fn android_package_kotlin(file: &HybridFileSpec) -> String {
    file.android_package()
        .split('.')
        .map(kotlin_package_segment)
        .collect::<Vec<_>>()
        .join(".")
}
use crate::schema::hybrid::{HybridFileSpec, HybridType, HybridViewSpec};

/// Validates a spec file for single-view export.
pub(crate) fn validate_export_view(
    file: &HybridFileSpec,
    view: &HybridViewSpec,
) -> Result<(), CodegenError> {
    file.validate()?;
    if view.name.trim().is_empty() {
        return Err(CodegenError::validation("HybridViewSpec.name must not be empty"));
    }
    Ok(())
}

/// Idiomatic camelCase callback name for a view event (`on_count_change` / `count_change` ->
/// `onCountChange`, `select` -> `onSelect`).
pub(crate) fn event_handler_name(raw: &str) -> String {
    let stripped = strip_on_prefix(raw);
    if stripped.is_empty() {
        return to_camel_case(raw);
    }
    format!("on{}", to_pascal_case(&stripped))
}

/// PascalCase stem of an event name without a leading `on` (`on_count_change` -> `CountChange`).
pub(crate) fn event_stem_pascal(raw: &str) -> String {
    let stripped = strip_on_prefix(raw);
    if stripped.is_empty() {
        to_pascal_case(raw)
    } else {
        to_pascal_case(&stripped)
    }
}

/// Deduplicated wire names an event dispatcher matches against `nv.custom` event names:
/// the declared spec name, the `on`-stripped form, and the camelCase handler name.
pub(crate) fn event_wire_aliases(raw: &str) -> Vec<String> {
    let mut out = Vec::with_capacity(3);
    let mut push = |candidate: String| {
        if !candidate.is_empty() && !out.contains(&candidate) {
            out.push(candidate);
        }
    };
    push(raw.to_owned());
    push(strip_on_prefix(raw));
    push(event_handler_name(raw));
    out
}

/// Resolves the integer discriminant of `EnumName::Variant` in `file`.
pub(crate) fn resolve_enum_discriminant(
    file: &HybridFileSpec,
    enum_name: &str,
    variant: &str,
) -> Option<i64> {
    file.find_enum(enum_name)?
        .variants
        .iter()
        .find(|v| v.name == variant)
        .map(|v| v.value)
}

/// Recursively tests whether `pred` holds for `ty` or any nested container/option type.
pub(crate) fn type_matches(ty: &HybridType, pred: fn(&HybridType) -> bool) -> bool {
    if pred(ty) {
        return true;
    }
    match ty {
        HybridType::Optional(inner)
        | HybridType::Vec(inner)
        | HybridType::FixedArray { elem: inner, .. } => type_matches(inner, pred),
        HybridType::Result { ok, .. } => type_matches(ok, pred),
        _ => false,
    }
}

/// Tests whether `pred` matches any prop, event param, method param, or transitive struct field
/// of `view`.
pub(crate) fn view_type_matches(
    file: &HybridFileSpec,
    view: &HybridViewSpec,
    pred: fn(&HybridType) -> bool,
) -> bool {
    let (_enums, structs) = view.referenced_types(file);
    view.props.iter().any(|p| type_matches(&p.ty, pred))
        || view
            .events
            .iter()
            .any(|e| e.params.iter().any(|p| type_matches(&p.ty, pred)))
        || view
            .methods
            .iter()
            .any(|m| m.params.iter().any(|p| type_matches(&p.ty, pred)))
        || structs
            .iter()
            .any(|s| s.fields.iter().any(|f| type_matches(&f.ty, pred)))
}