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
// Copyright (c) 2021-2021 Thomas Kramer.
// SPDX-FileCopyrightText: 2022 Thomas Kramer <code@tkramer.ch>
//
// SPDX-License-Identifier: AGPL-3.0-or-later

//! Write DEF data structure into DEF file format.

use crate::common::PinDirection;
use crate::def_ast::{
    Blockage, ComponentSource, DEFSignalUse, NetTerminal, PlacementBlockageType, RectOrPolygon,
    SpacingOrDesignRuleWidth, DEF,
};
use libreda_db::prelude::{SimpleRPolygon, TryBoundingBox};
use num_traits::PrimInt;
use std::fmt;
use std::fmt::{Debug, Display};
use std::io::Write;

/// Error type that can happen when serializing a DEF file.
#[derive(Debug)]
pub enum DEFWriterError {
    /// IO Error.
    IOError(std::io::Error),
}

impl From<std::io::Error> for DEFWriterError {
    fn from(err: std::io::Error) -> Self {
        match err.kind() {
            _ => DEFWriterError::IOError(err),
        }
    }
}

impl fmt::Display for DEFWriterError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        use DEFWriterError::*;
        match self {
            IOError(e) => write!(f, "{}", e),
        }
    }
}

/// Write the point of a polygon in the DEF format: ( x1 y1 ) ( x2 y2 ) ...
fn write_polygon<W: Write, T: PrimInt + Display>(
    w: &mut W,
    p: &SimpleRPolygon<T>,
) -> Result<(), DEFWriterError> {
    for point in p.points() {
        write!(w, "( {} {} ) ", point.x, point.y)?;
    }
    Ok(())
}

/// Write the DEF data structure into its ASCII representation.
/// Ordering of the statements follows the official recommendation.
pub fn write_def<W: Write>(w: &mut W, def: &DEF) -> Result<(), DEFWriterError> {
    let indent = |w: &mut W, level: u32| -> Result<(), std::io::Error> {
        for _ in 0..level {
            write!(w, "    ")?;
        }
        Ok(())
    };

    // VERSION
    for v in &def.version {
        writeln!(w, "VERSION {} ;", v)?;
    }

    // // NAMESCASESENSITIVE (not needed in DEF version 5.6 or later)
    // writeln!(w, "NAMESCASESENSITIVE ON ;")?;

    // DIVIDERCHAR
    writeln!(w, r#"DIVIDERCHAR "{}" ;"#, def.dividerchar)?;

    // BUSBITCHARS
    writeln!(
        w,
        r#"BUSBITCHARS "{}{}" ;"#,
        def.busbitchars.0, def.busbitchars.1
    )?;

    // DESIGN
    for n in &def.design_name {
        writeln!(w, "DESIGN {} ;", n)?;
    }

    // TECHNOLOGY
    for n in &def.technology {
        writeln!(w, "TECHNOLOGY {} ;", n)?;
    }

    // UNITS
    writeln!(w, "UNITS DISTANCE MICRONS {} ;", def.units)?;

    // HISTORY
    for h in &def.history {
        // TODO: Escape or deny special characters.
        writeln!(w, "HISTORY {} ;", h)?;
    }

    // PROPERTYDEFINITIONS
    if !def.property_definitions.is_empty() {
        writeln!(w, "PROPERTYDEFINITIONS")?;
        for (name, p) in &def.property_definitions {
            indent(w, 1)?;
            write!(w, "{} {} {} ", p.object_type, name, p.property_type)?;
            if let Some((min, max)) = &p.range {
                write!(w, "RANGE {} {} ", min, max)?;
            }
            if let Some(default) = &p.default_value {
                write!(w, "{} ", default)?;
            }
            writeln!(w, ";")?;
        }
        writeln!(w, "END PROPERTYDEFINITIONS")?;
    }

    // DIEAREA
    if let Some(area) = &def.die_area {
        write!(w, "DIEAREA ")?;
        if area.len() == 4 {
            // This is a rectangle.
            let rect = area.try_bounding_box().unwrap(); // Unwrap is safe since there are four points.
            write!(
                w,
                "( {} {} ) ( {} {} ) ",
                rect.lower_left().x,
                rect.lower_left().y,
                rect.upper_right().x,
                rect.upper_right().y
            )?;
        } else {
            write_polygon(w, area)?;
        }
        writeln!(w, ";")?;
    }

    // ROWS
    for (row_name, row) in &def.rows {
        write!(
            w,
            "ROW {} {} {} {} {}",
            row_name, row.site_name, row.orig.0, row.orig.1, row.site_orient
        )?;
        write!(
            w,
            " DO {} BY {}",
            row.step_pattern.num_x, row.step_pattern.num_y
        )?;
        if let Some((dx, dy)) = row.step_pattern.step {
            write!(w, " STEP {} {}", dx, dy)?;
        }
        if !row.properties.is_empty() {
            writeln!(w)?;
            for (name, value) in &row.properties {
                indent(w, 1)?;
                writeln!(w, "+ PROPERTY {} {}", name, value)?;
            }
        }
        writeln!(w, " ;")?;
    }

    // TRACKS
    for tracks in &def.tracks {
        let xy = if tracks.is_horizontal { "Y" } else { "X" };
        write!(
            w,
            "TRACKS {} {} DO {} STEP {}",
            xy, tracks.start, tracks.num_tracks, tracks.step
        )?;
        if let Some((mask_num, same_mask)) = &tracks.mask {
            write!(w, " MASK {}", mask_num)?;
            if *same_mask {
                write!(w, " SAMEMASK")?;
            }
        }
        if !tracks.layers.is_empty() {
            write!(w, " LAYER")?;
            for layer in &tracks.layers {
                write!(w, " {}", layer)?;
            }
        }
        writeln!(w, " ;")?;
    }

    // GCELLGRID
    // VIAS
    // STYLES
    // NONDEFAULTRULES

    // REGIONS
    if !def.regions.is_empty() {
        writeln!(w, "REGIONS {} ;", def.regions.len())?;
        for (name, region) in &def.regions {
            indent(w, 1)?;
            write!(w, "- {} ", name)?;
            // Write rectangles that define the region.
            for r in &region.regions {
                write!(w, "( {} {} ) ", r.lower_left(), r.upper_right())?;
            }
            writeln!(w)?;

            // TYPE
            for region_type in &region.region_type {
                indent(w, 2)?;
                writeln!(w, "+ TYPE {} ", region_type)?;
            }

            // TODO: PROPERTY
        }
        writeln!(w, "END REGIONS")?;
    }

    // COMPONENTMASKSHIFT

    // COMPONENTS
    if !def.components.is_empty() {
        writeln!(w, "COMPONENTS {} ;", def.components.len())?;
        for comp in &def.components {
            indent(w, 1)?;
            write!(w, "- {} {} ", comp.name, comp.model_name)?;

            for m in &comp.eeq_master {
                write!(w, "+ EEQMASTER {} ", m)?;
            }

            if comp.source != ComponentSource::default() {
                write!(w, "+ SOURCE {} ", comp.source)?;
            }

            // Position
            // TODO: COVER
            match &comp.position {
                None => write!(w, "+ UNPLACED ")?,
                Some((p, orient, false)) => write!(w, "+ PLACED ( {} {} ) {} ", p.x, p.y, orient)?,
                Some((p, orient, true)) => write!(w, "+ FIXED ( {} {} ) {} ", p.x, p.y, orient)?,
            }

            // TODO: MASKSHIFT

            // HALO
            for (soft, left, bottom, right, top) in &comp.halo {
                write!(w, "+ HALO ")?;
                if *soft {
                    write!(w, "SOFT ")?;
                }
                write!(w, "{} {} {} {} ", left, bottom, right, top)?;
            }
            // ROUTEHALO
            for (dist, min_layer, max_layer) in &comp.route_halo {
                write!(w, "+ ROUTEHALO {} {} {} ", dist, min_layer, max_layer)?;
            }

            // WEIGHT
            if comp.weight != 0 {
                write!(w, "+ WEIGHT {} ", comp.weight)?;
            }

            // REGION
            for r in &comp.region {
                write!(w, "+ REGION {} ", r)?;
            }

            // PROPERTY: TODO
            writeln!(w, ";")?;
        }
        writeln!(w, "END COMPONENTS")?;
    }

    // PINS
    if !def.pins.is_empty() {
        writeln!(w, "PINS {} ;", def.pins.len())?;

        for pin in &def.pins {
            indent(w, 1)?;
            writeln!(w, "- {} + NET {}", pin.pin_name, pin.net_name)?;
            if pin.special {
                indent(w, 2)?;
                writeln!(w, "+ SPECIAL")?;
            }
            if let Some(dir) = pin.direction {
                indent(w, 2)?;
                writeln!(w, "+ DIRECTION {}", dir)?;
            }
            if let Some(expr) = &pin.net_expr {
                indent(w, 2)?;
                writeln!(w, "+ NETEXPR \"{}\"", expr)?;
            }
            if let Some(s) = &pin.supply_sensitivity {
                indent(w, 2)?;
                writeln!(w, "+ SUPPLYSENSITIVITY {}", s)?;
            }
            if let Some(s) = &pin.ground_sensitivity {
                indent(w, 2)?;
                writeln!(w, "+ GROUNDSENSITIVITY {}", s)?;
            }
            if pin.signal_use != DEFSignalUse::default() {
                indent(w, 2)?;
                writeln!(w, "+ USE {}", pin.signal_use)?;
            }
            // TODO Antenna stuff.

            // PORT
            for port in &pin.ports {
                indent(w, 2)?;
                writeln!(w, "+ PORT")?;
            }

            indent(w, 1)?;
            writeln!(w, " ;")?;
        }

        writeln!(w, "END PINS")?;
    }

    // PINPROPERTIES
    // BLOCKAGES

    if !def.blockages.is_empty() {
        writeln!(w, "BLOCKAGES {} ;", def.blockages.len())?;

        for blockage in &def.blockages {
            match blockage {
                Blockage::PlacementBlockage(block) => {
                    indent(w, 1)?;
                    writeln!(w, "- PLACEMENT")?;

                    if let Some(t) = &block.blockage_type {
                        indent(w, 2)?;
                        match t {
                            PlacementBlockageType::Soft => writeln!(w, "+ SOFT")?,
                            PlacementBlockageType::Partial(max_density) => {
                                writeln!(w, "+ PARTIAL {}", max_density)?
                            }
                        }
                    }

                    if block.pushdown {
                        indent(w, 2)?;
                        writeln!(w, "+ PUSHDOWN")?;
                    }

                    if let Some(component_name) = &block.component {
                        indent(w, 2)?;
                        writeln!(w, "+ COMPONENT {}", component_name)?;
                    }

                    for r in &block.rects {
                        indent(w, 2)?;
                        writeln!(
                            w,
                            "RECT ( {} {} ) ( {} {} )",
                            r.lower_left().x,
                            r.lower_left().y,
                            r.upper_right().x,
                            r.upper_right().y
                        )?;
                    }

                    indent(w, 1)?;
                    writeln!(w, " ;")?;
                }
                Blockage::LayerBlockage(block) => {
                    indent(w, 1)?;
                    writeln!(w, "- LAYER {}", block.layer)?;

                    if block.slots {
                        indent(w, 2)?;
                        writeln!(w, "+ SLOTS")?;
                    }

                    if block.fills {
                        indent(w, 2)?;
                        writeln!(w, "+ FILLS")?;
                    }

                    if block.pushdown {
                        indent(w, 2)?;
                        writeln!(w, "+ PUSHDOWN")?;
                    }

                    if block.except_pg_net {
                        indent(w, 2)?;
                        writeln!(w, "+ EXCEPTPGNET")?;
                    }

                    if let Some(component_name) = &block.component {
                        indent(w, 2)?;
                        writeln!(w, "+ COMPONENT {}", component_name)?;
                    }

                    if let Some(s) = &block.spacing_or_designrule_width {
                        indent(w, 2)?;
                        match s {
                            SpacingOrDesignRuleWidth::MinSpacing(s) => {
                                writeln!(w, "+ SPACING {}", s)?
                            }
                            SpacingOrDesignRuleWidth::DesignRuleWidth(width) => {
                                writeln!(w, "+ DESIGNRULEWIDTH {}", width)?
                            }
                        };
                    }

                    if let Some(mask_num) = block.mask_num {
                        indent(w, 2)?;
                        writeln!(w, "+ MASK {}", mask_num)?;
                    }

                    for shape in &block.blockage_shapes {
                        indent(w, 2)?;
                        match shape {
                            RectOrPolygon::Rect(r) => {
                                writeln!(
                                    w,
                                    "RECT ( {} {} ) ( {} {} )",
                                    r.lower_left().x,
                                    r.lower_left().y,
                                    r.upper_right().x,
                                    r.upper_right().y
                                )?;
                            }
                            RectOrPolygon::Polygon(p) => {
                                write!(w, "POLYGON ")?;
                                for point in p.iter() {
                                    write!(w, "( {} {} ) ", point.x, point.y)?;
                                }
                                writeln!(w)?;
                            }
                        };
                    }
                    indent(w, 1)?;
                    writeln!(w, " ;")?;
                }
            }
        }

        writeln!(w, "END BLOCKAGES")?;
    }

    // SLOTS
    // FILLS
    // SPECIALNETS

    // NETS
    if !def.nets.is_empty() {
        writeln!(w, "NETS {} ;", def.nets.len())?;
        for net in &def.nets {
            indent(w, 1)?;

            if let Some(name) = &net.name {
                write!(w, "- {}", name)?;
                for term in &net.terminals {
                    match term {
                        NetTerminal::ComponentPin {
                            component_name,
                            pin_name,
                        } => write!(w, " ( {} {} )", component_name, pin_name)?,
                        NetTerminal::IoPin(pin_name) => write!(w, " ( PIN {} )", pin_name)?,
                    };
                }
            }

            // SHIELDEDNET
            if !net.shield_nets.is_empty() {
                writeln!(w)?;
                for s in &net.shield_nets {
                    indent(w, 1)?;
                    writeln!(w, "+ SHIELDEDNET {}", s)?;
                }
            }

            // VPIN
            // SUBNET

            // XTALK
            if net.xtalk_class != 0 {
                indent(w, 1)?;
                writeln!(w, "+ XTALK {}", net.xtalk_class)?;
            }

            // NONDEFAULTRULE
            if let Some(r) = &net.non_default_rule {
                indent(w, 1)?;
                writeln!(w, "+ NONDEFAULTRULE {}", r)?;
            }

            // regular wiring
            for wiring in &net.regular_wiring {
                // TODO
                indent(w, 1)?;
                writeln!(w, "+ {}", wiring.class)?;
                for wiring_stmt in &wiring.wiring {
                    // TODO
                }
            }

            // SOURCE
            if net.source != Default::default() {
                indent(w, 1)?;
                writeln!(w, "+ SOURCE {}", net.source)?;
            }

            // FIXEDBUMP
            if net.fixed_bump {
                indent(w, 1)?;
                writeln!(w, "+ FIXEDBUMP")?;
            }

            // FREQUENCY
            if let Some(f) = net.frequency {
                indent(w, 1)?;
                writeln!(w, "+ FREQUENCY {}", f)?;
            }

            // Original
            if let Some(o) = &net.original {
                indent(w, 1)?;
                writeln!(w, "+ ORIGINAL {}", o)?;
            }

            // USE
            if net.net_use != Default::default() {
                indent(w, 1)?;
                writeln!(w, "+ USE {}", net.net_use)?;
            }

            // PATTERN
            if net.pattern != Default::default() {
                indent(w, 1)?;
                writeln!(w, "+ PATTERN {}", net.pattern)?;
            }

            // ESTCAP
            if let Some(c) = net.est_cap {
                indent(w, 1)?;
                writeln!(w, "+ ESTCAP {}", c)?;
            }

            // WEIGHT
            if net.weight != 1 {
                indent(w, 1)?;
                writeln!(w, "+ WEIGHT {}", net.weight)?;
            }

            // PROPERTY
            for (name, value) in &net.properties {
                indent(w, 1)?;
                writeln!(w, "+ PROPERTY {} {}", name, value)?;
            }

            writeln!(w, " ;")?;
        }
        writeln!(w, "END NETS")?;
    }

    // SCANCHAINS
    // GROUPS
    // BEGINEXT

    writeln!(w, "END DESIGN")?;
    Ok(())
}