1use 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#[derive(Debug)]
20pub struct EventEnumModel {
21 pub name: String,
23 pub screaming: String,
25 pub variants: Vec<(&'static str, u32, u32)>,
27}
28
29#[derive(Debug)]
31pub struct TableModel<'a> {
32 pub desc: &'a TableDesc,
33 pub ident: String,
35 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 pub fn events_word(&self) -> u8 {
50 self.desc.events_word
51 }
52
53 pub fn inherited(&self) -> bool {
55 self.desc.inherited
56 }
57
58 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#[derive(Debug)]
66pub struct FieldModel<'a> {
67 pub desc: &'a FieldDesc,
68 pub bits: u8,
71 pub val_word: u8,
74 pub explicit_bit: u8,
76 pub inherits: bool,
78 pub resource_kind: Option<U64Split>,
80}
81
82impl FieldModel<'_> {
83 pub fn name(&self) -> &str {
84 self.desc.name
85 }
86}
87
88fn two_word(k: FieldKind) -> bool {
90 matches!(k, FieldKind::Str | FieldKind::U64 | FieldKind::I64 | FieldKind::F64)
91}
92
93pub 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 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
195fn 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
264pub fn value_sets(tables: &[TableModel<'_>]) -> Result<Vec<&'static ValueSetDesc>, CodegenError> {
269 value_sets_with_core(tables, &[], true)
270}
271
272pub 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 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
328pub 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
350pub 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
363fn 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
374fn 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 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
408pub mod kind {
410 use nativeview_abi::table::FieldKind;
411
412 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 pub fn c(k: &FieldKind) -> &'static str {
438 row(*k).1
439 }
440
441 pub fn swift(k: &FieldKind) -> &'static str {
443 row(*k).2
444 }
445
446 pub fn java(k: &FieldKind) -> &'static str {
448 row(*k).4
449 }
450
451 pub fn dart(k: &FieldKind) -> &'static str {
453 match k {
454 FieldKind::Bool => "boolean",
455 _ => row(*k).2,
456 }
457 }
458
459 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
475pub mod opt {
477 use nativeview_abi::table::OptEncoding;
478
479 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 pub fn c(o: &OptEncoding) -> &'static str {
497 row(*o).1
498 }
499
500 pub fn swift(o: &OptEncoding) -> &'static str {
502 row(*o).2
503 }
504
505 pub fn java(o: &OptEncoding) -> &'static str {
507 row(*o).4
508 }
509
510 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}