nativeview_abi/table/mod.rs
1//! Word-table schema ABI shared by the Rust `NodeStore`, the `NV02` wire and every foreign host.
2//!
3//! A table is a fixed row of `<= 32` little-endian `u32` words per node. Every word belongs to
4//! exactly one effect class so a write marks precisely the pipeline stages it invalidates. Hosts
5//! bind a [`TableKey`] once and read rows zero-copy through [`NvTableView`] using generated
6//! word offsets.
7
8mod pack;
9
10use nativeview_abi_macros::NvAbi;
11use nativeview_hash::{Key64, Xxh64Hasher};
12
13pub use pack::{
14 PackInput, PackKind, PackLayout, finalize_table_flags, pack_table, trim_bytes, trim_words,
15};
16
17/// One row word.
18pub type Word = u32;
19
20/// Maximum words per table row (the per-row dirty mask is one `u32`).
21pub const MAX_TABLE_WORDS: usize = 32;
22
23/// Maximum number of table slots per process (`NodeRow::tables` is a `u128`).
24pub const MAX_TABLE_SLOTS: usize = 128;
25
26nativeview_abi_macros::abi_consts! {
27 pub(crate) const TABLE_ABI_CONSTS;
28
29 /// `NvNodeRow::primary_slot` sentinel: a plain container with no realizing table. Any value in
30 /// `0..MAX_TABLE_SLOTS` is a `TableSlot` index into `NvSceneView::tables`.
31 #[nativeview_abi(hex)]
32 pub const NV_PRIMARY_SLOT_NONE: u8 = 0xFF;
33
34 /// `log2` of the node indices one [`NvTableView::row_index_pages`] page covers.
35 pub const NV_ROW_INDEX_PAGE_BITS: u32 = 8;
36 /// Entries per [`NvTableView::row_index_pages`] page.
37 pub const NV_ROW_INDEX_PAGE_LEN: u32 = 1 << NV_ROW_INDEX_PAGE_BITS;
38 /// [`NvTableView::row_index_dir`] entry of a node-index range that has no page.
39 #[nativeview_abi(hex)]
40 pub const NV_ROW_INDEX_NO_PAGE: u32 = u32::MAX;
41}
42
43nativeview_abi_macros::abi_aliases! {
44 pub(crate) const TABLE_ABI_ALIASES;
45
46 /// Stable 64-bit identity of a table: `xxh64(name)` baked at compile time.
47 #[nativeview_abi(name = "NvTableKey", target = "u64")]
48 pub type TableKey = Key64;
49}
50
51/// Pipeline stages a word invalidates.
52pub mod effect {
53 /// Box geometry inputs (Flexbox / Grid / position).
54 pub const LAYOUT: u8 = 1 << 0;
55 /// Intrinsic content size inputs (text, image natural size).
56 pub const MEASURE: u8 = 1 << 1;
57 /// Display-list / paint inputs.
58 pub const PAINT: u8 = 1 << 2;
59 /// Compositor-only inputs (opacity, transform) — no relayout, no repaint.
60 pub const COMPOSITE: u8 = 1 << 3;
61 /// Accessibility tree / semantic attributes.
62 pub const SEMANTICS: u8 = 1 << 4;
63 /// Native host class / DOM tag selection.
64 pub const REALIZE: u8 = 1 << 5;
65 /// Event subscription / interaction routing.
66 pub const EVENTS: u8 = 1 << 6;
67 pub const ALL: u8 = 0x7F;
68}
69
70/// Table storage strategy.
71#[repr(u8)]
72#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
73pub enum Storage {
74 /// Row `i` lives at node index `i` (tables present on most nodes).
75 Dense = 0,
76 /// Packed rows + owner list, node → row via a paged index (rare tables).
77 Sparse = 1,
78}
79
80/// `DeclareTables` flags.
81pub mod table_flags {
82 /// Table is owned by a host / out-of-tree module unknown to the core: pass through untouched.
83 pub const HOST_SLOT: u16 = 1 << 0;
84 /// Publish rows through `NvSceneView::tables`.
85 pub const PUBLISH_TO_SCENE: u16 = 1 << 1;
86 /// Any change to the table invalidates layout.
87 pub const AFFECTS_LAYOUT: u16 = 1 << 2;
88 /// Word 0 is the hidden `__explicit: u32` bitmask (`#[nv_table(inherited)]`).
89 pub const INHERITED: u16 = 1 << 3;
90 /// Word 0 is the `EventSet<E>` subscription bitmask (`#[nv_table(events = E)]`).
91 pub const HAS_EVENTS: u16 = 1 << 4;
92 /// Presence of this table on a box establishes a CSS stacking context (e.g. `nv.blur_surface`).
93 pub const STACKING_CONTEXT: u16 = 1 << 5;
94 /// Table establishes an inline formatting context for its descendants (e.g. `nv.text`):
95 /// children of a live node carrying this table (and no [`NO_INLINE_CONTEXT`] table) receive
96 /// `NV_NODE_ROW_FLAG_INLINE`.
97 pub const INLINE_CONTEXT: u16 = 1 << 6;
98 /// Replaced/non-paragraph host table (e.g. replaced media or control tables): prevents the node
99 /// from establishing an inline formatting context even when `nv.text` is also attached.
100 pub const NO_INLINE_CONTEXT: u16 = 1 << 7;
101 /// Table renders text styled by ancestor `nv.typography` inheritance, so ancestor typography
102 /// changes dirty nodes carrying this table in `NvSceneView::dirty_indices`.
103 pub const INHERITS_TYPOGRAPHY: u16 = 1 << 8;
104}
105
106/// Sentinel `FieldDesc::val_word` / `TableDesc::events_word` meaning "not applicable".
107pub const NO_VAL_WORD: u8 = u8::MAX;
108
109/// How a field's bits are interpreted (drives codegen getters and wire string/resource handling).
110#[repr(u8)]
111#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
112pub enum FieldKind {
113 U32 = 0,
114 I32 = 1,
115 F32 = 2,
116 Bool = 3,
117 /// Small enum / integer packed in `bits`.
118 Enum = 4,
119 /// Packed `RGBA8888` (`r | g<<8 | b<<16 | a<<24`).
120 Color = 5,
121 /// Tagged length (`Auto` / points / percent) — see `nativeview_store::Length`.
122 Length = 6,
123 /// Two words `{ offset, len }` into the text slab.
124 Str = 7,
125 /// `ResourceId` into the resource store.
126 Resource = 8,
127 /// Node reference (`NodeId` raw value, `0` = none).
128 Node = 9,
129 /// Two-word unsigned 64-bit integer (`lo`, `hi`).
130 U64 = 10,
131 /// Two-word signed 64-bit integer (`lo`, `hi`).
132 I64 = 11,
133 /// Two-word 64-bit float (`lo`, `hi`).
134 F64 = 12,
135 /// Packed 16-bit CSS Grid line placement (`Auto`, `Line(i16)`, `Span(u16)`).
136 GridLine = 13,
137}
138
139/// Optionality and wire-bit encoding strategy for a [`FieldDesc`].
140///
141/// Included in [`compute_table_schema_hash`] so `T` and `Option<T>` never collide even when
142/// niche encoding keeps their bit widths equal (e.g. `Length`, `GridLine`, 3-variant `WordEnum`).
143#[repr(u8)]
144#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
145pub enum OptEncoding {
146 /// Non-optional field (required value, `Str`, or `Res<R>`).
147 Required = 0,
148 /// Optional handle using zero as the `None` niche (`Option<NodeId>`, `Option<SurfaceId>`).
149 ZeroNiche = 1,
150 /// Optional sub-word integer/bitflags with presence bit at bit 0 and payload in bits `1..`.
151 Bit0Present = 2,
152 /// Optional `bool` or `WordEnum` where `0 = None` and `discriminant + 1 = Some(v)`.
153 PlusOne = 3,
154 /// Optional tagged value (`Length`, `GridLine`) XORed with its unused tag niche so `0 = None`.
155 TagXor = 4,
156 /// Wide optional (`Option<f32|u32|i32|Rgba>`): 1-bit presence flag in `word` + full `val_word`.
157 WideBit = 5,
158}
159
160/// Named values a field holds: the variants of a `word_enum!` or the bits of a flag set. Host
161/// mirrors emit one `NV_<NAME>_<VALUE>` constant each, so foreign code never hand-copies them.
162#[derive(Debug, Clone, Copy, PartialEq, Eq)]
163pub struct ValueSetDesc {
164 /// Rust type / set name (`AriaRole`, `TextDecoration`).
165 pub name: &'static str,
166 /// `true` for a bit-flag set (values combine with `|`), `false` for enum variants (exactly
167 /// one value at a time). Hosts mirror flags as namespaced masks and variants as enums.
168 pub flags: bool,
169 /// `(variant, value)` pairs in declaration order.
170 pub values: &'static [(&'static str, u32)],
171}
172
173/// One field of a table row.
174#[derive(Debug, Clone, Copy, PartialEq, Eq)]
175pub struct FieldDesc {
176 pub name: &'static str,
177 pub kind: FieldKind,
178 /// Optionality & bit-encoding strategy (`Required` for non-optional fields).
179 pub opt_encoding: OptEncoding,
180 /// First word (for wide `Option<T>`, the word holding the 1-bit presence flag).
181 pub word: u8,
182 /// Bit offset inside `word` (`0` for whole-word fields).
183 pub shift: u8,
184 /// Bit width inside `word` (`32` for whole-word fields; `64` for `Str`/64-bit; `1` for wide `Option<T>` presence bit).
185 pub bits: u8,
186 /// Effect class of the field's words.
187 pub effects: u8,
188 /// Value word for wide `Option<T>` fields (`NO_VAL_WORD` for all other fields).
189 pub val_word: u8,
190 /// True when marked `#[no_inherit]` on an inherited table (explicitly tracked, never inherited).
191 pub no_inherit: bool,
192 /// Named values (enum variants / flag bits); not part of the schema hash.
193 pub values: Option<&'static ValueSetDesc>,
194}
195
196impl FieldDesc {
197 /// Placeholder descriptor used to initialize fixed-size `const` arrays inside [`pack_table`].
198 pub const EMPTY: Self = Self {
199 name: "",
200 kind: FieldKind::U32,
201 opt_encoding: OptEncoding::Required,
202 word: 0,
203 shift: 0,
204 bits: 0,
205 effects: 0,
206 val_word: NO_VAL_WORD,
207 no_inherit: false,
208 values: None,
209 };
210}
211
212/// Compile-time description of a table, emitted by `#[derive(NvTable)]`.
213#[derive(Debug, Clone, Copy)]
214pub struct TableDesc {
215 pub key: TableKey,
216 pub name: &'static str,
217 /// `xxh64` over the canonical field layout; a mismatch across a boundary is a hard error.
218 pub schema_hash: u64,
219 pub storage: Storage,
220 pub flags: u16,
221 /// Declarative realization priority (`0` = non-realizing / modifier table; `1..=255` = realizing
222 /// component priority where higher wins and ties break deterministically by `TableKey`).
223 pub realization_priority: u8,
224 pub defaults: &'static [Word],
225 /// Effect class per word (`len == defaults.len()`).
226 pub word_effects: &'static [u8],
227 /// Bit `i` set: word `i` is the offset word of a two-word string reference.
228 pub str_words: u32,
229 /// Bit `i` set: word `i` holds a `ResourceId`.
230 pub resource_words: u32,
231 /// Word holding the `EventSet` subscription mask (`NO_VAL_WORD` if none).
232 pub events_word: u8,
233 /// Listener bits of that `EventSet<E>` (`EventEnum::EVENT_SET`: `<E>Set`, one
234 /// `(variant, 1 << id)` flag per event), mirrored to hosts; `None` without `events`.
235 pub events: Option<&'static ValueSetDesc>,
236 /// True when word 0 is the hidden `__explicit: u32` bitmask for `#[nv_table(inherited)]`.
237 pub inherited: bool,
238 pub fields: &'static [FieldDesc],
239 /// `(word_index, FlatResource::KIND)` pairs for every `Res<R>` field in this table.
240 pub resource_kinds: &'static [(u8, Key64)],
241}
242
243impl TableDesc {
244 #[inline]
245 pub const fn words(&self) -> usize {
246 self.defaults.len()
247 }
248
249 /// Returns the expected `FlatResource::KIND` for resource `word`, if declared on this table.
250 #[inline]
251 pub const fn resource_kind(&self, word: usize) -> Option<Key64> {
252 let mut i = 0;
253 while i < self.resource_kinds.len() {
254 if self.resource_kinds[i].0 as usize == word {
255 return Some(self.resource_kinds[i].1);
256 }
257 i += 1;
258 }
259 None
260 }
261
262 /// Union of all word effects.
263 pub const fn effects(&self) -> u8 {
264 let mut acc = 0;
265 let mut i = 0;
266 while i < self.word_effects.len() {
267 acc |= self.word_effects[i];
268 i += 1;
269 }
270 acc
271 }
272}
273
274/// Computes the canonical compile-time XXH64 `schema_hash` of a word table from its
275/// canonical layout, storage, flags, default words, word effects, string/resource masks,
276/// events/inheritance metadata, per-field `FieldKind`/offsets, and `resource_kinds` in
277/// deterministic ascending word order (independent of Rust spelling).
278#[allow(clippy::too_many_arguments)]
279pub const fn compute_table_schema_hash(
280 name: &str,
281 storage: Storage,
282 flags: u16,
283 realization_priority: u8,
284 defaults: &[Word],
285 word_effects: &[u8],
286 str_words: u32,
287 resource_words: u32,
288 events_word: u8,
289 inherited: bool,
290 fields: &[FieldDesc],
291 resource_kinds: &[(u8, Key64)],
292) -> u64 {
293 let mut h = Xxh64Hasher::new(0);
294 h.update(b"NV_TABLE_V7;");
295 h.update(name.as_bytes());
296 let [flags_lo, flags_hi] = flags.to_le_bytes();
297 h.update(&[
298 0xFF,
299 storage as u8,
300 flags_lo,
301 flags_hi,
302 realization_priority,
303 events_word,
304 inherited as u8,
305 ]);
306 h.update_u64(defaults.len() as u64);
307 let mut i = 0;
308 while i < defaults.len() {
309 h.update(&defaults[i].to_le_bytes());
310 i += 1;
311 }
312 h.update(word_effects);
313 h.update(&str_words.to_le_bytes());
314 h.update(&resource_words.to_le_bytes());
315 h.update_u64(fields.len() as u64);
316 let mut j = 0;
317 while j < fields.len() {
318 let f = &fields[j];
319 h.update(f.name.as_bytes());
320 h.update(&[
321 0xFF,
322 f.kind as u8,
323 f.opt_encoding as u8,
324 f.word,
325 f.shift,
326 f.bits,
327 f.effects,
328 f.val_word,
329 f.no_inherit as u8,
330 ]);
331 j += 1;
332 }
333 // Hash `(word, FlatResource::KIND)` pairs in deterministic ascending `word` order.
334 h.update_u64(resource_kinds.len() as u64);
335 if !resource_kinds.is_empty() {
336 let mut w = 0u16;
337 while w < 256 {
338 let mut k = 0usize;
339 while k < resource_kinds.len() {
340 if resource_kinds[k].0 as u16 == w {
341 h.update(&[resource_kinds[k].0]);
342 h.update_u64(resource_kinds[k].1.0);
343 }
344 k += 1;
345 }
346 w += 1;
347 }
348 }
349 h.digest()
350}
351
352/// Zero-copy view of one table published in `NvSceneView::tables`.
353///
354/// Dense tables: `owners` is null and row `i` belongs to node index `i` (`rows` spans the store's
355/// node capacity). Sparse tables: `rows[r]` belongs to `owners[r]` (raw `NodeId`), and the store's
356/// own paged node-index → row index is published alongside, so a host resolves a node's row in
357/// O(1) without building an owner map: node index `n` lives in page
358/// `p = row_index_dir[n >> NV_ROW_INDEX_PAGE_BITS]` (absent when `n`'s directory slot is out of
359/// range or `NV_ROW_INDEX_NO_PAGE`), whose entry `row_index_pages[p * NV_ROW_INDEX_PAGE_LEN +
360/// (n & (NV_ROW_INDEX_PAGE_LEN - 1))]` is `row + 1` (`0` = no row).
361#[repr(C)]
362#[derive(Debug, Clone, Copy, NvAbi)]
363#[nativeview_abi(size_64 = 88)]
364pub struct NvTableView {
365 /// Low 32 bits of the `TableKey`.
366 #[nativeview_abi(offset = 0)]
367 pub key_lo: u32,
368 /// High 32 bits of the `TableKey`.
369 #[nativeview_abi(offset = 4)]
370 pub key_hi: u32,
371 /// Process-local slot (bit index in `NodeRow::tables`).
372 #[nativeview_abi(offset = 8)]
373 pub slot: u32,
374 /// Words per row.
375 #[nativeview_abi(offset = 12)]
376 pub words: u32,
377 /// Number of rows reachable through `rows`.
378 #[nativeview_abi(offset = 16)]
379 pub row_count: u32,
380 /// Number of entries in `dirty_owners`.
381 #[nativeview_abi(offset = 20)]
382 pub dirty_count: u32,
383 /// Number of entries in `detached_owners`.
384 #[nativeview_abi(offset = 24)]
385 pub detached_count: u32,
386 /// Entries in `row_index_dir` (sparse tables; `0` for dense tables).
387 #[nativeview_abi(offset = 28)]
388 pub row_index_dir_len: u32,
389 /// Pages of `NV_ROW_INDEX_PAGE_LEN` entries in `row_index_pages` (sparse tables).
390 #[nativeview_abi(offset = 32)]
391 pub row_index_page_count: u32,
392 /// Explicit padding aligning pointer fields to 8 bytes on 64-bit targets (`0`).
393 #[nativeview_abi(offset = 36)]
394 pub _pad0: u32,
395 /// `row_count * words` row words.
396 pub rows: *const u32,
397 /// Raw `NodeId` owner per row (sparse tables) or null (dense tables).
398 pub owners: *const crate::NodeId,
399 /// Generation-checked live `NodeId` owners whose row changed this frame (excludes swap-remove
400 /// relocations).
401 pub dirty_owners: *const crate::NodeId,
402 /// Generation-checked live `NodeId` owners that detached this table this frame (and no longer
403 /// carry it at frame end). Idempotent teardown signal: consumers must treat detaching an owner
404 /// not currently mounted as a no-op (a same-frame attach+detach on an existing node may emit an
405 /// entry on a direct `NodeStore` or merged `ChangeSet`, while an `NV02` replica that never saw
406 /// the transient attach suppresses it).
407 pub detached_owners: *const crate::NodeId,
408 /// Sparse tables: page of each `NV_ROW_INDEX_PAGE_LEN` node indices, or
409 /// `NV_ROW_INDEX_NO_PAGE`. Null for dense tables (row = node index).
410 pub row_index_dir: *const u32,
411 /// Sparse tables: `row_index_page_count * NV_ROW_INDEX_PAGE_LEN` entries of `row + 1`
412 /// (`0` = no row), addressed through `row_index_dir`. Null for dense tables.
413 pub row_index_pages: *const u32,
414}