veryl-analyzer 0.22.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
use crate::analyzer_error::UnevaluableValueKind;
use crate::conv::Context;
use crate::ir::assign_table::{AssignContext, AssignTable};
use crate::ir::ff_table::FfTable;
use crate::ir::{
    AssignDestination, Comptime, Expression, Factor, HierVarRef, IrResult, Shape, Type, TypeKind,
    ValueVariant, VarPathSelect,
};
use crate::symbol::Affiliation;
use crate::value::Value;
use crate::{AnalyzerError, BigUint, ir_error};
use std::fmt;
use veryl_parser::resource_table::StrId;
use veryl_parser::token_range::TokenRange;

#[derive(Clone, Debug)]
pub struct Input(pub Expression);

impl fmt::Display for Input {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.0.fmt(f)
    }
}

#[derive(Clone, Debug)]
pub enum Output {
    /// Destinations in the calling scope.
    Local(Vec<AssignDestination>),
    /// A whole variable inside an instance (`$readmemh(path, u_dut.mem)`),
    /// resolved by the IR conversion once the instance tree exists.
    Hier(Box<HierVarRef>),
}

impl Output {
    pub fn local(&self) -> &[AssignDestination] {
        match self {
            Output::Local(x) => x,
            Output::Hier(_) => &[],
        }
    }
}

impl fmt::Display for Output {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let dst = match self {
            Output::Local(x) => x,
            Output::Hier(x) => {
                let path: Vec<String> = x.inst_path.iter().map(|x| x.to_string()).collect();
                return format!("{}.{}", path.join("."), x.var_path).fmt(f);
            }
        };
        let mut ret = String::new();

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

        ret.fmt(f)
    }
}

#[derive(Clone, Debug)]
pub struct SystemFunctionCall {
    pub kind: SystemFunctionKind,
    pub comptime: Comptime,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum AssertKind {
    Fatal,
    Continue,
}

impl AssertKind {
    pub fn as_str(&self) -> &'static str {
        match self {
            AssertKind::Fatal => "$assert",
            AssertKind::Continue => "$assert_continue",
        }
    }
}

#[derive(Clone, Debug)]
pub enum SystemFunctionKind {
    Bits(Input),
    /// `$size(x)` or `$size(x, dimension)`.
    Size(Input, Option<Input>),
    Clog2(Input),
    Onehot(Input),
    Readmemh(Input, Output),
    Display(Vec<Input>),
    Write(Vec<Input>),
    Assert {
        kind: AssertKind,
        cond: Input,
        args: Vec<Input>,
    },
    Finish,
    Signed(Input),
    Unsigned(Input),
}

impl SystemFunctionKind {
    fn return_type(&self) -> Type {
        match self {
            Self::Bits(_) | Self::Size(..) | Self::Clog2(_) => {
                // IEEE 1800-2023 20.6.2/20.7/20.8.1 return signed integers.
                // Use Bit like integer literals so known results remain
                // compatible with Veryl's u32/i32 types.
                let mut ret = Type::new(TypeKind::Bit);
                ret.set_concrete_width(Shape::new(vec![Some(32)]));
                ret.signed = true;
                ret
            }
            Self::Onehot(_) => Type::new(TypeKind::Bit),
            Self::Signed(x) | Self::Unsigned(x) => {
                // Sign casts preserve the operand's width and state type.
                let mut ret = x.0.comptime().r#type.clone();
                ret.signed = matches!(self, Self::Signed(_));
                ret
            }
            Self::Readmemh(..)
            | Self::Display(_)
            | Self::Write(_)
            | Self::Assert { .. }
            | Self::Finish => Type::new(TypeKind::Void),
        }
    }
}

fn create_input(
    context: &mut Context,
    name: StrId,
    r#type: Option<Type>,
    arg: (Expression, Vec<VarPathSelect>, TokenRange),
) -> Input {
    let (mut expr, _, token) = arg;

    // eval_comptime is required for width propagation, not just the type check.
    let comptime = expr.eval_comptime(context, None);
    if let Some(r#type) = r#type
        && !r#type.compatible(comptime, context.in_generic)
    {
        context.insert_error(AnalyzerError::mismatch_function_arg(
            &name.to_string(),
            &comptime.r#type.to_string(),
            &token,
        ));
    }

    Input(expr)
}

fn create_output(
    context: &mut Context,
    name: StrId,
    r#type: Option<Type>,
    arg: (Expression, Vec<VarPathSelect>, TokenRange),
) -> Output {
    let (mut expr, dst, token) = arg;

    let dst: Vec<AssignDestination> = dst
        .into_iter()
        .filter_map(|x| x.to_assign_destination(context, false))
        .collect();

    if let Some(r#type) = r#type {
        let comptime = expr.eval_comptime(context, None);
        if !r#type.compatible(comptime, context.in_generic) {
            context.insert_error(AnalyzerError::mismatch_function_arg(
                &name.to_string(),
                &comptime.r#type.to_string(),
                &token,
            ));
        }
    }

    // `find_path` only sees the calling scope, so a hierarchical target has no
    // local destination; the expression form of the argument carries the
    // resolved instance path instead.  A part of the variable is not a target.
    if dst.is_empty()
        && let Expression::Term(factor) = &expr
        && let Factor::HierVariable(hier) = factor.as_ref()
        && hier.index.0.is_empty()
        && hier.select.is_empty()
    {
        return Output::Hier(hier.clone());
    }

    Output::Local(dst)
}

impl SystemFunctionCall {
    pub fn new(
        context: &mut Context,
        name: StrId,
        mut args: Vec<(Expression, Vec<VarPathSelect>, TokenRange)>,
        token: TokenRange,
    ) -> IrResult<Self> {
        let mut comptime = Comptime::create_unknown(token);
        let function = name.to_string();

        let kind = match function.as_str() {
            "$bits" => {
                if args.len() != 1 {
                    context.insert_error(AnalyzerError::mismatch_function_arity(
                        "$bits",
                        1,
                        args.len(),
                        &token,
                    ));
                    return Err(ir_error!(token));
                }
                let arg0 = create_input(context, name, None, args.remove(0));
                comptime.is_const = true;
                SystemFunctionKind::Bits(arg0)
            }
            "$size" => {
                if args.is_empty() || args.len() > 2 {
                    context.insert_error(AnalyzerError::mismatch_function_arity(
                        "$size",
                        if args.is_empty() { 1 } else { 2 },
                        args.len(),
                        &token,
                    ));
                    return Err(ir_error!(token));
                }
                let arg1 =
                    (args.len() == 2).then(|| create_input(context, name, None, args.remove(1)));
                let arg0 = create_input(context, name, None, args.remove(0));
                comptime.is_const = true;
                SystemFunctionKind::Size(arg0, arg1)
            }
            "$clog2" => {
                if args.len() != 1 {
                    context.insert_error(AnalyzerError::mismatch_function_arity(
                        "$clog2",
                        1,
                        args.len(),
                        &token,
                    ));
                    return Err(ir_error!(token));
                }
                let arg0_type = {
                    let mut t = Type::new(TypeKind::Logic);
                    t.set_concrete_width(Shape::new(vec![Some(32)]));
                    t
                };
                let arg0 = create_input(context, name, Some(arg0_type), args.remove(0));
                // Function bodies are templates; const-ness is resolved per call.
                if !arg0.0.comptime().is_const && !context.is_affiliated(Affiliation::Function) {
                    context.insert_error(AnalyzerError::unevaluable_value(
                        UnevaluableValueKind::SystemFunctionArg("$clog2"),
                        &arg0.0.token_range(),
                    ));
                    return Err(ir_error!(token));
                }
                comptime.is_const = true;
                SystemFunctionKind::Clog2(arg0)
            }
            "$onehot" => {
                if args.len() != 1 {
                    context.insert_error(AnalyzerError::mismatch_function_arity(
                        "$onehot",
                        1,
                        args.len(),
                        &token,
                    ));
                    return Err(ir_error!(token));
                }
                let arg0_type = {
                    let mut t = Type::new(TypeKind::Logic);
                    t.set_concrete_width(Shape::new(vec![Some(32)]));
                    t
                };
                let arg0 = create_input(context, name, Some(arg0_type), args.remove(0));
                if !arg0.0.comptime().is_const && !context.is_affiliated(Affiliation::Function) {
                    context.insert_error(AnalyzerError::unevaluable_value(
                        UnevaluableValueKind::SystemFunctionArg("$onehot"),
                        &arg0.0.token_range(),
                    ));
                    return Err(ir_error!(token));
                }
                comptime.is_const = true;
                SystemFunctionKind::Onehot(arg0)
            }
            "$readmemh" => {
                if args.len() != 2 {
                    context.insert_error(AnalyzerError::mismatch_function_arity(
                        "$readmemh",
                        2,
                        args.len(),
                        &token,
                    ));
                    return Err(ir_error!(token));
                }
                let arg0 = create_input(context, name, None, args.remove(0));
                let arg1 = create_output(context, name, None, args.remove(0));
                SystemFunctionKind::Readmemh(arg0, arg1)
            }
            "$display" => {
                let inputs: Vec<Input> = args
                    .into_iter()
                    .map(|arg| create_input(context, name, None, arg))
                    .collect();
                SystemFunctionKind::Display(inputs)
            }
            "$write" => {
                let inputs: Vec<Input> = args
                    .into_iter()
                    .map(|arg| create_input(context, name, None, arg))
                    .collect();
                SystemFunctionKind::Write(inputs)
            }
            "$assert" | "$assert_continue" => {
                if args.is_empty() {
                    context.insert_error(AnalyzerError::mismatch_function_arity(
                        &name.to_string(),
                        1,
                        0,
                        &token,
                    ));
                    return Err(ir_error!(token));
                }
                let kind = if name.to_string() == "$assert_continue" {
                    AssertKind::Continue
                } else {
                    AssertKind::Fatal
                };
                let cond = create_input(context, name, None, args.remove(0));
                let args: Vec<Input> = args
                    .into_iter()
                    .map(|arg| create_input(context, name, None, arg))
                    .collect();
                SystemFunctionKind::Assert { kind, cond, args }
            }
            "$finish" => {
                if !args.is_empty() {
                    return Err(ir_error!(token));
                }
                comptime.is_const = true;
                SystemFunctionKind::Finish
            }
            "$signed" => {
                if args.len() != 1 {
                    return Err(ir_error!(token));
                }

                let mut arg = args.remove(0);
                arg.0.eval_comptime(context, None);

                let arg0 = create_input(context, name, None, arg);
                comptime.is_const = arg0.0.comptime().is_const;
                comptime.clock_domain = arg0.0.comptime().clock_domain;
                SystemFunctionKind::Signed(arg0)
            }
            "$unsigned" => {
                if args.len() != 1 {
                    return Err(ir_error!(token));
                }

                let mut arg = args.remove(0);
                arg.0.eval_comptime(context, None);

                let arg0 = create_input(context, name, None, arg);
                comptime.is_const = arg0.0.comptime().is_const;
                comptime.clock_domain = arg0.0.comptime().clock_domain;
                SystemFunctionKind::Unsigned(arg0)
            }
            _ => return Err(ir_error!(token)),
        };

        // Establish the return type before if-expression folding can replace
        // an unselected call with a constant of its type.
        comptime.r#type = kind.return_type();
        comptime.expr_context.signed = comptime.r#type.signed;
        Ok(SystemFunctionCall { kind, comptime })
    }

    pub fn eval_value(&self, context: &mut Context) -> Option<Value> {
        match &self.kind {
            // Both take the operand's TYPE, whatever its value variant is: an
            // unpacked-array variable has no single numeric value but its type
            // is fully sized.
            SystemFunctionKind::Bits(x) => {
                let mut expr = x.0.clone();
                let comptime = expr.eval_comptime(context, None);
                let value = match &comptime.value {
                    ValueVariant::Type(x) => x.total_bits(),
                    _ => comptime.r#type.total_bits(),
                };
                value.map(|x| Value::new(x as u64, 32, true))
            }
            SystemFunctionKind::Size(x, dimension) => {
                let dimension = match dimension {
                    Some(dimension) => {
                        let value = dimension.0.eval_value(context)?;
                        if value.is_xz() {
                            return None;
                        }
                        usize::try_from(value.payload().as_ref()).ok()?
                    }
                    None => 1,
                };
                let mut expr = x.0.clone();
                let comptime = expr.eval_comptime(context, None);
                let value = match &comptime.value {
                    ValueVariant::Type(x) => x.dimension(dimension),
                    _ => comptime.r#type.dimension(dimension),
                };
                value.map(|x| Value::new(x as u64, 32, true))
            }
            SystemFunctionKind::Clog2(x) => {
                let value = x.0.eval_value(context)?;
                if value.is_xz() {
                    return Some(Value::new_x(32, true));
                }
                let value = value.payload();
                let ret = if value.as_ref() == &BigUint::from(0u32) {
                    BigUint::from(0u32)
                } else {
                    value.as_ref() - BigUint::from(1u32)
                };
                Some(Value::new(ret.bits(), 32, true))
            }
            SystemFunctionKind::Onehot(x) => {
                let value = x.0.eval_value(context)?;
                if value.is_xz() {
                    return Some(Value::new_x(1, false));
                }
                let ret = value.payload().count_ones() == 1;
                Some(Value::new(ret.into(), 1, false))
            }
            SystemFunctionKind::Readmemh(_, _) => None,
            SystemFunctionKind::Display(_) => None,
            SystemFunctionKind::Write(_) => None,
            SystemFunctionKind::Assert { .. } => None,
            SystemFunctionKind::Finish => None,
            SystemFunctionKind::Signed(x) | SystemFunctionKind::Unsigned(x) => {
                let mut ret = x.0.eval_value(context)?;
                ret.set_signed(self.comptime.r#type.signed);
                Some(ret)
            }
        }
    }

    pub fn eval_comptime(&self, context: &mut Context) -> Comptime {
        let value = self.eval_value(context);
        match &self.kind {
            SystemFunctionKind::Bits(_)
            | SystemFunctionKind::Size(..)
            | SystemFunctionKind::Clog2(_)
            | SystemFunctionKind::Onehot(_) => {
                let mut ret = self.comptime.clone();
                if let Some(x) = value {
                    ret.value = ValueVariant::Numeric(x);
                }
                ret
            }
            SystemFunctionKind::Readmemh(_, _) => self.comptime.clone(),
            SystemFunctionKind::Display(_) => self.comptime.clone(),
            SystemFunctionKind::Write(_) => self.comptime.clone(),
            SystemFunctionKind::Assert { .. } => self.comptime.clone(),
            SystemFunctionKind::Finish => self.comptime.clone(),
            SystemFunctionKind::Signed(_) | SystemFunctionKind::Unsigned(_) => {
                let mut ret = self.comptime.clone();
                if let Some(x) = value {
                    ret.value = ValueVariant::Numeric(x);
                }
                ret
            }
        }
    }

    pub fn eval_assign(
        &self,
        context: &mut Context,
        assign_table: &mut AssignTable,
        assign_context: AssignContext,
    ) {
        if let SystemFunctionKind::Readmemh(_, x) = &self.kind {
            for x in x.local() {
                x.eval_assign(context, assign_table, assign_context);
            }
        }
    }
}

impl fmt::Display for SystemFunctionCall {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match &self.kind {
            SystemFunctionKind::Bits(x) => format!("$bits({x})").fmt(f),
            SystemFunctionKind::Size(x, None) => format!("$size({x})").fmt(f),
            SystemFunctionKind::Size(x, Some(y)) => format!("$size({x}, {y})").fmt(f),
            SystemFunctionKind::Clog2(x) => format!("$clog2({x})").fmt(f),
            SystemFunctionKind::Onehot(x) => format!("$onehot({x})").fmt(f),
            SystemFunctionKind::Readmemh(x, y) => format!("$readmemh({x}, {y})").fmt(f),
            SystemFunctionKind::Display(args) => {
                let args_str: Vec<_> = args.iter().map(|a| format!("{a}")).collect();
                format!("$display({})", args_str.join(", ")).fmt(f)
            }
            SystemFunctionKind::Write(args) => {
                let args_str: Vec<_> = args.iter().map(|a| format!("{a}")).collect();
                format!("$write({})", args_str.join(", ")).fmt(f)
            }
            SystemFunctionKind::Assert { kind, cond, args } => {
                let name = kind.as_str();
                if args.is_empty() {
                    format!("{name}({cond})").fmt(f)
                } else {
                    let args_str: Vec<_> = args.iter().map(|a| format!("{a}")).collect();
                    format!("{name}({cond}, {})", args_str.join(", ")).fmt(f)
                }
            }
            SystemFunctionKind::Finish => "$finish()".fmt(f),
            SystemFunctionKind::Signed(x) => format!("$signed({x})").fmt(f),
            SystemFunctionKind::Unsigned(x) => format!("$unsigned({x})").fmt(f),
        }
    }
}

impl SystemFunctionCall {
    pub fn gather_ff(
        &self,
        context: &mut Context,
        table: &mut FfTable,
        decl: usize,
        from_ff: bool,
    ) {
        let process_input = |input: &Input, context: &mut Context, table: &mut FfTable| {
            input.0.gather_ff(context, table, decl, None, from_ff);
        };
        match &self.kind {
            SystemFunctionKind::Bits(x)
            | SystemFunctionKind::Size(x, _)
            | SystemFunctionKind::Clog2(x)
            | SystemFunctionKind::Onehot(x)
            | SystemFunctionKind::Signed(x)
            | SystemFunctionKind::Unsigned(x) => {
                process_input(x, context, table);
            }
            SystemFunctionKind::Readmemh(_, _) => {
                // First arg is filename literal, second is output array
                // (written to, so handled via assignment, not reference).
            }
            SystemFunctionKind::Display(args) | SystemFunctionKind::Write(args) => {
                for arg in args {
                    process_input(arg, context, table);
                }
            }
            SystemFunctionKind::Assert { cond, args, .. } => {
                process_input(cond, context, table);
                for arg in args {
                    process_input(arg, context, table);
                }
            }
            SystemFunctionKind::Finish => {}
        }
    }
}