1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
//! Formatting utils that let you dump SPEF object to SPEF source.

use super::*;
use std::fmt::{ Display, Formatter, Result };
use itertools::Itertools;
use indexmap::IndexSet;

/// Name mapping.
/// 
/// Note that this definition contains **references** to Arc's,
/// which is different from that in spefpest.rs.
///
/// The index is the IndexSet index + 1.
type NameMap<'i> = IndexSet<(&'i Arc<HierName>, Option<isize>)>;

impl Display for Direction {
    #[inline]
    fn fmt(&self, f: &mut Formatter) -> Result {
        use Direction::*;
        write!(f, "{}", match self {
            I => "I", O => "O", B => "B"
        })
    }
}

impl Display for ParValue {
    #[inline]
    fn fmt(&self, f: &mut Formatter) -> Result {
        use ParValue::*;
        match self {
            Single(a) => write!(f, "{}", a),
            Three(a, b, c) => write!(f, "{}:{}:{}", a, b, c)
        }
    }
}

impl Display for SPEFConnAttr {
    #[inline]
    fn fmt(&self, f: &mut Formatter) -> Result {
        if let Some((x, y)) = self.coords {
            write!(f, " *C {} {}", x, y)?;
        }
        if let Some(v) = self.cap_load {
            write!(f, " *L {}", v)?;
        }
        if let Some((v1, v2)) = self.slew {
            write!(f, " *S {} {}", v1, v2)?;
        }
        if let Some(s) = &self.driving_cell {
            write!(f, " *D {}", s)?;
        }
        Ok(())
    }
}

struct BitIDFmt<'a>(isize, &'a SPEFHeader);

impl Display for BitIDFmt<'_> {
    #[inline]
    fn fmt(&self, f: &mut Formatter) -> Result {
        write!(f, "{}{}{}",
               self.1.bus_delimiter_left, self.0,
               self.1.bus_delimiter_right)
    }
}

struct HierNameFmt<'a>(&'a HierName, &'a SPEFHeader);

impl Display for HierNameFmt<'_> {
    #[inline]
    fn fmt(&self, f: &mut Formatter) -> Result {
        write!(f, "{}", self.0.0.iter().format(
            self.1.divider.encode_utf8(&mut [0; 1])))
    }
}

impl HierName {
    #[inline]
    fn display<'a>(&'a self, header: &'a SPEFHeader) -> HierNameFmt {
        HierNameFmt(self, header)
    }
}

struct SPEFHierPortPinRefFmt<'a>(
    &'a SPEFHierPortPinRef, &'a NameMap<'a>, &'a SPEFHeader);

impl Display for SPEFHierPortPinRefFmt<'_> {
    #[inline]
    fn fmt(&self, f: &mut Formatter) -> Result {
        let SPEFHierPortPinRefFmt(r, nm, header) = self;
        let raw_name = r.as_raw_name();
        let mut need_bit_output = false;
        if let Some(id) = nm.get_index_of(&raw_name) {
            write!(f, "*{}", id + 1)?;
        }
        else {
            write!(f, "{}", raw_name.0.display(header))?;
            need_bit_output = true;
        }
        if let Some(pin) = &r.1 {
            write!(f, "{}{}", header.delimiter, pin)?;
            need_bit_output = true;
        }
        if need_bit_output{
            if let Some(bit_id) = raw_name.1 {
                write!(f, "{}", BitIDFmt(bit_id, header))?;
            }
        }
        Ok(())
    }
}

impl SPEFHierPortPinRef {
    #[inline]
    fn as_raw_name(&self) -> (&Arc<HierName>, Option<isize>) {
        match &self.1 {
            Some(_) => (&self.0, None),
            None => (&self.0, self.2)
        }
    }
    
    #[inline]
    fn display<'a>(&'a self, nm: &'a NameMap<'a>, header: &'a SPEFHeader) -> SPEFHierPortPinRefFmt<'a> {
        SPEFHierPortPinRefFmt(self, nm, header)
    }
}

impl SPEFPort {
    #[inline]
    fn write_to_fmt(&self, f: &mut Formatter, nm: &NameMap, header: &SPEFHeader) -> Result {
        writeln!(f, "{} {}{}",
                 self.name.display(nm, header),
                 self.direction, self.conn_attr)
    }
}

impl SPEFNet {
    #[inline]
    fn write_to_fmt(&self, f: &mut Formatter, nm: &NameMap, header: &SPEFHeader) -> Result {
        writeln!(f, "*D_NET {} {}",
                 self.name.display(nm, header),
                 self.total_cap)?;
        
        writeln!(f, "*CONN")?;
        for conn in &self.conns {
            writeln!(f, "*{} {} {}{}",
                     if conn.name.1.is_some() { 'I' } else { 'P' },
                     conn.name.display(nm, header),
                     conn.direction, conn.conn_attr)?
        }
        
        writeln!(f, "*CAP")?;
        for (id, cap) in self.caps.iter().enumerate() {
            write!(f, "{} {}", id + 1, cap.a.display(nm, header))?;
            if let Some(b) = &cap.b {
                write!(f, " {}", b.display(nm, header))?;
            }
            writeln!(f, " {}", cap.val)?;
        }
        
        writeln!(f, "*RES")?;
        for (id, res) in self.ress.iter().enumerate() {
            writeln!(f, "{} {} {} {}",
                     id + 1,
                     res.a.display(nm, header),
                     res.b.display(nm, header),
                     res.val)?;
        }
        
        writeln!(f, "*END")?;
        Ok(())
    }
}

impl SPEF {
    #[inline]
    fn build_name_map(&self) -> NameMap {
        let mut ret = NameMap::new();
        ret.extend(self.top_ports.iter()
                   .map(|p| p.name.as_raw_name()));
        ret.extend(self.nets.iter()
                   .map(|p| p.name.as_raw_name()));
        for net in &self.nets {
            ret.extend(net.conns.iter()
                       .map(|c| c.name.as_raw_name()));
            ret.extend(net.caps.iter()
                       .map(|c| c.a.as_raw_name()));
            ret.extend(net.caps.iter()
                       .filter_map(|c| c.b.as_ref()
                                   .map(|b| b.as_raw_name())));
            ret.extend(net.ress.iter()
                       .map(|r| r.a.as_raw_name()));
            ret.extend(net.ress.iter()
                       .map(|r| r.b.as_raw_name()));
        }
        ret
    }

    #[inline]
    fn write_name_map(&self, f: &mut Formatter, nm: &NameMap) -> Result {
        if nm.len() == 0 {
            return Ok(());
        }
        writeln!(f, "*NAME_MAP")?;
        for (id, (name, bit_id)) in nm.iter().enumerate() {
            write!(f, "*{} {}",
                   id + 1, name.display(&self.header))?;
            if let Some(bit_id) = bit_id {
                write!(f, "{}", BitIDFmt(*bit_id, &self.header))?;
            }
            writeln!(f)?;
        }
        Ok(())
    }

    #[inline]
    fn write_header(&self, f: &mut Formatter) -> Result {
        /// Compute the best fit unit and ratio.
        macro_rules! fmt_unit {
            ($v:expr, $($k:expr => $u:expr),+) => {{
                let v = $v;
                let mut best: Option<(&'static str, f32, f32)> = None;
                $({
                    let v_div_log = (v / $u).ln().abs();
                    match best {
                        None => {
                            best = Some(($k, v_div_log, v / $u));
                        }
                        Some((_, w, _)) if w > v_div_log => {
                            best = Some(($k, v_div_log, v / $u));
                        }
                        _ => {}
                    }
                })+;
                let (best_unit, _, best_ratio) = best.unwrap();
                // (best_ratio, best_unit)
                format!("{} {}", best_ratio, best_unit)
            }}
        }
        
        let h = &self.header;
        write!(
            f, "\
*SPEF {:?}
*DESIGN {:?}
*DATE {:?}
*VENDOR {:?}
*PROGRAM {:?}
*VERSION {:?}
*DESIGN_FLOW {:?}
*DIVIDER {}
*DELIMITER {}
*BUS_DELIMITER {} {}
*T_UNIT {}
*C_UNIT {}
*R_UNIT {}
*L_UNIT {}
",
            h.edition, h.design, h.date, h.vendor, h.program,
            h.version, h.design_flow.iter().format(" "),
            h.divider, h.delimiter,
            h.bus_delimiter_left, h.bus_delimiter_right,
            fmt_unit!(h.time_unit, "NS" => 1e-9, "PS" => 1e-12),
            fmt_unit!(h.cap_unit, "PF" => 1e-12, "FF" => 1e-15),
            fmt_unit!(h.res_unit, "OHM" => 1., "KOHM" => 1e3),
            fmt_unit!(h.induct_unit, "HENRY" => 1., "MH" => 1e-3, "UH" => 1e-6))
    }
}

impl Display for SPEF {
    /// Dump SPEF object to SPEF source by just formatting it
    /// using `"{}"` (Display).
    fn fmt(&self, f: &mut Formatter) -> Result {
        self.write_header(f)?;
        writeln!(f)?;
        
        let name_map = self.build_name_map();
        self.write_name_map(f, &name_map)?;
        writeln!(f)?;
        
        if self.top_ports.len() != 0 {
            writeln!(f, "*PORTS")?;
            for port in &self.top_ports {
                port.write_to_fmt(f, &name_map, &self.header)?;
            }
            writeln!(f)?;
        }
        
        for net in &self.nets {
            net.write_to_fmt(f, &name_map, &self.header)?;
            writeln!(f)?;
        }
        Ok(())
    }
}