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
//! BSDL Parser
//!
//! We make a few assumptions here:
//!     an INSTRUCTION_OPCODE will always be 64 bits or less
//! # Example
//!
//! ```rust
//! # use std::path::PathBuf;
//! # let manifest_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
//! # let test_bsd = manifest_dir.join("tests").join("test_data").join("sample.bsd");
//! // test_bsd is a PathBuf pointing to tests/test_data/sample.bsd
//! let bsdl = bsdl::Entity::parse(&test_bsd, None).unwrap();
//! println!("opcodes = {:?}", bsdl.opcodes());
//! let idcode = &bsdl.idcode_register()[0];
//! println!("idcode = {} vendor = {:?}", idcode, idcode.vendor_string());
//! println!("generics = {:?}", bsdl.generics());
//! println!("use_statements = {:?}", bsdl.use_statements());
//! let boundary: &Vec<bsdl::ScanCell> = bsdl.boundary_register();
//! println!("boundary register [7] info = {:?}", boundary[7]);
//! // look up a port by pin name, this one is bidirectional in the example BSDL
//! let pin3: &bsdl::Port = bsdl.port_from_pinname("3").unwrap();
//! // indices in boundary
//! println!("pin 3 input boundary cell index is {}", pin3.cell_i.unwrap());
//! let cell_o = pin3.cell_o.unwrap();
//! println!("pin 3 output boundary cell index is {}", cell_o);
//! let cell_o = &boundary[cell_o];
//! println!("pin 3 control boundary cell index is {}", boundary[cell_o.ccell.unwrap()]);
//! assert!(cell_o.ctype==bsdl::CellType::BC(7));
//! assert!(cell_o.function==bsdl::CellFunction::Bidir);
//! ```

use jtag_idcode;
use std::collections::HashMap;
use std::io::Read;

mod error;
mod port;
mod scancell;
mod string_helpers;

pub use error::BsdlError;

use crate::port::Ports;
pub use crate::port::{Port, PortDirection};
pub use crate::scancell::ScanCell;
use crate::string_helpers::*;
pub use scancell::CellFunction;
pub use scancell::CellType;
pub use scancell::DisableResult;
pub use scancell::LogicVal;

/// a ';' terminated item from a BSDL file
#[derive(Debug, Clone)]
pub struct Item {
    /// the first word: constant, use, port, generic, attribute, etc
    pub itemtype: String,
    /// everything following itemtype up to but not including the ;
    pub content: String,
    /// line number where itemtype occurred.
    pub line: usize,
}

impl Item {
    fn new() -> Item {
        Item {
            itemtype: String::new(),
            content: String::new(),
            line: 0,
        }
    }
}

/// The base BSDL entity
#[derive(Debug)]
pub struct Entity {
    /// NAME from the "entity NAME is" line
    name: String,
    /// any "use" statements like "use STD_1149_1_2001.all;"
    /// stripped of "use", ";"
    use_statements: Vec<String>,
    /// "component_conformance" of entity if it exists, empty otherwise
    component_conformance: String,
    /// Opcodes as specified in INSTRUCTION_OPCODE attribute
    opcodes: HashMap<String, u64>,
    /// as specified in INSTRUCTION_LENGTH attribute of entity
    instruction_length: usize,
    /// as specified in BOUNDARY_LENGTH attribute of entity
    boundary_length: usize,
    /// derived from BOUNDARY_REGISTER attribute
    /// length is always instruction_length
    boundary_register: Vec<ScanCell>,
    /// the IDCODEs of the device as specified in attribute IDCODE_REGISTER if present
    /// usually, one IDCODE is specified in a BSDL but the standard allows none or multiple
    idcode_register: Vec<jtag_idcode::IDCodeMasked>,
    /// attributes extracted from the file excluding those fully parsed
    /// (BOUNDARY_LENGTH, BOUNDARY_REGISTER, INSTRUCTION_LENGTH,
    /// INSTRUCTION_OPCODE, IDCODE_REGISTER, TAP_SCAN_CLOCK)
    attributes: HashMap<String, Item>,
    /// all generics extracted from the file
    generics: HashMap<String, String>,
    /// all the ports extracted from the file, with information from PORT_GROUPING, PIN_MAP_STRING, etc added.
    ports: Ports,
    /// the maximum TCK clock frequency extracted from the TAP_SCAN_CLOCK attribute
    maxtck_hz: Option<f32>,
    /// allowable clock edge for TCK to stop at
    tck_both: bool,
}

impl std::fmt::Display for Entity {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        let name = &self.name;
        write!(f, "name: {name}")
    }
}

impl Entity {
    /// get the name of the entity from the BSDL file
    pub fn name(&self) -> &str {
        &self.name.as_str()
    }
    /// return the instruction length as specified in INSTRUCTION_LENGTH attribute
    pub fn instruction_length(&self) -> usize {
        self.instruction_length
    }
    /// return the boundary length as specified in BOUNDARY_LENGTH attribute
    pub fn boundary_length(&self) -> usize {
        self.boundary_length
    }
    /// return the opcodes as specified in INSTRUCTION_OPCODE attribute
    pub fn opcodes(&self) -> &HashMap<String, u64> {
        &self.opcodes
    }
    /// return a vector of all Port structs
    pub fn ports(&self) -> &Vec<Port> {
        &self.ports.v
    }
    /// return a Port associated with a pin name
    pub fn port_from_pinname(&self, name: &str) -> Option<&Port> {
        if let Some(idx) = self.ports.d_pin.get(name) {
            Some(&self.ports.v[*idx])
        } else {
            None
        }
    }
    /// get a Port by name
    pub fn port_from_portname(&self, name: &str) -> Option<&Port> {
        if let Some(idx) = self.ports.d_port.get(name) {
            Some(&self.ports.v[*idx])
        } else {
            None
        }
    }
    /// get a Port number by name
    pub(crate) fn port_number_from_portname(&self, name: &str) -> Option<usize> {
        if let Some(idx) = self.ports.d_port.get(name) {
            Some(*idx)
        } else {
            None
        }
    }
    /// return a vector of all ScanCells the index is same as the bit number in the boundary register
    pub fn boundary_register(&self) -> &Vec<ScanCell> {
        &self.boundary_register
    }
    /// return a vector of all "use" statements
    pub fn use_statements(&self) -> &Vec<String> {
        &self.use_statements
    }
    /// return "component_conformance" of entity if it exists, empty otherwise
    pub fn component_conformance(&self) -> &str {
        &self.component_conformance.as_str()
    }
    /// provides access to raw attributes including those that were parsed into other fields
    pub fn attributes(&self) -> &HashMap<String, Item> {
        &self.attributes
    }
    /// provides access to raw generics including those that were parsed into other fields
    pub fn generics(&self) -> &HashMap<String, String> {
        &self.generics
    }
    /// returns true if TCK is allowed to stop at either high or low. If false, TCK must stop low.
    pub fn tck_both(&self) -> bool {
        self.tck_both
    }
    /// the IDCODEs of the device as specified in attribute IDCODE_REGISTER if present
    /// usually, one IDCODE is specified in a BSDL but the standard allows none or multiple
    pub fn idcode_register(&self) -> &Vec<jtag_idcode::IDCodeMasked> {
        &self.idcode_register
    }
    /// the maximum TCK clock frequency extracted from the TAP_SCAN_CLOCK attribute
    pub fn maxtck_hz(&self) -> Option<f32> {
        self.maxtck_hz
    }
    /// fill an array with the values to scan in prior to EXTEST for don't care bits
    /// returns an error if the array is smaller than required to fit the boundary register
    pub fn get_safe(&self, a: &mut [u8]) -> Result<(), BsdlError> {
        let nbytes = (self.boundary_length + 7) >> 3;
        if a.len() < nbytes {
            return Err(BsdlError::OverflowError);
        }
        for i in 0..a.len() {
            a[i] = 0;
        }
        for i in 0..self.boundary_length {
            let bit = &self.boundary_register[i].safe;
            if *bit == LogicVal::One {
                let byte = i >> 3;
                let bit = 1 << (i & 7);
                a[byte] |= bit;
            }
        }
        Ok(())
    }

    /// parse a file to an Entity
    pub fn parse(filename: &std::path::Path, pinmap: Option<&str>) -> Result<Entity, BsdlError> {
        let mut file = std::fs::File::open(filename)?;
        let mut content = Vec::new();
        file.read_to_end(&mut content)?;
        let buf = String::from_utf8_lossy(&content);
        let mut lines = buf.lines().enumerate();
        let mut bsdl = Entity {
            name: String::new(),
            use_statements: Vec::new(),
            component_conformance: String::new(),
            opcodes: HashMap::new(),
            instruction_length: 0,
            boundary_length: 0,
            boundary_register: Vec::new(),
            idcode_register: Vec::new(),
            attributes: HashMap::new(),
            generics: HashMap::new(),
            ports: Ports::new(),
            maxtck_hz: None,
            tck_both: false,
        };
        // the first line aside from comments and whitespace should specify
        // the "entity"
        loop {
            if let Some((i, line)) = lines.next() {
                let line = strip_whitespace_comments(line);
                if line.len() == 0 {
                    continue;
                }
                let line = line.to_lowercase();
                let mut s = line.split_whitespace();
                if s.next() != Some("entity") {
                    return Err(BsdlError::ParseError(format!(
                        "in {filename:?} at line {i} expected 'entity' found {line}"
                    )));
                }
                match s.next() {
                    Some(entity) => {
                        bsdl.name.push_str(entity);
                    }
                    None => {
                        return Err(BsdlError::ParseError(format!(
                            "in {filename:?} at line {i} expected 'entity' found {line}"
                        )));
                    }
                }
                if s.next() != Some("is") {
                    return Err(BsdlError::ParseError(format!(
                        "in {filename:?} at line {i} expected 'is' as 3rd word, found {line}"
                    )));
                }
                break;
            } else {
                return Err(BsdlError::ParseError(format!(
                    "in {filename:?} failed to find 'entity'"
                )));
            }
        }
        // now we can expect a bunch of ";" terminated items
        // ending with the line "end <entity>;"
        // save each of the ";" terminated items into a String
        // then deal with further processing it
        loop {
            let mut item = Item::new();
            let mut openparen = 0usize; // the number of open parenthesis at this point
            let mut quote_continues = false;
            let mut first = true; // first line in an item
            'inner: loop {
                if let Some((i, line)) = lines.next() {
                    let mut line = strip_whitespace_comments(line);
                    if line.len() == 0 {
                        continue;
                    }
                    if first {
                        item.line = i + 1;
                        first = false;
                        let space = line.find(char::is_whitespace);
                        match space {
                            Some(space) => {
                                item.itemtype = line[0..space].to_lowercase();
                                line = strip_whitespace_comments(&line[space + 1..]);
                                if line.len() == 0 {
                                    continue;
                                }
                            }
                            None => {
                                item.itemtype = line.to_lowercase();
                                continue;
                            }
                        }
                    }
                    let mut in_quote = false;
                    for char in line.chars() {
                        if quote_continues & (char != '"') {
                            // if we have a quote continuation, the character must be the start
                            // of a new quote
                            if char.is_whitespace() {
                                continue;
                            }
                            return Err(BsdlError::ParseError(format!(
                                "in {filename:?} at line {i} unexpected character {char} after quote continuation"
                            )));
                        } else if in_quote {
                            // if we are in a quote, ignore anything but end of quote
                            if char == '"' {
                                in_quote = false;
                            }
                            item.content.push(char);
                        } else if char == '&' {
                            // quote continues
                            quote_continues = true;
                        } else if char == '"' {
                            in_quote = true;
                            if quote_continues {
                                quote_continues = false;
                                while item.content.pop() != Some('"') {}
                                item.content.push(' ');
                            } else {
                                item.content.push(char);
                            }
                        } else if (openparen == 0) & (char == ';') {
                            break 'inner;
                        } else {
                            if char.is_ascii() {
                                item.content.push(char.to_ascii_lowercase());
                            } else {
                                item.content.push(char);
                            }
                            if char == '(' {
                                openparen += 1;
                            } else if char == ')' {
                                if openparen == 0 {
                                    return Err(BsdlError::ParseError(format!(
                                        "in {filename:?} at line {i} parenthesis closed but not opened"
                                    )));
                                }
                                openparen -= 1;
                            }
                        }
                    }
                    if in_quote {
                        return Err(BsdlError::ParseError(format!(
                            "in {filename:?} at line {i} quotation not closed: {line}"
                        )));
                    }
                    item.content.push(' ');
                } else {
                    return Err(BsdlError::ParseError(format!(
                        "in {filename:?} unexpected EOF"
                    )));
                }
            }
            match item.itemtype.as_str() {
                "attribute" => bsdl.parse_attribute(&item),
                "constant" => bsdl.parse_constant(&item, pinmap),
                "port" => bsdl.parse_port(&item),
                "use" => bsdl.parse_use(&item),
                "generic" => bsdl.parse_generic(&item),
                "end" => {
                    break;
                }
                _ => Ok(()),
            }
            .map_err(|e| {
                BsdlError::ParseError(format!("in {:?} line {} {:?}", filename, item.line, e))
            })?;
        }
        Ok(bsdl)
    }
    fn parse_attribute(&mut self, item: &Item) -> Result<(), BsdlError> {
        let s = item.content.as_str();
        let (name, s2) = s.split_once("of").ok_or(BsdlError::AttributeError)?;
        let name = name.trim();
        let (of, of_type) = s2.split_once(":").ok_or(BsdlError::AttributeError)?;
        let (of_type, val) = of_type.split_once("is").ok_or(BsdlError::AttributeError)?;
        let of = of.trim();
        let of_type = of_type.trim();
        let val = val.trim();
        match name {
            "boundary_length" => {
                self.boundary_length = usize::from_str_radix(val, 10)?;
            }
            "boundary_register" => {
                if of != self.name {
                    return Err(BsdlError::ParseError(format!(
                        "boundary register 'of' parameter not same as entity"
                    )));
                }
                if of_type != "entity" {
                    return Err(BsdlError::ParseError(format!(
                        "boundary register 'of' type must be entity"
                    )));
                }
                let mut val = strip_prefix(val, '"')?;
                self.boundary_register = vec![ScanCell::default(); self.boundary_length];
                while val.len() != 0 {
                    // get the number
                    val = val.trim_start();
                    let (num, rest) = val
                        .split_once(char::is_whitespace)
                        .ok_or(BsdlError::AttributeError)?;
                    let cellnum = usize::from_str_radix(num, 10).map_err(|_| {
                        BsdlError::ParseError(format!(
                            "Error parsing BOUNDARY_REGISTER cell number {num}"
                        ))
                    })?;
                    if cellnum > self.boundary_length {
                        return Err(BsdlError::ParseError(format!(
                            "boundary register index out of range"
                        )));
                    }
                    // get the stuff in parenthesis
                    let (in_paren, rest) = split_parenthesis(rest)?;
                    let bsc = ScanCell::from_string(in_paren, self, cellnum);
                    self.boundary_register[cellnum] = bsc?;
                    // we have a trailing comma if there's more
                    val = rest.trim_start();
                    // eat the comma if it's present
                    if let Some(_) = val.strip_prefix(',') {
                        val = val.strip_prefix(',').ok_or(BsdlError::AttributeError)?;
                        val = val.trim_start();
                    } else {
                        break;
                    }
                }
            }
            "instruction_length" => {
                self.instruction_length = val.parse::<usize>().map_err(|_| {
                    BsdlError::ParseError(format!("instruction_length {val} invalid"))
                })?;
                if self.instruction_length > 64 {
                    return Err(BsdlError::ParseError(format!(
                        "instruction_length {} exceeds limit of 64",
                        self.instruction_length
                    )));
                }
                // IEEE 1149.1 does not require BYPASS and EXTEST to be specified in file, set the defaults
                // originally, EXTEST was required to be 0, in later standards, it must be specified, not 0
                let bypass = match self.instruction_length {
                    64 => u64::MAX,
                    x => (1 << x) - 1,
                };
                self.opcodes.insert("BYPASS".to_string(), bypass);
                self.opcodes.insert("EXTEST".to_string(), 0);
            }
            "instruction_opcode" => {
                self.parse_opcodes(val)?;
            }
            "idcode_register" => {
                let val = strip_quotes(val)?;
                for substr in val.split(',') {
                    self.idcode_register
                        .push(jtag_idcode::IDCodeMasked::from_str(substr)?);
                }
            }
            "tap_scan_clock" => {
                // (1234.56e6, both) or (1234.56e6, low)
                let val = strip_parenthesis(val)?;
                let (freq_str, edge) = val.split_once(',').ok_or(BsdlError::AttributeError)?;
                self.tck_both = edge.trim() == "both";
                let freq = freq_str.parse::<f32>();
                match freq {
                    Ok(freq) => {
                        self.maxtck_hz = Some(freq);
                    }
                    _ => return Err(BsdlError::AttributeError),
                }
            }
            "port_grouping" => {
                self.ports.apply_port_grouping(val)?;
            }
            _ => {}
        }
        self.attributes.insert(name.to_uppercase(), item.clone());
        Ok(())
    }

    fn parse_opcodes(&mut self, val: &str) -> Result<(), BsdlError> {
        let mut val = strip_quotes(val)?;
        loop {
            val = val.trim();
            if val.len() == 0 {
                return Ok(());
            }
            let comma = find_first_comma_outside_paren(val)?;
            let a = if let Some(comma) = comma {
                let rv = &val[..comma];
                val = &val[comma + 1..];
                rv
            } else {
                let rv = val;
                val = "";
                rv
            };
            let (a, b) = a.split_once('(').ok_or(BsdlError::AttributeError)?;
            let a = a.trim();
            let b = b.trim();
            let b = b.strip_suffix(')').ok_or(BsdlError::AttributeError)?;
            let b = b.trim();
            // we could have a comma separated list of opcodes
            // discard all but the first
            let comma = b.find(',');
            let opcode_str: &str = match comma {
                Some(x) => &b[..x].trim(),
                None => b,
            };
            let instr = a.to_uppercase();
            let mut opcode = 0u64;
            for c in opcode_str.chars() {
                match c {
                    '0' | 'x' | 'X' => {
                        if opcode & (1 << 63) != 0 {
                            return Err(BsdlError::ParseError(format!(
                                "opcode {instr} exceeds 64 bit limit"
                            )));
                        }
                        opcode = opcode << 1;
                    }
                    '1' => {
                        if opcode & (1 << 63) != 0 {
                            return Err(BsdlError::ParseError(format!(
                                "opcode {instr} exceeds 64 bit limit"
                            )));
                        }
                        opcode = opcode << 1 | 1;
                    }
                    // ignore spaces and tabs
                    ' ' | '\t' => {}
                    _ => {
                        return Err(BsdlError::ParseError(format!(
                            "opcode {instr} contains invalid character _{c}_"
                        )));
                    }
                }
            }
            self.opcodes.insert(instr, opcode);
        }
    }

    fn parse_port(&mut self, item: &Item) -> Result<(), BsdlError> {
        let s = item.content.as_str();
        self.ports = Ports::from_str(s)?;
        Ok(())
    }
    fn parse_constant(&mut self, item: &Item, pinmap: Option<&str>) -> Result<(), BsdlError> {
        let s = item.content.as_str();
        let s = s.trim();
        let (name, rest) = s.split_once(':').ok_or(BsdlError::ConstantError)?;
        let (ctype, rest) = rest.split_once(":=").ok_or(BsdlError::ConstantError)?;
        let name = name.trim();
        let ctype = ctype.trim();
        let rest = rest.trim();
        match ctype {
            "pin_map_string" => {
                self.parse_pin_map(name, rest, pinmap)?;
            }
            _ => {}
        }
        Ok(())
    }
    fn parse_pin_map(
        &mut self,
        name: &str,
        s: &str,
        pinmap: Option<&str>,
    ) -> Result<(), BsdlError> {
        if let Some(p) = pinmap {
            if name != p {
                return Ok(());
            }
        }
        if self.ports.pinmap_applied {
            return Ok(());
        }
        self.ports.apply_pinmap(s)?;
        Ok(())
    }
    fn parse_use(&mut self, item: &Item) -> Result<(), BsdlError> {
        let s = item.content.as_str();
        self.use_statements.push(s.to_string());
        Ok(())
    }
    fn parse_generic(&mut self, item: &Item) -> Result<(), BsdlError> {
        let s = item.content.as_str();
        let s = strip_parenthesis(s)?;
        let (k, v) = s.split_once(':').ok_or(BsdlError::GenericError)?;
        let k = k.trim();
        let v = v.trim();
        let (gtype, v) = v.split_once(":=").ok_or(BsdlError::GenericError)?;
        let gtype = gtype.trim();
        let v = if gtype == "string" {
            strip_quotes(v)?
        } else {
            v
        };
        self.generics.insert(k.to_string(), v.to_string());
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::ffi::OsStr;
    use std::fs;
    use std::path::PathBuf;
    #[test]
    fn read_bsdl() {
        let home = PathBuf::from(env!("HOME"));
        let bsdl_file = home
            .join("software")
            .join("bsdl")
            .join("xcsu35p_sbvb625.bsd");
        let bsdl = Entity::parse(&bsdl_file, None);
        println!("{bsdl:?}");
        let k = bsdl.unwrap();
        println!("opcodes = {:?}", k.opcodes);
        println!("idcodes = {:?}", k.idcode_register);
        let bsdl_file = home
            .join("software")
            .join("bsdl")
            .join("ccgm1a1_fbga324.bsd");
        let bsdl = Entity::parse(&bsdl_file, None);
        let bsdl = bsdl.unwrap();
        println!("parse successful, entity = {}", bsdl);
    }
    #[test]
    fn test_example() {
        let manifest_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
        let test_bsd = manifest_dir
            .join("tests")
            .join("test_data")
            .join("sample.bsd");
        println!("dir = {manifest_dir:?}, {test_bsd:?}");
        let bsdl = Entity::parse(&test_bsd, None);
        if bsdl.is_err() {
            println!("error {bsdl:?}");
        }
        let bsdl = bsdl.unwrap();
        println!("opcode USER = {:?}", bsdl.opcodes.get("USER"));
        let idcode = bsdl.idcode_register;
        println!(
            "idcode = {} vendor = {:?}",
            idcode[0],
            idcode[0].vendor_string()
        );
        println!("generics = {:?}", bsdl.generics);
        //println!("attributes = {:?}", bsdl.attributes);
        println!("use_statements = {:?}", bsdl.use_statements);
        println!("ports = {}", bsdl.ports);
        println!("bscs = {:?}", bsdl.boundary_register);
    }
    #[test]
    fn test_many() {
        let home = PathBuf::from(env!("HOME"));
        let bsdl_dir = home.join("software").join("bsdl");
        println!("bsdl_dir = {:?}", bsdl_dir);
        let mut count = 0;
        if let Ok(dir) = fs::read_dir(bsdl_dir) {
            for entry in dir {
                if let Ok(entry) = entry {
                    let path = entry.path();
                    let is_bsd = path.extension().and_then(OsStr::to_str) == Some("bsd");
                    if !is_bsd {
                        continue;
                    }
                    let bsdl = Entity::parse(&path, None);
                    println!("entry = {:?} {}", path, bsdl.is_ok());
                    if bsdl.is_err() {
                        println!("error {:?}", bsdl);
                        panic!();
                    }
                    count += 1;
                }
            }
        }
        println!("processed {count} bsdls");
    }
}