libreda_db/
chip.rs

1// Copyright (c) 2020-2021 Thomas Kramer.
2// SPDX-FileCopyrightText: 2022 Thomas Kramer
3//
4// SPDX-License-Identifier: AGPL-3.0-or-later
5
6//! Chip data structure holding netlist and layout together.
7//! [`Chip`] implements the [`trait@L2NEdit`] trait and hence qualifies for representing
8//! netlists fused with a layout. [`Chip`] can also be used solely as a netlist structure
9//! or as a layout structure.
10
11// TODO: Remove this when fully implemented.
12#![allow(unused_variables)]
13
14use iron_shapes::prelude::{Geometry, Rect};
15use iron_shapes::transform::SimpleTransform;
16use iron_shapes::CoordinateType;
17
18use crate::index::*;
19use crate::prelude::{
20    HierarchyBase, HierarchyEdit, HierarchyIds, L2NBase, L2NEdit, LayoutBase, LayoutEdit,
21    MapPointwise, NetlistBase, NetlistEdit,
22};
23use crate::traits::{LayoutIds, NetlistIds};
24use itertools::Itertools;
25use std::borrow::{Borrow, BorrowMut};
26use std::collections::HashMap;
27use std::hash::Hash;
28
29use crate::netlist::direction::Direction;
30// use crate::rc_string::RcString;
31use std::fmt::Debug;
32
33use crate::layout::types::LayerInfo;
34use crate::property_storage::{PropertyStore, PropertyValue};
35
36// Use an alternative hasher that has better performance for integer keys.
37use fnv::{FnvHashMap, FnvHashSet};
38
39use crate::prelude::TryBoundingBox;
40use num_traits::One;
41
42type NameT = String;
43
44type IntHashMap<K, V> = FnvHashMap<K, V>;
45type IntHashSet<V> = FnvHashSet<V>;
46
47/// Default unsigned integer type.
48pub type UInt = u32;
49/// Default signed integer type.
50pub type SInt = i32;
51
52/// Integer coordinate type.
53pub type Coord = i32;
54/// Integer area type.
55pub type Area = i64;
56
57/// Circuit identifier.
58#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
59#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
60pub struct CellId(u32);
61
62/// Circuit instance identifier.
63#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
64#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
65pub struct CellInstId(usize);
66
67/// Pin identifier.
68#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
69#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
70pub struct PinId(u32);
71
72/// Pin instance identifier.
73#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
74#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
75pub struct PinInstId(usize);
76
77/// Either a pin or pin instance identifier.
78#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
79#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
80pub enum TerminalId {
81    /// Terminal is a pin.
82    Pin(PinId),
83    /// Terminal is a pin instance.
84    PinInst(PinInstId),
85}
86
87impl From<PinId> for TerminalId {
88    fn from(id: PinId) -> Self {
89        TerminalId::Pin(id)
90    }
91}
92
93impl From<PinInstId> for TerminalId {
94    fn from(id: PinInstId) -> Self {
95        TerminalId::PinInst(id)
96    }
97}
98
99/// Net identifier.
100#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
101#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
102pub struct NetId(usize);
103
104/// Unique (across layout) identifier of a shape.
105pub type ShapeId = Index<Shape<Coord>, u32>;
106
107/// ID for layers.
108pub type LayerId = Index<LayerInfo<NameT>, u16>;
109
110/// Allow creating IDs from integers.
111macro_rules! impl_from_for_id {
112    ($t:tt, $i:ty) => {
113        impl From<$i> for $t {
114            fn from(id: $i) -> Self {
115                $t(id)
116            }
117        }
118    };
119}
120
121impl_from_for_id!(CellId, u32);
122impl_from_for_id!(CellInstId, usize);
123impl_from_for_id!(PinId, u32);
124impl_from_for_id!(PinInstId, usize);
125impl_from_for_id!(NetId, usize);
126
127/// A circuit is defined by an interface (pins) and
128/// a content which consists of interconnected circuit instances.
129///
130/// Template parameters:
131///
132/// * `U`: User defined data.
133#[derive(Debug, Clone)]
134#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
135pub struct Circuit<C = Coord, U = ()>
136where
137    C: CoordinateType,
138    U: Default,
139{
140    /// ID of this circuit.
141    id: CellId,
142    /// Name of the circuit.
143    name: NameT,
144
145    /// Instances inside this circuit.
146    instances: IntHashSet<CellInstId>,
147    /// Instances inside this circuit indexed by name.
148    /// Not every instance needs to have a name.
149    instances_by_name: HashMap<NameT, CellInstId>,
150    /// Circuit instances that reference to this circuit.
151    references: IntHashSet<CellInstId>,
152
153    /// Set of circuits that are direct dependencies of this circuit.
154    /// Stored together with a counter of how many instances of the dependency are present.
155    /// This are the circuits towards the leaves in the dependency tree.
156    dependencies: IntHashMap<CellId, usize>,
157    /// Circuits that use a instance of this circuit.
158    dependent_circuits: IntHashMap<CellId, usize>,
159
160    /// Properties related to the instances in this template.
161    /// Instance properties are stored here for lower overhead of cell instances.
162    #[allow(unused)]
163    instance_properties: IntHashMap<CellInstId, PropertyStore<NameT>>,
164    /// Properties related to this template.
165    properties: PropertyStore<NameT>,
166    /// User-defined data.
167    #[allow(unused)]
168    user_data: U,
169
170    // == Netlist == //
171    /// Pin definitions, the actual pin structs are in the top level `Chip` struct.
172    pins: Vec<PinId>,
173    /// All nets in this circuit.
174    nets: IntHashSet<NetId>,
175    /// Nets IDs stored by name.
176    nets_by_name: HashMap<NameT, NetId>,
177    /// Logic constant LOW net.
178    net_low: NetId,
179    /// Logic constant HIGH net.
180    net_high: NetId,
181
182    // == Layout == //
183    /// Mapping from layer indices to geometry data.
184    shapes_map: IntHashMap<LayerId, Shapes<C>>,
185}
186
187impl Circuit {
188    /// Get the ID of this circuit.
189    fn id(&self) -> CellId {
190        self.id
191    }
192
193    // == Layout == //
194
195    /// Get the shape container of this layer.
196    /// Returns `None` if the shapes object does not exist for this layer.
197    fn shapes(&self, layer_id: &LayerId) -> Option<&Shapes<Coord>> {
198        self.shapes_map.get(layer_id)
199    }
200
201    /// Get the mutable shape container of this layer.
202    /// Returns `None` if the shapes object does not exist for this layer.
203    fn shapes_mut(&mut self, layer_id: &LayerId) -> Option<&mut Shapes<Coord>> {
204        self.shapes_map.get_mut(layer_id)
205    }
206
207    /// Get a mutable reference to the shapes container of the `layer`. When none exists
208    /// a shapes object is created for this layer.
209    fn get_or_create_shapes_mut(&mut self, layer_id: &LayerId) -> &mut Shapes<Coord> {
210        let self_id = self.id();
211        self.shapes_map
212            .entry(*layer_id)
213            .or_insert_with(Shapes::new)
214            .borrow_mut()
215    }
216}
217
218// pub enum PlacementStatus {
219//     Unplaced,
220//     Fixed
221// }
222
223/// Instance of a circuit.
224///
225/// Template parameters:
226///
227/// * `U`: User defined data.
228#[derive(Debug, Clone)]
229#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
230pub struct CircuitInst<C = Coord, U = ()>
231where
232    C: CoordinateType,
233{
234    /// Name of the instance.
235    name: Option<NameT>,
236    /// The ID of the template circuit.
237    template_circuit_id: CellId,
238    /// The ID of the parent circuit where this instance lives in.
239    parent_circuit_id: CellId,
240    /// Properties related to this instance.
241    properties: PropertyStore<NameT>,
242
243    /// User-defined data.
244    #[allow(unused)]
245    user_data: U,
246
247    // == Netlist == //
248    /// List of pins of this instance.
249    pins: Vec<PinInstId>,
250
251    // == Layout == //
252    /// Transformation to put the cell to the right place an into the right scale/rotation.
253    transform: SimpleTransform<C>,
254    // TODO: Repetition
255    // /// Current status of the cell placement.
256    // placement_status: PlacementStatus
257}
258
259impl CircuitInst {
260    // == Layout == //
261
262    /// Get the transformation that represents the location and orientation of this instance.
263    fn get_transform(&self) -> &SimpleTransform<Coord> {
264        &self.transform
265    }
266
267    /// Set the transformation that represents the location and orientation of this instance.
268    fn set_transform(&mut self, tf: SimpleTransform<Coord>) {
269        self.transform = tf;
270    }
271}
272
273/// Single bit wire pin.
274#[derive(Debug, Clone)]
275#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
276pub struct Pin {
277    /// Name of the pin.
278    name: NameT,
279    /// Signal type/direction of the pin.
280    direction: Direction,
281    /// Parent circuit of this pin.
282    circuit: CellId,
283    /// Net that is connected to this pin.
284    net: Option<NetId>,
285
286    // == Layout == //
287    /// List of shapes in the layout that represent the physical pin.
288    pin_shapes: IntHashSet<ShapeId>,
289}
290
291/// Instance of a pin.
292#[derive(Debug, Clone)]
293#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
294pub struct PinInst {
295    /// ID of the template pin.
296    pub template_pin_id: PinId,
297    /// Circuit instance where this pin instance lives in.
298    pub circuit_inst: CellInstId,
299    /// Net connected to this pin instance.
300    net: Option<NetId>,
301}
302
303/// A net represents an electric potential or a wire.
304#[derive(Debug, Clone)]
305#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
306pub struct Net {
307    /// Name of the net.
308    pub name: Option<NameT>,
309    /// Parent circuit of the net.
310    pub parent_id: CellId,
311    /// Pins connected to this net.
312    pub pins: IntHashSet<PinId>,
313    /// Pin instances connected to this net.
314    pub pin_instances: IntHashSet<PinInstId>,
315
316    // == Layout == //
317    /// List of shapes in the layout that represent the physical net.
318    pub net_shapes: IntHashSet<ShapeId>,
319}
320
321impl Net {}
322
323/// A netlist is the container of circuits.
324#[derive(Debug, Clone)]
325#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
326pub struct Chip<C: CoordinateType = Coord> {
327    circuits: IntHashMap<CellId, Circuit<C>>,
328    circuits_by_name: HashMap<NameT, CellId>,
329    circuit_instances: IntHashMap<CellInstId, CircuitInst>,
330    nets: IntHashMap<NetId, Net>,
331    pins: IntHashMap<PinId, Pin>,
332    pin_instances: IntHashMap<PinInstId, PinInst>,
333
334    /// Top-level properties.
335    properties: PropertyStore<NameT>,
336
337    id_counter_circuit: u32,
338    id_counter_circuit_inst: usize,
339    id_counter_pin: u32,
340    id_counter_pin_inst: usize,
341    id_counter_net: usize,
342
343    // == Layout == //
344    dbu: C,
345
346    /// Counter for generating the next layer index.
347    layer_index_generator: IndexGenerator<LayerInfo<NameT>, u16>,
348    /// Lookup table for finding layers by name.
349    layers_by_name: HashMap<NameT, LayerId>,
350    /// Lookup table for finding layers by index/datatype numbers.
351    layers_by_index_datatype: IntHashMap<(UInt, UInt), LayerId>,
352    /// Info structures for all layers.
353    layer_info: IntHashMap<LayerId, LayerInfo<NameT>>,
354    /// ID generator for shapes.
355    shape_index_generator: IndexGenerator<Shape<C>>,
356
357    /// Link to the cell and layer that contain a shape.
358    shape_parents: IntHashMap<ShapeId, (CellId, LayerId)>,
359
360    /// Link to the shapes of a net.
361    net_shapes: IntHashMap<NetId, IntHashSet<ShapeId>>,
362}
363
364impl<C: CoordinateType + One> Default for Chip<C> {
365    fn default() -> Self {
366        Self {
367            circuits: Default::default(),
368            circuits_by_name: Default::default(),
369            circuit_instances: Default::default(),
370            nets: Default::default(),
371            pins: Default::default(),
372            pin_instances: Default::default(),
373            properties: Default::default(),
374            id_counter_circuit: 0,
375            id_counter_circuit_inst: 0,
376            id_counter_pin: 0,
377            id_counter_pin_inst: 0,
378            id_counter_net: 0,
379            dbu: C::one(),
380            layer_index_generator: Default::default(),
381            layers_by_name: Default::default(),
382            layers_by_index_datatype: Default::default(),
383            layer_info: Default::default(),
384            shape_index_generator: Default::default(),
385            shape_parents: Default::default(),
386            net_shapes: Default::default(),
387        }
388    }
389}
390
391impl Chip<Coord> {
392    /// Create an empty data structure.
393    pub fn new() -> Self {
394        Chip::default()
395    }
396
397    /// Find a circuit by its name.
398    fn circuit_by_name<S: ?Sized + Eq + Hash>(&self, name: &S) -> Option<CellId>
399    where
400        NameT: Borrow<S>,
401    {
402        self.circuits_by_name.get(name).copied()
403    }
404
405    /// Change the name of the cell.
406    ///
407    /// # Panics
408    /// Panics if the name already exists.
409    fn rename_cell(&mut self, cell: &CellId, name: NameT) {
410        assert!(
411            !self.circuits_by_name.contains_key(&name),
412            "Cell with this name already exists: {}",
413            &name
414        );
415
416        // Remove old name.
417        let old_name = &self.circuits[cell].name;
418        let id = self.circuits_by_name.remove(old_name);
419        debug_assert_eq!(id.as_ref(), Some(cell));
420
421        // Set the new name.
422        self.circuit_mut(cell).name.clone_from(&name);
423        self.circuits_by_name.insert(name, *cell);
424    }
425
426    /// Change the name of the cell instance.
427    ///
428    /// # Panics
429    /// Panics if the name already exists.
430    fn rename_cell_instance(&mut self, inst: &CellInstId, name: Option<NameT>) {
431        let parent = self.parent_cell(inst);
432        if let Some(name) = &name {
433            assert!(
434                !self.circuit(&parent).instances_by_name.contains_key(name),
435                "Cell with this name already exists: {}",
436                name
437            );
438        }
439
440        // Remove old name.
441        let old_name = self.circuit_inst_mut(inst).name.take();
442        if let Some(old_name) = old_name {
443            self.circuit_mut(&parent)
444                .instances_by_name
445                .remove(&old_name);
446        }
447
448        self.circuit_inst_mut(inst).name.clone_from(&name);
449        if let Some(name) = name {
450            self.circuit_mut(&parent)
451                .instances_by_name
452                .insert(name, *inst);
453        }
454    }
455
456    /// Create a new circuit template.
457    fn create_circuit(&mut self, name: NameT, pins: Vec<(NameT, Direction)>) -> CellId {
458        assert!(
459            !self.circuits_by_name.contains_key(&name),
460            "Circuit with this name already exists: {}",
461            &name
462        );
463        let id = CellId(Self::next_id_counter_u32(&mut self.id_counter_circuit));
464
465        let circuit = Circuit {
466            id,
467            name: name.clone(),
468            pins: Default::default(),
469            instances: Default::default(),
470            instances_by_name: Default::default(),
471            references: Default::default(),
472            nets: Default::default(),
473            nets_by_name: Default::default(),
474            // Create LOW and HIGH nets.
475            net_low: NetId(0),
476            net_high: NetId(0),
477            dependent_circuits: Default::default(),
478            instance_properties: Default::default(),
479            dependencies: Default::default(),
480            user_data: Default::default(),
481            shapes_map: Default::default(),
482            properties: Default::default(),
483        };
484
485        self.circuits.insert(id, circuit);
486        self.circuits_by_name.insert(name, id);
487
488        // Create LOW and HIGH nets.
489        let net_low = self.create_net(&id, Some("__LOW__".into()));
490        let net_high = self.create_net(&id, Some("__HIGH__".into()));
491
492        let c = self.circuit_mut(&id);
493        c.net_low = net_low;
494        c.net_high = net_high;
495
496        // Create pins.
497        pins.into_iter().for_each(|(name, direction)| {
498            self.create_pin(id, name, direction);
499        });
500
501        id
502    }
503
504    /// Remove all instances inside the circuit, remove all instances of the circuit
505    /// and remove finally the circuit itself.
506    fn remove_circuit(&mut self, circuit_id: &CellId) {
507        // Remove all instances inside this circuit.
508        let instances = self
509            .circuit(circuit_id)
510            .instances
511            .iter()
512            .copied()
513            .collect_vec();
514        for inst in instances {
515            self.remove_circuit_instance(&inst);
516        }
517
518        // Clean up links to cell shapes.
519        for shape_id in self.circuits[circuit_id]
520            .shapes_map
521            .iter()
522            .flat_map(|(layer, shapes)| shapes.shapes.keys())
523        {
524            self.shape_parents.remove(shape_id);
525        }
526
527        // Remove all instances of this circuit.
528        let references = self
529            .circuit(circuit_id)
530            .references
531            .iter()
532            .copied()
533            .collect_vec();
534        for inst in references {
535            self.remove_circuit_instance(&inst);
536        }
537        // Clean up pin definitions.
538        let pins = self.circuit(circuit_id).pins.clone();
539        for pin in pins {
540            self.pins.remove(&pin).unwrap();
541        }
542        // Remove the circuit.
543        let name = self.circuit(circuit_id).name.clone();
544        self.circuits_by_name.remove(&name).unwrap();
545        self.circuits.remove(circuit_id).unwrap();
546    }
547
548    /// Create a new instance of `circuit_template` in the `parent` circuit.
549    fn create_circuit_instance(
550        &mut self,
551        parent: &CellId,
552        circuit_template: &CellId,
553        name: Option<NameT>,
554    ) -> CellInstId {
555        let id = CellInstId(Self::next_id_counter_usize(
556            &mut self.id_counter_circuit_inst,
557        ));
558
559        {
560            // Check that creating this circuit instance does not create a cycle in the dependency graph.
561            // There can be no recursive instances.
562            let mut stack: Vec<CellId> = vec![*parent];
563            while let Some(c) = stack.pop() {
564                if &c == circuit_template {
565                    // The circuit to be instantiated depends on the current circuit.
566                    // This would insert a loop into the dependency tree.
567                    // TODO: Don't panic but return an `Err`.
568                    panic!("Cannot create recursive instances.");
569                }
570                // Follow the dependent circuits towards the root.
571                stack.extend(self.circuit(&c).dependent_circuits.keys().copied())
572            }
573        }
574
575        // Create pin instances from template pins.
576        let pins = self
577            .circuit(circuit_template)
578            .pins
579            .clone()
580            .iter()
581            .map(|&p| self.create_pin_inst(id, p))
582            .collect();
583
584        let inst = CircuitInst {
585            name: name.clone(),
586            template_circuit_id: *circuit_template,
587            parent_circuit_id: *parent,
588            properties: Default::default(),
589            user_data: (),
590            pins,
591            transform: Default::default(),
592        };
593
594        self.circuit_instances.insert(id, inst);
595        self.circuit_mut(parent).instances.insert(id);
596        self.circuit_mut(circuit_template).references.insert(id);
597
598        if let Some(name) = name {
599            debug_assert!(
600                !self.circuit(parent).instances_by_name.contains_key(&name),
601                "Circuit instance name already exists."
602            );
603            self.circuit_mut(parent).instances_by_name.insert(name, id);
604        }
605
606        // Remember dependency.
607        {
608            self.circuit_mut(parent)
609                .dependencies
610                .entry(*circuit_template)
611                .and_modify(|c| *c += 1)
612                .or_insert(1);
613        }
614
615        // Remember dependency.
616        {
617            self.circuit_mut(circuit_template)
618                .dependent_circuits
619                .entry(*parent)
620                .and_modify(|c| *c += 1)
621                .or_insert(1);
622        }
623
624        id
625    }
626
627    /// Remove a circuit instance after disconnecting it from the nets.
628    fn remove_circuit_instance(&mut self, circuit_inst_id: &CellInstId) {
629        // Remove the instance name.
630        self.rename_cell_instance(circuit_inst_id, None);
631
632        // Disconnect all pins first.
633        for pin in self.circuit_inst(circuit_inst_id).pins.clone() {
634            self.disconnect_pin_instance(&pin);
635        }
636        // Remove the instance and all references.
637        let parent = self.circuit_inst(circuit_inst_id).parent_circuit_id;
638        let template = self.circuit_inst(circuit_inst_id).template_circuit_id;
639
640        // Remove dependency.
641        {
642            // Decrement counter.
643            let count = self
644                .circuit_mut(&parent)
645                .dependencies
646                .entry(template)
647                .or_insert(0); // Should not happen.
648            *count -= 1;
649
650            if *count == 0 {
651                // Remove entry.
652                self.circuit_mut(&parent).dependencies.remove(&template);
653            }
654        }
655
656        // Remove dependency.
657        {
658            // Decrement counter.
659            let count = self
660                .circuit_mut(&template)
661                .dependent_circuits
662                .entry(parent)
663                .or_insert(0); // Should not happen.
664            *count -= 1;
665
666            if *count == 0 {
667                // Remove entry.
668                self.circuit_mut(&template)
669                    .dependent_circuits
670                    .remove(&parent);
671            }
672        }
673
674        self.circuit_instances.remove(circuit_inst_id).unwrap();
675        self.circuit_mut(&parent).instances.remove(circuit_inst_id);
676        self.circuit_mut(&template)
677            .references
678            .remove(circuit_inst_id);
679    }
680
681    /// Create a new net in the `parent` circuit.
682    fn create_net(&mut self, parent: &CellId, name: Option<NameT>) -> NetId {
683        assert!(self.circuits.contains_key(parent));
684
685        let id = NetId(Self::next_id_counter_usize(&mut self.id_counter_net));
686        let net = Net {
687            name: name.clone(),
688            parent_id: *parent,
689            pins: Default::default(),
690            pin_instances: Default::default(),
691            net_shapes: Default::default(),
692        };
693        self.nets.insert(id, net);
694        let circuit = self.circuit_mut(parent);
695        circuit.nets.insert(id);
696        if let Some(name) = name {
697            debug_assert!(
698                !circuit.nets_by_name.contains_key(&name),
699                "Net name already exists."
700            );
701            circuit.nets_by_name.insert(name, id);
702        }
703        id
704    }
705
706    /// Change the name of the net.
707    fn rename_net(&mut self, net_id: &NetId, new_name: Option<NameT>) -> Option<NameT> {
708        let parent_circuit = self.parent_cell_of_net(net_id);
709
710        // Check if a net with this name already exists.
711        if let Some(name) = &new_name {
712            if let Some(other) = self.circuit(&parent_circuit).nets_by_name.get(name) {
713                if other != net_id {
714                    panic!("Net name already exists.")
715                } else {
716                    // Name is the same as before.
717                    return new_name;
718                }
719            }
720        }
721
722        let maybe_old_name = self.net_mut(net_id).name.take();
723
724        // Remove the old name mapping.
725        if let Some(old_name) = &maybe_old_name {
726            self.circuit_mut(&parent_circuit)
727                .nets_by_name
728                .remove(old_name);
729        }
730
731        // Add the new name mapping.
732        if let Some(new_name) = new_name {
733            self.nets
734                .get_mut(net_id)
735                .expect("Net not found.")
736                .name
737                .replace(new_name.clone());
738            self.circuit_mut(&parent_circuit)
739                .nets_by_name
740                .insert(new_name, *net_id);
741        }
742
743        maybe_old_name
744    }
745
746    /// Disconnect all connected terminals and remove the net.
747    fn remove_net(&mut self, net: &NetId) {
748        let parent_circuit = self.net(net).parent_id;
749
750        assert_ne!(
751            net,
752            &self.net_zero(&parent_circuit),
753            "Cannot remove constant LOW net."
754        );
755        assert_ne!(
756            net,
757            &self.net_one(&parent_circuit),
758            "Cannot remove constant HIGH net."
759        );
760
761        // Remove all links from shapes to this net.
762        let net_shapes = self
763            .net_shapes
764            .get(net)
765            .iter()
766            .flat_map(|shape_ids| shape_ids.iter().cloned())
767            .collect_vec();
768        for net_shape in &net_shapes {
769            self.set_net_of_shape(net_shape, None);
770        }
771
772        // Remove all links to pins.
773        let pins = self.pins_for_net(net).collect_vec();
774        let pin_insts = self.pins_instances_for_net(net).collect_vec();
775
776        for p in pins {
777            self.disconnect_pin(&p);
778        }
779        for p in pin_insts {
780            self.disconnect_pin_instance(&p);
781        }
782        let name = self.net(net).name.clone();
783        let circuit = self.circuit_mut(&parent_circuit);
784        circuit.nets.remove(net);
785        if let Some(name) = &name {
786            circuit.nets_by_name.remove(name).unwrap();
787        }
788        self.nets.remove(net).unwrap();
789    }
790
791    /// Disconnect pin and return the ID of the net that was connected.
792    fn disconnect_pin(&mut self, pin: &PinId) -> Option<NetId> {
793        self.connect_pin(pin, None)
794    }
795
796    /// Connect the pin to a net.
797    fn connect_pin(&mut self, pin: &PinId, net: Option<NetId>) -> Option<NetId> {
798        if let Some(net) = net {
799            // Sanity check.
800            assert_eq!(
801                self.pin(pin).circuit,
802                self.net(&net).parent_id,
803                "Pin and net do not live in the same circuit."
804            );
805        }
806
807        let old_net = if let Some(net) = net {
808            self.pin_mut(pin).net.replace(net)
809        } else {
810            self.pin_mut(pin).net.take()
811        };
812
813        if let Some(net) = old_net {
814            // Remove the pin from the old net.
815            self.net_mut(&net).pins.remove(pin);
816        }
817
818        if let Some(net) = net {
819            // Store the pin in the new net.
820            self.net_mut(&net).pins.insert(*pin);
821        }
822
823        old_net
824    }
825
826    /// Disconnect the pin instance and return the net to which it was connected.
827    fn disconnect_pin_instance(&mut self, pin: &PinInstId) -> Option<NetId> {
828        self.connect_pin_instance(pin, None)
829    }
830
831    /// Connect the pin to a net.
832    fn connect_pin_instance(&mut self, pin: &PinInstId, net: Option<NetId>) -> Option<NetId> {
833        if let Some(net) = net {
834            assert_eq!(
835                self.circuit_inst(&self.pin_inst(pin).circuit_inst)
836                    .parent_circuit_id,
837                self.net(&net).parent_id,
838                "Pin and net do not live in the same circuit."
839            );
840        }
841
842        let old_net = if let Some(net) = net {
843            self.pin_inst_mut(pin).net.replace(net)
844        } else {
845            self.pin_inst_mut(pin).net.take()
846        };
847
848        if let Some(net) = old_net {
849            // Remove the pin from the old net.
850            self.net_mut(&net).pin_instances.remove(pin);
851        }
852
853        if let Some(net) = net {
854            // Store the pin in the new net.
855            self.net_mut(&net).pin_instances.insert(*pin);
856        }
857
858        old_net
859    }
860
861    /// Get a circuit reference by its ID.
862    fn circuit(&self, id: &CellId) -> &Circuit {
863        &self.circuits[id]
864    }
865
866    // /// Get a fat circuit reference by its ID.
867    // fn circuit_ref(&self, id: &CellId) -> CircuitRef {
868    //     CircuitRef {
869    //         netlist: self,
870    //         circuit: &self.circuits[id],
871    //     }
872    // }
873
874    /// Get a mutable reference to the circuit by its ID.
875    fn circuit_mut(&mut self, id: &CellId) -> &mut Circuit {
876        self.circuits.get_mut(id).expect("Cell ID not found.")
877    }
878
879    /// Get a reference to a circuit instance.
880    fn circuit_inst(&self, id: &CellInstId) -> &CircuitInst {
881        &self.circuit_instances[id]
882    }
883
884    /// Get a mutable reference to a circuit instance.
885    fn circuit_inst_mut(&mut self, id: &CellInstId) -> &mut CircuitInst {
886        self.circuit_instances.get_mut(id).unwrap()
887    }
888
889    /// Get a reference to a net by its ID.
890    fn net(&self, id: &NetId) -> &Net {
891        self.nets
892            .get(id)
893            .expect("Net ID does not exist in this netlist.")
894    }
895
896    /// Get a mutable reference to a net by its ID.
897    fn net_mut(&mut self, id: &NetId) -> &mut Net {
898        self.nets.get_mut(id).unwrap()
899    }
900
901    /// Get a reference to a pin by its ID.
902    fn pin(&self, id: &PinId) -> &Pin {
903        &self.pins[id]
904    }
905
906    /// Get a mutable reference to a pin by its ID.
907    fn pin_mut(&mut self, id: &PinId) -> &mut Pin {
908        self.pins.get_mut(id).unwrap()
909    }
910
911    /// Get a reference to a pin instance by its ID.
912    fn pin_inst(&self, id: &PinInstId) -> &PinInst {
913        &self.pin_instances[id]
914    }
915
916    /// Get a mutable reference to a pin instance by its ID.
917    fn pin_inst_mut(&mut self, id: &PinInstId) -> &mut PinInst {
918        self.pin_instances.get_mut(id).unwrap()
919    }
920
921    /// Get the value of a counter and increment the counter afterwards.
922    fn next_id_counter_usize(ctr: &mut usize) -> usize {
923        let c = *ctr;
924        *ctr += 1;
925        c
926    }
927
928    /// Get the value of a counter and increment the counter afterwards.
929    fn next_id_counter_u32(ctr: &mut u32) -> u32 {
930        let c = *ctr;
931        *ctr += 1;
932        c
933    }
934
935    /// Append a new pin to the `parent` circuit.
936    /// Update all circuit instances with the new pin.
937    fn create_pin(&mut self, parent: CellId, name: NameT, direction: Direction) -> PinId {
938        let pin_id = PinId(Self::next_id_counter_u32(&mut self.id_counter_pin));
939        let pin = Pin {
940            name,
941            direction,
942            circuit: parent,
943            net: Default::default(),
944            pin_shapes: Default::default(),
945        };
946        self.pins.insert(pin_id, pin);
947
948        // Register the pin in the circuit.
949        self.circuits.get_mut(&parent).unwrap().pins.push(pin_id);
950
951        // Insert the pin in all instances of this circuit.
952        for inst in &self.circuits[&parent].references {
953            // Create new pin instance.
954            let pin_inst_id = PinInstId(Self::next_id_counter_usize(&mut self.id_counter_pin_inst));
955            let pin = PinInst {
956                template_pin_id: pin_id,
957                circuit_inst: *inst,
958                net: None,
959            };
960            self.pin_instances.insert(pin_inst_id, pin);
961
962            // Register the pin instance in the circuit instance.
963            self.circuit_instances
964                .get_mut(inst)
965                .unwrap()
966                .pins
967                .push(pin_inst_id);
968        }
969
970        pin_id
971    }
972
973    /// Insert a new pin instance to a circuit instance.
974    fn create_pin_inst(&mut self, circuit: CellInstId, pin: PinId) -> PinInstId {
975        let id = PinInstId(Self::next_id_counter_usize(&mut self.id_counter_pin_inst));
976        let pin = PinInst {
977            template_pin_id: pin,
978            circuit_inst: circuit,
979            net: None,
980        };
981        self.pin_instances.insert(id, pin);
982        id
983    }
984
985    /// Iterate over all pins connected to a net.
986    fn pins_for_net(&self, net: &NetId) -> impl Iterator<Item = PinId> + '_ {
987        self.net(net).pins.iter().copied()
988    }
989
990    /// Iterate over all pin instances connected to a net.
991    fn pins_instances_for_net(&self, net: &NetId) -> impl Iterator<Item = PinInstId> + '_ {
992        self.net(net).pin_instances.iter().copied()
993    }
994
995    /// Get a mutable reference to a shape struct by its ID.
996    fn shape_mut(&mut self, shape_id: &ShapeId) -> &mut Shape<Coord> {
997        let (cell, layer) = *self.shape_parents.get(shape_id).expect("Shape not found.");
998        self.circuit_mut(&cell)
999            .shapes_mut(&layer)
1000            .expect("Layer not found.")
1001            .shapes
1002            .get_mut(shape_id)
1003            .expect("Shape not found.")
1004    }
1005
1006    /// Get a reference to a shape struct by its ID.
1007    fn shape(&self, shape_id: &ShapeId) -> &Shape<Coord> {
1008        let (cell, layer) = self.shape_parents.get(shape_id).expect("Shape not found.");
1009        self.circuit(cell)
1010            .shapes(layer)
1011            .expect("Layer not found.")
1012            .shapes
1013            .get(shape_id)
1014            .expect("Shape not found.")
1015    }
1016}
1017
1018impl NetlistIds for Chip {
1019    type PinId = PinId;
1020    type PinInstId = PinInstId;
1021    type NetId = NetId;
1022}
1023
1024impl NetlistBase for Chip {
1025    fn template_pin(&self, pin_instance: &Self::PinInstId) -> Self::PinId {
1026        self.pin_inst(pin_instance).template_pin_id
1027    }
1028
1029    fn pin_direction(&self, pin: &Self::PinId) -> Direction {
1030        self.pin(pin).direction
1031    }
1032
1033    fn pin_name(&self, pin: &Self::PinId) -> Self::NameType {
1034        self.pin(pin).name.clone()
1035    }
1036
1037    fn pin_by_name(&self, parent_circuit: &Self::CellId, name: &str) -> Option<Self::PinId> {
1038        // TODO: Create index for pin names.
1039        self.circuit(parent_circuit)
1040            .pins
1041            .iter()
1042            .find(|p| self.pin(p).name.as_str() == name)
1043            .copied()
1044    }
1045
1046    fn parent_cell_of_pin(&self, pin: &Self::PinId) -> Self::CellId {
1047        self.pin(pin).circuit
1048    }
1049
1050    fn parent_of_pin_instance(&self, pin_inst: &Self::PinInstId) -> Self::CellInstId {
1051        self.pin_inst(pin_inst).circuit_inst
1052    }
1053
1054    fn parent_cell_of_net(&self, net: &Self::NetId) -> Self::CellId {
1055        self.nets[net].parent_id
1056    }
1057
1058    fn net_of_pin(&self, pin: &Self::PinId) -> Option<Self::NetId> {
1059        self.pin(pin).net
1060    }
1061
1062    fn net_of_pin_instance(&self, pin_inst: &Self::PinInstId) -> Option<Self::NetId> {
1063        self.pin_inst(pin_inst).net
1064    }
1065
1066    fn net_zero(&self, parent_circuit: &Self::CellId) -> Self::NetId {
1067        self.circuit(parent_circuit).net_low
1068    }
1069
1070    fn net_one(&self, parent_circuit: &Self::CellId) -> Self::NetId {
1071        self.circuit(parent_circuit).net_high
1072    }
1073
1074    fn net_by_name(&self, parent_circuit: &Self::CellId, name: &str) -> Option<Self::NetId> {
1075        self.circuit(parent_circuit).nets_by_name.get(name).copied()
1076    }
1077
1078    fn net_name(&self, net: &Self::NetId) -> Option<Self::NameType> {
1079        self.net(net).name.clone()
1080    }
1081
1082    fn for_each_pin<F>(&self, circuit: &Self::CellId, f: F)
1083    where
1084        F: FnMut(Self::PinId),
1085    {
1086        self.circuit(circuit).pins.iter().copied().for_each(f)
1087    }
1088
1089    fn each_pin(&self, circuit_id: &CellId) -> Box<dyn Iterator<Item = PinId> + '_> {
1090        Box::new(self.circuit(circuit_id).pins.iter().copied())
1091    }
1092
1093    fn for_each_pin_instance<F>(&self, circuit_inst: &Self::CellInstId, f: F)
1094    where
1095        F: FnMut(Self::PinInstId),
1096    {
1097        self.circuit_inst(circuit_inst)
1098            .pins
1099            .iter()
1100            .copied()
1101            .for_each(f)
1102    }
1103
1104    fn each_pin_instance<'a>(
1105        &'a self,
1106        circuit_inst: &Self::CellInstId,
1107    ) -> Box<dyn Iterator<Item = Self::PinInstId> + 'a> {
1108        Box::new(self.circuit_inst(circuit_inst).pins.iter().copied())
1109    }
1110
1111    fn for_each_internal_net<F>(&self, circuit: &Self::CellId, f: F)
1112    where
1113        F: FnMut(Self::NetId),
1114    {
1115        self.circuit(circuit).nets.iter().copied().for_each(f)
1116    }
1117
1118    fn each_internal_net(
1119        &self,
1120        circuit: &Self::CellId,
1121    ) -> Box<dyn Iterator<Item = Self::NetId> + '_> {
1122        Box::new(self.circuit(circuit).nets.iter().copied())
1123    }
1124
1125    fn num_internal_nets(&self, circuit: &Self::CellId) -> usize {
1126        self.circuit(circuit).nets.len()
1127    }
1128
1129    fn num_pins(&self, circuit: &Self::CellId) -> usize {
1130        self.circuit(circuit).pins.len()
1131    }
1132
1133    fn for_each_pin_of_net<F>(&self, net: &Self::NetId, f: F)
1134    where
1135        F: FnMut(Self::PinId),
1136    {
1137        self.net(net).pins.iter().copied().for_each(f)
1138    }
1139
1140    fn each_pin_of_net<'a>(
1141        &'a self,
1142        net: &Self::NetId,
1143    ) -> Box<dyn Iterator<Item = Self::PinId> + 'a> {
1144        Box::new(self.net(net).pins.iter().copied())
1145    }
1146
1147    fn for_each_pin_instance_of_net<F>(&self, net: &Self::NetId, f: F)
1148    where
1149        F: FnMut(Self::PinInstId),
1150    {
1151        self.net(net).pin_instances.iter().copied().for_each(f)
1152    }
1153
1154    fn each_pin_instance_of_net<'a>(
1155        &'a self,
1156        net: &Self::NetId,
1157    ) -> Box<dyn Iterator<Item = Self::PinInstId> + 'a> {
1158        Box::new(self.net(net).pin_instances.iter().copied())
1159    }
1160}
1161
1162impl NetlistEdit for Chip {
1163    fn create_pin(
1164        &mut self,
1165        circuit: &Self::CellId,
1166        name: Self::NameType,
1167        direction: Direction,
1168    ) -> Self::PinId {
1169        Chip::create_pin(self, *circuit, name, direction)
1170    }
1171
1172    fn remove_pin(&mut self, id: &Self::PinId) {
1173        // Remove all links from shapes to this pin.
1174        let pin_shapes = self.pin(id).pin_shapes.iter().cloned().collect_vec();
1175        for pin_shape in &pin_shapes {
1176            self.set_pin_of_shape(pin_shape, None);
1177        }
1178
1179        // Disconnect the pin for all instances.
1180        let cell = self.parent_cell_of_pin(id);
1181        for inst in self.each_cell_instance_vec(&cell) {
1182            let pin_inst = self.pin_instance(&inst, id);
1183            self.disconnect_pin_instance(&pin_inst);
1184
1185            // Remove pin instance.
1186            self.circuit_inst_mut(&inst).pins.retain(|p| p != &pin_inst);
1187            // Delete the pin instance struct.
1188            self.pin_instances.remove(&pin_inst);
1189        }
1190
1191        // Disconnect this pin from internal nets.
1192        self.disconnect_pin(id);
1193
1194        // Remove the pin from the cell.
1195        self.circuit_mut(&cell).pins.retain(|p| p != id);
1196        // Delete the pin struct.
1197        self.pins.remove(id);
1198    }
1199
1200    fn rename_pin(&mut self, pin: &Self::PinId, new_name: Self::NameType) -> Self::NameType {
1201        let cell = self.parent_cell_of_pin(pin);
1202        let existing = self.pin_by_name(&cell, &new_name);
1203        if existing.is_some() {
1204            panic!(
1205                "Pin name already exists in cell '{}': '{}'",
1206                self.cell_name(&cell),
1207                new_name
1208            )
1209        }
1210        let old_name = std::mem::replace(&mut self.pin_mut(pin).name, new_name);
1211        old_name
1212    }
1213
1214    fn create_net(&mut self, parent: &CellId, name: Option<Self::NameType>) -> NetId {
1215        Chip::create_net(self, parent, name)
1216    }
1217
1218    fn rename_net(
1219        &mut self,
1220        net_id: &Self::NetId,
1221        new_name: Option<Self::NameType>,
1222    ) -> Option<Self::NameType> {
1223        Chip::rename_net(self, net_id, new_name)
1224    }
1225
1226    fn remove_net(&mut self, net: &NetId) {
1227        Chip::remove_net(self, net)
1228    }
1229
1230    fn connect_pin(&mut self, pin: &PinId, net: Option<NetId>) -> Option<NetId> {
1231        Chip::connect_pin(self, pin, net)
1232    }
1233
1234    fn connect_pin_instance(&mut self, pin: &PinInstId, net: Option<NetId>) -> Option<Self::NetId> {
1235        Chip::connect_pin_instance(self, pin, net)
1236    }
1237}
1238
1239#[test]
1240fn test_create_populated_netlist() {
1241    let mut netlist = Chip::default();
1242    let top = netlist.create_circuit("TOP".into(), vec![("A".into(), Direction::Input)]);
1243    netlist.create_pin(top, "B".into(), Direction::Output);
1244    assert_eq!(Some(top), netlist.circuit_by_name("TOP"));
1245
1246    let sub_a = netlist.create_circuit(
1247        "SUB_A".into(),
1248        vec![
1249            ("A".into(), Direction::Input),
1250            ("B".into(), Direction::Output),
1251        ],
1252    );
1253    let sub_b = netlist.create_circuit(
1254        "SUB_B".into(),
1255        vec![
1256            ("A".into(), Direction::Input),
1257            ("B".into(), Direction::Output),
1258        ],
1259    );
1260
1261    let inst_a = netlist.create_circuit_instance(&top, &sub_a, None);
1262    let _inst_b = netlist.create_circuit_instance(&top, &sub_b, None);
1263
1264    let net_a = netlist.create_net(&top, Some("NetA".into()));
1265    let net_b = netlist.create_net(&top, Some("NetB".into()));
1266
1267    let pins_a = netlist.each_pin_instance(&inst_a).collect_vec();
1268    let pins_top = netlist.each_pin(&top).collect_vec();
1269
1270    netlist.connect_pin_instance(&pins_a[0], Some(net_a));
1271    netlist.connect_pin_instance(&pins_a[1], Some(net_b));
1272
1273    netlist.connect_pin(&pins_top[0], Some(net_a));
1274    netlist.connect_pin(&pins_top[1], Some(net_b));
1275
1276    assert_eq!(netlist.num_net_terminals(&net_a), 2);
1277    assert_eq!(netlist.num_net_terminals(&net_b), 2);
1278}
1279
1280/// Wrapper around a `Geometry` struct.
1281#[derive(Clone, Debug)]
1282#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1283pub struct Shape<C, U = ()> {
1284    /// Identifier of this shape.
1285    index: Index<Shape<C, U>>,
1286    /// The geometry of this shape.
1287    pub geometry: Geometry<C>,
1288    // /// Reference ID to container.
1289    // parent_id: Index<Shapes<T>>,
1290    /// Net attached to this shape.
1291    net: Option<NetId>,
1292    /// Pin that belongs to this shape.
1293    pin: Option<PinId>,
1294    /// User-defined data.
1295    #[allow(unused)]
1296    user_data: U,
1297}
1298
1299/// `Shapes<T>` is a collection of `Shape<T>` structs. Each of
1300/// the elements is assigned an index when inserted into the collection.
1301#[derive(Clone, Debug)]
1302#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1303pub struct Shapes<C>
1304where
1305    C: CoordinateType,
1306{
1307    /// Shape elements.
1308    shapes: IntHashMap<ShapeId, Shape<C>>,
1309    /// Property stores for the shapes.
1310    shape_properties: IntHashMap<ShapeId, PropertyStore<NameT>>,
1311}
1312
1313impl<C: CoordinateType> Shapes<C> {
1314    /// Create a new empty shapes container.
1315    fn new() -> Self {
1316        Self {
1317            shapes: Default::default(),
1318            shape_properties: Default::default(),
1319        }
1320    }
1321    //
1322    // /// Get the ID of this shape container.
1323    // fn id(&self) -> Index<Self> {
1324    //     self.id
1325    // }
1326
1327    /// Iterate over all shapes in this container.
1328    fn each_shape(&self) -> impl Iterator<Item = &Shape<C>> {
1329        self.shapes.values()
1330    }
1331}
1332
1333impl<C: CoordinateType> TryBoundingBox<C> for Shapes<C> {
1334    fn try_bounding_box(&self) -> Option<Rect<C>> {
1335        // Compute the bounding box from scratch.
1336
1337        self.each_shape().fold(None, |bbox, shape| {
1338            let bbox_new = shape.geometry.try_bounding_box();
1339            match bbox {
1340                None => bbox_new,
1341                Some(bbox1) => {
1342                    Some(
1343                        // Compute bounding box of the two rectangles.
1344                        match bbox_new {
1345                            None => bbox1,
1346                            Some(bbox2) => bbox1.add_rect(&bbox2),
1347                        },
1348                    )
1349                }
1350            }
1351        })
1352    }
1353}
1354
1355impl HierarchyIds for Chip<Coord> {
1356    type CellId = CellId;
1357    type CellInstId = CellInstId;
1358}
1359
1360impl HierarchyBase for Chip<Coord> {
1361    type NameType = NameT;
1362
1363    fn cell_by_name(&self, name: &str) -> Option<CellId> {
1364        Chip::circuit_by_name(self, name)
1365    }
1366
1367    fn cell_instance_by_name(
1368        &self,
1369        parent_circuit: &Self::CellId,
1370        name: &str,
1371    ) -> Option<Self::CellInstId> {
1372        self.circuit(parent_circuit)
1373            .instances_by_name
1374            .get(name)
1375            .copied()
1376    }
1377
1378    fn cell_name(&self, circuit: &Self::CellId) -> Self::NameType {
1379        self.circuit(circuit).name.clone()
1380    }
1381
1382    fn cell_instance_name(&self, circuit_inst: &Self::CellInstId) -> Option<Self::NameType> {
1383        self.circuit_inst(circuit_inst).name.clone()
1384    }
1385
1386    fn parent_cell(&self, circuit_instance: &Self::CellInstId) -> Self::CellId {
1387        self.circuit_inst(circuit_instance).parent_circuit_id
1388    }
1389
1390    fn template_cell(&self, circuit_instance: &Self::CellInstId) -> Self::CellId {
1391        self.circuit_inst(circuit_instance).template_circuit_id
1392    }
1393
1394    fn for_each_cell<F>(&self, f: F)
1395    where
1396        F: FnMut(Self::CellId),
1397    {
1398        self.circuits.keys().copied().for_each(f)
1399    }
1400
1401    fn each_cell(&self) -> Box<dyn Iterator<Item = CellId> + '_> {
1402        Box::new(self.circuits.keys().copied())
1403    }
1404
1405    fn for_each_cell_instance<F>(&self, circuit: &Self::CellId, f: F)
1406    where
1407        F: FnMut(Self::CellInstId),
1408    {
1409        self.circuit(circuit).instances.iter().copied().for_each(f)
1410    }
1411
1412    fn each_cell_instance(
1413        &self,
1414        circuit: &Self::CellId,
1415    ) -> Box<dyn Iterator<Item = Self::CellInstId> + '_> {
1416        Box::new(self.circuit(circuit).instances.iter().copied())
1417    }
1418
1419    fn for_each_cell_dependency<F>(&self, circuit: &Self::CellId, f: F)
1420    where
1421        F: FnMut(Self::CellId),
1422    {
1423        self.circuit(circuit)
1424            .dependencies
1425            .keys()
1426            .copied()
1427            .for_each(f);
1428    }
1429
1430    fn each_cell_dependency(
1431        &self,
1432        circuit: &Self::CellId,
1433    ) -> Box<dyn Iterator<Item = Self::CellId> + '_> {
1434        Box::new(self.circuit(circuit).dependencies.keys().copied())
1435    }
1436
1437    fn num_cell_dependencies(&self, cell: &Self::CellId) -> usize {
1438        self.circuit(cell).dependencies.len()
1439    }
1440
1441    fn for_each_dependent_cell<F>(&self, circuit: &Self::CellId, f: F)
1442    where
1443        F: FnMut(Self::CellId),
1444    {
1445        self.circuit(circuit)
1446            .dependent_circuits
1447            .keys()
1448            .copied()
1449            .for_each(f);
1450    }
1451
1452    fn each_dependent_cell(
1453        &self,
1454        circuit: &Self::CellId,
1455    ) -> Box<dyn Iterator<Item = Self::CellId> + '_> {
1456        Box::new(self.circuit(circuit).dependent_circuits.keys().copied())
1457    }
1458
1459    fn num_dependent_cells(&self, cell: &Self::CellId) -> usize {
1460        self.circuit(cell).dependent_circuits.len()
1461    }
1462
1463    fn for_each_cell_reference<F>(&self, circuit: &Self::CellId, f: F)
1464    where
1465        F: FnMut(Self::CellInstId),
1466    {
1467        self.circuit(circuit).references.iter().copied().for_each(f)
1468    }
1469
1470    fn each_cell_reference(
1471        &self,
1472        circuit: &Self::CellId,
1473    ) -> Box<dyn Iterator<Item = Self::CellInstId> + '_> {
1474        Box::new(self.circuit(circuit).references.iter().copied())
1475    }
1476
1477    fn num_cell_references(&self, cell: &Self::CellId) -> usize {
1478        self.circuit(cell).references.len()
1479    }
1480
1481    fn num_child_instances(&self, cell: &Self::CellId) -> usize {
1482        self.circuit(cell).instances.len()
1483    }
1484
1485    fn num_cells(&self) -> usize {
1486        self.circuits.len()
1487    }
1488
1489    fn get_chip_property(&self, key: &Self::NameType) -> Option<PropertyValue> {
1490        self.properties.get(key).cloned()
1491    }
1492
1493    fn get_cell_property(
1494        &self,
1495        cell: &Self::CellId,
1496        key: &Self::NameType,
1497    ) -> Option<PropertyValue> {
1498        self.circuit(cell).properties.get(key).cloned()
1499    }
1500
1501    fn get_cell_instance_property(
1502        &self,
1503        inst: &Self::CellInstId,
1504        key: &Self::NameType,
1505    ) -> Option<PropertyValue> {
1506        self.circuit_inst(inst).properties.get(key).cloned()
1507    }
1508}
1509
1510impl LayoutIds for Chip<Coord> {
1511    type Coord = Coord;
1512    type Area = Area;
1513    type LayerId = LayerId;
1514    type ShapeId = ShapeId;
1515}
1516
1517impl LayoutBase for Chip<Coord> {
1518    fn dbu(&self) -> Self::Coord {
1519        self.dbu
1520    }
1521
1522    fn each_layer(&self) -> Box<dyn Iterator<Item = Self::LayerId> + '_> {
1523        Box::new(self.layer_info.keys().copied())
1524    }
1525
1526    fn layer_info(&self, layer: &Self::LayerId) -> LayerInfo<Self::NameType> {
1527        self.layer_info[layer].clone()
1528    }
1529
1530    fn find_layer(&self, index: u32, datatype: u32) -> Option<Self::LayerId> {
1531        self.layers_by_index_datatype
1532            .get(&(index, datatype))
1533            .copied()
1534    }
1535
1536    fn layer_by_name(&self, name: &str) -> Option<Self::LayerId> {
1537        self.layers_by_name.get(name).cloned()
1538    }
1539
1540    fn bounding_box_per_layer(
1541        &self,
1542        cell: &Self::CellId,
1543        layer: &Self::LayerId,
1544    ) -> Option<Rect<Coord>> {
1545        // Compute the bounding box of the cell's own shapes.
1546        let mut bbox = self
1547            .circuit(cell)
1548            .shapes(layer)
1549            .and_then(|shapes| shapes.try_bounding_box());
1550        // Update the bounding box with the children cells.
1551        self.for_each_cell_instance(cell, |i| {
1552            let template = self.template_cell(&i);
1553            let tf = self.get_transform(&i);
1554            let child_bbox = self
1555                .bounding_box_per_layer(&template, layer)
1556                // Transform the child bounding box to ther correct position.
1557                .map(|b| b.transform(|p| tf.transform_point(p)));
1558
1559            bbox = match (bbox, child_bbox) {
1560                (None, None) => None,
1561                (Some(b), None) | (None, Some(b)) => Some(b),
1562                (Some(a), Some(b)) => Some(a.add_rect(&b)),
1563            }
1564        });
1565
1566        bbox
1567    }
1568
1569    fn each_shape_id(
1570        &self,
1571        cell: &Self::CellId,
1572        layer: &Self::LayerId,
1573    ) -> Box<dyn Iterator<Item = Self::ShapeId> + '_> {
1574        if let Some(shapes) = self.circuit(cell).shapes(layer) {
1575            Box::new(shapes.each_shape().map(|s| s.index))
1576        } else {
1577            Box::new(None.into_iter()) // Empty iterator.
1578        }
1579    }
1580
1581    // fn each_shape(&self, cell: &Self::CellId, layer: &Self::LayerId) -> Box<dyn Iterator<Item=&Geometry<Self::Coord>> + '_> {
1582    //     Box::new(self.cells[cell].shapes_map[layer].shapes.values().map(|s| &s.geometry))
1583    // }
1584
1585    fn for_each_shape<F>(&self, cell_id: &Self::CellId, layer: &Self::LayerId, mut f: F)
1586    where
1587        F: FnMut(&Self::ShapeId, &Geometry<Self::Coord>),
1588    {
1589        self.circuits[cell_id]
1590            .shapes_map
1591            .get(layer)
1592            .into_iter()
1593            .for_each(|s| {
1594                s.shapes.values().for_each(|s| f(&s.index, &s.geometry));
1595            });
1596    }
1597
1598    fn with_shape<F, R>(&self, shape_id: &Self::ShapeId, mut f: F) -> R
1599    where
1600        F: FnMut(&Self::LayerId, &Geometry<Self::Coord>) -> R,
1601    {
1602        let shape = self.shape(shape_id);
1603        let (_, layer) = &self.shape_parents[shape_id];
1604        f(layer, &shape.geometry)
1605    }
1606
1607    fn parent_of_shape(&self, shape_id: &Self::ShapeId) -> (Self::CellId, Self::LayerId) {
1608        *self
1609            .shape_parents
1610            .get(shape_id)
1611            .expect("Shape ID not found.")
1612    }
1613
1614    fn get_transform(&self, cell_inst: &Self::CellInstId) -> SimpleTransform<Self::Coord> {
1615        *self.circuit_inst(cell_inst).get_transform()
1616    }
1617
1618    fn get_shape_property(
1619        &self,
1620        shape: &Self::ShapeId,
1621        key: &Self::NameType,
1622    ) -> Option<PropertyValue> {
1623        let (cell, layer) = self.shape_parents[shape];
1624        self.circuit(&cell).shapes_map[&layer]
1625            .shape_properties
1626            .get(shape)
1627            .and_then(|props| props.get(key))
1628            .cloned()
1629    }
1630}
1631
1632impl HierarchyEdit for Chip<Coord> {
1633    fn create_cell(&mut self, name: Self::NameType) -> Self::CellId {
1634        // TODO
1635        self.create_circuit(name, vec![])
1636    }
1637
1638    fn remove_cell(&mut self, cell_id: &Self::CellId) {
1639        self.remove_circuit(cell_id)
1640    }
1641
1642    fn create_cell_instance(
1643        &mut self,
1644        parent_cell: &Self::CellId,
1645        template_cell: &Self::CellId,
1646        name: Option<Self::NameType>,
1647    ) -> Self::CellInstId {
1648        self.create_circuit_instance(parent_cell, template_cell, name)
1649    }
1650
1651    fn remove_cell_instance(&mut self, id: &Self::CellInstId) {
1652        <Chip<Coord>>::remove_circuit_instance(self, id)
1653    }
1654
1655    fn rename_cell_instance(&mut self, inst: &Self::CellInstId, new_name: Option<Self::NameType>) {
1656        <Chip<Coord>>::rename_cell_instance(self, inst, new_name)
1657    }
1658
1659    fn rename_cell(&mut self, cell: &Self::CellId, new_name: Self::NameType) {
1660        <Chip<Coord>>::rename_cell(self, cell, new_name)
1661    }
1662
1663    fn set_chip_property(&mut self, key: Self::NameType, value: PropertyValue) {
1664        self.properties.insert(key, value);
1665    }
1666
1667    fn set_cell_property(
1668        &mut self,
1669        cell: &Self::CellId,
1670        key: Self::NameType,
1671        value: PropertyValue,
1672    ) {
1673        self.circuit_mut(cell).properties.insert(key, value);
1674    }
1675
1676    fn set_cell_instance_property(
1677        &mut self,
1678        inst: &Self::CellInstId,
1679        key: Self::NameType,
1680        value: PropertyValue,
1681    ) {
1682        self.circuit_inst_mut(inst).properties.insert(key, value);
1683    }
1684}
1685
1686impl LayoutEdit for Chip<Coord> {
1687    fn set_dbu(&mut self, dbu: Self::Coord) {
1688        self.dbu = dbu;
1689    }
1690
1691    fn create_layer(&mut self, index: u32, datatype: u32) -> Self::LayerId {
1692        // Find next free layer index.
1693        let layer_index = loop {
1694            let id = self.layer_index_generator.next();
1695            if !self.layer_info.contains_key(&id) {
1696                break id;
1697            }
1698        };
1699
1700        self.create_layer_with_id(layer_index, index, datatype)
1701            .unwrap(); // Unwrap is fine because layer ID is freshly generated.
1702
1703        layer_index
1704    }
1705
1706    fn create_layer_with_id(
1707        &mut self,
1708        layer_id: Self::LayerId,
1709        index: u32,
1710        datatype: u32,
1711    ) -> Result<(), ()> {
1712        if self.layer_info.contains_key(&layer_id) {
1713            return Err(());
1714        }
1715
1716        // Create new entries in the layer lookup tables.
1717        self.layers_by_index_datatype
1718            .insert((index, datatype), layer_id);
1719
1720        let info = LayerInfo {
1721            index,
1722            datatype,
1723            name: None,
1724        };
1725        self.layer_info.insert(layer_id, info);
1726
1727        Ok(())
1728    }
1729
1730    fn set_layer_name(
1731        &mut self,
1732        layer: &Self::LayerId,
1733        name: Option<Self::NameType>,
1734    ) -> Option<Self::NameType> {
1735        if let Some(name) = &name {
1736            // Check that we do not shadow another layer name.
1737            let existing = self.layers_by_name.get(name);
1738
1739            if existing == Some(layer) {
1740                // Nothing to be done.
1741                return Some(name.clone());
1742            }
1743
1744            if existing.is_some() {
1745                panic!("Layer name already exists: '{}'", name)
1746            }
1747        }
1748
1749        // Remove the name.
1750        let previous_name = self
1751            .layer_info
1752            .get_mut(layer)
1753            .expect("Layer ID not found.")
1754            .name
1755            .take();
1756        if let Some(prev_name) = &previous_name {
1757            // Remove the name from the table.
1758            self.layers_by_name.remove(prev_name);
1759        }
1760
1761        if let Some(name) = name {
1762            // Create the link from the name to the ID.
1763            self.layers_by_name.insert(name.clone(), *layer);
1764            // Store the name.
1765            self.layer_info
1766                .get_mut(layer)
1767                .expect("Layer ID not found.")
1768                .name = Some(name);
1769        }
1770        previous_name
1771    }
1772
1773    fn insert_shape(
1774        &mut self,
1775        parent_cell: &Self::CellId,
1776        layer: &Self::LayerId,
1777        geometry: Geometry<Self::Coord>,
1778    ) -> Self::ShapeId {
1779        let shape_id = self.shape_index_generator.next();
1780
1781        let shape = Shape {
1782            index: shape_id,
1783            geometry,
1784            net: None,
1785            pin: None,
1786            user_data: Default::default(),
1787        };
1788
1789        self.shape_parents.insert(shape_id, (*parent_cell, *layer));
1790
1791        self.circuit_mut(parent_cell)
1792            .get_or_create_shapes_mut(layer)
1793            .shapes
1794            .insert(shape_id, shape);
1795
1796        shape_id
1797    }
1798
1799    fn remove_shape(&mut self, shape_id: &Self::ShapeId) -> Option<Geometry<Self::Coord>> {
1800        // Remove all links to this shape.
1801        if let Some(net) = self.get_net_of_shape(shape_id) {
1802            self.net_mut(&net).net_shapes.remove(shape_id);
1803        }
1804        if let Some(pin) = self.get_pin_of_shape(shape_id) {
1805            self.pin_mut(&pin).pin_shapes.remove(shape_id);
1806        }
1807
1808        let (parent_cell, layer) = self.shape_parents[shape_id];
1809        self.shape_parents.remove(shape_id);
1810
1811        self.circuit_mut(&parent_cell)
1812            .shapes_mut(&layer)
1813            .expect("Layer not found.")
1814            .shapes
1815            .remove(shape_id)
1816            .map(|s| s.geometry)
1817    }
1818
1819    fn replace_shape(
1820        &mut self,
1821        shape_id: &Self::ShapeId,
1822        geometry: Geometry<Self::Coord>,
1823    ) -> Geometry<Self::Coord> {
1824        let (parent_cell, layer) = self.shape_parents[shape_id];
1825        let shape_id = *shape_id;
1826
1827        let g = &mut self
1828            .circuit_mut(&parent_cell)
1829            .shapes_mut(&layer)
1830            .expect("Layer not found.")
1831            .shapes
1832            .get_mut(&shape_id)
1833            .expect("Shape not found.")
1834            .geometry;
1835        let mut new_g = geometry;
1836        std::mem::swap(g, &mut new_g);
1837        new_g
1838    }
1839
1840    fn set_transform(&mut self, cell_inst: &Self::CellInstId, tf: SimpleTransform<Self::Coord>) {
1841        self.circuit_inst_mut(cell_inst).set_transform(tf)
1842    }
1843
1844    fn set_shape_property(
1845        &mut self,
1846        shape: &Self::ShapeId,
1847        key: Self::NameType,
1848        value: PropertyValue,
1849    ) {
1850        let (cell, layer) = self.shape_parents[shape];
1851        self.circuit_mut(&cell)
1852            .shapes_map
1853            .get_mut(&layer)
1854            .expect("Layer not found.")
1855            .shape_properties
1856            .entry(*shape)
1857            .or_default()
1858            .insert(key, value);
1859    }
1860}
1861
1862impl L2NBase for Chip<Coord> {
1863    fn shapes_of_net(&self, net_id: &Self::NetId) -> Box<dyn Iterator<Item = Self::ShapeId> + '_> {
1864        Box::new(self.net(net_id).net_shapes.iter().copied())
1865    }
1866
1867    fn shapes_of_pin(&self, pin_id: &Self::PinId) -> Box<dyn Iterator<Item = Self::ShapeId> + '_> {
1868        Box::new(self.pin(pin_id).pin_shapes.iter().cloned())
1869    }
1870
1871    fn get_net_of_shape(&self, shape_id: &Self::ShapeId) -> Option<Self::NetId> {
1872        self.shape(shape_id).net
1873    }
1874
1875    fn get_pin_of_shape(&self, shape_id: &Self::ShapeId) -> Option<Self::PinId> {
1876        self.shape(shape_id).pin
1877    }
1878}
1879
1880impl L2NEdit for Chip<Coord> {
1881    fn set_pin_of_shape(
1882        &mut self,
1883        shape_id: &Self::ShapeId,
1884        pin: Option<Self::PinId>,
1885    ) -> Option<Self::PinId> {
1886        // Create link from pin to shape.
1887        if let Some(pin) = &pin {
1888            let not_yet_present = self.pin_mut(pin).pin_shapes.insert(*shape_id);
1889            if !not_yet_present {
1890                // The shape is already assigned to this pin. Don't do anything more.
1891                return Some(*pin);
1892            }
1893        }
1894
1895        // Create from shape to link.
1896        let mut pin = pin;
1897        std::mem::swap(&mut self.shape_mut(shape_id).pin, &mut pin);
1898        let previous_pin = pin;
1899
1900        // Remove the old link to the pin.
1901        if let Some(previous_pin) = &previous_pin {
1902            assert!(
1903                self.pin_mut(previous_pin).pin_shapes.remove(shape_id),
1904                "Pin was not linked to the shape."
1905            );
1906        }
1907
1908        // Return the previous pin (got it by the above swap operation).
1909        previous_pin
1910    }
1911
1912    fn set_net_of_shape(
1913        &mut self,
1914        shape_id: &Self::ShapeId,
1915        net: Option<Self::NetId>,
1916    ) -> Option<Self::NetId> {
1917        // Create link from net to shape.
1918        if let Some(net) = &net {
1919            let not_yet_present = self.net_mut(net).net_shapes.insert(*shape_id);
1920            if !not_yet_present {
1921                // The shape is already assigned to this net. Don't do anything more.
1922                return Some(*net);
1923            }
1924        }
1925
1926        // Create from shape to link.
1927        let mut net = net;
1928        std::mem::swap(&mut self.shape_mut(shape_id).net, &mut net);
1929        let previous_net = net;
1930
1931        // Remove the old link to the net.
1932        if let Some(previous_net) = &previous_net {
1933            assert!(
1934                self.net_mut(previous_net).net_shapes.remove(shape_id),
1935                "Net was not linked to the shape."
1936            );
1937        }
1938
1939        // Return the previous net (got it by the above swap operation).
1940        previous_net
1941    }
1942}