vcd_rust 0.0.1

A value change dump parser for the Rust programming language
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
use crate::error::LoadError;
use crate::state_machine::StateMachine;
use crate::vcd::VCD;
use std::fs::File;
use std::io::{prelude::*, BufReader};

pub struct Parser {
    state_machine: StateMachine,
}

impl Parser {
    pub fn new() -> Parser {
        Parser {
            state_machine: StateMachine::new(),
        }
    }

    pub fn parse_from_string(&mut self, s: &str) -> Result<VCD, LoadError> {
        let mut line_num = 1;
        for line in s.lines() {
            self.parse(line.to_string(), line_num)?;
            line_num += 1;
        }
        line_num -= 1;
        self.state_machine.cleanup(line_num)?;
        Ok(self.state_machine.vcd.clone()) // TODO: Refactor to use take() to prevent clone
    }

    pub fn parse_from_file(&mut self, file: File) -> Result<VCD, LoadError> {
        let mut line_num = 1;
        for line in BufReader::new(file).lines() {
            match line {
                Ok(line) => self.parse(line, line_num)?,
                Err(_) => panic!("Failed reading file"), // FIXME cleanup
            };
            line_num += 1;
        }
        line_num -= 1;
        self.state_machine.cleanup(line_num)?;
        Ok(self.state_machine.vcd.clone()) // TODO: Refactor to use take() to prevent clone
    }

    fn parse(&mut self, line: String, line_num: usize) -> Result<(), LoadError> {
        let words: Vec<_> = line.split(" ").filter(|c| !c.is_empty()).collect();
        for word in words {
            self.state_machine.parse_word(word, line_num)?
        }
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::types::{
        scope::{Scope, ScopeType},
        timescale::{TimeScale, TimeUnit},
        variable::{VarType, Variable, VariableBuilder},
    };
    use std::collections::HashMap;

    fn get_scope_vec(scopes: Vec<(ScopeType, &str)>) -> Vec<Scope> {
        let mut scope_vec: Vec<Scope> = vec![];
        for (scope_type, id) in scopes.iter() {
            scope_vec.push(Scope::init(scope_type.clone(), id.to_string()));
        }
        return scope_vec;
    }

    fn get_var_hash_map(variables: Vec<Variable>) -> HashMap<String, Variable> {
        let mut var_hash_map = HashMap::<String, Variable>::new();
        for var in variables {
            var_hash_map.insert(var.ascii_identifier.clone(), var.clone());
        }
        return var_hash_map;
    }

    #[test]
    fn end_without_matching_command_throws_error() {
        let lines = r#"$end"#;
        let exp_err = LoadError::DanglingEnd { line: 1 };
        assert_eq!(Parser::new().parse_from_string(lines).err(), Some(exp_err));
    }

    #[test]
    fn date_command() {
        let contents = "$date Date text $end";
        let vcd = Parser::new().parse_from_string(contents).unwrap();
        assert_eq!(vcd.date, "Date text".to_string());
    }

    #[test]
    fn date_command_newline() {
        let contents = r#"$date
    Date text
$end"#;
        let vcd = Parser::new().parse_from_string(contents).unwrap();
        assert_eq!(vcd.date, "Date text".to_string());
    }

    #[test]
    fn date_command_with_no_end_throws_load_error() {
        let contents = r#"$date
Date text"#;
        let err = Parser::new().parse_from_string(contents).err();
        let exp_err = LoadError::MissingEnd {
            line: 2,
            command: "date".to_string(),
        };
        assert_eq!(err, Some(exp_err));
    }

    #[test]
    fn date_command_with_no_end_and_new_command_begins_throws_load_error() {
        let contents = r#"$date
    Date text
$version
    The version is 1.0
$end"#;
        let err = Parser::new().parse_from_string(contents).err();
        let exp_err = LoadError::MissingEnd {
            line: 3,
            command: "date".to_string(),
        };
        assert_eq!(err, Some(exp_err));
    }

    #[test]
    fn version_command_multiple_newlines() {
        let contents = r#"$version

The version number is 1.1

$end"#;
        let vcd = Parser::new().parse_from_string(contents).unwrap();
        assert_eq!(vcd.version, "The version number is 1.1");
    }

    #[test]
    fn version_command() {
        let contents = r#"$version This version number is 2.0 $end"#;
        let vcd = Parser::new().parse_from_string(contents).unwrap();
        assert_eq!(vcd.version, "This version number is 2.0");
    }

    #[test]
    fn version_command_with_no_end_throws_load_error() {
        let contents = r#"$version
            This version has no end"#;
        let err = Parser::new().parse_from_string(contents).err();
        let exp_err = LoadError::MissingEnd {
            line: 2,
            command: "version".to_string(),
        };
        assert_eq!(err, Some(exp_err));
    }

    #[test]
    fn vcd_file_with_multiple_versions_throws_error() {
        let contents = r#"$version
    Version 1.0
$end
$version
    Version 2.0. Which version is the right version?
$end"#;
        let err = Parser::new().parse_from_string(contents).err();
        let exp_err = LoadError::InvalidMultipleCommand {
            line: 4,
            command: "version".to_string(),
        };
        assert_eq!(err, Some(exp_err));
    }

    #[test]
    fn vcd_file_with_multiple_dates_throws_error() {
        let contents = r#"$date
    May 31st, 2020
$end
$date
    August 9th, 2020. Which is the correct date?
$end"#;
        let err = Parser::new().parse_from_string(contents).err();
        let exp_err = LoadError::InvalidMultipleCommand {
            line: 4,
            command: "date".to_string(),
        };
        assert_eq!(err, Some(exp_err));
    }

    #[test]
    fn timescale_command() {
        let contents = "$timescale 1 ps $end";
        let vcd = Parser::new().parse_from_string(contents).unwrap();
        assert_eq!(vcd.timescale, TimeScale::init(1, TimeUnit::PS));
    }

    #[test]
    fn comment_command_with_one_comment() {
        let contents = "$comment this is a comment $end";
        let vcd = Parser::new().parse_from_string(contents).unwrap();
        assert_eq!(vcd.comments, vec!["this is a comment"]);
    }

    #[test]
    fn comment_command_with_multiple_comments() {
        let contents = r#"$comment
    This is comment 1
$end
$comment
    This is comment 2
$end"#;
        let vcd = Parser::new().parse_from_string(contents).unwrap();
        assert_eq!(vcd.comments, vec!["This is comment 1", "This is comment 2"]);
    }

    #[test]
    fn comment_command_with_no_end_throws_load_error() {
        let contents = "$comment This comment is missing an end";
        let err = Parser::new().parse_from_string(contents).err();
        let exp_err = LoadError::MissingEnd {
            line: 1,
            command: "comment".to_string(),
        };
        assert_eq!(err, Some(exp_err));
    }

    #[test]
    fn parse_one_lvl1_scope_with_one_var() {
        let lines = r#"$scope module lvl_1 $end
$var wire 8 # data $end"#;
        let exp_var: Variable = VariableBuilder::default()
            .scope(get_scope_vec(vec![(ScopeType::Module, "lvl_1")]))
            .var_type(VarType::Wire)
            .bit_width(8)
            .ascii_identifier("#".to_string())
            .reference("data".to_string())
            .build()
            .unwrap();
        let exp_vars = get_var_hash_map(vec![exp_var]);
        let act_vars = Parser::new().parse_from_string(lines).unwrap().variables;
        assert_eq!(exp_vars, act_vars);
    }

    #[test]
    fn parse_two_lvl1_scopes_each_with_one_var() {
        let lines = r#"$scope module lvl_1_one $end
$var wire 8 # data $end
$upscope $end
$scope module lvl_1_two $end
$var integer 2 & num $end"#;
        let exp_vars = get_var_hash_map(vec![
            VariableBuilder::default()
                .scope(get_scope_vec(vec![(ScopeType::Module, "lvl_1_one")]))
                .var_type(VarType::Wire)
                .bit_width(8)
                .ascii_identifier("#".to_string())
                .reference("data".to_string())
                .build()
                .unwrap(),
            VariableBuilder::default()
                .scope(get_scope_vec(vec![(ScopeType::Module, "lvl_1_two")]))
                .var_type(VarType::Integer)
                .bit_width(2)
                .ascii_identifier("&".to_string())
                .reference("num".to_string())
                .build()
                .unwrap(),
        ]);
        let act_vars = Parser::new().parse_from_string(lines).unwrap().variables;
        assert_eq!(exp_vars, act_vars);
    }

    #[test]
    fn parse_one_lvl2_scope_with_one_var() {
        let lines = r#"$scope module lvl_1 $end
$scope task lvl_2 $end
$var reg 3 ' my_name $end"#;
        let scope_vec = get_scope_vec(vec![
            (ScopeType::Module, "lvl_1"),
            (ScopeType::Task, "lvl_2"),
        ]);
        let exp_var: Variable = VariableBuilder::default()
            .scope(scope_vec)
            .var_type(VarType::Reg)
            .bit_width(3)
            .ascii_identifier("'".to_string())
            .reference("my_name".to_string())
            .build()
            .unwrap();
        let exp_vars = get_var_hash_map(vec![exp_var]);
        let act_vars = Parser::new().parse_from_string(lines).unwrap().variables;
        assert_eq!(exp_vars, act_vars);
    }

    #[test]
    fn parse_one_lvl2_scope_with_two_vars() {
        let lines = r#"$scope fork lvl_1 $end
$scope begin lvl_2 $end
$var event 2 { my_event $end
$var tri 1 } my_tri $end"#;
        let scope_vec = get_scope_vec(vec![
            (ScopeType::Fork, "lvl_1"),
            (ScopeType::Begin, "lvl_2"),
        ]);
        let exp_vars = get_var_hash_map(vec![
            VariableBuilder::default()
                .scope(scope_vec.clone())
                .var_type(VarType::Event)
                .bit_width(2)
                .ascii_identifier("{".to_string())
                .reference("my_event".to_string())
                .build()
                .unwrap(),
            VariableBuilder::default()
                .scope(scope_vec.clone())
                .var_type(VarType::Tri)
                .bit_width(1)
                .ascii_identifier("}".to_string())
                .reference("my_tri".to_string())
                .build()
                .unwrap(),
        ]);
        let act_vars = Parser::new().parse_from_string(lines).unwrap().variables;
        assert_eq!(exp_vars, act_vars);
    }

    #[test]
    fn parse_one_lvl1_scope_with_one_var_with_var_parameters_on_newlines() {
        let lines = r#"$scope task lvl_1 $end
$var
event
2
p
my_ref
$end"#;
        let exp_var: Variable = VariableBuilder::default()
            .scope(get_scope_vec(vec![(ScopeType::Task, "lvl_1")]))
            .var_type(VarType::Event)
            .bit_width(2)
            .ascii_identifier("p".to_string())
            .reference("my_ref".to_string())
            .build()
            .unwrap();
        let exp_vars = get_var_hash_map(vec![exp_var]);
        let act_vars = Parser::new().parse_from_string(lines).unwrap().variables;
        assert_eq!(exp_vars, act_vars);
    }

    #[test]
    fn parse_one_lvl1_scope_with_scope_parameters_on_newlines() {
        let lines = r#"$scope
module
name
$end
$var wire 8 # data $end"#;
        let exp_var: Variable = VariableBuilder::default()
            .scope(get_scope_vec(vec![(ScopeType::Module, "name")]))
            .var_type(VarType::Wire)
            .bit_width(8)
            .ascii_identifier("#".to_string())
            .reference("data".to_string())
            .build()
            .unwrap();
        let exp_vars = get_var_hash_map(vec![exp_var]);
        let act_vars = Parser::new().parse_from_string(lines).unwrap().variables;
        assert_eq!(exp_vars, act_vars);
    }

    #[test]
    fn var_missing_end_same_line_throws_error() {
        let lines = r#"$scope module name $end
$var event 2 e my_var"#;

        let exp_err = LoadError::MissingEnd {
            command: "var".to_string(),
            line: 2,
        };

        assert_eq!(Parser::new().parse_from_string(lines).err(), Some(exp_err));
    }

    #[test]
    fn var_missing_end_different_line_throws_error() {
        let lines = r#"$scope module name $end
$var
event
2
e
my_var"#;

        let exp_err = LoadError::MissingEnd {
            command: "var".to_string(),
            line: 6,
        };
        assert_eq!(Parser::new().parse_from_string(lines).err(), Some(exp_err));
    }

    #[test]
    fn var_missing_end_middle_of_file_throws_error() {
        let lines = r#"$scope module name $end
$var event 2 e my_var
$upscope $end"#;

        let exp_err = LoadError::MissingEnd {
            command: "var".to_string(),
            line: 3,
        };

        assert_eq!(Parser::new().parse_from_string(lines).err(), Some(exp_err));
    }

    #[test]
    fn scope_missing_end_same_line_throws_error() {
        let lines = r#"$scope module name"#;
        let exp_err = LoadError::MissingEnd {
            command: "scope".to_string(),
            line: 1,
        };
        assert_eq!(Parser::new().parse_from_string(lines).err(), Some(exp_err));
    }

    #[test]
    fn scope_missing_end_different_line_throws_error() {
        let lines = r#"$scope
module
name"#;
        let exp_err = LoadError::MissingEnd {
            command: "scope".to_string(),
            line: 3,
        };
        assert_eq!(Parser::new().parse_from_string(lines).err(), Some(exp_err));
    }

    #[test]
    fn scope_missing_end_middle_of_file_throws_error() {
        let lines = r#"$scope
module
name
$var integer 8 a my_var $end"#;
        let exp_err = LoadError::MissingEnd {
            command: "scope".to_string(),
            line: 4,
        };
        assert_eq!(Parser::new().parse_from_string(lines).err(), Some(exp_err));
    }

    #[test]
    fn upscope_missing_end_same_line_throws_error() {
        let lines = r#"$upscope"#;
        let exp_err = LoadError::MissingEnd {
            command: "upscope".to_string(),
            line: 1,
        };
        assert_eq!(Parser::new().parse_from_string(lines).err(), Some(exp_err));
    }

    #[test]
    fn upscope_missing_end_middle_of_file_throws_error() {
        let lines = r#"$scope module name $end
$upscope
$scope module other_name $end"#;
        let exp_err = LoadError::MissingEnd {
            command: "upscope".to_string(),
            line: 3,
        };
        assert_eq!(Parser::new().parse_from_string(lines).err(), Some(exp_err));
    }

    #[test]
    fn var_with_too_few_params_throws_error() {
        let lines = r#"$scope module lvl_1 $end
$var wire 8 # $end"#;
        let exp_err = LoadError::TooFewParameters {
            command: "var".to_string(),
            line: 2,
        };
        assert_eq!(Parser::new().parse_from_string(lines).err(), Some(exp_err));
    }

    #[test]
    fn var_declared_with_empty_hierarchy_throws_error() {
        let lines = r#"$var wire 8 # data $end"#;
        let exp_err = LoadError::ScopeStackEmpty {
            command: "var".to_string(),
            line: 1,
        };
        assert_eq!(Parser::new().parse_from_string(lines).err(), Some(exp_err));
    }

    #[test]
    fn var_with_too_many_parameters_throws_error() {
        let lines = r#"$scope module lvl_1 $end
$var wire 8 # data BAD_PARAM $end"#;
        let exp_err = LoadError::TooManyParameters {
            command: "var".to_string(),
            line: 2,
        };
        assert_eq!(Parser::new().parse_from_string(lines).err(), Some(exp_err));
    }

    #[test]
    fn upscope_with_empty_hierarchy_throws_error() {
        let lines = r#"$upscope $end"#;
        let exp_err = LoadError::ScopeStackEmpty {
            line: 1,
            command: "upscope".to_string(),
        };
        assert_eq!(Parser::new().parse_from_string(lines).err(), Some(exp_err));
    }

    #[test]
    fn upscope_with_too_many_parameters_throws_error() {
        let lines = r#"$upscope parameter $end"#;
        let exp_err = LoadError::InvalidParameterForCommand {
            parameter: "parameter".to_string(),
            command: "upscope".to_string(),
            line: 1,
        };
        assert_eq!(Parser::new().parse_from_string(lines).err(), Some(exp_err));
    }
}