use std::collections::BTreeSet;
use nativeview_abi::table::{
FieldDesc, FieldKind, MAX_TABLE_WORDS, NO_VAL_WORD, OptEncoding, Storage, TableDesc,
ValueSetDesc, table_flags,
};
use nativeview_hash::Key64;
use super::model::U64Split;
use crate::error::CodegenError;
#[derive(Debug)]
pub struct EventEnumModel {
pub name: String,
pub screaming: String,
pub variants: Vec<(&'static str, u32, u32)>,
}
#[derive(Debug)]
pub struct TableModel<'a> {
pub desc: &'a TableDesc,
pub ident: String,
pub screaming: String,
pub key: U64Split,
pub schema: U64Split,
pub fields: Vec<FieldModel<'a>>,
pub event_enum: Option<EventEnumModel>,
}
impl TableModel<'_> {
pub fn dense(&self) -> bool {
self.desc.storage == Storage::Dense
}
pub fn events_word(&self) -> u8 {
self.desc.events_word
}
pub fn inherited(&self) -> bool {
self.desc.inherited
}
pub fn resource_fields(&self) -> impl Iterator<Item = (&FieldModel<'_>, U64Split)> {
self.fields.iter().filter_map(|f| f.resource_kind.map(|k| (f, k)))
}
}
#[derive(Debug)]
pub struct FieldModel<'a> {
pub desc: &'a FieldDesc,
pub bits: u8,
pub val_word: u8,
pub explicit_bit: u8,
pub inherits: bool,
pub resource_kind: Option<U64Split>,
}
impl FieldModel<'_> {
pub fn name(&self) -> &str {
self.desc.name
}
}
fn two_word(k: FieldKind) -> bool {
matches!(k, FieldKind::Str | FieldKind::U64 | FieldKind::I64 | FieldKind::F64)
}
pub fn tables_model<'a>(tables: &[&'a TableDesc]) -> Result<Vec<TableModel<'a>>, CodegenError> {
let mut names = BTreeSet::new();
let mut out = Vec::with_capacity(tables.len());
for desc in tables {
super::validate::table(desc)?;
let short = desc.name.strip_prefix("nv.").unwrap_or(desc.name);
let ident = super::spell::pascal(short);
if !names.insert(ident.clone()) {
return Err(table_error(desc, "duplicate table name"));
}
if desc.key != Key64::of(desc.name) {
return Err(table_error(desc, "key is not `xxh64(name)`"));
}
let words = desc.words();
if words == 0 || words > MAX_TABLE_WORDS || desc.word_effects.len() != words {
return Err(table_error(desc, "word count out of range"));
}
check_table_words(desc, words)?;
let fields = desc
.fields
.iter()
.enumerate()
.map(|(i, f)| field_model(desc, i, f, words))
.collect::<Result<Vec<_>, _>>()?;
let event_enum = desc.events.map(|set| event_enum_model(desc, set)).transpose()?;
out.push(TableModel {
desc,
screaming: short.replace('.', "_").to_ascii_uppercase(),
ident,
key: U64Split::new(desc.key.0),
schema: U64Split::new(desc.schema_hash),
fields,
event_enum,
});
}
Ok(out)
}
fn is_ident(s: &str) -> bool {
s.chars().next().is_some_and(|c| c.is_ascii_alphabetic())
&& s.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
}
fn event_enum_model(desc: &TableDesc, set: &'static ValueSetDesc) -> Result<EventEnumModel, CodegenError> {
if set.values.is_empty() {
return Err(table_error(desc, "the `EventSet` must have at least one variant"));
}
let stripped = set
.name
.strip_suffix("Set")
.filter(|s| !s.is_empty())
.unwrap_or(set.name);
let name = stripped
.strip_prefix("Nv")
.filter(|s| s.chars().next().is_some_and(|c| c.is_ascii_uppercase()))
.unwrap_or(stripped)
.to_owned();
if !is_ident(&name) {
return Err(table_error(desc, &format!("invalid `EventSet` enum name `{name}`")));
}
let mut variants = Vec::with_capacity(set.values.len());
let (mut seen_bits, mut seen_screaming, mut seen_swift, mut seen_dart) =
(BTreeSet::new(), BTreeSet::new(), BTreeSet::new(), BTreeSet::new());
for &(variant, bit) in set.values {
if !is_ident(variant) {
return Err(table_error(desc, &format!("invalid event variant name `{variant}`")));
}
if !bit.is_power_of_two() {
return Err(table_error(
desc,
&format!("event `{variant}` mask `{bit}` is not a single bit"),
));
}
if !seen_bits.insert(bit) {
return Err(table_error(
desc,
&format!("duplicate event bit mask {bit} (`{variant}`)"),
));
}
if !seen_screaming.insert(super::spell::screaming(variant)) {
return Err(table_error(
desc,
&format!("duplicate event variant name `{variant}`"),
));
}
if !seen_swift.insert(super::spell::swift::variant(variant))
|| !seen_dart.insert(super::spell::dart::variant(variant))
{
return Err(table_error(
desc,
&format!("event variant `{variant}` collides with another variant once escaped"),
));
}
variants.push((variant, bit.trailing_zeros(), bit));
}
let screaming = super::spell::screaming(&name);
Ok(EventEnumModel { name, screaming, variants })
}
fn check_table_words(desc: &TableDesc, words: usize) -> Result<(), CodegenError> {
let flag = |bit: u16| desc.flags & bit != 0;
if flag(table_flags::INHERITED) != desc.inherited {
return Err(table_error(desc, "`inherited` disagrees with `table_flags::INHERITED`"));
}
let has_events = desc.events_word != NO_VAL_WORD;
if flag(table_flags::HAS_EVENTS) != has_events || desc.events.is_some() != has_events {
return Err(table_error(
desc,
"`events_word`, `events`, and `table_flags::HAS_EVENTS` disagree",
));
}
if has_events && (usize::from(desc.events_word) >= words || desc.inherited) {
return Err(table_error(desc, "the `EventSet` word is out of range or shares word 0"));
}
if desc.events.is_some_and(|set| !set.flags) {
return Err(table_error(desc, "the `EventSet` values must be a flag set"));
}
if desc.inherited && desc.fields.len() > 32 {
return Err(table_error(desc, "an inherited table holds at most 32 fields"));
}
Ok(())
}
fn field_model<'a>(
desc: &TableDesc,
index: usize,
f: &'a FieldDesc,
words: usize,
) -> Result<FieldModel<'a>, CodegenError> {
let bad = |why: &str| Err(table_error(desc, &format!("field `{}` {why}", f.name)));
let (span, shape_ok) = if two_word(f.kind) {
(2, f.shift == 0 && f.bits == 64)
} else {
(1, (1..=32).contains(&f.bits) && u32::from(f.shift) + u32::from(f.bits) <= 32)
};
if !shape_ok || usize::from(f.word) + span > words {
return bad("does not fit its row");
}
let wide = f.opt_encoding == OptEncoding::WideBit;
if wide != (f.val_word != NO_VAL_WORD)
|| wide && (f.bits != 1 || usize::from(f.val_word) >= words || f.val_word == f.word)
{
return bad("has a value word that disagrees with its `Option` encoding");
}
let hidden = [desc.inherited.then_some(0), (desc.events_word != NO_VAL_WORD).then_some(desc.events_word)];
let touched = f.word..f.word + span as u8;
if hidden.into_iter().flatten().any(|w| touched.contains(&w) || wide && w == f.val_word) {
return bad("overlaps the explicit-mask or `EventSet` word");
}
if f.no_inherit && !desc.inherited {
return bad("is `#[no_inherit]` on a table that does not inherit");
}
let resource_kind = match (f.kind, desc.resource_kind(usize::from(f.word))) {
(FieldKind::Resource, Some(kind)) => Some(U64Split::new(kind.0)),
(FieldKind::Resource, None) => return bad("has no `FlatResource::KIND`"),
_ => None,
};
Ok(FieldModel {
desc: f,
bits: if two_word(f.kind) { 32 } else { f.bits },
val_word: f.val_word,
explicit_bit: if desc.inherited { index as u8 } else { NO_VAL_WORD },
inherits: desc.inherited && !f.no_inherit,
resource_kind,
})
}
pub fn value_sets(tables: &[TableModel<'_>]) -> Result<Vec<&'static ValueSetDesc>, CodegenError> {
value_sets_with_core(tables, &[], true)
}
pub fn value_sets_with_core(
tables: &[TableModel<'_>],
shared_sets: &[&'static ValueSetDesc],
omit_shared: bool,
) -> Result<Vec<&'static ValueSetDesc>, CodegenError> {
let mut out: Vec<&'static ValueSetDesc> = Vec::new();
let mut constants = BTreeSet::new();
for shared in shared_sets {
let prefix = super::spell::screaming(shared.name);
for &(name, _) in shared.values {
constants.insert(format!("{prefix}_{}", super::spell::screaming(name)));
}
}
for t in tables {
let fields = t.desc.fields.iter().filter_map(|f| f.values.map(|set| (set, Some(f))));
for (set, field) in t.desc.events.map(|set| (set, None)).into_iter().chain(fields) {
let fail = |why: String| table_error(t.desc, &format!("value set `{}`: {why}", set.name));
if let Some(f) = field
&& let Some(&(name, _)) = set.values.iter().find(|&&(_, v)| !fits(f, v))
{
return Err(fail(format!("value `{name}` exceeds field `{}`", f.name)));
}
if let Some(shared) = shared_sets.iter().find(|s| s.name == set.name) {
if *shared != set {
return Err(fail("defined twice differently".into()));
}
if !omit_shared && out.iter().all(|s| s.name != set.name) {
out.push(set);
}
continue;
}
if let Some(seen) = out.iter().find(|s| s.name == set.name) {
if *seen != set {
return Err(fail("defined twice differently".into()));
}
continue;
}
check_set(set, &mut constants).map_err(fail)?;
out.push(set);
}
}
Ok(out)
}
pub fn validate_shared_value_sets(
sets: &[&'static ValueSetDesc],
) -> Result<Vec<&'static ValueSetDesc>, CodegenError> {
let mut out: Vec<&'static ValueSetDesc> = Vec::with_capacity(sets.len());
let mut constants = BTreeSet::new();
for &set in sets {
let fail = |why: String| CodegenError::validation(format!("shared value set `{}`: {why}", set.name));
if let Some(seen) = out.iter().find(|s| s.name == set.name) {
if *seen != set {
return Err(fail("defined twice differently".into()));
}
continue;
}
check_set(set, &mut constants).map_err(fail)?;
out.push(set);
}
Ok(out)
}
pub fn merge_shared_value_sets(
core_sets: &[&'static ValueSetDesc],
extra_shared: &[&'static ValueSetDesc],
) -> Result<Vec<&'static ValueSetDesc>, CodegenError> {
let mut merged: Vec<&'static ValueSetDesc> = Vec::with_capacity(core_sets.len() + extra_shared.len());
merged.extend_from_slice(core_sets);
merged.extend_from_slice(extra_shared);
validate_shared_value_sets(&merged)
}
fn fits(f: &FieldDesc, v: u32) -> bool {
let stored = match f.opt_encoding {
OptEncoding::PlusOne => u64::from(v) + 1,
OptEncoding::Bit0Present => (u64::from(v) << 1) | 1,
OptEncoding::WideBit => return true,
OptEncoding::Required | OptEncoding::ZeroNiche | OptEncoding::TagXor => u64::from(v),
};
f.bits >= 32 || stored >> f.bits == 0
}
fn check_set(set: &ValueSetDesc, constants: &mut BTreeSet<String>) -> Result<(), String> {
let prefix = super::spell::screaming(set.name);
if !is_ident(set.name) || set.values.is_empty() || prefix == "TABLE" || prefix.starts_with("TABLE_") {
return Err("needs an identifier name outside `TABLE*` and at least one value".into());
}
let (mut swift, mut dart, mut values) = (BTreeSet::new(), BTreeSet::new(), BTreeSet::new());
for &(name, value) in set.values {
let constant = format!("{prefix}_{}", super::spell::screaming(name));
if !is_ident(name) || !constants.insert(constant.clone()) {
return Err(format!("bad or duplicate name `{name}` (NV_{constant})"));
}
if !swift.insert(super::spell::swift::variant(name)) || !dart.insert(super::spell::dart::variant(name)) {
return Err(format!("name `{name}` collides with another member once escaped"));
}
if !values.insert(value) {
return Err(format!("duplicate value {value} (`{name}`)"));
}
if set.flags && !value.is_power_of_two() {
return Err(format!("flag `{name}` is not a single bit"));
}
}
Ok(())
}
pub(super) fn table_error(desc: &TableDesc, why: &str) -> CodegenError {
CodegenError::validation(format!("table `{}`: {why}", desc.name))
}
pub mod kind {
use nativeview_abi::table::FieldKind;
type Row = (FieldKind, &'static str, &'static str, &'static str, &'static str);
const NAMES: [Row; 14] = [
(FieldKind::U32, "NV_FIELD_U32", "u32", "U32", "U32"),
(FieldKind::I32, "NV_FIELD_I32", "i32", "I32", "I32"),
(FieldKind::F32, "NV_FIELD_F32", "f32", "F32", "F32"),
(FieldKind::Bool, "NV_FIELD_BOOL", "bool", "Bool", "BOOL"),
(FieldKind::Enum, "NV_FIELD_ENUM", "enumeration", "Enum", "ENUM"),
(FieldKind::Color, "NV_FIELD_COLOR", "color", "Color", "COLOR"),
(FieldKind::Length, "NV_FIELD_LENGTH", "length", "Length", "LENGTH"),
(FieldKind::Str, "NV_FIELD_STR", "str", "Str", "STR"),
(FieldKind::Resource, "NV_FIELD_RESOURCE", "resource", "Resource", "RESOURCE"),
(FieldKind::Node, "NV_FIELD_NODE", "node", "Node", "NODE"),
(FieldKind::U64, "NV_FIELD_U64", "u64", "U64", "U64"),
(FieldKind::I64, "NV_FIELD_I64", "i64", "I64", "I64"),
(FieldKind::F64, "NV_FIELD_F64", "f64", "F64", "F64"),
(FieldKind::GridLine, "NV_FIELD_GRID_LINE", "gridLine", "GridLine", "GRID_LINE"),
];
fn row(k: FieldKind) -> Row {
NAMES[k as usize]
}
pub fn c(k: &FieldKind) -> &'static str {
row(*k).1
}
pub fn swift(k: &FieldKind) -> &'static str {
row(*k).2
}
pub fn java(k: &FieldKind) -> &'static str {
row(*k).4
}
pub fn dart(k: &FieldKind) -> &'static str {
match k {
FieldKind::Bool => "boolean",
_ => row(*k).2,
}
}
pub fn ts(k: &FieldKind) -> &'static str {
row(*k).3
}
#[cfg(test)]
mod tests {
#[test]
fn names_are_indexed_by_discriminant() {
for (i, row) in super::NAMES.iter().enumerate() {
assert_eq!(row.0 as usize, i);
}
}
}
}
pub mod opt {
use nativeview_abi::table::OptEncoding;
type Row = (OptEncoding, &'static str, &'static str, &'static str, &'static str);
const NAMES: [Row; 6] = [
(OptEncoding::Required, "NV_OPT_REQUIRED", "required", "Required", "REQUIRED"),
(OptEncoding::ZeroNiche, "NV_OPT_ZERO_NICHE", "zeroNiche", "ZeroNiche", "ZERO_NICHE"),
(OptEncoding::Bit0Present, "NV_OPT_BIT0_PRESENT", "bit0Present", "Bit0Present", "BIT0_PRESENT"),
(OptEncoding::PlusOne, "NV_OPT_PLUS_ONE", "plusOne", "PlusOne", "PLUS_ONE"),
(OptEncoding::TagXor, "NV_OPT_TAG_XOR", "tagXor", "TagXor", "TAG_XOR"),
(OptEncoding::WideBit, "NV_OPT_WIDE_BIT", "wideBit", "WideBit", "WIDE_BIT"),
];
fn row(o: OptEncoding) -> Row {
NAMES[o as usize]
}
pub fn c(o: &OptEncoding) -> &'static str {
row(*o).1
}
pub fn swift(o: &OptEncoding) -> &'static str {
row(*o).2
}
pub fn java(o: &OptEncoding) -> &'static str {
row(*o).4
}
pub fn ts(o: &OptEncoding) -> &'static str {
row(*o).3
}
#[cfg(test)]
mod tests {
#[test]
fn names_are_indexed_by_discriminant() {
for (i, row) in super::NAMES.iter().enumerate() {
assert_eq!(row.0 as usize, i);
}
}
}
}