netlist_db/lexer/
mod.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
#[cfg(test)]
mod _test_impl;
pub mod parser;
use indexmap::IndexMap;
use nom::error::ErrorKind;

use crate::file::{FileId, LocatedSpan, ParsedId, Pos, Span};
use core::fmt;
use std::{
    cell::LazyCell,
    path::PathBuf,
    sync::{Arc, OnceLock},
};

#[derive(Debug, Clone, Default)]
#[cfg_attr(not(test), derive(Copy))]
pub struct KeyValue {
    pub k: Span,
    pub v: Value,
}
#[derive(Debug, Clone)]
#[cfg_attr(not(test), derive(Copy))]
pub enum Token {
    KV(KeyValue),
    Value(Value),
}

#[derive(Debug, Clone)]
#[cfg_attr(not(test), derive(Copy))]
pub enum Value {
    Num(f64),
    Expr(Span),
}

impl Default for Value {
    #[inline]
    fn default() -> Self {
        Self::Num(0.0)
    }
}

/// ``` spice
/// .subckt pulvt11ll_ckt d g s b w=1e-6 l=1e-6 sa='sar'
/// ...
/// .ends pulvt11ll_ckt
/// ```
/// Do NOT support `.include` / `.lib` in `.subckt`
#[derive(Debug)]
pub struct Subckt {
    pub name: Span,
    /// subckt/model name is the last arg
    pub ports: Vec<Span>,
    pub params: Vec<KeyValue>,
    pub ast: AST,
}

/// ``` spice
/// XX1 net48 D VDD VNW PHVT11LL_CKT W=0.22u L=40.00n
/// ```
#[derive(Debug, Clone)]
pub struct Instance {
    pub name: Span,
    pub instance_type: InstanceType,
    /// subckt/model name is the last arg
    pub ports: Vec<Span>,
    /// (fisrt, rest)
    pub params: Vec<KeyValue>,
}

#[derive(Debug, Clone)]
pub struct General {
    pub cmd: GeneralCmd,
    pub tokens: Vec<Token>,
}

#[derive(Debug, Clone)]
pub struct Unknwon {
    pub cmd: Span,
    pub tokens: Vec<Token>,
}

#[derive(Debug, Clone)]
pub struct Model {
    pub name: Span,
    pub model_type: ModelType,
    pub params: Vec<KeyValue>,
}

/// The `.include` and `.lib file tt` will be directly evaluated
#[derive(Debug, Default)]
pub struct LocalAST {
    pub subckt: Vec<Subckt>,
    pub instance: Vec<Instance>,
    pub model: Vec<Model>,
    pub param: Vec<KeyValue>,
    pub option: Vec<Token>,
    pub general: Vec<General>,
    pub unknwon: Vec<Unknwon>,
    pub errors: Vec<ParseError>,
}

impl LocalAST {
    pub fn is_empty(&self) -> bool {
        self.subckt.is_empty()
            && self.instance.is_empty()
            && self.model.is_empty()
            && self.param.is_empty()
            && self.option.is_empty()
            && self.general.is_empty()
            && self.unknwon.is_empty()
            && self.errors.is_empty()
    }
}

impl From<nom::Err<nom::error::Error<LocatedSpan<'_>>>> for ParseError {
    #[inline]
    fn from(e: nom::Err<nom::error::Error<LocatedSpan<'_>>>) -> Self {
        match e {
            nom::Err::Incomplete(_) => ParseErrorInner::Nom(None).with(None),
            nom::Err::Failure(e) | nom::Err::Error(e) => {
                ParseErrorInner::Nom(Some(e.code)).record(e.input)
            }
        }
    }
}

#[derive(Debug, thiserror::Error)]
pub enum ParseErrorInner {
    #[error("Incomplete")]
    IO(#[from] std::io::Error),
    #[error("Can NOT find section [{section}] in file {path}")]
    NoLibSection { path: PathBuf, section: String },
    /// Nom Error
    #[error("Syntax error")]
    Nom(Option<ErrorKind>),
    /// something else
    #[error("{0:?}")]
    Unknown(Span),
    #[error("Circular definition")]
    CircularDefinition(IndexMap<FileId, Option<Pos>>, usize),
}

impl ParseErrorInner {
    pub fn record(self, i: LocatedSpan) -> ParseError {
        ParseError {
            pos: Pos::new(i),
            err: self,
        }
    }
    pub fn with(self, pos: Option<Pos>) -> ParseError {
        ParseError { pos, err: self }
    }
}

const IS_TTY: LazyCell<bool> = LazyCell::new(|| {
    use std::io::IsTerminal;
    std::io::stdout().is_terminal()
});

#[derive(Debug)]
pub struct ParseError {
    pub pos: Option<Pos>,
    pub err: ParseErrorInner,
}

impl ParseError {
    pub fn report(&self, has_err: &mut bool, file_id: &FileId, file: &str) {
        *has_err = true;
        struct ReportDisplay<'a> {
            err: &'a ParseError,
            file_id: &'a FileId,
            file: &'a str,
        }
        impl fmt::Display for ReportDisplay<'_> {
            #[inline]
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                use crate::builder::Builder;
                use anstyle::{AnsiColor, Color, Style};
                let (msg_style, typ_style, err_style) = if *IS_TTY {
                    (
                        Style::new().fg_color(Some(Color::Ansi(AnsiColor::BrightMagenta))),
                        Style::new()
                            .fg_color(Some(Color::Ansi(AnsiColor::BrightMagenta)))
                            .bold(),
                        Style::new()
                            .fg_color(Some(AnsiColor::BrightRed.into()))
                            .bold(),
                    )
                } else {
                    (Style::new(), Style::new(), Style::new())
                };

                write!(
                    f,
                    "\nFile {}\"{}\"{}",
                    msg_style.render(),
                    self.file_id.path().display(),
                    msg_style.render_reset()
                )?;
                if let Some(pos) = self.err.pos {
                    write!(
                        f,
                        ", line {}{}{}",
                        msg_style.render(),
                        pos.line_num,
                        msg_style.render_reset()
                    )?;
                    let span = unsafe {
                        LocatedSpan::new_from_raw_offset(
                            pos.start,
                            pos.line_num,
                            &self.file[pos.start..],
                            (),
                        )
                    };
                    if let Ok(s) = core::str::from_utf8(span.get_line_beginning()) {
                        write!(f, "\n{s}\n")?;
                        for _ in 0..span.get_column() - 1 {
                            write!(f, " ")?;
                        }
                        write!(f, "{}<-{}", err_style.render(), err_style.render_reset())?;
                    }
                }
                writeln!(f)?;
                match &self.err.err {
                    ParseErrorInner::IO(error) => {
                        writeln!(
                            f,
                            "{}Error{}: {}{error}{}",
                            typ_style.render(),
                            typ_style.render_reset(),
                            msg_style.render(),
                            msg_style.render_reset()
                        )
                    }
                    ParseErrorInner::NoLibSection { path, section } => {
                        writeln!(
                            f,
                            "{}Error{}: {}Can NOT find section `{section}` in file \"{}\"{}",
                            typ_style.render(),
                            typ_style.render_reset(),
                            msg_style.render(),
                            path.display(),
                            msg_style.render_reset()
                        )
                    }
                    ParseErrorInner::Nom(e) => {
                        write!(
                            f,
                            "{}ParserError{}",
                            typ_style.render(),
                            typ_style.render_reset(),
                        )?;
                        if let Some(e) = e {
                            writeln!(
                                f,
                                ": {}{e:?}{}",
                                msg_style.render(),
                                msg_style.render_reset()
                            )
                        } else {
                            writeln!(f)
                        }
                    }
                    ParseErrorInner::Unknown(span) => {
                        writeln!(
                            f,
                            "{}SyntaxError{}: {}Unknwon command `{}`{}",
                            typ_style.render(),
                            typ_style.render_reset(),
                            msg_style.render(),
                            span.build(self.file),
                            msg_style.render_reset()
                        )
                    }
                    ParseErrorInner::CircularDefinition(index_set, idx) => {
                        struct FileDisplay<'a>(&'a FileId, &'a Option<Pos>);
                        impl fmt::Display for FileDisplay<'_> {
                            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                                match self.0 {
                                    FileId::Include { path } => {
                                        write!(f, "File \"{}\"", path.display())?;
                                        if let Some(pos) = self.1 {
                                            write!(f, ", line {}", pos.line_num)?;
                                        }
                                        Ok(())
                                    }
                                    FileId::Section { path, section } => {
                                        write!(f, "File \"{}\"", path.display())?;
                                        if let Some(pos) = self.1 {
                                            write!(f, ", line {}", pos.line_num)?;
                                        }
                                        write!(f, ", section {section}")
                                    }
                                }
                            }
                        }
                        impl<'s> FileDisplay<'s> {
                            fn new(f: (&'s FileId, &'s Option<Pos>)) -> Self {
                                Self(f.0, f.1)
                            }
                        }
                        let circular_file = index_set.get_index(*idx).unwrap();
                        writeln!(
                            f,
                            "{}CircularDefinition{}: {}Detect circular definition in {}{}",
                            typ_style.render(),
                            typ_style.render_reset(),
                            msg_style.render(),
                            FileDisplay::new(circular_file),
                            msg_style.render_reset()
                        )?;
                        for (i, file) in index_set.iter().enumerate() {
                            if *idx == i {
                                writeln!(
                                    f,
                                    "{} * {}{}\n     ↓",
                                    err_style.render(),
                                    FileDisplay::new(file),
                                    err_style.render_reset()
                                )?;
                            } else {
                                writeln!(f, "   {}\n     ↓", FileDisplay::new(file))?;
                            }
                        }
                        writeln!(
                            f,
                            "{} * {}{}",
                            err_style.render(),
                            FileDisplay::new(circular_file),
                            err_style.render_reset()
                        )
                    }
                }
            }
        }
        log::error!(
            "{}",
            ReportDisplay {
                err: self,
                file_id,
                file
            }
        )
    }
}

#[derive(Debug)]
pub enum Segment {
    Local(LocalAST),
    Include(Arc<OnceLock<Result<ParsedId, ParseError>>>),
}
#[derive(Debug, Default)]
pub struct AST {
    pub segments: Vec<Segment>,
}

impl AST {
    fn new() -> Self {
        Self {
            segments: Vec::new(),
        }
    }
}

impl From<u8> for InstanceType {
    fn from(value: u8) -> Self {
        match value.to_ascii_lowercase() {
            b'r' => Self::Resistor,
            b'c' => Self::Capacitor,
            b'v' => Self::VoltageSource,
            b'i' => Self::CurrentSource,
            b'm' => Self::MOSFET,
            b'q' => Self::BJT,
            b'd' => Self::Diode,
            b'x' => Self::Subckt,
            _ => Self::Unknown(value),
        }
    }
}

#[derive(Debug, Clone, Copy)]
pub enum InstanceType {
    /// `R`
    Resistor,
    /// `C`
    Capacitor,
    /// `V`
    VoltageSource,
    /// `I`
    CurrentSource,
    /// `M`
    MOSFET,
    /// `Q`
    BJT,
    /// `D`
    Diode,
    /// `X`
    Subckt,
    /// char
    Unknown(u8),
}

#[derive(Debug, Clone)]
#[cfg_attr(not(test), derive(Copy))]
pub enum ModelType {
    /// operational amplifier model
    AMP,
    /// capacitor model
    C,
    /// magnetic core model
    CORE,
    /// diode model
    D,
    /// inductor model or magnetic core mutual inductor model
    L,
    /// n-channel JFET model
    NJF,
    /// n-channel MOSFET model
    NMOS,
    /// npn BJT model
    NPN,
    /// optimization model
    OPT,
    /// p-channel JFET model
    PJF,
    /// p-channel MOSFET model
    PMOS,
    /// pnp BJT model
    PNP,
    /// resistor model
    R,
    /// lossy transmission line model (lumped)
    U,
    /// lossy transmission line model
    W,
    /// S-parameter
    S,
    Unknown(Span),
}
impl From<(&str, Span)> for ModelType {
    #[inline]
    fn from(value: (&str, Span)) -> Self {
        let (_str, _type) = value;
        match _str.to_uppercase().as_str() {
            "AMP" => Self::AMP,
            "C" => Self::C,
            "CORE" => Self::CORE,
            "D" => Self::D,
            "L" => Self::L,
            "NJF" => Self::NJF,
            "NMOS" => Self::NMOS,
            "NPN" => Self::NPN,
            "OPT" => Self::OPT,
            "PJF" => Self::PJF,
            "PMOS" => Self::PMOS,
            "PNP" => Self::PNP,
            "R" => Self::R,
            "U" => Self::U,
            "W" => Self::W,
            "S" => Self::S,
            _ => Self::Unknown(_type),
        }
    }
}
#[derive(Debug, Clone, Copy)]
pub enum GeneralCmd {
    /// `.ic` initial condition
    Ic,
    /// `.ic` initial condition
    Meas,
}