1#![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;
30use std::fmt::Debug;
32
33use crate::layout::types::LayerInfo;
34use crate::property_storage::{PropertyStore, PropertyValue};
35
36use 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
47pub type UInt = u32;
49pub type SInt = i32;
51
52pub type Coord = i32;
54pub type Area = i64;
56
57#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
59#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
60pub struct CellId(u32);
61
62#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
64#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
65pub struct CellInstId(usize);
66
67#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
69#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
70pub struct PinId(u32);
71
72#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
74#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
75pub struct PinInstId(usize);
76
77#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
79#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
80pub enum TerminalId {
81 Pin(PinId),
83 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#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
101#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
102pub struct NetId(usize);
103
104pub type ShapeId = Index<Shape<Coord>, u32>;
106
107pub type LayerId = Index<LayerInfo<NameT>, u16>;
109
110macro_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#[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: CellId,
142 name: NameT,
144
145 instances: IntHashSet<CellInstId>,
147 instances_by_name: HashMap<NameT, CellInstId>,
150 references: IntHashSet<CellInstId>,
152
153 dependencies: IntHashMap<CellId, usize>,
157 dependent_circuits: IntHashMap<CellId, usize>,
159
160 #[allow(unused)]
163 instance_properties: IntHashMap<CellInstId, PropertyStore<NameT>>,
164 properties: PropertyStore<NameT>,
166 #[allow(unused)]
168 user_data: U,
169
170 pins: Vec<PinId>,
173 nets: IntHashSet<NetId>,
175 nets_by_name: HashMap<NameT, NetId>,
177 net_low: NetId,
179 net_high: NetId,
181
182 shapes_map: IntHashMap<LayerId, Shapes<C>>,
185}
186
187impl Circuit {
188 fn id(&self) -> CellId {
190 self.id
191 }
192
193 fn shapes(&self, layer_id: &LayerId) -> Option<&Shapes<Coord>> {
198 self.shapes_map.get(layer_id)
199 }
200
201 fn shapes_mut(&mut self, layer_id: &LayerId) -> Option<&mut Shapes<Coord>> {
204 self.shapes_map.get_mut(layer_id)
205 }
206
207 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#[derive(Debug, Clone)]
229#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
230pub struct CircuitInst<C = Coord, U = ()>
231where
232 C: CoordinateType,
233{
234 name: Option<NameT>,
236 template_circuit_id: CellId,
238 parent_circuit_id: CellId,
240 properties: PropertyStore<NameT>,
242
243 #[allow(unused)]
245 user_data: U,
246
247 pins: Vec<PinInstId>,
250
251 transform: SimpleTransform<C>,
254 }
258
259impl CircuitInst {
260 fn get_transform(&self) -> &SimpleTransform<Coord> {
264 &self.transform
265 }
266
267 fn set_transform(&mut self, tf: SimpleTransform<Coord>) {
269 self.transform = tf;
270 }
271}
272
273#[derive(Debug, Clone)]
275#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
276pub struct Pin {
277 name: NameT,
279 direction: Direction,
281 circuit: CellId,
283 net: Option<NetId>,
285
286 pin_shapes: IntHashSet<ShapeId>,
289}
290
291#[derive(Debug, Clone)]
293#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
294pub struct PinInst {
295 pub template_pin_id: PinId,
297 pub circuit_inst: CellInstId,
299 net: Option<NetId>,
301}
302
303#[derive(Debug, Clone)]
305#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
306pub struct Net {
307 pub name: Option<NameT>,
309 pub parent_id: CellId,
311 pub pins: IntHashSet<PinId>,
313 pub pin_instances: IntHashSet<PinInstId>,
315
316 pub net_shapes: IntHashSet<ShapeId>,
319}
320
321impl Net {}
322
323#[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 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 dbu: C,
345
346 layer_index_generator: IndexGenerator<LayerInfo<NameT>, u16>,
348 layers_by_name: HashMap<NameT, LayerId>,
350 layers_by_index_datatype: IntHashMap<(UInt, UInt), LayerId>,
352 layer_info: IntHashMap<LayerId, LayerInfo<NameT>>,
354 shape_index_generator: IndexGenerator<Shape<C>>,
356
357 shape_parents: IntHashMap<ShapeId, (CellId, LayerId)>,
359
360 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 pub fn new() -> Self {
394 Chip::default()
395 }
396
397 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 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 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 self.circuit_mut(cell).name.clone_from(&name);
423 self.circuits_by_name.insert(name, *cell);
424 }
425
426 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 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 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 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 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 pins.into_iter().for_each(|(name, direction)| {
498 self.create_pin(id, name, direction);
499 });
500
501 id
502 }
503
504 fn remove_circuit(&mut self, circuit_id: &CellId) {
507 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 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 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 let pins = self.circuit(circuit_id).pins.clone();
539 for pin in pins {
540 self.pins.remove(&pin).unwrap();
541 }
542 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 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 let mut stack: Vec<CellId> = vec![*parent];
563 while let Some(c) = stack.pop() {
564 if &c == circuit_template {
565 panic!("Cannot create recursive instances.");
569 }
570 stack.extend(self.circuit(&c).dependent_circuits.keys().copied())
572 }
573 }
574
575 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 {
608 self.circuit_mut(parent)
609 .dependencies
610 .entry(*circuit_template)
611 .and_modify(|c| *c += 1)
612 .or_insert(1);
613 }
614
615 {
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 fn remove_circuit_instance(&mut self, circuit_inst_id: &CellInstId) {
629 self.rename_cell_instance(circuit_inst_id, None);
631
632 for pin in self.circuit_inst(circuit_inst_id).pins.clone() {
634 self.disconnect_pin_instance(&pin);
635 }
636 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 {
642 let count = self
644 .circuit_mut(&parent)
645 .dependencies
646 .entry(template)
647 .or_insert(0); *count -= 1;
649
650 if *count == 0 {
651 self.circuit_mut(&parent).dependencies.remove(&template);
653 }
654 }
655
656 {
658 let count = self
660 .circuit_mut(&template)
661 .dependent_circuits
662 .entry(parent)
663 .or_insert(0); *count -= 1;
665
666 if *count == 0 {
667 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 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 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 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 return new_name;
718 }
719 }
720 }
721
722 let maybe_old_name = self.net_mut(net_id).name.take();
723
724 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 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 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 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 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 fn disconnect_pin(&mut self, pin: &PinId) -> Option<NetId> {
793 self.connect_pin(pin, None)
794 }
795
796 fn connect_pin(&mut self, pin: &PinId, net: Option<NetId>) -> Option<NetId> {
798 if let Some(net) = net {
799 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 self.net_mut(&net).pins.remove(pin);
816 }
817
818 if let Some(net) = net {
819 self.net_mut(&net).pins.insert(*pin);
821 }
822
823 old_net
824 }
825
826 fn disconnect_pin_instance(&mut self, pin: &PinInstId) -> Option<NetId> {
828 self.connect_pin_instance(pin, None)
829 }
830
831 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 self.net_mut(&net).pin_instances.remove(pin);
851 }
852
853 if let Some(net) = net {
854 self.net_mut(&net).pin_instances.insert(*pin);
856 }
857
858 old_net
859 }
860
861 fn circuit(&self, id: &CellId) -> &Circuit {
863 &self.circuits[id]
864 }
865
866 fn circuit_mut(&mut self, id: &CellId) -> &mut Circuit {
876 self.circuits.get_mut(id).expect("Cell ID not found.")
877 }
878
879 fn circuit_inst(&self, id: &CellInstId) -> &CircuitInst {
881 &self.circuit_instances[id]
882 }
883
884 fn circuit_inst_mut(&mut self, id: &CellInstId) -> &mut CircuitInst {
886 self.circuit_instances.get_mut(id).unwrap()
887 }
888
889 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 fn net_mut(&mut self, id: &NetId) -> &mut Net {
898 self.nets.get_mut(id).unwrap()
899 }
900
901 fn pin(&self, id: &PinId) -> &Pin {
903 &self.pins[id]
904 }
905
906 fn pin_mut(&mut self, id: &PinId) -> &mut Pin {
908 self.pins.get_mut(id).unwrap()
909 }
910
911 fn pin_inst(&self, id: &PinInstId) -> &PinInst {
913 &self.pin_instances[id]
914 }
915
916 fn pin_inst_mut(&mut self, id: &PinInstId) -> &mut PinInst {
918 self.pin_instances.get_mut(id).unwrap()
919 }
920
921 fn next_id_counter_usize(ctr: &mut usize) -> usize {
923 let c = *ctr;
924 *ctr += 1;
925 c
926 }
927
928 fn next_id_counter_u32(ctr: &mut u32) -> u32 {
930 let c = *ctr;
931 *ctr += 1;
932 c
933 }
934
935 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 self.circuits.get_mut(&parent).unwrap().pins.push(pin_id);
950
951 for inst in &self.circuits[&parent].references {
953 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 self.circuit_instances
964 .get_mut(inst)
965 .unwrap()
966 .pins
967 .push(pin_inst_id);
968 }
969
970 pin_id
971 }
972
973 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 fn pins_for_net(&self, net: &NetId) -> impl Iterator<Item = PinId> + '_ {
987 self.net(net).pins.iter().copied()
988 }
989
990 fn pins_instances_for_net(&self, net: &NetId) -> impl Iterator<Item = PinInstId> + '_ {
992 self.net(net).pin_instances.iter().copied()
993 }
994
995 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 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 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 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 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 self.circuit_inst_mut(&inst).pins.retain(|p| p != &pin_inst);
1187 self.pin_instances.remove(&pin_inst);
1189 }
1190
1191 self.disconnect_pin(id);
1193
1194 self.circuit_mut(&cell).pins.retain(|p| p != id);
1196 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#[derive(Clone, Debug)]
1282#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1283pub struct Shape<C, U = ()> {
1284 index: Index<Shape<C, U>>,
1286 pub geometry: Geometry<C>,
1288 net: Option<NetId>,
1292 pin: Option<PinId>,
1294 #[allow(unused)]
1296 user_data: U,
1297}
1298
1299#[derive(Clone, Debug)]
1302#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1303pub struct Shapes<C>
1304where
1305 C: CoordinateType,
1306{
1307 shapes: IntHashMap<ShapeId, Shape<C>>,
1309 shape_properties: IntHashMap<ShapeId, PropertyStore<NameT>>,
1311}
1312
1313impl<C: CoordinateType> Shapes<C> {
1314 fn new() -> Self {
1316 Self {
1317 shapes: Default::default(),
1318 shape_properties: Default::default(),
1319 }
1320 }
1321 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 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 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 let mut bbox = self
1547 .circuit(cell)
1548 .shapes(layer)
1549 .and_then(|shapes| shapes.try_bounding_box());
1550 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 .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()) }
1579 }
1580
1581 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 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 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(); 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 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 let existing = self.layers_by_name.get(name);
1738
1739 if existing == Some(layer) {
1740 return Some(name.clone());
1742 }
1743
1744 if existing.is_some() {
1745 panic!("Layer name already exists: '{}'", name)
1746 }
1747 }
1748
1749 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 self.layers_by_name.remove(prev_name);
1759 }
1760
1761 if let Some(name) = name {
1762 self.layers_by_name.insert(name.clone(), *layer);
1764 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 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 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 return Some(*pin);
1892 }
1893 }
1894
1895 let mut pin = pin;
1897 std::mem::swap(&mut self.shape_mut(shape_id).pin, &mut pin);
1898 let previous_pin = pin;
1899
1900 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 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 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 return Some(*net);
1923 }
1924 }
1925
1926 let mut net = net;
1928 std::mem::swap(&mut self.shape_mut(shape_id).net, &mut net);
1929 let previous_net = net;
1930
1931 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 previous_net
1941 }
1942}