layouttk 0.1.1

Integer-grid GDSII and OASIS layout processing with hierarchy-aware extraction
Documentation
use super::*;
use crate::{Interval, LayerName, Property, PropertyValue};
use pyo3::types::{PyAny, PyTuple};

pub(super) type PyProperties = Vec<(Py<PyAny>, bool, Vec<(String, Py<PyAny>)>)>;

fn binding<'py>(object: &Bound<'py, PyAny>) -> PyResult<(Bound<'py, PyAny>, Option<u64>)> {
    if object.is_instance_of::<PyTuple>() {
        let class = object
            .py()
            .import("layouttk.metadata")?
            .getattr("TableRef")?;
        if object.is_instance(&class)? {
            return Ok((
                object.getattr("value")?,
                Some(object.getattr("reference")?.extract()?),
            ));
        }
    }
    Ok((object.clone(), None))
}

fn with_binding(py: Python<'_>, value: Py<PyAny>, reference: Option<u64>) -> PyResult<Py<PyAny>> {
    match reference {
        Some(index) => Ok(py
            .import("layouttk.metadata")?
            .getattr("TableRef")?
            .call1((value, index))?
            .unbind()),
        None => Ok(value),
    }
}

fn decode_value(kind: &str, value: &Bound<'_, PyAny>) -> PyResult<PropertyValue> {
    Ok(match kind {
        "unsigned" => PropertyValue::Unsigned(value.extract()?),
        "signed" => PropertyValue::Signed(value.extract()?),
        "real" => PropertyValue::Real(value.extract()?),
        "ratio" => {
            let (negative, numerator, denominator) = value.extract()?;
            if denominator == 0 {
                return Err(LayoutError::new_err("a ratio needs a nonzero denominator"));
            }
            PropertyValue::Ratio {
                negative,
                numerator,
                denominator,
            }
        }
        "ascii" | "name" | "binary" => {
            let (content, reference) = binding(value)?;
            let string = match kind {
                "ascii" => PropertyValue::Ascii(content.extract()?),
                "name" => PropertyValue::Name(content.extract()?),
                _ => PropertyValue::Binary(content.cast::<PyBytes>()?.as_bytes().to_owned()),
            };
            match reference {
                Some(reference) => PropertyValue::ReferencedString {
                    reference,
                    value: Box::new(string),
                },
                None => string,
            }
        }
        _ => {
            return Err(LayoutError::new_err(format!(
                "unknown property value type {kind:?}"
            )));
        }
    })
}

pub(super) fn decode(py: Python<'_>, properties: PyProperties) -> PyResult<Vec<Property>> {
    properties
        .into_iter()
        .map(|(name, standard, values)| {
            let (name, name_reference) = binding(name.bind(py))?;
            let values = values
                .into_iter()
                .map(|(kind, object)| decode_value(&kind, object.bind(py)))
                .collect::<PyResult<Vec<_>>>()?;
            Ok(Property {
                name: name.extract()?,
                name_reference,
                standard,
                values,
            })
        })
        .collect()
}

fn encode_value(py: Python<'_>, value: &PropertyValue) -> PyResult<(String, Py<PyAny>)> {
    let (kind, value) = match value {
        PropertyValue::Unsigned(n) => ("unsigned", n.into_pyobject(py)?.into_any().unbind()),
        PropertyValue::Signed(n) => ("signed", n.into_pyobject(py)?.into_any().unbind()),
        PropertyValue::Real(n) => ("real", n.into_pyobject(py)?.into_any().unbind()),
        PropertyValue::Ratio {
            negative,
            numerator,
            denominator,
        } => (
            "ratio",
            (negative, numerator, denominator)
                .into_pyobject(py)?
                .into_any()
                .unbind(),
        ),
        PropertyValue::Ascii(s) => ("ascii", s.into_pyobject(py)?.into_any().unbind()),
        PropertyValue::Name(s) => ("name", s.into_pyobject(py)?.into_any().unbind()),
        PropertyValue::Binary(b) => ("binary", PyBytes::new(py, b).into_any().unbind()),
        PropertyValue::ReferencedString { reference, value } => {
            let (kind, content) = encode_value(py, value)?;
            return Ok((kind, with_binding(py, content, Some(*reference))?));
        }
    };
    Ok((kind.to_owned(), value))
}

pub(super) fn encode(py: Python<'_>, properties: &[Property]) -> PyResult<PyProperties> {
    properties
        .iter()
        .map(|p| {
            let values = p
                .values
                .iter()
                .map(|value| encode_value(py, value))
                .collect::<PyResult<_>>()?;
            let name = p.name.as_str().into_pyobject(py)?.into_any().unbind();
            Ok((
                with_binding(py, name, p.name_reference)?,
                p.standard,
                values,
            ))
        })
        .collect()
}

pub(super) type Bounds = (Option<u32>, Option<u32>);
fn interval((low, high): Bounds) -> PyResult<Interval> {
    Ok(match (low, high) {
        (None, None) => Interval::All,
        (Some(n), None) => Interval::AtLeast(n),
        (None, Some(n)) => Interval::AtMost(n),
        (Some(a), Some(b)) if a == b => Interval::Exactly(a),
        (Some(a), Some(b)) if a < b => Interval::Range(a, b),
        _ => return Err(LayoutError::new_err("lower bound exceeds upper bound")),
    })
}
fn bounds(i: Interval) -> Bounds {
    match i {
        Interval::All => (None, None),
        Interval::AtLeast(n) => (Some(n), None),
        Interval::AtMost(n) => (None, Some(n)),
        Interval::Exactly(n) => (Some(n), Some(n)),
        Interval::Range(a, b) => (Some(a), Some(b)),
    }
}
pub(super) fn layer_name(
    name: String,
    text: bool,
    layers: Bounds,
    datatypes: Bounds,
    properties: Vec<Property>,
) -> PyResult<LayerName> {
    Ok(LayerName {
        name,
        text,
        layers: interval(layers)?,
        datatypes: interval(datatypes)?,
        properties,
    })
}
pub(super) fn layer_dict<'py>(py: Python<'py>, layer: &LayerName) -> PyResult<Bound<'py, PyDict>> {
    let d = PyDict::new(py);
    d.set_item("name", &layer.name)?;
    d.set_item("text", layer.text)?;
    d.set_item("layers", bounds(layer.layers))?;
    d.set_item("datatypes", bounds(layer.datatypes))?;
    d.set_item("properties", property_objects(py, &layer.properties)?)?;
    Ok(d)
}

pub(super) fn table_entry(kind: &str, value: &Bound<'_, PyAny>) -> PyResult<crate::TableEntry> {
    Ok(match kind {
        "cell_name" => crate::TableEntry::CellName(value.extract()?),
        "text" => crate::TableEntry::Text(value.extract()?),
        "property_name" => crate::TableEntry::PropertyName(value.extract()?),
        "property_string" => {
            crate::TableEntry::PropertyString(value.cast::<PyBytes>()?.as_bytes().to_owned())
        }
        _ => {
            return Err(LayoutError::new_err(
                "expected cell_name, text, property_name or property_string table",
            ));
        }
    })
}

pub(super) fn table_dict<'py>(
    py: Python<'py>,
    t: &crate::TableProperties,
) -> PyResult<Bound<'py, PyDict>> {
    let d = PyDict::new(py);
    if let Some(reference) = t.reference {
        d.set_item("reference", reference)?;
    }
    match &t.entry {
        crate::TableEntry::CellName(s) => {
            d.set_item("kind", "cell_name")?;
            d.set_item("value", s)?;
        }
        crate::TableEntry::Text(s) => {
            d.set_item("kind", "text")?;
            d.set_item("value", s)?
        }
        crate::TableEntry::PropertyName(s) => {
            d.set_item("kind", "property_name")?;
            d.set_item("value", s)?
        }
        crate::TableEntry::PropertyString(b) => {
            d.set_item("kind", "property_string")?;
            d.set_item("value", PyBytes::new(py, b))?
        }
    }
    d.set_item("properties", property_objects(py, &t.properties)?)?;
    Ok(d)
}

pub(super) fn property_objects(py: Python<'_>, props: &[Property]) -> PyResult<Py<PyAny>> {
    Ok(py
        .import("layouttk.metadata")?
        .getattr("_from_native")?
        .call1((encode(py, props)?,))?
        .unbind())
}