xschem-parser 0.1.0

Xschem schematic and symbol parser
Documentation
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
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
//! Parsed data structures.
use std::collections::HashMap;
use std::fmt;
use std::fmt::Formatter;
use std::hash::Hash;
use std::vec::Vec;

use derive_more::{Deref, DerefMut, Display, From, Into, TryFrom};

use crate::error::Error;
use crate::{ByteSpan, Span, parse};

/// Xschem schematic (or symbol).
#[derive(Clone, Debug, Default)]
pub struct Schematic<I> {
    pub version: Version<I>,
    pub vhdl_property: Option<VhdlProperty<I>>,
    pub symbol_property: Option<SymbolProperty<I>>,
    pub verilog_property: Option<VerilogProperty<I>>,
    pub spice_property: Option<SpiceProperty<I>>,
    pub tedax_property: Option<TedaXProperty<I>>,
    pub texts: Objects<Text<I>>,
    pub lines: Objects<Line<I>>,
    pub rectangles: Objects<Rectangle<I>>,
    pub polygons: Objects<Polygon<I>>,
    pub arcs: Objects<Arc<I>>,
    pub wires: Objects<Wire<I>>,
    pub components: Objects<Component<I>>,
}

/// Xschem property string with parsed attributes.
#[derive(Clone, Debug, Default, Display)]
#[display("{{{prop}}}")]
pub struct Property<I> {
    /// Full property input.
    pub prop: I,
    /// Parsed attributes from `prop`.
    pub attrs: HashMap<I, I>,
}

/// Xschem schematic or symbol version specifiication.
#[derive(Clone, Debug, Default, Display)]
#[display("v {_0}")]
pub struct Version<I>(pub Property<I>);

#[derive(Clone, Debug, Default, Deref, Display, From)]
#[display("G {_0}")]
pub struct VhdlProperty<I>(pub Property<I>);

#[derive(Clone, Debug, Default, Deref, Display, From)]
#[display("K {_0}")]
pub struct SymbolProperty<I>(pub Property<I>);

#[derive(Clone, Debug, Default, Deref, Display, From)]
#[display("V {_0}")]
pub struct VerilogProperty<I>(pub Property<I>);

#[derive(Clone, Debug, Default, Deref, Display, From)]
#[display("S {_0}")]
pub struct SpiceProperty<I>(pub Property<I>);

#[derive(Clone, Debug, Default, Deref, Display, From)]
#[display("E {_0}")]
pub struct TedaXProperty<I>(pub Property<I>);

#[derive(Clone, Debug, From)]
#[from(forward)]
#[allow(clippy::large_enum_variant)]
pub enum Object<I> {
    SpiceProperty(SpiceProperty<I>),
    VerilogProperty(VerilogProperty<I>),
    VhdlProperty(VhdlProperty<I>),
    TedaXProperty(TedaXProperty<I>),
    SymbolProperty(SymbolProperty<I>),

    Arc(Arc<I>),
    Component(Component<I>),
    Line(Line<I>),
    Polygon(Polygon<I>),
    Rectangle(Rectangle<I>),
    Text(Text<I>),
    Wire(Wire<I>),
}

#[derive(Clone, Debug, Deref, DerefMut, From, Into, PartialEq)]
pub struct Objects<O>(pub Vec<O>);

/// Xschem arc object.
#[derive(Clone, Debug, Default, Display)]
#[display("A {layer} {center} {radius} {start_angle} {sweep_angle} {property}")]
pub struct Arc<I> {
    pub layer: u64,
    pub center: Coordinate,
    pub radius: FiniteDouble,
    pub start_angle: FiniteDouble,
    pub sweep_angle: FiniteDouble,
    pub property: Property<I>,
}

/// Xschem component instance.
#[derive(Clone, Debug, Default)]
pub struct Component<I> {
    pub reference: I,
    pub position: Coordinate,
    pub rotation: Rotation,
    pub flip: Flip,
    pub property: Property<I>,
    pub embedding: Option<Embedding<I>>,
}

/// Xschem line object.
#[derive(Clone, Debug, Default, Display)]
#[display("L {layer} {start} {end} {property}")]
pub struct Line<I> {
    pub layer: u64,
    pub start: Coordinate,
    pub end: Coordinate,
    pub property: Property<I>,
}

/// Xschem polygon object.
#[derive(Clone, Debug, Default, Display)]
#[display("P {layer} {npoints} {points} {property}", npoints = points.len())]
pub struct Polygon<I> {
    pub layer: u64,
    pub points: Coordinates,
    pub property: Property<I>,
}

/// Xschem rectangle object.
#[derive(Clone, Debug, Default, Display)]
#[display("B {layer} {start} {end} {property}")]
pub struct Rectangle<I> {
    pub layer: u64,
    pub start: Coordinate,
    pub end: Coordinate,
    pub property: Property<I>,
}

/// Xschem text object.
#[derive(Clone, Debug, Default, Display)]
#[display("T {{{text}}} {position} {rotation} {flip} {size} {property}")]
pub struct Text<I> {
    pub text: I,
    pub position: Coordinate,
    pub rotation: Rotation,
    pub flip: Flip,
    pub size: Size,
    pub property: Property<I>,
}

/// Xschem wire object.
#[derive(Clone, Debug, Default, Display)]
#[display("N {start} {end} {property}")]
pub struct Wire<I> {
    pub start: Coordinate,
    pub end: Coordinate,
    pub property: Property<I>,
}

#[derive(Clone, Debug, Default, Deref, Display, From, Into)]
#[display("[\n{_0}\n]")]
pub struct Embedding<I>(pub Schematic<I>);

/// Finite double precision type.
#[derive(Clone, Copy, Debug, Default, Deref, Display, Into, PartialEq, PartialOrd)]
pub struct FiniteDouble(f64);

#[derive(Clone, Copy, Debug, Default, Display, From, Into, PartialEq, PartialOrd)]
#[from((FiniteDouble, FiniteDouble))]
#[into((FiniteDouble, FiniteDouble))]
#[display("{x} {y}")]
pub struct Vec2 {
    pub x: FiniteDouble,
    pub y: FiniteDouble,
}

pub type Coordinate = Vec2;
pub type Size = Vec2;

#[derive(Clone, Debug, Default, Deref, DerefMut, From, Into, PartialEq)]
pub struct Coordinates(pub Vec<Coordinate>);

#[derive(Clone, Copy, Debug, Default, Display, PartialEq, Eq, PartialOrd, Ord, TryFrom)]
#[try_from(repr)]
#[repr(u8)]
pub enum Rotation {
    #[default]
    #[display("0")]
    Zero,
    #[display("1")]
    One,
    #[display("2")]
    Two,
    #[display("3")]
    Three,
}

#[derive(Clone, Copy, Debug, Default, Display, PartialEq, Eq, PartialOrd, Ord, TryFrom)]
#[try_from(repr)]
#[repr(u8)]
pub enum Flip {
    #[default]
    #[display("0")]
    Unflipped,
    #[display("1")]
    Flipped,
}

impl<'a, X: Clone + Default> TryFrom<&'a str> for Schematic<Span<'a, X>> {
    type Error = Error<Span<'a, X>>;

    /// Tries to parse a schematic from a `str`.
    fn try_from(value: &'a str) -> Result<Self, Self::Error> {
        Self::try_from(Span::new_extra(value, X::default()))
    }
}

impl<'a, X: Clone + Default> TryFrom<&'a [u8]> for Schematic<ByteSpan<'a, X>> {
    type Error = Error<ByteSpan<'a, X>>;

    /// Tries to parse a schematic from a slice.
    fn try_from(value: &'a [u8]) -> Result<Self, Self::Error> {
        Self::try_from(ByteSpan::new_extra(value, X::default()))
    }
}

impl<'a, X: Clone> TryFrom<Span<'a, X>> for Schematic<Span<'a, X>> {
    type Error = Error<Span<'a, X>>;

    /// Tries to parse a schematic from a spanned `str`.
    fn try_from(value: Span<'a, X>) -> Result<Self, Self::Error> {
        parse::schematic_full(value)
    }
}

impl<'a, X: Clone> TryFrom<ByteSpan<'a, X>> for Schematic<ByteSpan<'a, X>> {
    type Error = Error<ByteSpan<'a, X>>;

    /// Tries to parse a schematic from a spanned slice.
    fn try_from(value: ByteSpan<'a, X>) -> Result<Self, Self::Error> {
        parse::schematic_full(value)
    }
}

impl<I> fmt::Display for Schematic<I>
where
    I: fmt::Display,
{
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.version)?;
        if let Some(p) = &self.vhdl_property {
            write!(f, "\n{p}")?;
        }
        if let Some(p) = &self.symbol_property {
            write!(f, "\n{p}")?;
        }
        if let Some(p) = &self.verilog_property {
            write!(f, "\n{p}")?;
        }
        if let Some(p) = &self.spice_property {
            write!(f, "\n{p}")?;
        }
        if let Some(p) = &self.tedax_property {
            write!(f, "\n{p}")?;
        }
        if !self.texts.is_empty() {
            write!(f, "\n{}", self.texts)?;
        }
        if !self.lines.is_empty() {
            write!(f, "\n{}", self.lines)?;
        }
        if !self.rectangles.is_empty() {
            write!(f, "\n{}", self.rectangles)?;
        }
        if !self.polygons.is_empty() {
            write!(f, "\n{}", self.polygons)?;
        }
        if !self.arcs.is_empty() {
            write!(f, "\n{}", self.arcs)?;
        }
        if !self.wires.is_empty() {
            write!(f, "\n{}", self.wires)?;
        }
        if !self.components.is_empty() {
            write!(f, "\n{}", self.components)?;
        }
        Ok(())
    }
}

impl<'a> Schematic<Span<'a>> {
    /// Parses a string as a [`Schematic`].
    pub fn parse_str<I: AsRef<str> + ?Sized>(input: &'a I) -> Result<Self, Error<Span<'a>>> {
        Self::try_from(input.as_ref())
    }
}

impl<'a, X: Clone> Schematic<Span<'a, X>> {
    /// Parses a string as a [`Schematic`].
    pub fn parse_str_with_extra<I: AsRef<str> + ?Sized>(
        input: &'a I,
        extra: X,
    ) -> Result<Self, Error<Span<'a, X>>> {
        Self::try_from(Span::new_extra(input.as_ref(), extra))
    }
}

impl<'a> Schematic<ByteSpan<'a>> {
    /// Parses bytes as a [`Schematic`].
    pub fn parse_slice<I: AsRef<[u8]> + ?Sized>(input: &'a I) -> Result<Self, Error<ByteSpan<'a>>> {
        Self::try_from(input.as_ref())
    }
}

impl<'a, X: Clone> Schematic<ByteSpan<'a, X>> {
    /// Parses a string as a [`Schematic`].
    pub fn parse_slice_with_extra<I: AsRef<[u8]> + ?Sized>(
        input: &'a I,
        extra: X,
    ) -> Result<Self, Error<ByteSpan<'a, X>>> {
        Self::try_from(ByteSpan::new_extra(input.as_ref(), extra))
    }
}

impl<'a, X: Clone> Schematic<Span<'a, X>> {
    /// Parses a string span as a [`Schematic`].
    pub fn parse_span(input: Span<'a, X>) -> Result<Self, Error<Span<'a, X>>> {
        Self::try_from(input)
    }
}

impl<'a, X: Clone> Schematic<ByteSpan<'a, X>> {
    /// Parses a string span as a [`Schematic`].
    pub fn parse_span(input: ByteSpan<'a, X>) -> Result<Self, Error<ByteSpan<'a, X>>> {
        Self::try_from(input)
    }
}

impl<I: PartialEq> PartialEq for Schematic<I>
where
    Property<I>: PartialEq,
{
    fn eq(&self, other: &Self) -> bool {
        self.version == other.version
            && self.vhdl_property == other.vhdl_property
            && self.symbol_property == other.symbol_property
            && self.verilog_property == other.verilog_property
            && self.spice_property == other.spice_property
            && self.tedax_property == other.tedax_property
            && self.texts == other.texts
            && self.lines == other.lines
            && self.rectangles == other.rectangles
            && self.polygons == other.polygons
            && self.arcs == other.arcs
            && self.wires == other.wires
            && self.components == other.components
    }
}

impl<I> Schematic<I> {
    pub fn new(version: Version<I>) -> Self {
        Self {
            version,
            vhdl_property: Option::default(),
            symbol_property: Option::default(),
            verilog_property: Option::default(),
            spice_property: Option::default(),
            tedax_property: Option::default(),
            texts: Objects::default(),
            lines: Objects::default(),
            rectangles: Objects::default(),
            polygons: Objects::default(),
            arcs: Objects::default(),
            wires: Objects::default(),
            components: Objects::default(),
        }
    }

    #[must_use]
    pub fn add_object(mut self, object: Object<I>) -> Self {
        match object {
            Object::VhdlProperty(p) => {
                self.vhdl_property.replace(p);
            }
            Object::SymbolProperty(p) => {
                self.symbol_property.replace(p);
            }
            Object::VerilogProperty(p) => {
                self.verilog_property.replace(p);
            }
            Object::SpiceProperty(p) => {
                self.spice_property.replace(p);
            }
            Object::TedaXProperty(p) => {
                self.tedax_property.replace(p);
            }
            Object::Arc(o) => {
                self.arcs.push(o);
            }
            Object::Component(o) => {
                self.components.push(o);
            }
            Object::Line(o) => {
                self.lines.push(o);
            }
            Object::Polygon(o) => {
                self.polygons.push(o);
            }
            Object::Rectangle(o) => {
                self.rectangles.push(o);
            }
            Object::Text(o) => {
                self.texts.push(o);
            }
            Object::Wire(o) => {
                self.wires.push(o);
            }
        }

        self
    }
}

impl<I: Eq + Hash + PartialEq> PartialEq for Property<I> {
    fn eq(&self, other: &Self) -> bool {
        self.prop == other.prop && self.attrs == other.attrs
    }
}

impl<I> PartialEq for Version<I>
where
    Property<I>: PartialEq,
{
    fn eq(&self, other: &Self) -> bool {
        self.0 == other.0
    }
}

impl<I> PartialEq for SpiceProperty<I>
where
    Property<I>: PartialEq,
{
    fn eq(&self, other: &Self) -> bool {
        self.0 == other.0
    }
}

impl<I> PartialEq for VerilogProperty<I>
where
    Property<I>: PartialEq,
{
    fn eq(&self, other: &Self) -> bool {
        self.0 == other.0
    }
}

impl<I> PartialEq for VhdlProperty<I>
where
    Property<I>: PartialEq,
{
    fn eq(&self, other: &Self) -> bool {
        self.0 == other.0
    }
}

impl<I> PartialEq for TedaXProperty<I>
where
    Property<I>: PartialEq,
{
    fn eq(&self, other: &Self) -> bool {
        self.0 == other.0
    }
}

impl<I> PartialEq for SymbolProperty<I>
where
    Property<I>: PartialEq,
{
    fn eq(&self, other: &Self) -> bool {
        self.0 == other.0
    }
}

impl<I> PartialEq for Arc<I>
where
    Property<I>: PartialEq,
{
    fn eq(&self, other: &Self) -> bool {
        self.layer == other.layer
            && self.center == other.center
            && self.radius == other.radius
            && self.start_angle == other.start_angle
            && self.sweep_angle == other.sweep_angle
            && self.property == other.property
    }
}

impl<I> fmt::Display for Component<I>
where
    I: fmt::Display,
{
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        let Self {
            reference,
            position,
            rotation,
            flip,
            property,
            embedding,
        } = self;
        write!(
            f,
            "C {{{reference}}} {position} {rotation} {flip} {property}"
        )?;
        if let Some(e) = embedding {
            write!(f, "\n{e}")?;
        }
        Ok(())
    }
}

impl<I: PartialEq> PartialEq for Component<I>
where
    Property<I>: PartialEq,
{
    fn eq(&self, other: &Self) -> bool {
        self.reference == other.reference
            && self.position == other.position
            && self.rotation == other.rotation
            && self.flip == other.flip
            && self.property == other.property
            && self.embedding == other.embedding
    }
}

impl<I> PartialEq for Line<I>
where
    Property<I>: PartialEq,
{
    fn eq(&self, other: &Self) -> bool {
        self.layer == other.layer
            && self.start == other.start
            && self.end == other.end
            && self.property == other.property
    }
}

impl<I> PartialEq for Polygon<I>
where
    Property<I>: PartialEq,
{
    fn eq(&self, other: &Self) -> bool {
        self.layer == other.layer && self.points == other.points && self.property == other.property
    }
}

impl<I> PartialEq for Rectangle<I>
where
    Property<I>: PartialEq,
{
    fn eq(&self, other: &Self) -> bool {
        self.layer == other.layer
            && self.start == other.start
            && self.end == other.end
            && self.property == other.property
    }
}

impl<I: PartialEq> PartialEq for Text<I>
where
    Property<I>: PartialEq,
{
    fn eq(&self, other: &Self) -> bool {
        self.text == other.text
            && self.position == other.position
            && self.rotation == other.rotation
            && self.flip == other.flip
            && self.size == other.size
            && self.property == other.property
    }
}

impl<I> PartialEq for Wire<I>
where
    Property<I>: PartialEq,
{
    fn eq(&self, other: &Self) -> bool {
        self.start == other.start && self.end == other.end && self.property == other.property
    }
}

impl<I: PartialEq> PartialEq for Embedding<I>
where
    Property<I>: PartialEq,
{
    fn eq(&self, other: &Self) -> bool {
        self.0 == other.0
    }
}

impl<O> Default for Objects<O> {
    fn default() -> Self {
        Self(Vec::default())
    }
}

impl<O: fmt::Display> fmt::Display for Objects<O> {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        self.iter().enumerate().try_for_each(
            |(i, o)| {
                if i == 0 { o.fmt(f) } else { write!(f, "\n{o}") }
            },
        )
    }
}

impl fmt::Display for Coordinates {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        self.iter().enumerate().try_for_each(
            |(i, c)| {
                if i == 0 { c.fmt(f) } else { write!(f, " {c}") }
            },
        )
    }
}

impl TryFrom<f64> for FiniteDouble {
    type Error = &'static str;

    fn try_from(value: f64) -> Result<Self, Self::Error> {
        if value.is_finite() {
            Ok(Self(value))
        } else {
            Err("value is not finite")
        }
    }
}

impl Eq for FiniteDouble {}

impl TryFrom<(f64, f64)> for Vec2 {
    type Error = <FiniteDouble as TryFrom<f64>>::Error;

    fn try_from(value: (f64, f64)) -> Result<Self, Self::Error> {
        let (x, y) = value;
        let x = x.try_into()?;
        let y = y.try_into()?;
        Ok(Self { x, y })
    }
}

impl<T> From<Vec<(T, T)>> for Coordinates
where
    Vec2: From<(T, T)>,
{
    fn from(value: Vec<(T, T)>) -> Self {
        Self(value.into_iter().map(Vec2::from).collect())
    }
}

impl FromIterator<Vec2> for Coordinates {
    fn from_iter<T: IntoIterator<Item = Vec2>>(iter: T) -> Self {
        Self(iter.into_iter().collect())
    }
}

impl TryFrom<Vec<(f64, f64)>> for Coordinates {
    type Error = <Vec2 as TryFrom<(f64, f64)>>::Error;

    fn try_from(value: Vec<(f64, f64)>) -> Result<Self, Self::Error> {
        value.into_iter().map(Vec2::try_from).collect()
    }
}

impl From<Rotation> for u8 {
    fn from(value: Rotation) -> Self {
        match value {
            Rotation::Zero => 0,
            Rotation::One => 1,
            Rotation::Two => 2,
            Rotation::Three => 3,
        }
    }
}

impl From<bool> for Flip {
    fn from(value: bool) -> Self {
        if value {
            Flip::Flipped
        } else {
            Flip::Unflipped
        }
    }
}

impl From<Flip> for bool {
    fn from(value: Flip) -> Self {
        match value {
            Flip::Unflipped => false,
            Flip::Flipped => true,
        }
    }
}