use super::*;
#[derive(Clone, Copy)]
pub(super) enum Scope {
File,
Cell(usize),
CellName(u64),
Element(usize, usize),
LayerName(usize),
Dropped,
Table(u8, u64),
}
enum WireValue {
Direct(PropertyValue),
TableString { kind: u64, index: u64 },
}
pub(super) struct WireValues {
items: Vec<WireValue>,
pub bytes: usize,
}
pub(super) struct PendingProperty {
owner: Scope,
at: Location,
name: Name,
standard: bool,
values: Rc<WireValues>,
}
fn rational(negative: bool, n: u64, d: u64) -> Result<PropertyValue> {
if d == 0 {
return Err(Error::invalid("zero OASIS real denominator"));
}
let (mut a, mut b) = (n, d);
while b != 0 {
(a, b) = (b, a % b);
}
let numerator = n / a;
let denominator = d / a;
let significant = if numerator == 0 {
0
} else {
64 - numerator.leading_zeros() - numerator.trailing_zeros()
};
if denominator.is_power_of_two() && significant <= 53 {
let abs = (numerator as f64) / (denominator as f64);
Ok(PropertyValue::Real(if negative { -abs } else { abs }))
} else {
Ok(PropertyValue::Ratio {
negative,
numerator: n,
denominator: d,
})
}
}
fn payload(v: &PropertyValue) -> usize {
match v {
PropertyValue::Ascii(s) | PropertyValue::Name(s) => s.len(),
PropertyValue::Binary(b) => b.len(),
_ => 0,
}
}
fn value(input: &mut In) -> Result<WireValue> {
let t = input.uint()?;
let val = match t {
0..=5 => {
let first = input.uint()?;
let (n, d) = match t {
0 | 1 => (first, 1),
2 | 3 => (1, first),
_ => (first, input.uint()?),
};
rational(!t.is_multiple_of(2), n, d)?
}
6 | 7 => PropertyValue::Real(input.real_payload(t)?),
8 => PropertyValue::Unsigned(input.uint()?),
9 => PropertyValue::Signed(input.sint()?),
10 => PropertyValue::Ascii(input.string(false)?),
11 => PropertyValue::Binary(input.blob()?),
12 => PropertyValue::Name(input.string(true)?),
13..=15 => {
return Ok(WireValue::TableString {
kind: t,
index: input.uint()?,
});
}
_ => return Err(Error::invalid("unknown OASIS property value type")),
};
Ok(WireValue::Direct(val))
}
fn interval(input: &mut In) -> Result<Interval> {
let t = input.uint()?;
let mut u = || {
u32::try_from(input.uint()?)
.map_err(|_| Error::unsupported("OASIS layer interval exceeds u32"))
};
Ok(match t {
0 => Interval::All,
1 => Interval::AtMost(u()?),
2 => Interval::AtLeast(u()?),
3 => Interval::Exactly(u()?),
4 => {
let a = u()?;
let b = u()?;
if a > b {
return Err(Error::invalid("reversed OASIS layer interval"));
}
Interval::Range(a, b)
}
_ => return Err(Error::invalid("unknown OASIS layer interval type")),
})
}
impl Parser<'_, '_, '_> {
pub(super) fn layer_name(&mut self, input: &mut In, text: bool) -> Result<()> {
let name = input.string(true)?;
let layers = interval(input)?;
let datatypes = interval(input)?;
self.spend(192 + name.len())?;
self.scope = Scope::LayerName(self.layer_names.len());
self.layer_names.push(LayerName {
name,
text,
layers,
datatypes,
properties: vec![],
});
self.current = None;
self.m = Modals::default();
Ok(())
}
pub(super) fn named(&mut self, input: &mut In, id: u64) -> Result<()> {
self.current = None;
self.m = Modals::default();
let explicit = id.is_multiple_of(2);
if matches!(id, 9 | 10) {
let data = input.blob()?;
let index = if explicit { Some(input.uint()?) } else { None };
self.spend(128 + data.len())?;
self.scope = Scope::Table(10, self.prop_strings.insert(data, index, false)?);
} else {
let name = input.string(matches!(id, 3 | 4 | 7 | 8))?;
let index = if explicit { Some(input.uint()?) } else { None };
let name_bytes = if matches!(id, 3 | 4 | 7 | 8) {
2 * name.len() + 192
} else {
128 + name.len()
};
self.spend(name_bytes)?;
self.scope = match id {
3 | 4 => Scope::CellName(self.cells_table.insert(name, index, true)?),
5 | 6 => Scope::Table(6, self.text_table.insert(name, index, false)?),
_ => Scope::Table(8, self.prop_names.insert(name, index, true)?),
};
}
Ok(())
}
pub(super) fn property(&mut self, input: &mut In, id: u64) -> Result<()> {
let f = if id == 29 {
8 | u8::from(required(self.m.standard, "property standard flag")?)
} else {
input.byte()?
};
let standard = f & 1 != 0;
self.m.standard = Some(standard);
if f & 4 != 0 {
if f & 2 == 0 {
self.observed.literal(2, self.at);
}
self.m.property_name = Some(Name::read(input, f & 2 != 0, true)?);
}
let name = required(self.m.property_name.clone(), "property name")?;
if f & 8 == 0 {
self.m.property_values = None;
let n = if f >> 4 == 15 {
input.count(super::super::MAX_POINTS)?
} else {
usize::from(f >> 4)
};
let room = self.available()?;
let mut bytes = n * size_of::<WireValue>();
if bytes > room {
return Err(Error::unsupported(
"OASIS property value list exceeds retained byte budget",
));
}
let mut items = Vec::with_capacity(n);
for _ in 0..n {
let v = value(input)?;
if matches!(
&v,
WireValue::Direct(
PropertyValue::Ascii(_) | PropertyValue::Binary(_) | PropertyValue::Name(_)
)
) {
self.observed.literal(3, self.at);
}
if let WireValue::Direct(p) = &v {
bytes += payload(p);
}
if bytes > room {
return Err(Error::unsupported(
"OASIS property values exceed retained byte budget",
));
}
items.push(v);
}
self.m.property_values = Some(Rc::new(WireValues { items, bytes }));
}
let values = required(self.m.property_values.clone(), "property values")?;
if matches!(self.scope, Scope::Dropped) {
return Ok(());
}
self.spend(144 + name.retained_bytes() + values.bytes)?;
self.pending.push(PendingProperty {
owner: self.scope,
at: self.at,
name,
standard,
values,
});
Ok(())
}
fn resolved(
&mut self,
wire: &PendingProperty,
explicit: &BTreeSet<(u8, u64)>,
) -> Result<Property> {
let name = wire.name.lookup(&self.prop_names)?;
let mut bytes = name.len()
+ size_of::<Property>()
+ wire.values.items.len() * size_of::<PropertyValue>();
if bytes > self.remaining {
return Err(Error::unsupported(
"resolved OASIS property exceeds byte budget",
));
}
let name = name.to_owned();
let mut values = Vec::with_capacity(wire.values.items.len());
for item in &wire.values.items {
let size = match item {
WireValue::Direct(v) => payload(v),
WireValue::TableString { index, .. } => self
.prop_strings
.values
.get(index)
.ok_or_else(|| {
Error::invalid(format!("undefined OASIS PROPSTRING index {index}"))
})?
.len(),
};
bytes = bytes
.checked_add(size)
.ok_or_else(|| Error::unsupported("OASIS property size overflow"))?;
if bytes > self.remaining {
return Err(Error::unsupported(
"resolved OASIS property exceeds byte budget",
));
}
let value = match item {
WireValue::Direct(v) => v.clone(),
WireValue::TableString { kind, index } => {
let data = &self.prop_strings.values[index];
if *kind == 14 {
PropertyValue::Binary(data.clone())
} else {
let n = *kind == 15;
if !legal_string(data, n) {
return Err(Error::invalid(
"invalid referenced OASIS property string characters",
));
}
let s = String::from_utf8(data.clone()).expect("ASCII was verified");
if n {
PropertyValue::Name(s)
} else {
PropertyValue::Ascii(s)
}
}
}
};
if let WireValue::TableString { index, .. } = item
&& explicit.contains(&(10, *index))
{
bytes += size_of::<PropertyValue>();
values.push(PropertyValue::ReferencedString {
reference: *index,
value: Box::new(value),
});
} else {
values.push(value);
}
}
self.spend(bytes)?;
let name_reference = match wire.name {
Name::Index(id) if explicit.contains(&(8, id)) => Some(id),
_ => None,
};
Ok(Property {
name,
name_reference,
standard: wire.standard,
values,
})
}
fn table_bytes(&self, kind: u8, id: u64) -> &[u8] {
match kind {
4 => self.cells_table.values[&id].as_bytes(),
6 => self.text_table.values[&id].as_bytes(),
8 => self.prop_names.values[&id].as_bytes(),
10 => &self.prop_strings.values[&id],
_ => unreachable!(),
}
}
pub(super) fn explicit_table_refs<'a>(&'a self) -> BTreeSet<(u8, u64)> {
let entries = || {
self.text_table
.values
.iter()
.map(|(&id, s)| (6, id, s.as_bytes()))
.chain(
self.prop_names
.values
.iter()
.map(|(&id, s)| (8, id, s.as_bytes())),
)
.chain(
self.prop_strings
.values
.iter()
.map(|(&id, b)| (10, id, b.as_slice())),
)
};
let mut aliases = BTreeMap::new();
for (kind, _, bytes) in entries() {
aliases
.entry((kind, bytes))
.and_modify(|(_, explicit)| *explicit = true)
.or_insert((false, false));
}
if aliases.is_empty() {
return BTreeSet::new();
}
for p in &self.pending {
if let Scope::Table(kind, id) = p.owner {
let flags = aliases
.get_mut(&(kind, self.table_bytes(kind, id)))
.expect("defined owner");
flags.0 = true;
flags.1 |= match kind {
6 => self.text_table.explicit == Some(true),
8 => self.prop_names.explicit == Some(true),
10 => self.prop_strings.explicit == Some(true),
_ => false,
};
}
}
let check_text = !self.text_table.values.is_empty();
let mut literal = |kind, bytes: &'a [u8]| {
if let Some((true, explicit)) = aliases.get_mut(&(kind, bytes)) {
*explicit = true;
}
};
for p in &self.pending {
if let Name::Inline(s) = &p.name {
literal(8, s.as_bytes());
}
for v in &p.values.items {
match v {
WireValue::Direct(PropertyValue::Ascii(s) | PropertyValue::Name(s)) => {
literal(10, s.as_bytes())
}
WireValue::Direct(PropertyValue::Binary(b)) => literal(10, b),
_ => {}
}
}
}
if check_text {
let mut indexed = self
.bindings
.iter()
.filter_map(|(b, _, _)| match b {
Binding::Label(c, i) => Some((*c, *i)),
_ => None,
})
.peekable();
for (c, cell) in self.cells.iter().enumerate() {
for (i, e) in cell.elements.iter().enumerate() {
if indexed.next_if_eq(&(c, i)).is_some() {
continue;
}
let shape = match e {
Element::Repeated { element, .. } => element.as_ref(),
other => other,
};
if let Element::Text { text, .. } = shape {
literal(6, text.as_bytes());
}
}
}
}
entries()
.filter_map(|(kind, id, b)| {
aliases
.get(&(kind, b))
.and_then(|(_, exp)| exp.then_some((kind, id)))
})
.collect()
}
fn table_owner(
&mut self,
kind: u8,
id: u64,
explicit: &BTreeSet<(u8, u64)>,
owners: &mut BTreeMap<(u8, u64), usize>,
) -> Result<usize> {
if let Some(i) = owners.get(&(kind, id)) {
return Ok(*i);
}
self.spend(192 + self.table_bytes(kind, id).len())?;
let entry = match kind {
4 => TableEntry::CellName(self.cells_table.values[&id].clone()),
6 => TableEntry::Text(self.text_table.values[&id].clone()),
8 => TableEntry::PropertyName(self.prop_names.values[&id].clone()),
10 => TableEntry::PropertyString(self.prop_strings.values[&id].clone()),
_ => unreachable!(),
};
let i = self.table_properties.len();
self.table_properties.push(TableProperties {
entry,
reference: (explicit.contains(&(kind, id))
|| (kind == 4 && self.cells_table.explicit == Some(true)))
.then_some(id),
properties: vec![],
});
owners.insert((kind, id), i);
Ok(i)
}
pub(super) fn resolve_properties(
&mut self,
explicit: &BTreeSet<(u8, u64)>,
) -> Result<Vec<Property>> {
let mut file = vec![];
if self.pending.is_empty() && explicit.is_empty() {
return Ok(file);
}
let mut name_owners = BTreeMap::new();
if self
.pending
.iter()
.any(|p| matches!(p.owner, Scope::CellName(_)))
{
let cells: BTreeMap<_, _> = self
.cells
.iter()
.enumerate()
.map(|(i, c)| (c.name.as_str(), i))
.collect();
for (id, name) in &self.cells_table.values {
if let Some(i) = cells.get(name.as_str()) {
name_owners.insert(*id, *i);
}
}
}
let mut table_owners = BTreeMap::new();
for raw in std::mem::take(&mut self.pending) {
let p = self
.resolved(&raw, explicit)
.map_err(|e| raw.at.annotate(e))?;
if p.standard
&& matches!(
(p.name.as_str(), raw.owner, p.values.as_slice()),
(
"S_CELL_OFFSET",
Scope::CellName(_),
[PropertyValue::Unsigned(_)]
) | (
"S_MAX_SIGNED_INTEGER_WIDTH" | "S_MAX_UNSIGNED_INTEGER_WIDTH",
Scope::File,
[PropertyValue::Unsigned(1..)]
)
)
{
continue;
}
match raw.owner {
Scope::File => file.push(p),
Scope::Cell(i) => self.cells[i].properties.push(p),
Scope::CellName(id) => {
if let Some(&i) = name_owners.get(&id) {
self.cells[i].name_properties.push(p);
} else {
let i = self.table_owner(4, id, explicit, &mut table_owners)?;
self.table_properties[i].properties.push(p);
}
}
Scope::LayerName(i) => self.layer_names[i].properties.push(p),
Scope::Element(c, i) => {
let slot = &mut self.cells[c].elements[i];
if let Element::Attributed { properties, .. } = slot {
properties.push(p);
} else {
self.spend(size_of::<Element>())?;
let slot = &mut self.cells[c].elements[i];
let original = std::mem::replace(
slot,
Element::Polygon {
layer: Layer {
number: 0,
datatype: 0,
},
points: vec![],
},
);
*slot = Element::Attributed {
element: Box::new(original),
properties: vec![p],
};
}
}
Scope::Table(kind, id) => {
let idx = self.table_owner(kind, id, explicit, &mut table_owners)?;
self.table_properties[idx].properties.push(p);
}
Scope::Dropped => unreachable!("filtered owners are skipped in the decoder"),
}
}
for &(kind, id) in explicit {
self.table_owner(kind, id, explicit, &mut table_owners)?;
}
let annotated_top = self
.table_properties
.iter()
.any(|t| matches!(&t.entry,TableEntry::PropertyName(s) if s=="S_TOP_CELL"));
let top_name = |p: &Property| {
!annotated_top
&& p.standard
&& p.name == "S_TOP_CELL"
&& matches!(p.values.as_slice(), [PropertyValue::Name(_)])
};
if file.iter().any(top_name) {
let mut actual: BTreeSet<_> = self.cells.iter().map(|c| c.name.as_str()).collect();
for cell in &self.cells {
for e in &cell.elements {
if let Element::Reference { cell, .. } = e.unadorned() {
actual.remove(cell.as_str());
}
}
}
let declared: BTreeSet<_> = file
.iter()
.filter(|p| top_name(p))
.filter_map(|p| match p.values.as_slice() {
[PropertyValue::Name(s)] => Some(s.as_str()),
_ => None,
})
.collect();
if actual == declared {
file.retain(|p| !top_name(p));
}
}
Ok(file)
}
}