Skip to main content

nativeview_codegen/abi/
policy.rs

1//! The one generic emitter of `nv_policy!` constants ([`nativeview_abi::policy`]) for every host
2//! language a policy's consumers read, plus the symbol names each consumer must read (shared with
3//! the `[INV:host-policy-single-source]` read check, so emitter and guard never disagree).
4//!
5//! Per policy `family` (`image-cache` → `ImageCache`) and constant `NAME` (`MAX_ITEMS`):
6//!
7//! | Language | File | Scalar | Table |
8//! |---|---|---|---|
9//! | C (C/C++/ObjC) | `nv_<family>_policy.generated.h` | `#define NV_NAME 16u` | `NV_NAME[NV_NAME_COUNT]` |
10//! | Swift | `Nv<Family>Policy.generated.swift` | `Nv<Family>Policy.maxItems` | `[Int]` |
11//! | Java | `io/github/nativeview/host/generated/Nv<Family>Policy.java` | `Nv<Family>Policy.NAME` | `maxItems(index)`, `NAME_COUNT` |
12//! | Kotlin | `Nv<Family>Policy.generated.kt` | `Nv<Family>Policy.NAME` | `List<Int>` |
13//!
14//! Java and Kotlin integers follow the Rust type, never the value: `u64` is `long` / `Long`,
15//! every other type (`usize` included, a size) is `int` / `Int` and must hold its value.
16//! | TypeScript | `nv_<family>_policy.generated.ts` | `Nv<Family>Policy.maxItems` | `readonly number[]` |
17//! | Dart | `nv_<family>_policy.generated.dart` | `Nv<Family>Policy.maxItems` | `List<int>` |
18
19use std::collections::{BTreeMap, BTreeSet};
20use std::fmt::Write as _;
21
22use nativeview_abi::policy::{Policy, PolicyConstant, PolicyHome, PolicyLang, PolicyValue};
23
24use super::spell::{camel, pascal};
25use crate::direct_specs::{ModuleLayout, ModuleLeaf};
26use crate::error::CodegenError;
27use crate::schema::export::GeneratedFile;
28
29/// A generated symbol a consumer must read: `NV_NAME` (C) or `Container.member`.
30#[derive(Clone, Debug, PartialEq, Eq)]
31pub struct PolicySymbol {
32    /// The Rust constant it renders.
33    pub constant: &'static str,
34    /// `Nv<Family>Policy` (absent for the global C macros).
35    pub container: Option<String>,
36    pub member: String,
37}
38
39/// `kebab-case` family → `snake_case`.
40fn snake(family: &str) -> String {
41    family.replace('-', "_")
42}
43
44/// `Nv<Family>Policy`.
45pub fn policy_container(policy: &Policy) -> String {
46    format!("Nv{}Policy", pascal(policy.family))
47}
48
49/// The symbols of `policy` a `lang` consumer must read, one per constant.
50pub fn policy_read_symbols(policy: &Policy, lang: PolicyLang) -> Vec<PolicySymbol> {
51    let container = policy_container(policy);
52    policy
53        .constants
54        .iter()
55        .map(|c| {
56            let table = matches!(c.value, PolicyValue::Table { .. });
57            let (container, member) = match lang {
58                PolicyLang::C => (None, format!("NV_{}", c.name)),
59                PolicyLang::Java if table => (Some(container.clone()), camel(c.name)),
60                PolicyLang::Java | PolicyLang::Kotlin => (Some(container.clone()), c.name.to_owned()),
61                PolicyLang::Swift | PolicyLang::TypeScript | PolicyLang::Dart => (Some(container.clone()), camel(c.name)),
62            };
63            PolicySymbol { constant: c.name, container, member }
64        })
65        .collect()
66}
67
68const UNSIGNED: &[&str] = &["u8", "u16", "u32", "u64", "usize"];
69
70/// The Rust type of a constant (a table's element type).
71fn rust_ty(c: &PolicyConstant) -> &'static str {
72    match c.value {
73        PolicyValue::Int { ty, .. } => ty,
74        PolicyValue::Table { elem, .. } => elem,
75    }
76}
77
78/// `u64` renders as a Java / Kotlin `long`; every other type as `int`.
79fn jvm_long(c: &PolicyConstant) -> bool {
80    rust_ty(c) == "u64"
81}
82
83/// The `NV_<NAME>` (and, for a table, `NV_<NAME>_COUNT`) names a constant renders in C; Java
84/// fields are the same names without the prefix.
85fn c_names(c: &PolicyConstant) -> Vec<String> {
86    let mut names = vec![format!("NV_{}", c.name)];
87    if matches!(c.value, PolicyValue::Table { .. }) {
88        names.push(format!("NV_{}_COUNT", c.name));
89    }
90    names
91}
92
93/// Values every target can represent: unsigned Rust types, tables of fixed-width elements, and
94/// magnitudes within the target's integer (Java / Kotlin `int`, TypeScript's 2^53).
95fn validate(policy: &Policy, langs: &[PolicyLang]) -> Result<(), CodegenError> {
96    let fail = |c: &PolicyConstant, why: &str| Err(CodegenError::validation(format!("nv_policy `{}` constant `{}`: {why}", policy.family, c.name)));
97    let kebab = policy.family.split('-').all(|w| !w.is_empty() && w.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit()));
98    if !kebab {
99        return Err(CodegenError::validation(format!("nv_policy family `{}` must be kebab-case", policy.family)));
100    }
101    if policy.constants.is_empty() || policy.consumers.is_empty() {
102        return Err(CodegenError::validation(format!("nv_policy `{}` needs constants and consumers", policy.family)));
103    }
104    for c in policy.constants {
105        let (ty, values): (&str, &[u64]) = match &c.value {
106            PolicyValue::Int { ty, value } => (ty, std::slice::from_ref(value)),
107            PolicyValue::Table { elem, values } => (elem, values),
108        };
109        if !UNSIGNED.contains(&ty) {
110            return fail(c, "policies are unsigned (u8 / u16 / u32 / u64 / usize)");
111        }
112        let max = values.iter().copied().max().unwrap_or(0);
113        if matches!(c.value, PolicyValue::Table { .. }) && ty == "usize" && langs.contains(&PolicyLang::C) {
114            return fail(c, "a C table needs a fixed-width element type, not usize");
115        }
116        let jvm = langs.iter().any(|l| matches!(l, PolicyLang::Java | PolicyLang::Kotlin));
117        if jvm && !jvm_long(c) && max > i32::MAX as u64 {
118            return fail(c, &format!("a `{ty}` renders as a Java / Kotlin `int` (<= i32::MAX); declare it `u64` for `long`"));
119        }
120        if langs.contains(&PolicyLang::TypeScript) && max > (1 << 53) {
121            return fail(c, "TypeScript numbers are exact only up to 2^53");
122        }
123        if max > i64::MAX as u64 {
124            return fail(c, "Swift / Kotlin / Dart integers are signed 64-bit");
125        }
126    }
127    Ok(())
128}
129
130/// The consumer languages of `policy`, deduplicated in [`PolicyLang::ALL`] order.
131pub fn policy_langs(policy: &Policy) -> Vec<PolicyLang> {
132    PolicyLang::ALL.into_iter().filter(|l| policy.consumers.iter().any(|c| c.lang == *l)).collect()
133}
134
135fn path(policy: &Policy, lang: PolicyLang, modules: &[ModuleLayout]) -> Result<String, CodegenError> {
136    let (snake, container) = (snake(policy.family), policy_container(policy));
137    let file = match lang {
138        PolicyLang::C => format!("nv_{snake}_policy.generated.h"),
139        PolicyLang::Swift => format!("{container}.generated.swift"),
140        PolicyLang::Java => format!("{container}.java"),
141        PolicyLang::Kotlin => format!("{container}.generated.kt"),
142        PolicyLang::TypeScript => format!("nv_{snake}_policy.generated.ts"),
143        PolicyLang::Dart => format!("nv_{snake}_policy.generated.dart"),
144    };
145    let unsupported = |home: &str| CodegenError::validation(format!("nv_policy `{}`: {home} has no {lang:?} runtime", policy.family));
146    let dir = match policy.home {
147        PolicyHome::Core => match lang {
148            PolicyLang::C => "packages/core/host-cxx/include/nv/generated".to_owned(),
149            PolicyLang::Swift => "packages/core/host-swift/Sources/NativeViewHost".to_owned(),
150            PolicyLang::Java => "packages/core/host-java/src/main/java/io/github/nativeview/host/generated".to_owned(),
151            PolicyLang::TypeScript => "packages/core/host-ts/src/generated".to_owned(),
152            PolicyLang::Dart => "packages/core/host-dart/lib/src/generated".to_owned(),
153            PolicyLang::Kotlin => return Err(unsupported("the core")),
154        },
155        PolicyHome::Module(cap) => {
156            let layout = modules.iter().find(|m| m.cap_dir == cap).ok_or_else(|| {
157                CodegenError::validation(format!(
158                    "nv_policy `{}`: module `{cap}` has no discovered `src/spec.rs` or `[package.metadata.nativeview]` manifest to locate its leaves",
159                    policy.family
160                ))
161            })?;
162            let leaf = match lang {
163                PolicyLang::C => ModuleLeaf::CxxInclude,
164                PolicyLang::Swift => ModuleLeaf::AppleSources,
165                PolicyLang::Java => ModuleLeaf::JavaGenerated,
166                PolicyLang::Kotlin => ModuleLeaf::KotlinSources,
167                PolicyLang::TypeScript => ModuleLeaf::WebTs,
168                PolicyLang::Dart => ModuleLeaf::DartLib,
169            };
170            layout.leaf_dir(leaf)?
171        }
172    };
173    Ok(format!("{dir}/{file}"))
174}
175
176fn doc_lines(doc: &str) -> impl Iterator<Item = &str> {
177    doc.lines().map(str::trim).filter(|l| !l.is_empty())
178}
179
180/// `doc` as `prefix`-led comment lines at `indent`.
181fn line_doc(out: &mut String, indent: &str, prefix: &str, doc: &str) {
182    for line in doc_lines(doc) {
183        let _ = writeln!(out, "{indent}{prefix} {line}");
184    }
185}
186
187/// `doc` as a `/* … */` (C) or `/** … */` (Kotlin / TypeScript) block at `indent`.
188fn block_doc(out: &mut String, indent: &str, open: &str, doc: &str) {
189    let _ = writeln!(out, "{indent}{open}");
190    for line in doc_lines(doc) {
191        let _ = writeln!(out, "{indent} * {}", crate::naming::sanitize_block_comment(line));
192    }
193    let _ = writeln!(out, "{indent} */");
194}
195
196/// `doc` as a Javadoc block: Markdown `code` spans become `{@code code}`, so `<` / `>` in them
197/// never read as HTML under doclint.
198fn javadoc(out: &mut String, indent: &str, doc: &str) {
199    let converted: String = doc.split('`').enumerate().map(|(i, part)| if i % 2 == 1 { format!("{{@code {part}}}") } else { part.to_owned() }).collect();
200    block_doc(out, indent, "/**", &converted);
201}
202
203fn list(values: &[u64]) -> String {
204    values.iter().map(u64::to_string).collect::<Vec<_>>().join(", ")
205}
206
207fn header(policy: &Policy) -> String {
208    format!("@generated by nativeview-codegen (abi/policy.rs) from nv_policy `{}`. DO NOT EDIT.", policy.family)
209}
210
211fn render_c(p: &Policy) -> String {
212    let guard = format!("NV_{}_POLICY_GENERATED_H", snake(p.family).to_ascii_uppercase());
213    let mut o = format!("/* {} */\n#ifndef {guard}\n#define {guard}\n\n", header(p));
214    if p.constants.iter().any(|c| matches!(c.value, PolicyValue::Table { .. })) {
215        o.push_str("#include <stdint.h>\n\n");
216    }
217    block_doc(&mut o, "", "/*", p.doc);
218    for c in p.constants {
219        o.push('\n');
220        block_doc(&mut o, "", "/*", c.doc);
221        match c.value {
222            PolicyValue::Int { value, .. } => {
223                let suffix = if value > u64::from(u32::MAX) { "ull" } else { "u" };
224                let _ = writeln!(o, "#define NV_{} {value}{suffix}", c.name);
225            }
226            PolicyValue::Table { elem, values } => {
227                let _ = writeln!(o, "#define NV_{}_COUNT {}u", c.name, values.len());
228                let _ = writeln!(o, "static const uint{}_t NV_{n}[NV_{n}_COUNT] = {{{}}};", &elem[1..], list(values), n = c.name);
229            }
230        }
231    }
232    let _ = write!(o, "\n#endif /* {guard} */\n");
233    o
234}
235
236fn render_swift(p: &Policy) -> String {
237    let mut o = format!("// {}\n\n", header(p));
238    line_doc(&mut o, "", "///", p.doc);
239    let _ = writeln!(o, "public enum {} {{", policy_container(p));
240    for c in p.constants {
241        line_doc(&mut o, "    ", "///", c.doc);
242        let _ = match c.value {
243            PolicyValue::Int { value, .. } => writeln!(o, "    public static let {}: Int = {value}", camel(c.name)),
244            PolicyValue::Table { values, .. } => writeln!(o, "    public static let {}: [Int] = [{}]", camel(c.name), list(values)),
245        };
246    }
247    o.push_str("}\n");
248    o
249}
250
251fn java_package_for(policy: &Policy, modules: &[ModuleLayout]) -> Result<String, CodegenError> {
252    match policy.home {
253        PolicyHome::Core => Ok("io.github.nativeview.host.generated".to_owned()),
254        PolicyHome::Module(cap) => {
255            let layout = modules.iter().find(|m| m.cap_dir == cap).ok_or_else(|| {
256                CodegenError::validation(format!(
257                    "nv_policy `{}`: module `{cap}` has no discovered `src/spec.rs` or `[package.metadata.nativeview]` manifest to locate its Java package",
258                    policy.family
259                ))
260            })?;
261            let pkg = layout.java_package.as_deref().ok_or_else(|| {
262                CodegenError::validation(format!(
263                    "nv_policy `{}`: module `{cap}` has no `[package.metadata.nativeview] java_package` for Java output",
264                    policy.family
265                ))
266            })?;
267            Ok(format!("{pkg}.generated"))
268        }
269    }
270}
271
272fn render_java(p: &Policy, package_name: &str) -> String {
273    let container = policy_container(p);
274    let mut o = format!("// {}\npackage {package_name};\n\n", header(p));
275    javadoc(&mut o, "", p.doc);
276    let _ = writeln!(o, "public final class {container} {{\n    private {container}() {{}}");
277    for c in p.constants {
278        o.push('\n');
279        let (ty, suffix) = if jvm_long(c) { ("long", "L") } else { ("int", "") };
280        match c.value {
281            PolicyValue::Int { value, .. } => {
282                javadoc(&mut o, "    ", c.doc);
283                let _ = writeln!(o, "    public static final {ty} {} = {value}{suffix};", c.name);
284            }
285            PolicyValue::Table { values, .. } => {
286                let _ = writeln!(o, "    private static final {ty}[] {} = {{{}}};", c.name, list(values));
287                let _ = writeln!(o, "    /** Number of entries of {{@link #{}(int)}}. */", camel(c.name));
288                let _ = writeln!(o, "    public static final int {}_COUNT = {};", c.name, values.len());
289                javadoc(&mut o, "    ", c.doc);
290                let _ = writeln!(o, "    public static {ty} {}(int index) {{\n        return {}[index];\n    }}", camel(c.name), c.name);
291            }
292        }
293    }
294    o.push_str("}\n");
295    o
296}
297
298fn render_kotlin(p: &Policy) -> String {
299    let mut o = format!("// {}\npackage io.github.nativeview.hybrid\n\n", header(p));
300    block_doc(&mut o, "", "/**", p.doc);
301    let _ = writeln!(o, "object {} {{", policy_container(p));
302    for c in p.constants {
303        block_doc(&mut o, "    ", "/**", c.doc);
304        let (ty, suffix) = if jvm_long(c) { ("Long", "L") } else { ("Int", "") };
305        let _ = match c.value {
306            PolicyValue::Int { value, .. } => writeln!(o, "    const val {}: {ty} = {value}{suffix}", c.name),
307            PolicyValue::Table { values, .. } => {
308                let items: Vec<String> = values.iter().map(|v| format!("{v}{suffix}")).collect();
309                writeln!(o, "    val {}: List<{ty}> = listOf({})", c.name, items.join(", "))
310            }
311        };
312    }
313    o.push_str("}\n");
314    o
315}
316
317fn render_ts(p: &Policy) -> String {
318    let mut o = format!("// {}\n\n", header(p));
319    block_doc(&mut o, "", "/**", p.doc);
320    let _ = writeln!(o, "export const {} = {{", policy_container(p));
321    for c in p.constants {
322        block_doc(&mut o, "  ", "/**", c.doc);
323        let _ = match c.value {
324            PolicyValue::Int { value, .. } => writeln!(o, "  {}: {value},", camel(c.name)),
325            PolicyValue::Table { values, .. } => writeln!(o, "  {}: [{}],", camel(c.name), list(values)),
326        };
327    }
328    o.push_str("} as const;\n");
329    o
330}
331
332fn render_dart(p: &Policy) -> String {
333    let mut o = format!("// {}\n\n", header(p));
334    line_doc(&mut o, "", "///", p.doc);
335    let _ = writeln!(o, "abstract final class {} {{", policy_container(p));
336    for c in p.constants {
337        line_doc(&mut o, "  ", "///", c.doc);
338        let _ = match c.value {
339            PolicyValue::Int { value, .. } => writeln!(o, "  static const int {} = {value};", camel(c.name)),
340            PolicyValue::Table { values, .. } => writeln!(o, "  static const List<int> {} = [{}];", camel(c.name), list(values)),
341        };
342    }
343    o.push_str("}\n");
344    o
345}
346
347/// Every consumer-language file of every policy; module-homed policies are located through the
348/// discovered [`ModuleLayout`]s (Direct-FFI `src/spec.rs` modules and `[package.metadata.nativeview]`
349/// table-only modules).
350pub fn generate_policy_files(policies: &[&Policy], modules: &[ModuleLayout]) -> Result<Vec<GeneratedFile>, CodegenError> {
351    let mut out = Vec::new();
352    // Global C macro names: the core ABI's, then every C-consuming policy's.
353    let mut c_owners: BTreeMap<String, String> =
354        nativeview_abi::schema::core_abi_descriptor().consts.iter().map(|c| (c.name.to_owned(), "nativeview_abi::CORE_CONSTS".to_owned())).collect();
355    for (i, p) in policies.iter().enumerate() {
356        if policies[..i].iter().any(|q| q.family == p.family) {
357            return Err(CodegenError::validation(format!("nv_policy family `{}` is registered twice", p.family)));
358        }
359        let langs = policy_langs(p);
360        validate(p, &langs)?;
361        let mut own = BTreeSet::new();
362        for name in p.constants.iter().flat_map(c_names) {
363            if !own.insert(name.clone()) {
364                return Err(CodegenError::validation(format!("nv_policy `{}`: `{name}` is declared twice (a constant and a table count?)", p.family)));
365            }
366            if langs.contains(&PolicyLang::C)
367                && let Some(owner) = c_owners.insert(name.clone(), format!("nv_policy `{}`", p.family))
368            {
369                return Err(CodegenError::validation(format!("nv_policy `{}`: C macro `{name}` collides with {owner}", p.family)));
370            }
371        }
372        for lang in langs {
373            let content = match lang {
374                PolicyLang::C => render_c(p),
375                PolicyLang::Swift => render_swift(p),
376                PolicyLang::Java => render_java(p, &java_package_for(p, modules)?),
377                PolicyLang::Kotlin => render_kotlin(p),
378                PolicyLang::TypeScript => render_ts(p),
379                PolicyLang::Dart => render_dart(p),
380            };
381            out.push(GeneratedFile { relative_path: path(p, lang, modules)?, content });
382        }
383    }
384    Ok(out)
385}
386
387#[cfg(test)]
388#[path = "policy_tests.rs"]
389mod tests;