use crate::{
Element, Error, Format, Interval, Layer, Layout, PathEnds, Point, Property, Repetition, Result,
TableEntry,
};
use serde::Serialize;
use std::borrow::Cow;
use std::collections::HashMap;
use std::io;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum Severity {
Error,
Warning,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Diagnostic {
pub severity: Severity,
pub cell: Option<String>,
pub element: Option<usize>,
pub layer: Option<Layer>,
pub field: String,
pub reason: String,
}
#[derive(Clone, Copy, Default)]
struct Location<'a> {
cell: Option<&'a str>,
element: Option<usize>,
layer: Option<Layer>,
}
struct Reporter<'a> {
oasis: Option<crate::oasis::Preflight<'a>>,
target: Format,
rows: Vec<Diagnostic>,
}
impl Reporter<'_> {
fn add(
&mut self,
place: Location<'_>,
field: impl Into<String>,
severity: Severity,
reason: impl Into<String>,
) {
self.rows.push(Diagnostic {
severity,
cell: place.cell.map(str::to_owned),
element: place.element,
layer: place.layer,
field: field.into(),
reason: reason.into(),
});
}
fn error(&mut self, p: Location<'_>, field: impl Into<String>, reason: impl Into<String>) {
self.add(p, field, Severity::Error, reason);
}
fn check(&mut self, p: Location<'_>, field: impl Into<String>, result: Result<()>) {
if let Err(e) = result {
self.error(p, field, e.to_string());
}
}
fn properties(
&mut self,
p: Location<'_>,
field: &str,
props: &[Property],
element_scope: bool,
) {
for (i, prop) in props.iter().enumerate() {
let path = || format!("{field}[{i}] ({})", prop.name);
let result = match self.target {
Format::Gdsii if !element_scope => Err(Error::unsupported(
"GDSII allows properties on elements only",
)),
Format::Gdsii => crate::gds::check_property(prop),
Format::Oasis => match &self.oasis {
Some(t) => t.check_property(prop),
None => crate::oasis::check_property(prop),
},
};
if let Err(e) = result {
self.error(p, path(), e.to_string());
}
}
}
fn element(&mut self, p: Location<'_>, e: &Element) {
self.properties(p, "properties", e.properties(), true);
let shape = e.unadorned();
if let Err(err) = shape.validate() {
self.error(p, "element", err.to_string());
return;
}
let first = self.rows.len();
if let Element::Repeated { element, .. } = shape {
if self.target == Format::Gdsii {
self.error(p, "repetition", "GDSII has no shape repetition record");
}
self.element(p, element);
if self.target == Format::Gdsii {
return;
}
}
if self.target == Format::Gdsii {
if let Some(l) = shape.layer() {
if l.number > u32::from(u16::MAX) {
self.error(p, "layer.number", "layer exceeds GDSII 16 bits");
}
if l.datatype > u32::from(u16::MAX) {
self.error(p, "layer.datatype", "datatype exceeds GDSII 16 bits");
}
}
match shape {
Element::Circle { .. } => {
self.error(p, "circle", "GDSII has no native circle record")
}
Element::Reference {
cell,
origin,
transform,
array,
} => {
self.check(p, "reference.cell", crate::gds::check_name(cell));
self.gds_transform(p, transform);
match array {
Some(Repetition::Offsets(_)) => self.error(
p,
"repetition.offsets",
"GDSII AREF requires regular row and column vectors",
),
Some(Repetition::Regular(a)) => {
self.check(p, "reference.array", crate::gds::check_array(*origin, a))
}
None => {}
}
}
Element::Text {
text,
text_reference,
style,
..
} => {
if text_reference.is_some() {
self.error(
p,
"text.reference",
"GDSII cannot preserve an explicit OASIS TEXTSTRING binding",
);
}
self.check(p, "text.value", crate::gds::check_text(text));
if let Some(style) = style {
self.gds_transform(p, &style.transform);
if style.width.is_some_and(|v| i32::try_from(v).is_err()) {
self.error(
p,
"text.stroke_width",
"stroke width exceeds GDSII signed 32-bit range",
);
}
}
}
Element::Path { width, .. } | Element::ExtendedPath { width, .. } => {
let absolute = matches!(
shape,
Element::ExtendedPath {
absolute_width: true,
..
}
);
if *width > i64::from(i32::MAX) + i64::from(absolute) {
self.error(
p,
"path.width",
"width exceeds the GDSII signed 32-bit range",
);
}
if let Element::ExtendedPath {
ends: PathEnds::Explicit { begin, end },
..
} = shape
{
if i32::try_from(*begin).is_err() {
self.error(
p,
"path.begin_extension",
"extension exceeds GDSII signed 32-bit range",
);
}
if i32::try_from(*end).is_err() {
self.error(
p,
"path.end_extension",
"extension exceeds GDSII signed 32-bit range",
);
}
}
}
_ => {}
}
let coordinates: &[Point] = match shape {
Element::Polygon { points, .. }
| Element::Path { points, .. }
| Element::ExtendedPath { points, .. } => points,
Element::Reference { origin, .. } | Element::Text { origin, .. } => {
std::slice::from_ref(origin)
}
_ => &[],
};
if let Some(i) = coordinates
.iter()
.position(|v| i32::try_from(v.x).is_err() || i32::try_from(v.y).is_err())
{
self.error(
p,
format!("coordinates[{i}]"),
"coordinate exceeds GDSII signed 32-bit range",
);
}
} else {
match shape {
Element::Text { text, .. } if !oas_string(text, false) => self.error(
p,
"text.value",
"OASIS TEXT must use printable ASCII and fit the string limit",
),
Element::Reference { cell, .. } if !oas_string(cell, true) => {
self.error(p, "reference.cell", "invalid OASIS referenced cell name")
}
_ => {}
}
match shape {
Element::Path { width, .. } | Element::ExtendedPath { width, .. } => {
if width % 2 != 0 {
self.error(p,"path.width",format!("odd full width {width} DBU has no integer OASIS half-width; a grid refinement factor of 2 preserves it exactly"));
}
if let Element::ExtendedPath {
absolute_width,
ends,
..
} = shape
{
if *absolute_width {
self.error(p,"path.absolute_width","OASIS cannot preserve absolute GDSII width under reference magnification");
}
if *ends == PathEnds::Round {
self.error(p, "path.ends", "OASIS PATH cannot encode round caps");
}
}
}
Element::Text {
style: Some(style), ..
} => {
if style.width.is_some() {
self.error(
p,
"text.stroke_width",
"OASIS TEXT has no GDSII stroke width",
);
}
if style.path_type.is_some() {
self.error(
p,
"text.path_type",
"OASIS TEXT has no GDSII stroke path type",
);
}
if style.presentation != 0 {
self.error(
p,
"text.presentation",
"OASIS TEXT cannot encode GDSII font and anchor bits",
);
}
if style.transform != crate::Transform::default() {
self.error(p,"text.transform","OASIS TEXT cannot encode GDSII label rotation, reflection or magnification");
}
}
_ => {}
}
}
if self.rows.len() == first {
let result = match self.target {
Format::Gdsii => crate::gds::check_element(shape),
Format::Oasis => match &self.oasis {
Some(t) => t.check_element(shape),
None => crate::oasis::check_element(shape),
},
};
if let Err(error) = result {
let reason = error.to_string();
let field = if reason.contains("string") {
"string"
} else if reason.contains("AREF") {
"reference.array"
} else if reason.contains("point") || reason.contains("coordinate") {
"points"
} else {
"element"
};
self.error(p, field, reason);
}
}
}
fn gds_transform(&mut self, p: Location<'_>, t: &crate::Transform) {
self.check(
p,
"transform.magnification",
crate::gds::encode_real(t.magnification).map(|_| ()),
);
self.check(
p,
"transform.angle_deg",
crate::gds::encode_real(t.angle_deg).map(|_| ()),
);
}
fn library(&mut self, layout: &Layout) {
let root = Location::default();
self.properties(root, "library.properties", &layout.properties, false);
match self.target {
Format::Gdsii => {
self.check(root, "library.name", crate::gds::check_name(&layout.name));
self.check(
root,
"dbu_meters",
crate::gds::write_header(
io::sink(),
"LIB",
1e-6,
layout.dbu_meters,
[100, 1, 1, 0, 0, 0],
),
);
}
Format::Oasis => {
let dbu_per_micron = 1e-6 / layout.dbu_meters;
if !dbu_per_micron.is_finite() || dbu_per_micron <= 0.0 {
self.error(
root,
"dbu_meters",
"OASIS database units per micrometre exceed the real range",
);
}
if layout.name != "LIBRARY" {
self.add(
root,
"library.name",
Severity::Warning,
"OASIS has no library-name field",
);
}
}
}
let mut orphan_names = HashMap::new();
for (i, t) in layout.table_properties.iter().enumerate() {
let field = format!("table_properties[{i}]");
if self.target == Format::Gdsii {
self.error(
root,
field,
"GDSII cannot store OASIS string table metadata",
);
continue;
}
let valid = match &t.entry {
TableEntry::Text(s) => oas_string(s, false),
TableEntry::PropertyName(s) => oas_string(s, true),
TableEntry::CellName(s) => {
orphan_names.insert(s.as_str(), i);
oas_string(s, true)
}
TableEntry::PropertyString(b) => b.len() <= crate::oasis::MAX_STRING,
};
if !valid {
self.error(
root,
format!("{field}.entry"),
"OASIS table string exceeds length or alphabet restrictions",
);
}
self.properties(root, &format!("{field}.properties"), &t.properties, false);
}
for (i, l) in layout.layer_names.iter().enumerate() {
let field = format!("layer_names[{i}]");
if self.target == Format::Gdsii {
self.error(root, field, "GDSII has no layer-name records");
continue;
}
if !oas_string(&l.name, true) {
self.error(root, format!("{field}.name"), "invalid OASIS layer name");
}
for (suffix, v) in [("layers", l.layers), ("datatypes", l.datatypes)] {
if matches!(v,Interval::Range(a,b) if b<a) {
self.error(root, format!("{field}.{suffix}"), "reversed layer interval");
}
}
self.properties(root, &format!("{field}.properties"), &l.properties, false);
}
for cell in &layout.cells {
let cp = Location {
cell: Some(&cell.name),
..root
};
if let Some(i) = orphan_names.get(cell.name.as_str()) {
self.error(cp, format!("table_properties[{i}].entry"), "orphan CELLNAME has a cell definition; specify its metadata on cell.name_properties");
}
match self.target {
Format::Gdsii => self.check(cp, "cell.name", crate::gds::check_name(&cell.name)),
Format::Oasis if !oas_string(&cell.name, true) => self.error(
cp,
"cell.name",
"invalid OASIS cell-name alphabet or length",
),
_ => {}
}
self.properties(cp, "cell.properties", &cell.properties, false);
self.properties(cp, "cell.name_properties", &cell.name_properties, false);
for (idx, element) in cell.elements.iter().enumerate() {
self.element(
Location {
element: Some(idx),
layer: element.layer(),
..cp
},
element,
);
}
}
}
}
fn oas_string(s: &str, name: bool) -> bool {
s.len() <= crate::oasis::MAX_STRING && crate::oasis::legal_string(s.as_bytes(), name)
}
fn check_regrid_properties(props: &[Property]) -> Result<()> {
for p in props {
if p.standard && !matches!(p.name.as_str(), "S_GDS_PROPERTY" | "S_TOP_CELL") {
return Err(Error::unsupported(format!(
"refining an OASIS standard property {:?} requires interpreting its values",
p.name
)));
}
}
Ok(())
}
struct GridMap<S, U> {
signed: S,
unsigned: U,
}
impl<S, U> GridMap<S, U>
where
S: Fn(i64, &str) -> Result<i64>,
U: Fn(u64, &str) -> Result<u64>,
{
fn point(&self, p: &mut Point) -> Result<()> {
p.x = (self.signed)(p.x, "x")?;
p.y = (self.signed)(p.y, "y")?;
Ok(())
}
fn repetition(&self, r: &mut Repetition) -> Result<()> {
match r {
Repetition::Regular(a) => {
self.point(&mut a.column_step)?;
self.point(&mut a.row_step)?;
}
Repetition::Offsets(offsets) => {
for p in offsets {
self.point(p)?;
}
}
}
Ok(())
}
fn path(&self, points: &mut [Point], width: &mut i64) -> Result<()> {
for p in points {
self.point(p)?;
}
*width = (self.signed)(*width, "path.width")?;
Ok(())
}
fn element(&self, e: &mut Element) -> Result<()> {
match e {
Element::Attributed {
element,
properties,
} => {
check_regrid_properties(properties)?;
self.element(element)?;
}
Element::Repeated { element, array } => {
self.repetition(array)?;
self.element(element)?;
}
Element::Reference { origin, array, .. } => {
self.point(origin)?;
if let Some(a) = array {
self.repetition(a)?;
}
}
Element::Text { origin, style, .. } => {
self.point(origin)?;
if let Some(s) = style
&& let Some(w) = &mut s.width
{
*w = (self.signed)(*w, "text.stroke_width")?;
}
}
Element::Circle { center, radius, .. } => {
self.point(center)?;
*radius = (self.unsigned)(*radius, "circle.radius")?;
}
Element::Polygon { points, .. } => {
for p in points {
self.point(p)?;
}
}
Element::Path { points, width, .. } => self.path(points, width)?,
Element::ExtendedPath {
points,
width,
ends,
..
} => {
self.path(points, width)?;
if let PathEnds::Explicit { begin, end } = ends {
*begin = (self.signed)(*begin, "begin extension")?;
*end = (self.signed)(*end, "end extension")?;
}
}
}
Ok(())
}
}
impl Layout {
pub fn conversion_diagnostics(&self, format: Format) -> Vec<Diagnostic> {
let mut report = Reporter {
target: format,
rows: Vec::new(),
oasis: None,
};
if format == Format::Oasis {
match crate::oasis::Preflight::new(&self.table_properties) {
Ok(t) => report.oasis = Some(t),
Err(e) => report.error(Location::default(), "table_properties", e.to_string()),
}
}
if let Err(e) = self.validate() {
report.error(Location::default(), "layout", e.to_string());
}
report.library(self);
report.rows
}
pub fn regrid_exact(&self, factor: u32) -> Result<Self> {
self.regrid_selection(factor, false)
}
pub(crate) fn regrid_selection(&self, factor: u32, allow_external: bool) -> Result<Self> {
self.validate_references(allow_external)?;
if factor == 0 {
return Err(Error::invalid("regrid factor must be positive"));
}
if factor == 1 {
return Ok(self.clone());
}
let odd = u64::from(factor >> factor.trailing_zeros());
let bits = self.dbu_meters.to_bits();
let stored_fraction = bits & ((1u64 << 52) - 1);
let significand = if bits >> 52 == 0 {
stored_fraction
} else {
(1u64 << 52) | stored_fraction
};
let dbu = self.dbu_meters / f64::from(factor);
if !significand.is_multiple_of(odd)
|| dbu == 0.
|| dbu * f64::from(factor) != self.dbu_meters
{
return Err(Error::unsupported(
"refined DBU cannot be represented exactly as f64",
));
}
self.map_grid_dimensions(
dbu,
allow_external,
|v, field| {
v.checked_mul(i64::from(factor)).ok_or_else(|| {
Error::unsupported(format!("regrid overflow in {field} ({v} × {factor})"))
})
},
|v, field| {
v.checked_mul(u64::from(factor)).ok_or_else(|| {
Error::unsupported(format!("regrid overflow in {field} ({v} × {factor})"))
})
},
)
}
pub(crate) fn map_grid_dimensions(
&self,
new_dbu: f64,
allow_external: bool,
signed: impl Fn(i64, &str) -> Result<i64>,
unsigned: impl Fn(u64, &str) -> Result<u64>,
) -> Result<Self> {
if !new_dbu.is_finite() || new_dbu <= 0. {
return Err(Error::invalid("target DBU must be positive and finite"));
}
self.validate_references(allow_external)?;
let map = GridMap { signed, unsigned };
check_regrid_properties(&self.properties)?;
for l in &self.layer_names {
check_regrid_properties(&l.properties)?;
}
for t in &self.table_properties {
check_regrid_properties(&t.properties)?;
}
let mut out = self.clone();
out.dbu_meters = new_dbu;
for cell in &mut out.cells {
check_regrid_properties(&cell.name_properties)?;
check_regrid_properties(&cell.properties)?;
for (index, e) in cell.elements.iter_mut().enumerate() {
if let Err(err) = map.element(e) {
return Err(err.at_element(&cell.name, index, e));
}
}
}
out.validate_references(allow_external)?;
Ok(out)
}
pub fn with_regrid(&self, factor: u32) -> Result<Cow<'_, Self>> {
if factor == 1 {
Ok(Cow::Borrowed(self))
} else {
Ok(Cow::Owned(self.regrid_exact(factor)?))
}
}
}
#[cfg(feature = "python")]
pub(crate) fn python_rows(
py: pyo3::Python<'_>,
rows: Vec<Diagnostic>,
) -> pyo3::PyResult<Vec<pyo3::Py<pyo3::types::PyDict>>> {
use pyo3::prelude::*;
use pyo3::types::PyDict;
rows.into_iter()
.map(|r| {
let d = PyDict::new(py);
d.set_item(
"severity",
if r.severity == Severity::Error {
"error"
} else {
"warning"
},
)?;
d.set_item("cell", r.cell)?;
d.set_item("element", r.element)?;
d.set_item("layer", r.layer.map(|l| (l.number, l.datatype)))?;
d.set_item("field", r.field)?;
d.set_item("reason", r.reason)?;
Ok(d.unbind())
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{Array, TextStyle, Transform};
fn layer() -> Layer {
Layer {
number: 4,
datatype: 11,
}
}
fn p(x: i64, y: i64) -> Point {
Point { x, y }
}
fn path(width: i64) -> Element {
Element::Path {
layer: layer(),
points: vec![p(-5, 0), p(7, 13)],
width,
}
}
#[test]
fn reports_independent_fields_on_multiple_elements() {
let mut l = Layout::new("LIBRARY", 1e-9).unwrap();
l.add_cell("WIRE").unwrap();
l.add_element(
"WIRE",
Element::ExtendedPath {
layer: layer(),
points: vec![p(0, 0), p(4, 0)],
width: 3,
absolute_width: true,
ends: PathEnds::Round,
},
)
.unwrap();
l.add_element(
"WIRE",
Element::Text {
layer: layer(),
origin: p(1, 2),
text: "P".into(),
text_reference: None,
style: Some(TextStyle {
presentation: 5,
path_type: None,
width: None,
transform: Transform {
angle_deg: 45.,
..Default::default()
},
}),
},
)
.unwrap();
let report = l.conversion_diagnostics(Format::Oasis);
let keys: Vec<_> = report
.iter()
.map(|r| (r.element, r.field.as_str()))
.collect();
assert_eq!(
keys,
[
(Some(0), "path.width"),
(Some(0), "path.absolute_width"),
(Some(0), "path.ends"),
(Some(1), "text.presentation"),
(Some(1), "text.transform")
]
);
assert!(report.iter().all(|row| row.cell.as_deref() == Some("WIRE")
&& row.layer == Some(layer())
&& row.severity == Severity::Error));
}
#[test]
fn preflight_matches_writer_on_explicit_oasis_table_bindings() {
let mut layout = Layout::new("LIBRARY", 1e-9).unwrap();
for id in [11, 23] {
layout.table_properties.push(crate::TableProperties {
entry: TableEntry::Text("PIN".into()),
reference: Some(id),
properties: Vec::new(),
});
}
layout.add_cell("CELL").unwrap();
layout
.add_element(
"CELL",
Element::Text {
layer: layer(),
text: "PIN".into(),
text_reference: Some(23),
origin: p(0, 0),
style: None,
},
)
.unwrap();
assert!(layout.conversion_diagnostics(Format::Oasis).is_empty());
let mut wire = Vec::new();
crate::write_to(&layout, &mut wire, Format::Oasis).unwrap();
let decoded = crate::read_from(wire.as_slice(), None).unwrap();
assert!(decoded.conversion_diagnostics(Format::Oasis).is_empty());
assert_eq!(decoded.cells[0].elements, layout.cells[0].elements);
let issues = decoded.conversion_diagnostics(Format::Gdsii);
assert!(issues.iter().any(|row| row.field == "text.reference"
&& row.cell.as_deref() == Some("CELL")
&& row.element == Some(0)));
assert_eq!(
issues
.iter()
.filter(|r| r.field.starts_with("table_properties["))
.count(),
2
);
assert!(crate::write_to(&decoded, std::io::sink(), Format::Gdsii).is_err());
}
#[test]
fn doubling_database_resolution_keeps_physical_grid_and_repetition() {
let mut l = Layout::new("LIBRARY", 1e-9).unwrap();
l.add_cell("LEAF").unwrap();
l.add_cell("TOP").unwrap();
l.add_element("LEAF", path(3)).unwrap();
l.add_element(
"TOP",
Element::Reference {
cell: "LEAF".into(),
origin: p(-3, 4),
transform: Transform::default(),
array: Some(Repetition::Regular(Array {
columns: 2,
rows: 4,
column_step: p(10, 0),
row_step: p(0, 25),
})),
},
)
.unwrap();
let refined = l.regrid_exact(2).unwrap();
assert_eq!(l.dbu_meters, 1e-9);
assert_eq!(refined.dbu_meters, 0.5e-9);
assert_eq!(
refined.cells[0].elements[0],
Element::Path {
layer: layer(),
points: vec![p(-10, 0), p(14, 26)],
width: 6
}
);
if let Element::Reference {
origin,
array: Some(Repetition::Regular(a)),
..
} = &refined.cells[1].elements[0]
{
assert_eq!(*origin, p(-6, 8));
assert_eq!(a.column_step, p(20, 0));
assert_eq!(a.row_step, p(0, 50));
assert_eq!(a.rows, 4);
} else {
panic!("missing regular array")
}
assert!(refined.conversion_diagnostics(Format::Oasis).is_empty());
}
#[test]
fn refine_refuses_inexact_units_and_coordinate_overflow() {
let mut l = Layout::new("MASK", 1.0).unwrap();
assert!(l.regrid_exact(3).is_err());
l.add_cell("X").unwrap();
l.add_element(
"X",
Element::Polygon {
layer: layer(),
points: vec![p(i64::MAX, 0), p(0, 2), p(0, 3)],
},
)
.unwrap();
let err = l.regrid_exact(2).unwrap_err().to_string();
assert!(err.contains("X") && err.contains("overflow"));
assert_eq!(l.dbu_meters, 1.);
}
}