Skip to main content

nativeview_codegen/abi/
tables.rs

1//! The word-table view-model every host table mirror renders: per-table metadata (inheritance,
2//! `EventSet` word), per-field host specs (kind, `Option` encoding, wide value word, explicit
3//! bit, resource kind), and the named value sets, all validated once so every host constructor
4//! accepts them.
5
6use std::collections::BTreeSet;
7
8use nativeview_abi::table::{
9    FieldDesc, FieldKind, MAX_TABLE_WORDS, NO_VAL_WORD, OptEncoding, Storage, TableDesc,
10    ValueSetDesc, table_flags,
11};
12use nativeview_hash::Key64;
13
14use super::model::U64Split;
15use crate::error::CodegenError;
16
17/// 0-based event discriminants and listener bitmasks derived from `TableDesc::events`
18/// (`EventEnum::EVENT_SET`), where every `(name, bit)` has `bit == 1 << id`.
19#[derive(Debug)]
20pub struct EventEnumModel {
21    /// Event enum name, e.g. `TextInputEvent` (derived by stripping `"Set"` from `"TextInputEventSet"`).
22    pub name: String,
23    /// `SCREAMING_SNAKE` prefix, e.g. `TEXT_INPUT_EVENT`.
24    pub screaming: String,
25    /// `(variant_name, event_id, bit_mask)` in declaration order (`bit_mask == 1 << event_id`).
26    pub variants: Vec<(&'static str, u32, u32)>,
27}
28
29/// One word table, validated once so every host constructor accepts its field specs.
30#[derive(Debug)]
31pub struct TableModel<'a> {
32    pub desc: &'a TableDesc,
33    /// `nv.text_input` -> `TextInput` (hosts nest it under `NvTables`).
34    pub ident: String,
35    /// `nv.text_input` -> `TEXT_INPUT` (C macro / Java constant prefix).
36    pub screaming: String,
37    pub key: U64Split,
38    pub schema: U64Split,
39    pub fields: Vec<FieldModel<'a>>,
40    pub event_enum: Option<EventEnumModel>,
41}
42
43impl TableModel<'_> {
44    pub fn dense(&self) -> bool {
45        self.desc.storage == Storage::Dense
46    }
47
48    /// Word of the `EventSet<E>` listener mask, or [`NO_VAL_WORD`].
49    pub fn events_word(&self) -> u8 {
50        self.desc.events_word
51    }
52
53    /// Word 0 is the explicit-override mask (`#[nv_table(inherited)]`).
54    pub fn inherited(&self) -> bool {
55        self.desc.inherited
56    }
57
58    /// Resource fields with their `FlatResource::KIND`.
59    pub fn resource_fields(&self) -> impl Iterator<Item = (&FieldModel<'_>, U64Split)> {
60        self.fields.iter().filter_map(|f| f.resource_kind.map(|k| (f, k)))
61    }
62}
63
64/// One field as every host `FieldSpec` spells it.
65#[derive(Debug)]
66pub struct FieldModel<'a> {
67    pub desc: &'a FieldDesc,
68    /// Host bit width: a two-word field (`Str`, 64-bit) is `bits = 64` in Rust but `(shift 0,
69    /// bits 32)` on every host (the second word is implied by the kind).
70    pub bits: u8,
71    /// `OptEncoding::WideBit` value word (`word` / `shift` hold the presence bit), else
72    /// [`NO_VAL_WORD`].
73    pub val_word: u8,
74    /// Bit of the field in an inherited table's explicit mask (word 0), else [`NO_VAL_WORD`].
75    pub explicit_bit: u8,
76    /// An unset value resolves from the parent row (inherited table, not `#[no_inherit]`).
77    pub inherits: bool,
78    /// `FlatResource::KIND` of a `Resource` field.
79    pub resource_kind: Option<U64Split>,
80}
81
82impl FieldModel<'_> {
83    pub fn name(&self) -> &str {
84        self.desc.name
85    }
86}
87
88/// Fields spanning two whole words (`{ offset, len }` / `lo, hi`).
89fn two_word(k: FieldKind) -> bool {
90    matches!(k, FieldKind::Str | FieldKind::U64 | FieldKind::I64 | FieldKind::F64)
91}
92
93/// Validates `tables` (unique names, keys that match their names, fields every host reader
94/// accepts) and wraps them for rendering, in the given order.
95pub fn tables_model<'a>(tables: &[&'a TableDesc]) -> Result<Vec<TableModel<'a>>, CodegenError> {
96    let mut names = BTreeSet::new();
97    let mut out = Vec::with_capacity(tables.len());
98    for desc in tables {
99        super::validate::table(desc)?;
100        let short = desc.name.strip_prefix("nv.").unwrap_or(desc.name);
101        let ident = super::spell::pascal(short);
102        if !names.insert(ident.clone()) {
103            return Err(table_error(desc, "duplicate table name"));
104        }
105        if desc.key != Key64::of(desc.name) {
106            return Err(table_error(desc, "key is not `xxh64(name)`"));
107        }
108        let words = desc.words();
109        if words == 0 || words > MAX_TABLE_WORDS || desc.word_effects.len() != words {
110            return Err(table_error(desc, "word count out of range"));
111        }
112        check_table_words(desc, words)?;
113        let fields = desc
114            .fields
115            .iter()
116            .enumerate()
117            .map(|(i, f)| field_model(desc, i, f, words))
118            .collect::<Result<Vec<_>, _>>()?;
119        let event_enum = desc.events.map(|set| event_enum_model(desc, set)).transpose()?;
120        out.push(TableModel {
121            desc,
122            screaming: short.replace('.', "_").to_ascii_uppercase(),
123            ident,
124            key: U64Split::new(desc.key.0),
125            schema: U64Split::new(desc.schema_hash),
126            fields,
127            event_enum,
128        });
129    }
130    Ok(out)
131}
132
133fn is_ident(s: &str) -> bool {
134    s.chars().next().is_some_and(|c| c.is_ascii_alphabetic())
135        && s.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
136}
137
138fn event_enum_model(desc: &TableDesc, set: &'static ValueSetDesc) -> Result<EventEnumModel, CodegenError> {
139    if set.values.is_empty() {
140        return Err(table_error(desc, "the `EventSet` must have at least one variant"));
141    }
142    let stripped = set
143        .name
144        .strip_suffix("Set")
145        .filter(|s| !s.is_empty())
146        .unwrap_or(set.name);
147    // Avoid `NvNvFooEvent` / `NV_NV_FOO_EVENT` when an `EventSet` already carries an `Nv` prefix.
148    let name = stripped
149        .strip_prefix("Nv")
150        .filter(|s| s.chars().next().is_some_and(|c| c.is_ascii_uppercase()))
151        .unwrap_or(stripped)
152        .to_owned();
153    if !is_ident(&name) {
154        return Err(table_error(desc, &format!("invalid `EventSet` enum name `{name}`")));
155    }
156    let mut variants = Vec::with_capacity(set.values.len());
157    let (mut seen_bits, mut seen_screaming, mut seen_swift, mut seen_dart) =
158        (BTreeSet::new(), BTreeSet::new(), BTreeSet::new(), BTreeSet::new());
159    for &(variant, bit) in set.values {
160        if !is_ident(variant) {
161            return Err(table_error(desc, &format!("invalid event variant name `{variant}`")));
162        }
163        if !bit.is_power_of_two() {
164            return Err(table_error(
165                desc,
166                &format!("event `{variant}` mask `{bit}` is not a single bit"),
167            ));
168        }
169        if !seen_bits.insert(bit) {
170            return Err(table_error(
171                desc,
172                &format!("duplicate event bit mask {bit} (`{variant}`)"),
173            ));
174        }
175        if !seen_screaming.insert(super::spell::screaming(variant)) {
176            return Err(table_error(
177                desc,
178                &format!("duplicate event variant name `{variant}`"),
179            ));
180        }
181        if !seen_swift.insert(super::spell::swift::variant(variant))
182            || !seen_dart.insert(super::spell::dart::variant(variant))
183        {
184            return Err(table_error(
185                desc,
186                &format!("event variant `{variant}` collides with another variant once escaped"),
187            ));
188        }
189        variants.push((variant, bit.trailing_zeros(), bit));
190    }
191    let screaming = super::spell::screaming(&name);
192    Ok(EventEnumModel { name, screaming, variants })
193}
194
195/// The hidden words (explicit mask, `EventSet`) agree with the table flags and stay field-free.
196fn check_table_words(desc: &TableDesc, words: usize) -> Result<(), CodegenError> {
197    let flag = |bit: u16| desc.flags & bit != 0;
198    if flag(table_flags::INHERITED) != desc.inherited {
199        return Err(table_error(desc, "`inherited` disagrees with `table_flags::INHERITED`"));
200    }
201    let has_events = desc.events_word != NO_VAL_WORD;
202    if flag(table_flags::HAS_EVENTS) != has_events || desc.events.is_some() != has_events {
203        return Err(table_error(
204            desc,
205            "`events_word`, `events`, and `table_flags::HAS_EVENTS` disagree",
206        ));
207    }
208    if has_events && (usize::from(desc.events_word) >= words || desc.inherited) {
209        return Err(table_error(desc, "the `EventSet` word is out of range or shares word 0"));
210    }
211    if desc.events.is_some_and(|set| !set.flags) {
212        return Err(table_error(desc, "the `EventSet` values must be a flag set"));
213    }
214    if desc.inherited && desc.fields.len() > 32 {
215        return Err(table_error(desc, "an inherited table holds at most 32 fields"));
216    }
217    Ok(())
218}
219
220fn field_model<'a>(
221    desc: &TableDesc,
222    index: usize,
223    f: &'a FieldDesc,
224    words: usize,
225) -> Result<FieldModel<'a>, CodegenError> {
226    let bad = |why: &str| Err(table_error(desc, &format!("field `{}` {why}", f.name)));
227    let (span, shape_ok) = if two_word(f.kind) {
228        (2, f.shift == 0 && f.bits == 64)
229    } else {
230        (1, (1..=32).contains(&f.bits) && u32::from(f.shift) + u32::from(f.bits) <= 32)
231    };
232    if !shape_ok || usize::from(f.word) + span > words {
233        return bad("does not fit its row");
234    }
235    let wide = f.opt_encoding == OptEncoding::WideBit;
236    if wide != (f.val_word != NO_VAL_WORD)
237        || wide && (f.bits != 1 || usize::from(f.val_word) >= words || f.val_word == f.word)
238    {
239        return bad("has a value word that disagrees with its `Option` encoding");
240    }
241    let hidden = [desc.inherited.then_some(0), (desc.events_word != NO_VAL_WORD).then_some(desc.events_word)];
242    let touched = f.word..f.word + span as u8;
243    if hidden.into_iter().flatten().any(|w| touched.contains(&w) || wide && w == f.val_word) {
244        return bad("overlaps the explicit-mask or `EventSet` word");
245    }
246    if f.no_inherit && !desc.inherited {
247        return bad("is `#[no_inherit]` on a table that does not inherit");
248    }
249    let resource_kind = match (f.kind, desc.resource_kind(usize::from(f.word))) {
250        (FieldKind::Resource, Some(kind)) => Some(U64Split::new(kind.0)),
251        (FieldKind::Resource, None) => return bad("has no `FlatResource::KIND`"),
252        _ => None,
253    };
254    Ok(FieldModel {
255        desc: f,
256        bits: if two_word(f.kind) { 32 } else { f.bits },
257        val_word: f.val_word,
258        explicit_bit: if desc.inherited { index as u8 } else { NO_VAL_WORD },
259        inherits: desc.inherited && !f.no_inherit,
260        resource_kind,
261    })
262}
263
264/// Distinct named value sets (`WordEnum` variants, flag bits, `EventSet` listener bits) the
265/// `tables` carry, in first-use order. Sets sharing a name must be identical; names must spell
266/// identifiers, every emitted `NV_<SET>_<VALUE>` constant must be unique across all sets and
267/// clear of the `NV_TABLE_*` namespace, and every value must fit its field once encoded.
268pub fn value_sets(tables: &[TableModel<'_>]) -> Result<Vec<&'static ValueSetDesc>, CodegenError> {
269    value_sets_with_core(tables, &[], true)
270}
271
272/// Like [`value_sets`], validating `tables` against already-emitted `shared_sets` (core
273/// `NvTables` value sets plus any registered cross-module shared value sets, e.g. `nativeview-media-fit`).
274///
275/// Any value set whose name matches an entry in `shared_sets` MUST have an identical definition
276/// (otherwise validation fails with `"defined twice differently"`). When `omit_shared` is `true`
277/// (Swift, Dart, Java, TypeScript), shared sets are omitted from the returned list so they are
278/// defined once in their owning module/core; when `false` (standalone C/C++ module headers using
279/// `#ifndef`), they are retained so standalone inclusion stays self-contained. Every field
280/// carrying a shared set is still checked for bit-width fit, and new module sets are checked for
281/// constant collisions against `shared_sets`.
282pub fn value_sets_with_core(
283    tables: &[TableModel<'_>],
284    shared_sets: &[&'static ValueSetDesc],
285    omit_shared: bool,
286) -> Result<Vec<&'static ValueSetDesc>, CodegenError> {
287    let mut out: Vec<&'static ValueSetDesc> = Vec::new();
288    let mut constants = BTreeSet::new();
289    for shared in shared_sets {
290        let prefix = super::spell::screaming(shared.name);
291        for &(name, _) in shared.values {
292            constants.insert(format!("{prefix}_{}", super::spell::screaming(name)));
293        }
294    }
295    for t in tables {
296        let fields = t.desc.fields.iter().filter_map(|f| f.values.map(|set| (set, Some(f))));
297        for (set, field) in t.desc.events.map(|set| (set, None)).into_iter().chain(fields) {
298            let fail = |why: String| table_error(t.desc, &format!("value set `{}`: {why}", set.name));
299            // Every field that carries the set must hold every value, also when the set was
300            // already emitted for a wider field.
301            if let Some(f) = field
302                && let Some(&(name, _)) = set.values.iter().find(|&&(_, v)| !fits(f, v))
303            {
304                return Err(fail(format!("value `{name}` exceeds field `{}`", f.name)));
305            }
306            if let Some(shared) = shared_sets.iter().find(|s| s.name == set.name) {
307                if *shared != set {
308                    return Err(fail("defined twice differently".into()));
309                }
310                if !omit_shared && out.iter().all(|s| s.name != set.name) {
311                    out.push(set);
312                }
313                continue;
314            }
315            if let Some(seen) = out.iter().find(|s| s.name == set.name) {
316                if *seen != set {
317                    return Err(fail("defined twice differently".into()));
318                }
319                continue;
320            }
321            check_set(set, &mut constants).map_err(fail)?;
322            out.push(set);
323        }
324    }
325    Ok(out)
326}
327
328/// Validates and deduplicates standalone shared value sets (such as `nativeview-media-fit`'s `ImageFit`
329/// and `ImageSampling`), rejecting empty/invalid names, duplicate constant spellings, or
330/// conflicting redefinitions.
331pub fn validate_shared_value_sets(
332    sets: &[&'static ValueSetDesc],
333) -> Result<Vec<&'static ValueSetDesc>, CodegenError> {
334    let mut out: Vec<&'static ValueSetDesc> = Vec::with_capacity(sets.len());
335    let mut constants = BTreeSet::new();
336    for &set in sets {
337        let fail = |why: String| CodegenError::validation(format!("shared value set `{}`: {why}", set.name));
338        if let Some(seen) = out.iter().find(|s| s.name == set.name) {
339            if *seen != set {
340                return Err(fail("defined twice differently".into()));
341            }
342            continue;
343        }
344        check_set(set, &mut constants).map_err(fail)?;
345        out.push(set);
346    }
347    Ok(out)
348}
349
350/// Merges core table value sets with registered cross-module shared value sets, allowing exact
351/// identical definitions during transitions and rejecting conflicting definitions or C constant
352/// collisions.
353pub fn merge_shared_value_sets(
354    core_sets: &[&'static ValueSetDesc],
355    extra_shared: &[&'static ValueSetDesc],
356) -> Result<Vec<&'static ValueSetDesc>, CodegenError> {
357    let mut merged: Vec<&'static ValueSetDesc> = Vec::with_capacity(core_sets.len() + extra_shared.len());
358    merged.extend_from_slice(core_sets);
359    merged.extend_from_slice(extra_shared);
360    validate_shared_value_sets(&merged)
361}
362
363/// `v` stored with `f`'s `Option` encoding fits `f.bits` (a wide value word holds any `u32`).
364fn fits(f: &FieldDesc, v: u32) -> bool {
365    let stored = match f.opt_encoding {
366        OptEncoding::PlusOne => u64::from(v) + 1,
367        OptEncoding::Bit0Present => (u64::from(v) << 1) | 1,
368        OptEncoding::WideBit => return true,
369        OptEncoding::Required | OptEncoding::ZeroNiche | OptEncoding::TagXor => u64::from(v),
370    };
371    f.bits >= 32 || stored >> f.bits == 0
372}
373
374/// A set's name and member spellings are identifiers unique after each host's escaping, its
375/// values are distinct (single bits for a flag set), and its `NV_<SET>_<VALUE>` constants are
376/// new.
377fn check_set(set: &ValueSetDesc, constants: &mut BTreeSet<String>) -> Result<(), String> {
378    let prefix = super::spell::screaming(set.name);
379    if !is_ident(set.name) || set.values.is_empty() || prefix == "TABLE" || prefix.starts_with("TABLE_") {
380        return Err("needs an identifier name outside `TABLE*` and at least one value".into());
381    }
382    // Per-set member spellings each host renders (keyword-escaped), and the values: a collision
383    // after escaping or a repeated value would not compile (Swift raw values) or would alias two
384    // members.
385    let (mut swift, mut dart, mut values) = (BTreeSet::new(), BTreeSet::new(), BTreeSet::new());
386    for &(name, value) in set.values {
387        let constant = format!("{prefix}_{}", super::spell::screaming(name));
388        if !is_ident(name) || !constants.insert(constant.clone()) {
389            return Err(format!("bad or duplicate name `{name}` (NV_{constant})"));
390        }
391        if !swift.insert(super::spell::swift::variant(name)) || !dart.insert(super::spell::dart::variant(name)) {
392            return Err(format!("name `{name}` collides with another member once escaped"));
393        }
394        if !values.insert(value) {
395            return Err(format!("duplicate value {value} (`{name}`)"));
396        }
397        if set.flags && !value.is_power_of_two() {
398            return Err(format!("flag `{name}` is not a single bit"));
399        }
400    }
401    Ok(())
402}
403
404pub(super) fn table_error(desc: &TableDesc, why: &str) -> CodegenError {
405    CodegenError::validation(format!("table `{}`: {why}", desc.name))
406}
407
408/// `FieldKind` as spelled by each host runtime's enum.
409pub mod kind {
410    use nativeview_abi::table::FieldKind;
411
412    /// `(kind, C, Swift / Dart, TypeScript, Java)`.
413    type Row = (FieldKind, &'static str, &'static str, &'static str, &'static str);
414
415    const NAMES: [Row; 14] = [
416        (FieldKind::U32, "NV_FIELD_U32", "u32", "U32", "U32"),
417        (FieldKind::I32, "NV_FIELD_I32", "i32", "I32", "I32"),
418        (FieldKind::F32, "NV_FIELD_F32", "f32", "F32", "F32"),
419        (FieldKind::Bool, "NV_FIELD_BOOL", "bool", "Bool", "BOOL"),
420        (FieldKind::Enum, "NV_FIELD_ENUM", "enumeration", "Enum", "ENUM"),
421        (FieldKind::Color, "NV_FIELD_COLOR", "color", "Color", "COLOR"),
422        (FieldKind::Length, "NV_FIELD_LENGTH", "length", "Length", "LENGTH"),
423        (FieldKind::Str, "NV_FIELD_STR", "str", "Str", "STR"),
424        (FieldKind::Resource, "NV_FIELD_RESOURCE", "resource", "Resource", "RESOURCE"),
425        (FieldKind::Node, "NV_FIELD_NODE", "node", "Node", "NODE"),
426        (FieldKind::U64, "NV_FIELD_U64", "u64", "U64", "U64"),
427        (FieldKind::I64, "NV_FIELD_I64", "i64", "I64", "I64"),
428        (FieldKind::F64, "NV_FIELD_F64", "f64", "F64", "F64"),
429        (FieldKind::GridLine, "NV_FIELD_GRID_LINE", "gridLine", "GridLine", "GRID_LINE"),
430    ];
431
432    fn row(k: FieldKind) -> Row {
433        NAMES[k as usize]
434    }
435
436    /// C `NvFieldKind` constant.
437    pub fn c(k: &FieldKind) -> &'static str {
438        row(*k).1
439    }
440
441    /// Swift `FieldKind` case.
442    pub fn swift(k: &FieldKind) -> &'static str {
443        row(*k).2
444    }
445
446    /// Java `FieldKind` constant.
447    pub fn java(k: &FieldKind) -> &'static str {
448        row(*k).4
449    }
450
451    /// Dart `FieldKind` value (`bool` is a keyword there).
452    pub fn dart(k: &FieldKind) -> &'static str {
453        match k {
454            FieldKind::Bool => "boolean",
455            _ => row(*k).2,
456        }
457    }
458
459    /// TypeScript `FieldKind` key.
460    pub fn ts(k: &FieldKind) -> &'static str {
461        row(*k).3
462    }
463
464    #[cfg(test)]
465    mod tests {
466        #[test]
467        fn names_are_indexed_by_discriminant() {
468            for (i, row) in super::NAMES.iter().enumerate() {
469                assert_eq!(row.0 as usize, i);
470            }
471        }
472    }
473}
474
475/// `OptEncoding` as spelled by each host runtime's enum.
476pub mod opt {
477    use nativeview_abi::table::OptEncoding;
478
479    /// `(encoding, C, Swift / Dart, TypeScript, Java)`.
480    type Row = (OptEncoding, &'static str, &'static str, &'static str, &'static str);
481
482    const NAMES: [Row; 6] = [
483        (OptEncoding::Required, "NV_OPT_REQUIRED", "required", "Required", "REQUIRED"),
484        (OptEncoding::ZeroNiche, "NV_OPT_ZERO_NICHE", "zeroNiche", "ZeroNiche", "ZERO_NICHE"),
485        (OptEncoding::Bit0Present, "NV_OPT_BIT0_PRESENT", "bit0Present", "Bit0Present", "BIT0_PRESENT"),
486        (OptEncoding::PlusOne, "NV_OPT_PLUS_ONE", "plusOne", "PlusOne", "PLUS_ONE"),
487        (OptEncoding::TagXor, "NV_OPT_TAG_XOR", "tagXor", "TagXor", "TAG_XOR"),
488        (OptEncoding::WideBit, "NV_OPT_WIDE_BIT", "wideBit", "WideBit", "WIDE_BIT"),
489    ];
490
491    fn row(o: OptEncoding) -> Row {
492        NAMES[o as usize]
493    }
494
495    /// C `NvOptEncoding` constant.
496    pub fn c(o: &OptEncoding) -> &'static str {
497        row(*o).1
498    }
499
500    /// Swift / Dart `OptEncoding` case.
501    pub fn swift(o: &OptEncoding) -> &'static str {
502        row(*o).2
503    }
504
505    /// Java `OptEncoding` constant.
506    pub fn java(o: &OptEncoding) -> &'static str {
507        row(*o).4
508    }
509
510    /// TypeScript `OptEncoding` key.
511    pub fn ts(o: &OptEncoding) -> &'static str {
512        row(*o).3
513    }
514
515    #[cfg(test)]
516    mod tests {
517        #[test]
518        fn names_are_indexed_by_discriminant() {
519            for (i, row) in super::NAMES.iter().enumerate() {
520                assert_eq!(row.0 as usize, i);
521            }
522        }
523    }
524}