layouttk 0.3.1

GDSII and OASIS layout toolkit for layer extraction, verification, and window clipping
Documentation
//! Rebind file-local OASIS names when importing one cell closure into another library.
use crate::{
    Cell, Element, Error, Layout, Property, PropertyValue, Result, TableEntry, TableProperties,
};
use std::collections::{BTreeMap, BTreeSet};

fn key(entry: &TableEntry) -> (u8, &[u8]) {
    match entry {
        TableEntry::CellName(s) => (4, s.as_bytes()),
        TableEntry::Text(s) => (6, s.as_bytes()),
        TableEntry::PropertyName(s) => (8, s.as_bytes()),
        TableEntry::PropertyString(b) => (10, b),
    }
}

#[derive(Default)]
struct Allocator {
    used: BTreeSet<(u8, u64)>,
    next: [u64; 11],
}

impl Allocator {
    fn assign(&mut self, kind: u8, preferred: Option<u64>) -> u64 {
        if let Some(id) = preferred
            && self.used.insert((kind, id))
        {
            return id;
        }
        let next = &mut self.next[kind as usize];
        while !self.used.insert((kind, *next)) {
            *next += 1;
        }
        *next
    }
}

struct Bindings<'a> {
    // These keys are from the pre-import library; indices point into its table list.
    numbered: BTreeMap<(u8, u64), (usize, &'a [u8])>,
    defaults: BTreeMap<(u8, &'a [u8]), usize>,
    output_ids: Vec<u64>,
    used: BTreeSet<usize>,
    pending: Vec<usize>,
}

impl<'a> Bindings<'a> {
    fn new(tables: &'a [TableProperties], output_ids: Vec<u64>) -> Self {
        let mut numbered = BTreeMap::new();
        let mut defaults = BTreeMap::new();
        for (i, table) in tables.iter().enumerate() {
            let (kind, bytes) = key(&table.entry);
            if let Some(id) = table.reference {
                numbered.insert((kind, id), (i, bytes));
            }
            // CELLNAME is globally unique by name even when a file assigns it an ID.
            if table.reference.is_none() || kind == 4 {
                defaults.insert((kind, bytes), i);
            }
        }
        Self {
            numbered,
            defaults,
            output_ids,
            used: BTreeSet::new(),
            pending: vec![],
        }
    }

    fn bind(&mut self, kind: u8, bytes: &[u8], reference: Option<u64>) -> Result<Option<u64>> {
        let index = match reference {
            Some(id) => match self.numbered.get(&(kind, id)) {
                Some(&(i, b)) if bytes == b => Some(i),
                _ => {
                    return Err(Error::invalid(format!(
                        "OASIS table {kind} reference {id} is missing or has a different value"
                    )));
                }
            },
            None => self.defaults.get(&(kind, bytes)).copied(),
        };
        Ok(index.map(|i| {
            if self.used.insert(i) {
                self.pending.push(i);
            }
            self.output_ids[i]
        }))
    }

    fn properties(&mut self, props: &mut [Property]) -> Result<()> {
        for p in props {
            p.name_reference = self.bind(8, p.name.as_bytes(), p.name_reference)?;
            for item in &mut p.values {
                let (payload, old_id) = match &*item {
                    PropertyValue::ReferencedString { reference, value } => {
                        (value.as_ref(), Some(*reference))
                    }
                    plain => (plain, None),
                };
                let bytes = match payload {
                    PropertyValue::Ascii(s) | PropertyValue::Name(s) => s.as_bytes(),
                    PropertyValue::Binary(v) => v.as_slice(),
                    _ if old_id.is_some() => {
                        return Err(Error::invalid("invalid referenced OASIS property string"));
                    }
                    _ => continue,
                };
                if let Some(id) = self.bind(10, bytes, old_id)? {
                    match item {
                        PropertyValue::ReferencedString { reference, .. } => *reference = id,
                        plain => {
                            *plain = PropertyValue::ReferencedString {
                                reference: id,
                                value: Box::new(plain.clone()),
                            }
                        }
                    }
                }
            }
        }
        Ok(())
    }

    fn element(&mut self, e: &mut Element) -> Result<()> {
        match e {
            Element::Text {
                text,
                text_reference,
                ..
            } => {
                *text_reference = self.bind(6, text.as_bytes(), *text_reference)?;
                Ok(())
            }
            Element::Attributed {
                element,
                properties,
            } => {
                self.properties(properties)?;
                self.element(element)
            }
            Element::Repeated { element, .. } => self.element(element),
            _ => Ok(()),
        }
    }

    fn cell(&mut self, c: &mut Cell) -> Result<()> {
        self.properties(&mut c.properties)?;
        self.properties(&mut c.name_properties)?;
        for e in &mut c.elements {
            self.element(e)?;
        }
        Ok(())
    }
}

/// Plan every failure before committing changes to the destination. Materializing
/// its by-value bindings prevents incoming inline strings from inheriting annotations.
pub(super) fn merge(
    destination: &mut Layout,
    subset: &mut Layout,
    external_names: &[String],
) -> Result<()> {
    if subset.cells.is_empty()
        || (destination.table_properties.is_empty() && subset.table_properties.is_empty())
    {
        return Ok(());
    }
    let mut alloc = Allocator::default();
    for t in &destination.table_properties {
        if let Some(id) = t.reference {
            alloc.used.insert((key(&t.entry).0, id));
        }
    }
    let dest_ids: Vec<_> = destination
        .table_properties
        .iter()
        .map(|t| {
            t.reference
                .unwrap_or_else(|| alloc.assign(key(&t.entry).0, None))
        })
        .collect();
    let unique_names: BTreeMap<_, _> = destination
        .table_properties
        .iter()
        .enumerate()
        .filter_map(|(i, t)| match &t.entry {
            TableEntry::PropertyName(_) | TableEntry::CellName(_) => Some((&t.entry, i)),
            _ => None,
        })
        .collect();
    let src_ids = subset
        .table_properties
        .iter()
        .map(|t| {
            if let Some(&i) = unique_names.get(&t.entry) {
                return dest_ids[i];
            }
            alloc.assign(key(&t.entry).0, t.reference)
        })
        .collect();
    let mut src = Bindings::new(&subset.table_properties, src_ids);
    for name in external_names {
        src.bind(4, name.as_bytes(), None)?;
    }
    for c in &mut subset.cells {
        src.cell(c)?;
    }
    let mut imported = Vec::new();
    let mut coalesced = Vec::new();
    let mut cell_owners = Vec::new();
    // Property names and string values on table records may themselves own properties.
    while let Some(i) = src.pending.pop() {
        let mut record = subset.table_properties[i].clone();
        record.reference = Some(src.output_ids[i]);
        src.properties(&mut record.properties)?;
        if let TableEntry::CellName(name) = &record.entry
            && let Some(cell) = subset.cells.iter_mut().find(|c| &c.name == name)
        {
            if cell.name_properties.is_empty() {
                cell.name_properties = record.properties;
            } else if !record.properties.is_empty() && cell.name_properties != record.properties {
                return Err(Error::invalid(format!(
                    "incompatible OASIS CELLNAME properties on {name:?}"
                )));
            }
        } else if let Some(&j) = unique_names.get(&record.entry) {
            coalesced.push((j, record));
        } else if let TableEntry::CellName(s) = &record.entry
            && let Some(j) = destination.cells.iter().position(|c| &c.name == s)
        {
            cell_owners.push((j, record));
        } else {
            imported.push((i, record));
        }
    }
    imported.sort_unstable_by_key(|(i, _)| *i);

    // Most file reads already carry explicit IDs. Only the authored by-value case
    // needs to update preexisting consumers; stage it so any conflict is atomic.
    let mut staged = None;
    if destination
        .table_properties
        .iter()
        .any(|t| t.reference.is_none())
    {
        let mut result = destination.clone();
        let mut dest = Bindings::new(&destination.table_properties, dest_ids);
        dest.properties(&mut result.properties)?;
        for c in &mut result.cells {
            dest.cell(c)?;
        }
        for l in &mut result.layer_names {
            dest.properties(&mut l.properties)?;
        }
        for (i, t) in result.table_properties.iter_mut().enumerate() {
            dest.properties(&mut t.properties)?;
            t.reference = Some(dest.output_ids[i]);
        }
        staged = Some(result);
    }
    let target = staged.as_ref().unwrap_or(destination);
    for (j, record) in coalesced {
        if target.table_properties[j].properties != record.properties {
            return Err(Error::invalid(format!(
                "import has incompatible annotations on unique OASIS CELLNAME/PROPNAME {:?}",
                record.entry
            )));
        }
    }
    for (i, record) in &cell_owners {
        let existing = &target.cells[*i].name_properties;
        if !existing.is_empty() && !record.properties.is_empty() && existing != &record.properties {
            return Err(Error::invalid(format!(
                "incompatible OASIS CELLNAME properties on {:?}",
                target.cells[*i].name
            )));
        }
    }
    // A formerly external target can acquire a definition in this import.
    // Its annotated name now belongs on the cell, even if its old ID changes.
    let mut promoted = BTreeSet::new();
    for c in &mut subset.cells {
        if let Some(&i) = unique_names.get(&TableEntry::CellName(c.name.clone())) {
            let previous = &target.table_properties[i].properties;
            if c.name_properties.is_empty() {
                c.name_properties.clone_from(previous);
            } else if !previous.is_empty() && previous != &c.name_properties {
                return Err(Error::invalid(format!(
                    "incompatible OASIS CELLNAME properties on {:?}",
                    c.name
                )));
            }
            promoted.insert(i);
        }
    }
    if let Some(result) = staged {
        *destination = result;
    }
    for (i, record) in cell_owners {
        if destination.cells[i].name_properties.is_empty() {
            destination.cells[i].name_properties = record.properties;
        }
    }
    if !promoted.is_empty() {
        let mut index = 0;
        destination.table_properties.retain(|_| {
            index += 1;
            !promoted.contains(&(index - 1))
        });
    }
    destination
        .table_properties
        .extend(imported.into_iter().map(|(_, r)| r));
    Ok(())
}