veryl-analyzer 0.20.0

A modern hardware description 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
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
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
use crate::AnalyzerError;
use crate::conv::Context;
use crate::ir::assign_table::{AssignContext, AssignTable};
use crate::ir::utils::{allow_missing_reset_statement, has_cond_type};
use crate::ir::{
    Comptime, Expression, FfTable, FunctionCall, Op, SystemFunctionCall, Type, VarId, VarIndex,
    VarPath, VarSelect,
};
use crate::value::{Value, ValueBigUint};
use indent::indent_all_by;
use std::borrow::Cow;
use std::fmt;
use veryl_parser::resource_table::StrId;
use veryl_parser::token_range::TokenRange;

#[derive(Clone, Default)]
pub struct StatementBlock(pub Vec<Statement>);

#[derive(Clone, Copy, PartialEq, Eq)]
pub enum ControlFlow {
    Continue,
    Break,
}

#[derive(Clone)]
pub enum Statement {
    Assign(AssignStatement),
    If(IfStatement),
    IfReset(IfResetStatement),
    For(ForStatement),
    SystemFunctionCall(Box<SystemFunctionCall>),
    FunctionCall(Box<FunctionCall>),
    TbMethodCall(TbMethodCall),
    Break,
    Unsupported(TokenRange),
    Null,
}

#[derive(Clone)]
pub struct ForStatement {
    pub var_id: VarId,
    pub var_name: StrId,
    pub var_type: Type,
    pub range: ForRange,
    pub body: Vec<Statement>,
    pub token: TokenRange,
}

#[derive(Clone, Debug)]
pub enum ForBound {
    Const(usize),
    Expression(Box<Expression>),
}

impl ForBound {
    pub fn eval_value(&self, context: &mut Context) -> Option<usize> {
        match self {
            Self::Const(x) => Some(*x),
            Self::Expression(exp) => {
                let exp = exp.as_ref().clone();
                exp.eval_value(context)?.to_usize()
            }
        }
    }
}

impl fmt::Display for ForBound {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ForBound::Const(x) => x.fmt(f),
            ForBound::Expression(x) => write!(f, "{}", x.as_ref()),
        }
    }
}

/// Loop iteration range representation.
#[derive(Clone, Debug)]
pub enum ForRange {
    /// start..end with additive step (default step=1)
    Forward {
        start: ForBound,
        end: ForBound,
        inclusive: bool,
        step: usize,
    },
    /// (start..end).rev() with additive step (default step=1)
    Reverse {
        start: ForBound,
        end: ForBound,
        inclusive: bool,
        step: usize,
    },
    /// start..end with arbitrary step operator (e.g., step *= 2)
    Stepped {
        start: ForBound,
        end: ForBound,
        inclusive: bool,
        step: usize,
        op: Op,
    },
}

impl ForRange {
    pub fn eval_iter(&self, context: &mut Context) -> Option<Vec<usize>> {
        let limit = context.config.evaluate_size_limit;
        match self {
            ForRange::Forward {
                start,
                end,
                inclusive,
                step,
            } => {
                let start = start.eval_value(context)?;
                let end = end.eval_value(context)?;
                let end = if *inclusive { end + 1 } else { end };
                if end.saturating_sub(start) > limit {
                    return None;
                }
                if *step == 1 {
                    Some((start..end).collect())
                } else {
                    let mut ret = vec![];
                    let mut i = start;
                    while i < end {
                        ret.push(i);
                        i += step;
                    }
                    Some(ret)
                }
            }
            ForRange::Reverse {
                start,
                end,
                inclusive,
                ..
            } => {
                let start = start.eval_value(context)?;
                let end = end.eval_value(context)?;
                if end.saturating_sub(start) > limit {
                    return None;
                }
                if *inclusive {
                    Some((start..=end).rev().collect())
                } else {
                    Some((start..end).rev().collect())
                }
            }
            ForRange::Stepped {
                start,
                end,
                inclusive,
                step,
                op,
            } => {
                let start = start.eval_value(context)?;
                let end = end.eval_value(context)?;
                let end = if *inclusive { end + 1 } else { end };
                let mut ret = vec![];
                let mut i = start;
                while i < end {
                    if ret.len() > limit {
                        return None;
                    }
                    ret.push(i);
                    let new_i = op.eval(i, *step);
                    if new_i == i {
                        break;
                    }
                    i = new_i;
                }
                Some(ret)
            }
        }
    }
}

#[derive(Clone)]
pub struct TbMethodCall {
    pub inst: StrId,
    pub method: TbMethod,
}

#[derive(Clone)]
pub enum TbMethod {
    ClockNext {
        count: Option<Expression>,
        period: Option<Expression>,
    },
    ResetAssert {
        clock: StrId,
        duration: Option<Expression>,
    },
}

impl Statement {
    pub fn is_null(&self) -> bool {
        matches!(self, Statement::Null)
    }

    pub fn eval_value(&self, context: &mut Context) -> ControlFlow {
        match self {
            Statement::Assign(x) => {
                x.eval_value(context);
                ControlFlow::Continue
            }
            Statement::If(x) => x.eval_value(context),
            Statement::IfReset(_) => ControlFlow::Continue,
            Statement::For(x) => {
                if let Some(iter) = x.range.eval_iter(context) {
                    'outer: for i in iter {
                        if let Some(var) = context.variables.get_mut(&x.var_id)
                            && let Some(total_width) = x.var_type.total_width()
                        {
                            let val = Value::new(i as u64, total_width, x.var_type.signed);
                            var.set_value(&[], val, None);
                        }
                        for s in &x.body {
                            if s.eval_value(context) == ControlFlow::Break {
                                break 'outer;
                            }
                        }
                    }
                }
                ControlFlow::Continue
            }
            Statement::SystemFunctionCall(_) => ControlFlow::Continue,
            Statement::FunctionCall(x) => {
                x.eval_value(context);
                ControlFlow::Continue
            }
            Statement::TbMethodCall(_) => ControlFlow::Continue,
            Statement::Break => ControlFlow::Break,
            Statement::Unsupported(_) => ControlFlow::Continue,
            Statement::Null => ControlFlow::Continue,
        }
    }

    pub fn eval_assign(
        &self,
        context: &mut Context,
        assign_table: &mut AssignTable,
        assign_context: AssignContext,
        base_tables: &[&AssignTable],
    ) {
        match self {
            Statement::Assign(x) => x.eval_assign(context, assign_table, assign_context),
            Statement::If(x) => x.eval_assign(context, assign_table, assign_context, base_tables),
            Statement::IfReset(x) => x.eval_assign(context, assign_table, base_tables),
            Statement::SystemFunctionCall(x) => {
                x.eval_assign(context, assign_table, assign_context)
            }
            Statement::FunctionCall(x) => x.eval_assign(context, assign_table, assign_context),
            Statement::For(x) => {
                for s in &x.body {
                    s.eval_assign(context, assign_table, assign_context, base_tables);
                }
            }
            Statement::TbMethodCall(_) | Statement::Break => (),
            Statement::Unsupported(_) => (),
            Statement::Null => (),
        }
    }

    pub fn gather_ff(&self, context: &mut Context, table: &mut FfTable, decl: usize) {
        match self {
            Statement::Assign(x) => x.gather_ff(context, table, decl),
            Statement::If(x) => x.gather_ff(context, table, decl),
            Statement::IfReset(x) => x.gather_ff(context, table, decl),
            Statement::FunctionCall(x) => x.gather_ff(context, table, decl, None, true),
            Statement::SystemFunctionCall(x) => x.gather_ff(context, table, decl, true),
            Statement::For(x) => {
                for s in &x.body {
                    s.gather_ff(context, table, decl);
                }
            }
            Statement::TbMethodCall(_)
            | Statement::Break
            | Statement::Unsupported(_)
            | Statement::Null => (),
        }
    }

    pub fn gather_ff_comb_assign(&self, context: &mut Context, table: &mut FfTable, decl: usize) {
        match self {
            Statement::Assign(x) => x.gather_ff_comb_assign(context, table, decl),
            Statement::If(x) => {
                // Record the condition expression's reads so analyses
                // that distinguish comb vs ff context (e.g. comb-to-FF
                // hoist eligibility) see them.  `from_ff=false` keeps
                // these out of `is_ff` classification.
                x.cond.gather_ff(context, table, decl, None, false);
                for s in &x.true_side {
                    s.gather_ff_comb_assign(context, table, decl);
                }
                for s in &x.false_side {
                    s.gather_ff_comb_assign(context, table, decl);
                }
            }
            Statement::IfReset(x) => {
                for s in &x.true_side {
                    s.gather_ff_comb_assign(context, table, decl);
                }
                for s in &x.false_side {
                    s.gather_ff_comb_assign(context, table, decl);
                }
            }
            Statement::FunctionCall(x) => x.gather_ff_comb_assign(context, table, decl),
            Statement::SystemFunctionCall(x) => x.gather_ff(context, table, decl, false),
            Statement::For(x) => {
                for s in &x.body {
                    s.gather_ff_comb_assign(context, table, decl);
                }
            }
            _ => (),
        }
    }

    pub fn set_index(&mut self, index: &VarIndex) {
        match self {
            Statement::Assign(x) => x.set_index(index),
            Statement::If(x) => x.set_index(index),
            Statement::IfReset(x) => x.set_index(index),
            Statement::SystemFunctionCall(_) => (),
            Statement::FunctionCall(x) => x.set_index(index),
            Statement::For(x) => {
                for s in &mut x.body {
                    s.set_index(index);
                }
            }
            Statement::TbMethodCall(_) | Statement::Break => (),
            Statement::Unsupported(_) => (),
            Statement::Null => (),
        }
    }
}

impl fmt::Display for Statement {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Statement::Assign(x) => x.fmt(f),
            Statement::If(x) => x.fmt(f),
            Statement::IfReset(x) => x.fmt(f),
            Statement::SystemFunctionCall(x) => format!("{x};").fmt(f),
            Statement::FunctionCall(x) => format!("{x};").fmt(f),
            Statement::TbMethodCall(x) => match &x.method {
                TbMethod::ClockNext { count, .. } => {
                    if let Some(c) = count {
                        write!(f, "{}.next({c});", x.inst)
                    } else {
                        write!(f, "{}.next();", x.inst)
                    }
                }
                TbMethod::ResetAssert { clock, duration } => {
                    if let Some(d) = duration {
                        write!(f, "{}.assert({clock}, {d});", x.inst)
                    } else {
                        write!(f, "{}.assert({clock});", x.inst)
                    }
                }
            },
            Statement::For(x) => {
                let range_op = if let ForRange::Reverse { .. } = &x.range {
                    "rev "
                } else {
                    ""
                };
                let (start, end, inclusive, step_info) = match &x.range {
                    ForRange::Forward {
                        start,
                        end,
                        inclusive,
                        step,
                    } => (
                        start,
                        end,
                        *inclusive,
                        if *step == 1 {
                            None
                        } else {
                            Some(format!("+= {step}"))
                        },
                    ),
                    ForRange::Reverse {
                        start,
                        end,
                        inclusive,
                        ..
                    } => (start, end, *inclusive, None),
                    ForRange::Stepped {
                        start,
                        end,
                        inclusive,
                        step,
                        op,
                    } => (start, end, *inclusive, Some(format!("{op}= {step}"))),
                };
                let dots = if inclusive { "..=" } else { ".." };
                if let Some(step_str) = step_info {
                    writeln!(
                        f,
                        "for {} in {range_op}{start}{dots}{end} step {step_str} {{",
                        x.var_name
                    )?;
                } else {
                    writeln!(f, "for {} in {range_op}{start}{dots}{end} {{", x.var_name)?;
                }
                for s in &x.body {
                    writeln!(f, "  {s}")?;
                }
                write!(f, "}}")
            }
            Statement::Break => "break;".fmt(f),
            Statement::Unsupported(_) => "/* unsupported */".fmt(f),
            Statement::Null => "".fmt(f),
        }
    }
}

#[derive(Clone, Debug)]
pub struct AssignDestination {
    pub id: VarId,
    pub path: VarPath,
    pub index: VarIndex,
    pub select: VarSelect,
    pub comptime: Comptime,
    pub token: TokenRange,
}

impl AssignDestination {
    pub fn total_width(&self, context: &mut Context) -> Option<usize> {
        let (beg, end) = self
            .select
            .eval_value(context, &self.comptime.r#type, false)?;
        Some(beg - end + 1)
    }

    pub fn eval_assign(
        &self,
        context: &mut Context,
        assign_table: &mut AssignTable,
        assign_context: AssignContext,
    ) {
        if let Some(variable) = context.get_variable_info(self.id) {
            let is_index_const = self.index.is_const();
            let is_select_const = self.select.is_const();
            let is_const = is_index_const & is_select_const;

            let range = if !is_index_const {
                variable.r#type.array.calc_range(&[])
            } else {
                let Some(index) = self.index.eval_value(context) else {
                    return;
                };
                variable.r#type.array.calc_range(&index)
            };

            // If select is not const, assign to the whole width
            let mask = if !is_select_const {
                let Some(width) = variable.total_width() else {
                    return;
                };
                ValueBigUint::gen_mask(width)
            } else {
                let Some((beg, end)) = self.select.eval_value(context, &variable.r#type, false)
                else {
                    return;
                };
                ValueBigUint::gen_mask_range(beg, end)
            };

            let mut errors = vec![];
            if let Some((beg, end)) = range {
                // `insert_assign` / `check_refered` bail out on arrays over
                // `array_limit`; iterating beg..=end just to hit that guard
                // is wasted work for any whole-array assignment.
                let skip_large_array =
                    variable.r#type.total_array().unwrap_or(0) > assign_table.array_limit;

                if !skip_large_array {
                    for i in beg..=end {
                        let index = VarIndex::from_index(i, &variable.r#type.array);
                        if let Some(index) = index.eval_value(context) {
                            if assign_context.is_comb()
                                && assign_table.check_refered(&variable.id, &index, &mask)
                            {
                                let mut text = variable.path.to_string();
                                for i in &index {
                                    text.push_str(&format!("[{i}]"));
                                }
                                // ignore `#[allow(unassign_variable)]` attribute
                                errors.push(AnalyzerError::unassign_variable(&text, &self.token));
                            }

                            let maybe = !is_const | assign_context.is_system_verilog();
                            let _ = assign_table.insert_assign(
                                &variable,
                                index,
                                mask.clone(),
                                maybe,
                                self.token,
                            );
                        }
                    }
                }
            }

            for e in errors {
                context.insert_error(e);
            }
        }
    }

    pub fn gather_ff(&self, context: &mut Context, table: &mut FfTable, decl: usize) {
        if let Some(variable) = context.get_variable_info(self.id) {
            // Let-bound variables use blocking assignment (BA) semantics
            // and must not be registered as FF in the table.
            if variable.kind == crate::ir::VarKind::Let {
                return;
            }
            if let Some(index) = self.index.eval_value(context) {
                if let Some(index) = variable.r#type.array.calc_index(&index) {
                    table.insert_assigned(self.id, index, decl);
                }
            } else if let Some(total_array) = variable.r#type.total_array() {
                for i in 0..total_array {
                    table.insert_assigned(self.id, i, decl);
                }
            }
        }
    }

    pub fn gather_ff_comb_assign(&self, context: &mut Context, table: &mut FfTable, decl: usize) {
        if let Some(variable) = context.get_variable_info(self.id) {
            if let Some(index) = self.index.eval_value(context) {
                if let Some(index) = variable.r#type.array.calc_index(&index) {
                    table.insert_assigned_comb(self.id, index, decl);
                }
            } else if let Some(total_array) = variable.r#type.total_array() {
                for i in 0..total_array {
                    table.insert_assigned_comb(self.id, i, decl);
                }
            }
        }
    }

    pub fn set_index(&mut self, index: &VarIndex) {
        self.index.add_prelude(index);
    }
}

impl fmt::Display for AssignDestination {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let ret = format!("{}{}{}", self.id, self.index, self.select);
        ret.fmt(f)
    }
}

#[derive(Clone)]
pub struct AssignStatement {
    pub dst: Vec<AssignDestination>,
    pub width: Option<usize>,
    pub expr: Expression,
    pub token: TokenRange,
}

impl AssignStatement {
    pub fn eval_value(&self, context: &mut Context) {
        if let Some(value) = self.expr.eval_value(context) {
            // TODO multiple dst
            if let Some(index) = self.dst[0].index.eval_value(context)
                && let Some((beg, end)) =
                    self.dst[0]
                        .select
                        .eval_value(context, &self.dst[0].comptime.r#type, false)
                && let Some(variable) = context.variables.get_mut(&self.dst[0].id)
            {
                variable.set_value(&index, value, Some((beg, end)));
            }
        }
    }

    pub fn eval_assign(
        &self,
        context: &mut Context,
        assign_table: &mut AssignTable,
        assign_context: AssignContext,
    ) {
        self.expr.eval_assign(context, assign_table, assign_context);
        for dst in &self.dst {
            dst.eval_assign(context, assign_table, assign_context);
        }
    }

    pub fn gather_ff(&self, context: &mut Context, table: &mut FfTable, decl: usize) {
        let assign_target = self.dst.first().map(|d| {
            let idx = d
                .index
                .eval_value(context)
                .and_then(|v| context.get_variable_info(d.id)?.r#type.array.calc_index(&v));
            (d.id, idx)
        });
        self.expr
            .gather_ff(context, table, decl, assign_target, true);
        for dst in &self.dst {
            dst.gather_ff(context, table, decl);
        }
    }

    pub fn gather_ff_comb_assign(&self, context: &mut Context, table: &mut FfTable, decl: usize) {
        let assign_target = self.dst.first().map(|d| {
            let idx = d
                .index
                .eval_value(context)
                .and_then(|v| context.get_variable_info(d.id)?.r#type.array.calc_index(&v));
            (d.id, idx)
        });
        self.expr
            .gather_ff(context, table, decl, assign_target, false);
        for dst in &self.dst {
            dst.gather_ff_comb_assign(context, table, decl);
        }
    }

    pub fn set_index(&mut self, index: &VarIndex) {
        for dst in &mut self.dst {
            dst.set_index(index);
        }
        self.expr.set_index(index);
    }
}

impl fmt::Display for AssignStatement {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut ret = String::new();

        if self.dst.len() == 1 {
            ret.push_str(&format!("{} = {};", self.dst[0], self.expr));
        } else {
            ret.push_str(&format!("{{{}", self.dst[0]));
            for d in &self.dst[1..] {
                ret.push_str(&format!(", {}", d));
            }
            ret.push_str(&format!("}} = {};", self.expr));
        }
        ret.fmt(f)
    }
}

#[derive(Clone)]
pub struct IfStatement {
    pub cond: Expression,
    pub true_side: Vec<Statement>,
    pub false_side: Vec<Statement>,
    pub token: TokenRange,
}

impl IfStatement {
    pub fn eval_value(&self, context: &mut Context) -> ControlFlow {
        if let Some(cond) = self.cond.eval_value(context) {
            if cond.to_usize().unwrap_or(0) != 0 {
                for stmt in &self.true_side {
                    if stmt.eval_value(context) == ControlFlow::Break {
                        return ControlFlow::Break;
                    }
                }
            } else {
                for stmt in &self.false_side {
                    if stmt.eval_value(context) == ControlFlow::Break {
                        return ControlFlow::Break;
                    }
                }
            }
        }
        ControlFlow::Continue
    }

    pub fn insert_leaf_false(&mut self, false_side: Vec<Statement>) {
        if self.false_side.is_empty() {
            self.false_side = false_side;
        } else if let Statement::If(x) = &mut self.false_side[0] {
            x.insert_leaf_false(false_side);
        }
    }

    pub fn eval_assign(
        &self,
        context: &mut Context,
        assign_table: &mut AssignTable,
        assign_context: AssignContext,
        base_tables: &[&AssignTable],
    ) {
        let mut true_table = AssignTable::new(context);
        let mut false_table = AssignTable::new(context);

        std::mem::swap(&mut true_table.refernced, &mut assign_table.refernced);

        let base_tables = if assign_table.table.is_empty() {
            Cow::Borrowed(base_tables)
        } else {
            let mut base_tables = base_tables.to_vec();
            base_tables.push(assign_table);
            Cow::Owned(base_tables)
        };

        for x in &self.true_side {
            x.eval_assign(context, &mut true_table, assign_context, &base_tables);
        }

        std::mem::swap(&mut false_table.refernced, &mut true_table.refernced);
        for x in &self.false_side {
            x.eval_assign(context, &mut false_table, assign_context, &base_tables);
        }

        if assign_context.is_comb() && !has_cond_type(&self.token) {
            true_table.check_uncoverd(context, &false_table, &base_tables);
        }

        true_table.merge_by_or(context, &mut false_table, false);
        assign_table.merge_by_or(context, &mut true_table, false);
        std::mem::swap(&mut assign_table.refernced, &mut false_table.refernced);
    }

    pub fn gather_ff(&self, context: &mut Context, table: &mut FfTable, decl: usize) {
        self.cond.gather_ff(context, table, decl, None, true);
        for x in &self.true_side {
            x.gather_ff(context, table, decl);
        }
        for x in &self.false_side {
            x.gather_ff(context, table, decl);
        }
    }

    pub fn set_index(&mut self, index: &VarIndex) {
        self.cond.set_index(index);
        for x in &mut self.true_side {
            x.set_index(index);
        }
        for x in &mut self.false_side {
            x.set_index(index);
        }
    }
}

impl fmt::Display for IfStatement {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut ret = format!("if {} {{\n", self.cond);
        for x in &self.true_side {
            let text = format!("{}\n", x);
            ret.push_str(&indent_all_by(2, text));
        }
        ret.push('}');
        if !self.false_side.is_empty() {
            ret.push_str(" else {\n");
            for x in &self.false_side {
                let text = format!("{}\n", x);
                ret.push_str(&indent_all_by(2, text));
            }
            ret.push('}');
        }
        ret.fmt(f)
    }
}

#[derive(Clone)]
pub struct IfResetStatement {
    pub true_side: Vec<Statement>,
    pub false_side: Vec<Statement>,
    pub token: TokenRange,
}

impl IfResetStatement {
    pub fn eval_assign(
        &self,
        context: &mut Context,
        assign_table: &mut AssignTable,
        base_tables: &[&AssignTable],
    ) {
        let mut true_table = AssignTable::new(context);
        let mut false_table = AssignTable::new(context);

        std::mem::swap(&mut true_table.refernced, &mut assign_table.refernced);

        let mut base_tables = base_tables.to_vec();
        base_tables.push(assign_table);

        for x in &self.true_side {
            x.eval_assign(context, &mut true_table, AssignContext::Ff, &base_tables);
        }

        std::mem::swap(&mut false_table.refernced, &mut true_table.refernced);
        for x in &self.false_side {
            x.eval_assign(context, &mut false_table, AssignContext::Ff, &base_tables);
        }

        if !allow_missing_reset_statement(&self.token) {
            true_table.check_missing_reset(context, &false_table);
        }

        true_table.merge_by_or(context, &mut false_table, false);
        assign_table.merge_by_or(context, &mut true_table, false);
        std::mem::swap(&mut assign_table.refernced, &mut false_table.refernced);
    }

    pub fn gather_ff(&self, context: &mut Context, table: &mut FfTable, decl: usize) {
        for x in &self.true_side {
            x.gather_ff(context, table, decl);
        }
        for x in &self.false_side {
            x.gather_ff(context, table, decl);
        }
    }

    pub fn set_index(&mut self, index: &VarIndex) {
        for x in &mut self.true_side {
            x.set_index(index);
        }
        for x in &mut self.false_side {
            x.set_index(index);
        }
    }
}

impl fmt::Display for IfResetStatement {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut ret = "if_reset {\n".to_string();
        for x in &self.true_side {
            let text = format!("{}\n", x);
            ret.push_str(&indent_all_by(2, text));
        }
        ret.push('}');
        if !self.false_side.is_empty() {
            ret.push_str(" else {\n");
            for x in &self.false_side {
                let text = format!("{}\n", x);
                ret.push_str(&indent_all_by(2, text));
            }
            ret.push('}');
        }
        ret.fmt(f)
    }
}