use crate::{Error, Result};
use serde::Serialize;
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet, VecDeque};
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
pub struct Layer {
pub number: u32,
pub datatype: u32,
}
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Serialize)]
pub struct Point {
pub x: i64,
pub y: i64,
}
#[derive(Debug, Clone, Copy, PartialEq, Serialize)]
pub struct Transform {
pub angle_deg: f64,
pub magnification: f64,
pub reflect_x: bool,
}
impl Transform {
fn validate(&self) -> Result<()> {
if !self.angle_deg.is_finite()
|| !self.magnification.is_finite()
|| self.magnification <= 0.0
{
return Err(Error::invalid(
"transform needs a finite angle and positive finite magnification",
));
}
Ok(())
}
}
impl Default for Transform {
fn default() -> Self {
Self {
angle_deg: 0.0,
magnification: 1.0,
reflect_x: false,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Serialize)]
pub struct TextStyle {
pub presentation: u16,
pub path_type: Option<u16>,
pub width: Option<i64>,
pub transform: Transform,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Array {
pub columns: u32,
pub rows: u32,
pub column_step: Point,
pub row_step: Point,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub enum Repetition {
Regular(Array),
Offsets(Vec<Point>),
}
impl Repetition {
pub fn count(&self) -> u64 {
match self {
Self::Regular(a) => u64::from(a.columns) * u64::from(a.rows),
Self::Offsets(points) => points.len() as u64 + 1,
}
}
fn validate(&self) -> Result<()> {
if self.count() < 2 {
return Err(Error::invalid("a repetition needs at least two positions"));
}
Ok(())
}
}
#[derive(Debug, Clone, PartialEq, Serialize)]
pub enum PropertyValue {
Unsigned(u64),
Signed(i64),
Real(f64),
Ratio {
negative: bool,
numerator: u64,
denominator: u64,
},
Ascii(String),
Binary(Vec<u8>),
Name(String),
ReferencedString {
reference: u64,
value: Box<PropertyValue>,
},
}
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct Property {
pub name: String,
pub name_reference: Option<u64>,
pub standard: bool,
pub values: Vec<PropertyValue>,
}
impl Property {
pub fn gds(attribute: u16, value: impl Into<Vec<u8>>) -> Self {
Self {
name: "S_GDS_PROPERTY".into(),
name_reference: None,
standard: true,
values: vec![
PropertyValue::Unsigned(attribute.into()),
PropertyValue::Binary(value.into()),
],
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize)]
pub enum TableEntry {
CellName(String),
Text(String),
PropertyName(String),
PropertyString(Vec<u8>),
}
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct TableProperties {
pub entry: TableEntry,
pub reference: Option<u64>,
pub properties: Vec<Property>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
pub enum Interval {
All,
AtMost(u32),
AtLeast(u32),
Exactly(u32),
Range(u32, u32),
}
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct LayerName {
pub name: String,
pub text: bool,
pub layers: Interval,
pub datatypes: Interval,
pub properties: Vec<Property>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
pub enum PathEnds {
Flush,
Round,
HalfWidth,
Explicit { begin: i64, end: i64 },
}
#[derive(Debug, Clone, PartialEq, Serialize)]
#[non_exhaustive]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum Element {
Attributed {
element: Box<Element>,
properties: Vec<Property>,
},
ExtendedPath {
layer: Layer,
points: Vec<Point>,
width: i64,
absolute_width: bool,
ends: PathEnds,
},
Circle {
layer: Layer,
center: Point,
radius: u64,
},
Polygon {
layer: Layer,
points: Vec<Point>,
},
Path {
layer: Layer,
points: Vec<Point>,
width: i64,
},
Text {
layer: Layer,
origin: Point,
text: String,
text_reference: Option<u64>,
style: Option<TextStyle>,
},
Repeated {
element: Box<Element>,
array: Repetition,
},
Reference {
cell: String,
origin: Point,
transform: Transform,
array: Option<Repetition>,
},
}
impl Element {
pub fn unadorned(&self) -> &Self {
match self {
Self::Attributed { element, .. } => element.unadorned(),
other => other,
}
}
pub fn unadorned_mut(&mut self) -> &mut Self {
match self {
Self::Attributed { element, .. } => element.unadorned_mut(),
other => other,
}
}
pub fn properties(&self) -> &[Property] {
match self {
Self::Attributed { properties, .. } => properties,
_ => &[],
}
}
pub fn with_properties(self, properties: Vec<Property>) -> Self {
let element = match self {
Self::Attributed { element, .. } => element,
shape if properties.is_empty() => return shape,
shape => Box::new(shape),
};
if properties.is_empty() {
*element
} else {
Self::Attributed {
element,
properties,
}
}
}
pub fn set_repetition(&mut self, replacement: Option<Repetition>) -> Result<()> {
if let Some(r) = &replacement {
r.validate()?;
}
let shape = self.unadorned_mut();
match shape {
Self::Reference { array, .. } => *array = replacement,
Self::Repeated { array, .. } if replacement.is_some() => {
*array = replacement.expect("checked");
}
Self::Repeated { element, .. } => {
*shape = std::mem::replace(element.as_mut(), Self::empty_polygon())
}
_ => {
if let Some(array) = replacement {
let element = Box::new(std::mem::replace(shape, Self::empty_polygon()));
*shape = Self::Repeated { element, array };
}
}
}
Ok(())
}
fn empty_polygon() -> Self {
Self::Polygon {
layer: Layer {
number: 0,
datatype: 0,
},
points: Vec::new(),
}
}
pub fn set_properties(&mut self, properties: Vec<Property>) {
match self {
Self::Attributed {
properties: old, ..
} if !properties.is_empty() => *old = properties,
Self::Attributed { .. } => {
*self = std::mem::replace(self, Self::empty_polygon()).with_properties(properties)
}
_ if properties.is_empty() => {}
_ => *self = std::mem::replace(self, Self::empty_polygon()).with_properties(properties),
}
}
pub fn layer(&self) -> Option<Layer> {
match self {
Self::ExtendedPath { layer, .. }
| Self::Circle { layer, .. }
| Self::Polygon { layer, .. }
| Self::Path { layer, .. }
| Self::Text { layer, .. } => Some(*layer),
Self::Attributed { element, .. } | Self::Repeated { element, .. } => element.layer(),
Self::Reference { .. } => None,
}
}
pub(crate) fn validate(&self) -> Result<()> {
match self {
Self::Polygon { points, .. } if points.len() < 3 || points.first() == points.last() => {
Err(Error::invalid(
"a polygon needs at least three points and an implicit closing edge",
))
}
Self::Attributed { element, .. } if matches!(**element, Self::Attributed { .. }) => {
Err(Error::invalid("nested property containers"))
}
Self::Attributed { element, .. } => element.validate(),
Self::Path { points, width, .. } | Self::ExtendedPath { points, width, .. }
if *width < 0 || points.len() < 2 =>
{
Err(Error::invalid(
"a path needs two or more points and a nonnegative width",
))
}
Self::Repeated { element, array } => {
if matches!(
element.as_ref(),
Self::Reference { .. } | Self::Repeated { .. } | Self::Attributed { .. }
) {
return Err(Error::invalid(
"a geometry repetition needs a geometric element or text",
));
}
array.validate()?;
element.validate()
}
Self::Text {
style: Some(style), ..
} => {
style.transform.validate()?;
if style.presentation & !0x3f != 0
|| style.presentation & 3 == 3
|| (style.presentation >> 2) & 3 == 3
{
return Err(Error::invalid("invalid GDSII text presentation bits"));
}
Ok(())
}
Self::Reference {
transform, array, ..
} => {
transform.validate()?;
if let Some(array) = array {
array.validate()?;
}
Ok(())
}
_ => Ok(()),
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct Cell {
pub name: String,
pub elements: Vec<Element>,
pub properties: Vec<Property>,
pub name_properties: Vec<Property>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Layout {
pub name: String,
pub dbu_meters: f64,
pub cells: Vec<Cell>,
pub properties: Vec<Property>,
pub layer_names: Vec<LayerName>,
pub table_properties: Vec<TableProperties>,
}
#[derive(Debug, Serialize)]
pub struct Summary {
pub name: String,
pub dbu_meters: f64,
pub cell_count: usize,
pub top_cells: Vec<String>,
pub layers: Vec<Layer>,
pub element_counts: BTreeMap<&'static str, usize>,
}
impl Layout {
pub fn new(name: impl Into<String>, dbu_meters: f64) -> Result<Self> {
let layout = Self {
name: name.into(),
dbu_meters,
cells: Vec::new(),
properties: vec![],
layer_names: vec![],
table_properties: vec![],
};
layout.validate()?;
Ok(layout)
}
pub(crate) fn orphan_cell_name_index(&self, name: &str) -> Option<usize> {
self.table_properties
.iter()
.position(|t| matches!(&t.entry, TableEntry::CellName(s) if s == name))
}
pub fn add_cell(&mut self, name: impl Into<String>) -> Result<&mut Cell> {
let name = name.into();
if name.is_empty() || self.cells.iter().any(|c| c.name == name) {
return Err(Error::invalid(format!(
"empty or duplicate cell name: {name:?}"
)));
}
let name_properties = self
.orphan_cell_name_index(&name)
.map(|i| self.table_properties.remove(i).properties)
.unwrap_or_default();
self.cells.push(Cell {
name,
elements: Vec::new(),
properties: vec![],
name_properties,
});
Ok(self.cells.last_mut().expect("just added a cell"))
}
pub fn add_element(&mut self, cell: &str, element: Element) -> Result<()> {
element.validate()?;
self.cells
.iter_mut()
.find(|c| c.name == cell)
.ok_or_else(|| Error::invalid(format!("unknown cell {cell:?}")))?
.elements
.push(element);
Ok(())
}
fn index(&self) -> Result<HashMap<&str, usize>> {
let mut index = HashMap::with_capacity(self.cells.len());
for (i, cell) in self.cells.iter().enumerate() {
if cell.name.is_empty() || index.insert(cell.name.as_str(), i).is_some() {
return Err(Error::invalid(format!(
"empty or duplicate cell name: {:?}",
cell.name
)));
}
}
Ok(index)
}
pub fn validate(&self) -> Result<()> {
self.validate_references(false)
}
pub fn validate_references(&self, allow_external: bool) -> Result<()> {
if !(self.dbu_meters.is_finite() && self.dbu_meters > 0.0) {
return Err(Error::invalid("database unit must be positive and finite"));
}
if !self.table_properties.is_empty() {
let mut by_value = BTreeMap::new();
let mut ids = BTreeSet::new();
for table in &self.table_properties {
let kind = match table.entry {
TableEntry::CellName(_) => 4,
TableEntry::Text(_) => 6,
TableEntry::PropertyName(_) => 8,
TableEntry::PropertyString(_) => 10,
};
if table.properties.is_empty() && table.reference.is_none() {
return Err(Error::invalid(
"unbound OASIS table entry with no properties",
));
}
if let Some(id) = table.reference
&& !ids.insert((kind, id))
{
return Err(Error::invalid("duplicate OASIS table reference number"));
}
if let Some(previous) = by_value.insert(&table.entry, table.reference)
&& (previous.is_none() || table.reference.is_none() || matches!(kind, 4 | 8))
{
return Err(Error::invalid("ambiguous OASIS table definition"));
}
}
}
let index = self.index()?;
let mut incoming = vec![0usize; self.cells.len()];
for cell in &self.cells {
for (idx, e) in cell.elements.iter().enumerate() {
e.validate()
.map_err(|err| err.at_element(&cell.name, idx, e))?;
if let Element::Reference { cell: target, .. } = e.unadorned() {
if let Some(&i) = index.get(target.as_str()) {
incoming[i] += 1;
} else if !allow_external {
return Err(Error::invalid(format!(
"cell {:?} references missing cell {target:?}",
cell.name
)));
}
}
}
}
let mut queue: VecDeque<_> = (0..incoming.len()).filter(|i| incoming[*i] == 0).collect();
while let Some(i) = queue.pop_front() {
for e in &self.cells[i].elements {
if let Element::Reference { cell, .. } = e.unadorned() {
let Some(&target) = index.get(cell.as_str()) else {
continue;
};
incoming[target] -= 1;
if incoming[target] == 0 {
queue.push_back(target);
}
}
}
}
if let Some(i) = incoming.iter().position(|n| *n != 0) {
return Err(Error::invalid(format!(
"unresolved cyclic hierarchy affecting {:?}",
self.cells[i].name
)));
}
Ok(())
}
pub fn external_references(&self) -> BTreeSet<&str> {
let defined: BTreeSet<_> = self.cells.iter().map(|c| c.name.as_str()).collect();
self.cells
.iter()
.flat_map(|c| &c.elements)
.filter_map(|e| match e.unadorned() {
Element::Reference { cell, .. } if !defined.contains(cell.as_str()) => {
Some(cell.as_str())
}
_ => None,
})
.collect()
}
pub fn summary(&self) -> Summary {
let mut layers = BTreeSet::new();
let mut referenced = HashSet::new();
let mut counts = BTreeMap::new();
for e in self.cells.iter().flat_map(|c| &c.elements) {
if let Some(l) = e.layer() {
layers.insert(l);
}
let kind = match e.unadorned() {
Element::Attributed { .. } => unreachable!("unadorned strips attributes"),
Element::Circle { .. } => "circle",
Element::Polygon { .. } => "polygon",
Element::Path { .. } | Element::ExtendedPath { .. } => "path",
Element::Text { .. } => "text",
Element::Repeated { .. } => "repeated",
Element::Reference { cell, .. } => {
referenced.insert(cell.as_str());
"reference"
}
};
*counts.entry(kind).or_default() += 1;
}
let mut tops: Vec<_> = self
.cells
.iter()
.filter(|c| !referenced.contains(c.name.as_str()))
.map(|c| c.name.clone())
.collect();
tops.sort();
Summary {
name: self.name.clone(),
dbu_meters: self.dbu_meters,
cell_count: self.cells.len(),
top_cells: tops,
layers: layers.into_iter().collect(),
element_counts: counts,
}
}
fn tree_indices(&self, top: &str) -> Result<HashSet<usize>> {
let index = self.index()?;
let first = index
.get(top)
.ok_or_else(|| Error::invalid(format!("unknown top cell {top:?}")))?;
let mut seen = HashSet::new();
let mut todo = vec![*first];
while let Some(i) = todo.pop() {
if !seen.insert(i) {
continue;
}
for e in &self.cells[i].elements {
if let Element::Reference { cell, .. } = e.unadorned() {
todo.push(*index.get(cell.as_str()).ok_or_else(|| {
Error::invalid(format!("missing referenced cell {cell:?}"))
})?);
}
}
}
Ok(seen)
}
pub fn layers_in(&self, cell: &str, recursive: bool) -> Result<BTreeSet<Layer>> {
if recursive {
let indices = self.tree_indices(cell)?;
Ok(indices
.into_iter()
.flat_map(|i| self.cells[i].elements.iter())
.filter_map(Element::layer)
.collect())
} else {
let cell = self
.cells
.iter()
.find(|c| c.name == cell)
.ok_or_else(|| Error::invalid(format!("unknown cell {cell:?}")))?;
Ok(cell.elements.iter().filter_map(Element::layer).collect())
}
}
pub fn subtree(&self, top: &str) -> Result<Self> {
let seen = self.tree_indices(top)?;
let cells = self
.cells
.iter()
.enumerate()
.filter(|(i, _)| seen.contains(i))
.map(|(_, c)| c.clone())
.collect();
Ok(Self {
name: self.name.clone(),
dbu_meters: self.dbu_meters,
cells,
properties: self.properties.clone(),
layer_names: self.layer_names.clone(),
table_properties: self.table_properties.clone(),
})
}
pub fn retain_tree(&mut self, top: &str) -> Result<()> {
let seen = self.tree_indices(top)?;
let mut i = 0;
self.cells.retain(|_| {
let keep = seen.contains(&i);
i += 1;
keep
});
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
fn reference(target: &str) -> Element {
Element::Reference {
cell: target.to_owned(),
origin: Point::default(),
transform: Transform::default(),
array: None,
}
}
#[test]
fn reports_missing_cells_and_cycles_without_recursive_traversal() {
let mut layout = Layout::new("MASK", 1e-9).unwrap();
layout.add_cell("A").unwrap();
layout.add_element("A", reference("B")).unwrap();
assert!(
layout
.validate()
.unwrap_err()
.to_string()
.contains("missing cell \"B\"")
);
layout.add_cell("B").unwrap();
layout.add_element("B", reference("A")).unwrap();
assert!(
layout
.validate()
.unwrap_err()
.to_string()
.contains("cyclic hierarchy")
);
}
#[test]
fn tree_retains_shared_dependencies_once_in_file_order() {
let mut layout = Layout::new("MASK", 1e-9).unwrap();
for name in ["LEAF", "TOP", "LEFT", "UNUSED", "RIGHT"] {
layout.add_cell(name).unwrap();
}
for (parent, target) in [
("TOP", "LEFT"),
("TOP", "RIGHT"),
("LEFT", "LEAF"),
("RIGHT", "LEAF"),
] {
layout.add_element(parent, reference(target)).unwrap();
}
layout.validate().unwrap();
let subtree = layout.subtree("TOP").unwrap();
assert_eq!(
subtree
.cells
.iter()
.map(|c| c.name.as_str())
.collect::<Vec<_>>(),
["LEAF", "TOP", "LEFT", "RIGHT"]
);
assert!(layout.retain_tree("MISSING").is_err());
assert_eq!(layout.cells.len(), 5);
layout.retain_tree("TOP").unwrap();
assert_eq!(subtree, layout);
}
}