layouttk 0.1.2

Integer-grid GDSII and OASIS layout processing with hierarchy-aware extraction
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
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 {
    /// Reflection about the x axis is applied before rotation.
    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 {
    /// GDSII PRESENTATION bits (font and anchor).
    pub presentation: u16,
    /// Optional GDSII stroke style for the glyph renderer.
    pub path_type: Option<u16>,
    /// Signed stroke width in DBU. A negative value is absolute under magnification.
    pub width: Option<i64>,
    pub transform: Transform,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Array {
    pub columns: u32,
    pub rows: u32,
    /// Step vectors in the coordinate system of the containing cell.
    pub column_step: Point,
    pub row_step: Point,
}

/// Offsets are in the parent coordinate system, relative to the implicit first position.
#[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),
    /// Exact OASIS real whose numerator or denominator should survive rewriting.
    Ratio {
        negative: bool,
        numerator: u64,
        denominator: u64,
    },
    Ascii(String),
    Binary(Vec<u8>),
    Name(String),
    /// OASIS PROPSTRING binding. The payload is exactly one Ascii, Binary or Name.
    ReferencedString {
        reference: u64,
        value: Box<PropertyValue>,
    },
}

#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct Property {
    pub name: String,
    /// Explicit OASIS PROPNAME identity when equal bytes have distinct bindings.
    pub name_reference: Option<u64>,
    pub standard: bool,
    pub values: Vec<PropertyValue>,
}

impl Property {
    /// The OASIS standard carrier for a numeric GDSII element attribute.
    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()),
            ],
        }
    }
}

/// OASIS string table entry that owns one or more properties.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize)]
pub enum TableEntry {
    /// CELLNAME metadata for a name without a CELL declaration.
    CellName(String),
    Text(String),
    PropertyName(String),
    PropertyString(Vec<u8>),
}

#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct TableProperties {
    pub entry: TableEntry,
    /// An explicit identity in this entry's own table. None binds uses by value.
    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 {
    /// Ordered metadata for one stored element, including an entire placement or shape repetition.
    Attributed {
        element: Box<Element>,
        properties: Vec<Property>,
    },
    ExtendedPath {
        layer: Layer,
        points: Vec<Point>,
        width: i64,
        absolute_width: bool,
        ends: PathEnds,
    },
    /// Native OASIS circle. The radius is in the same integer DBU as the center.
    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,
        /// Identifies the precise OASIS TEXTSTRING entry in an alias group.
        text_reference: Option<u64>,
        style: Option<TextStyle>,
    },
    /// A compact OASIS regular array of a geometric element or text.
    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,
            }
        }
    }

    /// Attach, replace, or remove the repetition on this element.
    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>,
    /// Number of stored records in each category; array instances are counted once.
    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))
    }

    /// Define a cell, retaining any existing OASIS annotations on its 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)
    }

    /// Check geometry, reference targets and acyclicity without flattening or recursion.
    pub fn validate(&self) -> Result<()> {
        self.validate_references(false)
    }

    /// Allow unresolved references for a library fragment, while checking all defined cells.
    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(())
    }

    /// Referenced names whose definitions are supplied by a different library.
    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)
    }

    /// Distinct layer/type pairs used by a cell, optionally including all dependencies.
    /// Neither array placements nor repeated geometry need to be expanded.
    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())
        }
    }

    /// Copy the root and its dependencies, preserving cell order.
    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(),
        })
    }

    /// Keep a root and its transitive references, retaining original cell order.
    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);
    }
}