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

//! Data types and parser functions used for both LEF and DEF.

use crate::stream_parser::{LefDefLexer, LefDefParseError};
use itertools::PeekingNext;
use libreda_stream_parser::{tokenize, Tokenized};
use std::fmt;
use std::str::FromStr;

/// Data type of a property value.
#[derive(Clone, Debug)]
pub enum PropertyType {
    /// Integer number.
    Integer,
    /// Floating point number.
    Real,
    /// String.
    String,
}

impl FromStr for PropertyType {
    type Err = ();

    fn from_str(input: &str) -> Result<Self, Self::Err> {
        match input {
            "INTEGER" => Ok(Self::Integer),
            "REAL" => Ok(Self::Real),
            "STRING" => Ok(Self::String),
            _ => Err(()),
        }
    }
}

impl fmt::Display for PropertyType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Integer => f.write_str("INTEGER"),
            Self::Real => f.write_str("REAL"),
            Self::String => f.write_str("STRING"),
        }
    }
}

/// Value of a LEF/DEF property.
#[derive(Clone, Debug)]
pub enum PropertyValue {
    /// Integer.
    Int(i32),
    /// Floating point number.
    Real(f64),
    /// Quoted ASCII string.
    String(String),
}

impl fmt::Display for PropertyValue {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            PropertyValue::Int(v) => write!(f, "{}", v),
            PropertyValue::Real(v) => write!(f, "{}", v),
            PropertyValue::String(v) => write!(f, r#""{}""#, v),
        }
    }
}

/// Read a point of the form `( x y )`, `x y` or `( x , y )`.
pub fn read_point<T: FromStr, I>(
    tokens: &mut Tokenized<I, LefDefLexer>,
) -> Result<(T, T), LefDefParseError>
where
    I: Iterator<Item = char> + PeekingNext,
{
    // Points should be declared in parenthesis. This is not always the case though.
    let uses_parentheses = tokens.test_str("(")?;
    let x: T = tokens.take_and_parse()?;
    tokens.test_str(",")?;
    let y: T = tokens.take_and_parse()?;
    if uses_parentheses {
        tokens.expect_str(")")?;
    }

    Ok((x, y))
}

/// Read a polygon. Does not expect 'POLYGON' token at the beginning.
pub fn read_polygon<T: FromStr, I>(
    tokens: &mut Tokenized<I, LefDefLexer>,
) -> Result<Vec<(T, T)>, LefDefParseError>
where
    I: Iterator<Item = char> + PeekingNext,
{
    // Read points until ';'.
    let mut points = Vec::new();
    loop {
        if tokens.test_str(";")? {
            break;
        } else {
            points.push(read_point(tokens)?);
        }
    }

    Ok(points)
}

/// Read a rectangle of the form `( x1 y1 ) ( x2 y2 )`.
pub fn read_rect<T: FromStr, I>(
    tokens: &mut Tokenized<I, LefDefLexer>,
) -> Result<((T, T), (T, T)), LefDefParseError>
where
    I: Iterator<Item = char> + PeekingNext,
{
    let p1 = read_point(tokens)?;
    let p2 = read_point(tokens)?;

    Ok((p1, p2))
}

/// Macro orientations that can be used by the placer.
#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
pub struct Symmetry {
    /// Mirroring macro at x-axis.
    x: bool,
    /// Mirroring macro at y-axis.
    y: bool,
    /// Rotating by 90 degrees. Intended for pad cells only.
    r90: bool,
}

impl Symmetry {
    /// Create a new symmetry definition.
    pub fn new(x: bool, y: bool, r90: bool) -> Self {
        Self { x, y, r90 }
    }

    /// Mirror symmetry at x-axis.
    pub fn x() -> Self {
        Self::new(true, false, false)
    }
    /// Mirror symmetry at y-axis.
    pub fn y() -> Self {
        Self::new(false, true, false)
    }
    /// Rotation by 90 degrees.
    pub fn r90() -> Self {
        Self::new(false, false, true)
    }

    /// Take the union of the both symmetry definitions.
    pub fn union(self, other: Self) -> Self {
        Self {
            x: self.x | other.x,
            y: self.y | other.y,
            r90: self.r90 | other.r90,
        }
    }
}

impl FromStr for Symmetry {
    type Err = ();

    fn from_str(input: &str) -> Result<Self, Self::Err> {
        match input {
            "X" => Ok(Self::x()),
            "Y" => Ok(Self::y()),
            "R90" => Ok(Self::r90()),
            _ => Err(()),
        }
    }
}

impl fmt::Display for Symmetry {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.x {
            f.write_str("X")?;
        }
        if self.y {
            f.write_str("Y")?;
        }
        if self.r90 {
            f.write_str("R90")?;
        }

        Ok(())
    }
}

/// Antenna rule definitions.
#[derive(Clone, Debug, Default)]
pub struct AntennaRules {
    /// Antenna model.
    model: (),
    area_ratio: (),
    diff_area_ration: (),
    cum_area_ratio: (),
    cum_diff_area_ratio: (),
    // ...
}

/// Orientation, consists of rotation and mirroring.
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub enum Orient {
    /// North.
    N,
    /// South.
    S,
    /// East.
    E,
    /// West.
    W,
    /// Flipped North.
    FN,
    /// Flipped South.
    FS,
    /// FLipped East.
    FE,
    /// Flipped West.
    FW,
}

impl Default for Orient {
    fn default() -> Self {
        Self::N
    }
}

impl Orient {
    /// Decompose into a non-flipped orientation and a flag telling whether the orientation is flipped
    /// or not.
    ///
    /// Returns `(orientation, is_flipped)`.
    pub fn decomposed(&self) -> (Self, bool) {
        match self {
            Orient::FN => (Orient::N, true),
            Orient::FS => (Orient::S, true),
            Orient::FE => (Orient::E, true),
            Orient::FW => (Orient::W, true),
            other => (*other, false),
        }
    }

    /// Returns the flipped orientation.
    /// For example turns a `N` into a `FN`.
    pub fn flipped(&self) -> Self {
        use Orient::*;
        match self {
            N => FN,
            S => FS,
            E => FE,
            W => FW,
            FN => N,
            FS => S,
            FE => E,
            FW => W,
        }
    }
}

impl FromStr for Orient {
    type Err = ();

    fn from_str(input: &str) -> Result<Self, Self::Err> {
        match input {
            "N" => Ok(Self::N),
            "S" => Ok(Self::S),
            "E" => Ok(Self::E),
            "W" => Ok(Self::W),
            "FN" => Ok(Self::FN),
            "FS" => Ok(Self::FS),
            "FE" => Ok(Self::FE),
            "FW" => Ok(Self::FW),
            _ => Err(()),
        }
    }
}

impl fmt::Display for Orient {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::N => f.write_str("N"),
            Self::S => f.write_str("S"),
            Self::E => f.write_str("E"),
            Self::W => f.write_str("W"),
            Self::FN => f.write_str("FN"),
            Self::FS => f.write_str("FS"),
            Self::FE => f.write_str("FE"),
            Self::FW => f.write_str("FW"),
        }
    }
}

/// Signal direction of a pin.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum PinDirection {
    /// INPUT
    Input,
    /// OUTPUT. Is TRISTATE when the boolean flag is set.
    Output(bool),
    /// INOUT: Both input and output.
    Inout,
    /// FEEDTHRU: Pin crosses the cell. Direct electrical connection.
    Feedthru,
}

impl FromStr for PinDirection {
    type Err = ();

    fn from_str(input: &str) -> Result<Self, Self::Err> {
        match input {
            "INPUT" => Ok(Self::Input),
            "OUTPUT" => Ok(Self::Output(false)),
            "INOUT" => Ok(Self::Inout),
            "FEEDTHRU" => Ok(Self::Feedthru),
            _ => Err(()),
        }
    }
}

impl fmt::Display for PinDirection {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Input => f.write_str("INPUT"),
            Self::Output(false) => f.write_str("OUTPUT"),
            Self::Output(true) => f.write_str("OUTPUT TRISTATE"),
            Self::Inout => f.write_str("INOUT"),
            Self::Feedthru => f.write_str("FEEDTHRU"),
        }
    }
}