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
//! The one generic emitter of `nv_policy!` constants ([`nativeview_abi::policy`]) for every host
//! language a policy's consumers read, plus the symbol names each consumer must read (shared with
//! the `[INV:host-policy-single-source]` read check, so emitter and guard never disagree).
//!
//! Per policy `family` (`image-cache` → `ImageCache`) and constant `NAME` (`MAX_ITEMS`):
//!
//! | Language | File | Scalar | Table |
//! |---|---|---|---|
//! | C (C/C++/ObjC) | `nv_<family>_policy.generated.h` | `#define NV_NAME 16u` | `NV_NAME[NV_NAME_COUNT]` |
//! | Swift | `Nv<Family>Policy.generated.swift` | `Nv<Family>Policy.maxItems` | `[Int]` |
//! | Java | `io/github/nativeview/host/generated/Nv<Family>Policy.java` | `Nv<Family>Policy.NAME` | `maxItems(index)`, `NAME_COUNT` |
//! | Kotlin | `Nv<Family>Policy.generated.kt` | `Nv<Family>Policy.NAME` | `List<Int>` |
//!
//! Java and Kotlin integers follow the Rust type, never the value: `u64` is `long` / `Long`,
//! every other type (`usize` included, a size) is `int` / `Int` and must hold its value.
//! | TypeScript | `nv_<family>_policy.generated.ts` | `Nv<Family>Policy.maxItems` | `readonly number[]` |
//! | Dart | `nv_<family>_policy.generated.dart` | `Nv<Family>Policy.maxItems` | `List<int>` |

use std::collections::{BTreeMap, BTreeSet};
use std::fmt::Write as _;

use nativeview_abi::policy::{Policy, PolicyConstant, PolicyHome, PolicyLang, PolicyValue};

use super::spell::{camel, pascal};
use crate::direct_specs::{ModuleLayout, ModuleLeaf};
use crate::error::CodegenError;
use crate::schema::export::GeneratedFile;

/// A generated symbol a consumer must read: `NV_NAME` (C) or `Container.member`.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PolicySymbol {
    /// The Rust constant it renders.
    pub constant: &'static str,
    /// `Nv<Family>Policy` (absent for the global C macros).
    pub container: Option<String>,
    pub member: String,
}

/// `kebab-case` family → `snake_case`.
fn snake(family: &str) -> String {
    family.replace('-', "_")
}

/// `Nv<Family>Policy`.
pub fn policy_container(policy: &Policy) -> String {
    format!("Nv{}Policy", pascal(policy.family))
}

/// The symbols of `policy` a `lang` consumer must read, one per constant.
pub fn policy_read_symbols(policy: &Policy, lang: PolicyLang) -> Vec<PolicySymbol> {
    let container = policy_container(policy);
    policy
        .constants
        .iter()
        .map(|c| {
            let table = matches!(c.value, PolicyValue::Table { .. });
            let (container, member) = match lang {
                PolicyLang::C => (None, format!("NV_{}", c.name)),
                PolicyLang::Java if table => (Some(container.clone()), camel(c.name)),
                PolicyLang::Java | PolicyLang::Kotlin => (Some(container.clone()), c.name.to_owned()),
                PolicyLang::Swift | PolicyLang::TypeScript | PolicyLang::Dart => (Some(container.clone()), camel(c.name)),
            };
            PolicySymbol { constant: c.name, container, member }
        })
        .collect()
}

const UNSIGNED: &[&str] = &["u8", "u16", "u32", "u64", "usize"];

/// The Rust type of a constant (a table's element type).
fn rust_ty(c: &PolicyConstant) -> &'static str {
    match c.value {
        PolicyValue::Int { ty, .. } => ty,
        PolicyValue::Table { elem, .. } => elem,
    }
}

/// `u64` renders as a Java / Kotlin `long`; every other type as `int`.
fn jvm_long(c: &PolicyConstant) -> bool {
    rust_ty(c) == "u64"
}

/// The `NV_<NAME>` (and, for a table, `NV_<NAME>_COUNT`) names a constant renders in C; Java
/// fields are the same names without the prefix.
fn c_names(c: &PolicyConstant) -> Vec<String> {
    let mut names = vec![format!("NV_{}", c.name)];
    if matches!(c.value, PolicyValue::Table { .. }) {
        names.push(format!("NV_{}_COUNT", c.name));
    }
    names
}

/// Values every target can represent: unsigned Rust types, tables of fixed-width elements, and
/// magnitudes within the target's integer (Java / Kotlin `int`, TypeScript's 2^53).
fn validate(policy: &Policy, langs: &[PolicyLang]) -> Result<(), CodegenError> {
    let fail = |c: &PolicyConstant, why: &str| Err(CodegenError::validation(format!("nv_policy `{}` constant `{}`: {why}", policy.family, c.name)));
    let kebab = policy.family.split('-').all(|w| !w.is_empty() && w.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit()));
    if !kebab {
        return Err(CodegenError::validation(format!("nv_policy family `{}` must be kebab-case", policy.family)));
    }
    if policy.constants.is_empty() || policy.consumers.is_empty() {
        return Err(CodegenError::validation(format!("nv_policy `{}` needs constants and consumers", policy.family)));
    }
    for c in policy.constants {
        let (ty, values): (&str, &[u64]) = match &c.value {
            PolicyValue::Int { ty, value } => (ty, std::slice::from_ref(value)),
            PolicyValue::Table { elem, values } => (elem, values),
        };
        if !UNSIGNED.contains(&ty) {
            return fail(c, "policies are unsigned (u8 / u16 / u32 / u64 / usize)");
        }
        let max = values.iter().copied().max().unwrap_or(0);
        if matches!(c.value, PolicyValue::Table { .. }) && ty == "usize" && langs.contains(&PolicyLang::C) {
            return fail(c, "a C table needs a fixed-width element type, not usize");
        }
        let jvm = langs.iter().any(|l| matches!(l, PolicyLang::Java | PolicyLang::Kotlin));
        if jvm && !jvm_long(c) && max > i32::MAX as u64 {
            return fail(c, &format!("a `{ty}` renders as a Java / Kotlin `int` (<= i32::MAX); declare it `u64` for `long`"));
        }
        if langs.contains(&PolicyLang::TypeScript) && max > (1 << 53) {
            return fail(c, "TypeScript numbers are exact only up to 2^53");
        }
        if max > i64::MAX as u64 {
            return fail(c, "Swift / Kotlin / Dart integers are signed 64-bit");
        }
    }
    Ok(())
}

/// The consumer languages of `policy`, deduplicated in [`PolicyLang::ALL`] order.
pub fn policy_langs(policy: &Policy) -> Vec<PolicyLang> {
    PolicyLang::ALL.into_iter().filter(|l| policy.consumers.iter().any(|c| c.lang == *l)).collect()
}

fn path(policy: &Policy, lang: PolicyLang, modules: &[ModuleLayout]) -> Result<String, CodegenError> {
    let (snake, container) = (snake(policy.family), policy_container(policy));
    let file = match lang {
        PolicyLang::C => format!("nv_{snake}_policy.generated.h"),
        PolicyLang::Swift => format!("{container}.generated.swift"),
        PolicyLang::Java => format!("{container}.java"),
        PolicyLang::Kotlin => format!("{container}.generated.kt"),
        PolicyLang::TypeScript => format!("nv_{snake}_policy.generated.ts"),
        PolicyLang::Dart => format!("nv_{snake}_policy.generated.dart"),
    };
    let unsupported = |home: &str| CodegenError::validation(format!("nv_policy `{}`: {home} has no {lang:?} runtime", policy.family));
    let dir = match policy.home {
        PolicyHome::Core => match lang {
            PolicyLang::C => "packages/core/host-cxx/include/nv/generated".to_owned(),
            PolicyLang::Swift => "packages/core/host-swift/Sources/NativeViewHost".to_owned(),
            PolicyLang::Java => "packages/core/host-java/src/main/java/io/github/nativeview/host/generated".to_owned(),
            PolicyLang::TypeScript => "packages/core/host-ts/src/generated".to_owned(),
            PolicyLang::Dart => "packages/core/host-dart/lib/src/generated".to_owned(),
            PolicyLang::Kotlin => return Err(unsupported("the core")),
        },
        PolicyHome::Module(cap) => {
            let layout = modules.iter().find(|m| m.cap_dir == cap).ok_or_else(|| {
                CodegenError::validation(format!(
                    "nv_policy `{}`: module `{cap}` has no discovered `src/spec.rs` or `[package.metadata.nativeview]` manifest to locate its leaves",
                    policy.family
                ))
            })?;
            let leaf = match lang {
                PolicyLang::C => ModuleLeaf::CxxInclude,
                PolicyLang::Swift => ModuleLeaf::AppleSources,
                PolicyLang::Java => ModuleLeaf::JavaGenerated,
                PolicyLang::Kotlin => ModuleLeaf::KotlinSources,
                PolicyLang::TypeScript => ModuleLeaf::WebTs,
                PolicyLang::Dart => ModuleLeaf::DartLib,
            };
            layout.leaf_dir(leaf)?
        }
    };
    Ok(format!("{dir}/{file}"))
}

fn doc_lines(doc: &str) -> impl Iterator<Item = &str> {
    doc.lines().map(str::trim).filter(|l| !l.is_empty())
}

/// `doc` as `prefix`-led comment lines at `indent`.
fn line_doc(out: &mut String, indent: &str, prefix: &str, doc: &str) {
    for line in doc_lines(doc) {
        let _ = writeln!(out, "{indent}{prefix} {line}");
    }
}

/// `doc` as a `/* … */` (C) or `/** … */` (Kotlin / TypeScript) block at `indent`.
fn block_doc(out: &mut String, indent: &str, open: &str, doc: &str) {
    let _ = writeln!(out, "{indent}{open}");
    for line in doc_lines(doc) {
        let _ = writeln!(out, "{indent} * {}", crate::naming::sanitize_block_comment(line));
    }
    let _ = writeln!(out, "{indent} */");
}

/// `doc` as a Javadoc block: Markdown `code` spans become `{@code code}`, so `<` / `>` in them
/// never read as HTML under doclint.
fn javadoc(out: &mut String, indent: &str, doc: &str) {
    let converted: String = doc.split('`').enumerate().map(|(i, part)| if i % 2 == 1 { format!("{{@code {part}}}") } else { part.to_owned() }).collect();
    block_doc(out, indent, "/**", &converted);
}

fn list(values: &[u64]) -> String {
    values.iter().map(u64::to_string).collect::<Vec<_>>().join(", ")
}

fn header(policy: &Policy) -> String {
    format!("@generated by nativeview-codegen (abi/policy.rs) from nv_policy `{}`. DO NOT EDIT.", policy.family)
}

fn render_c(p: &Policy) -> String {
    let guard = format!("NV_{}_POLICY_GENERATED_H", snake(p.family).to_ascii_uppercase());
    let mut o = format!("/* {} */\n#ifndef {guard}\n#define {guard}\n\n", header(p));
    if p.constants.iter().any(|c| matches!(c.value, PolicyValue::Table { .. })) {
        o.push_str("#include <stdint.h>\n\n");
    }
    block_doc(&mut o, "", "/*", p.doc);
    for c in p.constants {
        o.push('\n');
        block_doc(&mut o, "", "/*", c.doc);
        match c.value {
            PolicyValue::Int { value, .. } => {
                let suffix = if value > u64::from(u32::MAX) { "ull" } else { "u" };
                let _ = writeln!(o, "#define NV_{} {value}{suffix}", c.name);
            }
            PolicyValue::Table { elem, values } => {
                let _ = writeln!(o, "#define NV_{}_COUNT {}u", c.name, values.len());
                let _ = writeln!(o, "static const uint{}_t NV_{n}[NV_{n}_COUNT] = {{{}}};", &elem[1..], list(values), n = c.name);
            }
        }
    }
    let _ = write!(o, "\n#endif /* {guard} */\n");
    o
}

fn render_swift(p: &Policy) -> String {
    let mut o = format!("// {}\n\n", header(p));
    line_doc(&mut o, "", "///", p.doc);
    let _ = writeln!(o, "public enum {} {{", policy_container(p));
    for c in p.constants {
        line_doc(&mut o, "    ", "///", c.doc);
        let _ = match c.value {
            PolicyValue::Int { value, .. } => writeln!(o, "    public static let {}: Int = {value}", camel(c.name)),
            PolicyValue::Table { values, .. } => writeln!(o, "    public static let {}: [Int] = [{}]", camel(c.name), list(values)),
        };
    }
    o.push_str("}\n");
    o
}

fn java_package_for(policy: &Policy, modules: &[ModuleLayout]) -> Result<String, CodegenError> {
    match policy.home {
        PolicyHome::Core => Ok("io.github.nativeview.host.generated".to_owned()),
        PolicyHome::Module(cap) => {
            let layout = modules.iter().find(|m| m.cap_dir == cap).ok_or_else(|| {
                CodegenError::validation(format!(
                    "nv_policy `{}`: module `{cap}` has no discovered `src/spec.rs` or `[package.metadata.nativeview]` manifest to locate its Java package",
                    policy.family
                ))
            })?;
            let pkg = layout.java_package.as_deref().ok_or_else(|| {
                CodegenError::validation(format!(
                    "nv_policy `{}`: module `{cap}` has no `[package.metadata.nativeview] java_package` for Java output",
                    policy.family
                ))
            })?;
            Ok(format!("{pkg}.generated"))
        }
    }
}

fn render_java(p: &Policy, package_name: &str) -> String {
    let container = policy_container(p);
    let mut o = format!("// {}\npackage {package_name};\n\n", header(p));
    javadoc(&mut o, "", p.doc);
    let _ = writeln!(o, "public final class {container} {{\n    private {container}() {{}}");
    for c in p.constants {
        o.push('\n');
        let (ty, suffix) = if jvm_long(c) { ("long", "L") } else { ("int", "") };
        match c.value {
            PolicyValue::Int { value, .. } => {
                javadoc(&mut o, "    ", c.doc);
                let _ = writeln!(o, "    public static final {ty} {} = {value}{suffix};", c.name);
            }
            PolicyValue::Table { values, .. } => {
                let _ = writeln!(o, "    private static final {ty}[] {} = {{{}}};", c.name, list(values));
                let _ = writeln!(o, "    /** Number of entries of {{@link #{}(int)}}. */", camel(c.name));
                let _ = writeln!(o, "    public static final int {}_COUNT = {};", c.name, values.len());
                javadoc(&mut o, "    ", c.doc);
                let _ = writeln!(o, "    public static {ty} {}(int index) {{\n        return {}[index];\n    }}", camel(c.name), c.name);
            }
        }
    }
    o.push_str("}\n");
    o
}

fn render_kotlin(p: &Policy) -> String {
    let mut o = format!("// {}\npackage io.github.nativeview.hybrid\n\n", header(p));
    block_doc(&mut o, "", "/**", p.doc);
    let _ = writeln!(o, "object {} {{", policy_container(p));
    for c in p.constants {
        block_doc(&mut o, "    ", "/**", c.doc);
        let (ty, suffix) = if jvm_long(c) { ("Long", "L") } else { ("Int", "") };
        let _ = match c.value {
            PolicyValue::Int { value, .. } => writeln!(o, "    const val {}: {ty} = {value}{suffix}", c.name),
            PolicyValue::Table { values, .. } => {
                let items: Vec<String> = values.iter().map(|v| format!("{v}{suffix}")).collect();
                writeln!(o, "    val {}: List<{ty}> = listOf({})", c.name, items.join(", "))
            }
        };
    }
    o.push_str("}\n");
    o
}

fn render_ts(p: &Policy) -> String {
    let mut o = format!("// {}\n\n", header(p));
    block_doc(&mut o, "", "/**", p.doc);
    let _ = writeln!(o, "export const {} = {{", policy_container(p));
    for c in p.constants {
        block_doc(&mut o, "  ", "/**", c.doc);
        let _ = match c.value {
            PolicyValue::Int { value, .. } => writeln!(o, "  {}: {value},", camel(c.name)),
            PolicyValue::Table { values, .. } => writeln!(o, "  {}: [{}],", camel(c.name), list(values)),
        };
    }
    o.push_str("} as const;\n");
    o
}

fn render_dart(p: &Policy) -> String {
    let mut o = format!("// {}\n\n", header(p));
    line_doc(&mut o, "", "///", p.doc);
    let _ = writeln!(o, "abstract final class {} {{", policy_container(p));
    for c in p.constants {
        line_doc(&mut o, "  ", "///", c.doc);
        let _ = match c.value {
            PolicyValue::Int { value, .. } => writeln!(o, "  static const int {} = {value};", camel(c.name)),
            PolicyValue::Table { values, .. } => writeln!(o, "  static const List<int> {} = [{}];", camel(c.name), list(values)),
        };
    }
    o.push_str("}\n");
    o
}

/// Every consumer-language file of every policy; module-homed policies are located through the
/// discovered [`ModuleLayout`]s (Direct-FFI `src/spec.rs` modules and `[package.metadata.nativeview]`
/// table-only modules).
pub fn generate_policy_files(policies: &[&Policy], modules: &[ModuleLayout]) -> Result<Vec<GeneratedFile>, CodegenError> {
    let mut out = Vec::new();
    // Global C macro names: the core ABI's, then every C-consuming policy's.
    let mut c_owners: BTreeMap<String, String> =
        nativeview_abi::schema::core_abi_descriptor().consts.iter().map(|c| (c.name.to_owned(), "nativeview_abi::CORE_CONSTS".to_owned())).collect();
    for (i, p) in policies.iter().enumerate() {
        if policies[..i].iter().any(|q| q.family == p.family) {
            return Err(CodegenError::validation(format!("nv_policy family `{}` is registered twice", p.family)));
        }
        let langs = policy_langs(p);
        validate(p, &langs)?;
        let mut own = BTreeSet::new();
        for name in p.constants.iter().flat_map(c_names) {
            if !own.insert(name.clone()) {
                return Err(CodegenError::validation(format!("nv_policy `{}`: `{name}` is declared twice (a constant and a table count?)", p.family)));
            }
            if langs.contains(&PolicyLang::C)
                && let Some(owner) = c_owners.insert(name.clone(), format!("nv_policy `{}`", p.family))
            {
                return Err(CodegenError::validation(format!("nv_policy `{}`: C macro `{name}` collides with {owner}", p.family)));
            }
        }
        for lang in langs {
            let content = match lang {
                PolicyLang::C => render_c(p),
                PolicyLang::Swift => render_swift(p),
                PolicyLang::Java => render_java(p, &java_package_for(p, modules)?),
                PolicyLang::Kotlin => render_kotlin(p),
                PolicyLang::TypeScript => render_ts(p),
                PolicyLang::Dart => render_dart(p),
            };
            out.push(GeneratedFile { relative_path: path(p, lang, modules)?, content });
        }
    }
    Ok(out)
}

#[cfg(test)]
#[path = "policy_tests.rs"]
mod tests;