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
use crate::analyzer_error::InvalidSelectKind;
use crate::conv::checker::separator::check_separator;
use crate::conv::{Context, Conv, generate_block_label};
use crate::ir::{self, IrResult, VarPath, VarPathSelect, VarSelect, VarSelectOp};
use crate::namespace::Namespace;
use crate::symbol::{Symbol, SymbolKind};
use crate::symbol_path::{GenericSymbol, GenericSymbolPath};
use crate::symbol_table;
use crate::{AnalyzerError, ir_error};
use veryl_parser::resource_table::StrId;
use veryl_parser::token_range::TokenRange;
use veryl_parser::veryl_grammar_trait::*;
use veryl_parser::veryl_token::Token;
use veryl_parser::veryl_walker::VerylWalker;

impl Conv<&Identifier> for VarPath {
    fn conv(_context: &mut Context, value: &Identifier) -> IrResult<Self> {
        Ok(VarPath(vec![value.text()]))
    }
}

impl Conv<&ScopedIdentifier> for VarPath {
    fn conv(_context: &mut Context, value: &ScopedIdentifier) -> IrResult<Self> {
        let mut path = Vec::new();
        match value.scoped_identifier_group.as_ref() {
            ScopedIdentifierGroup::DollarIdentifier(x) => {
                path.push(x.dollar_identifier.dollar_identifier_token.token.text);
            }
            ScopedIdentifierGroup::IdentifierScopedIdentifierOpt(x) => {
                path.push(x.identifier.identifier_token.token.text);
            }
        }

        for x in &value.scoped_identifier_list {
            path.push(x.identifier.identifier_token.token.text);
        }

        Ok(VarPath(path))
    }
}

impl Conv<&SelectOperator> for VarSelectOp {
    fn conv(_context: &mut Context, value: &SelectOperator) -> IrResult<Self> {
        let ret = match value {
            SelectOperator::Colon(_) => VarSelectOp::Colon,
            SelectOperator::PlusColon(_) => VarSelectOp::PlusColon,
            SelectOperator::MinusColon(_) => VarSelectOp::MinusColon,
            SelectOperator::Step(_) => VarSelectOp::Step,
        };
        Ok(ret)
    }
}

fn check_select_type(context: &mut Context, expr: &mut ir::Expression, value: &Expression) {
    let token: TokenRange = value.into();
    let comptime = expr.eval_comptime(context, None);
    if comptime.r#type.is_type() {
        context.insert_error(AnalyzerError::invalid_factor(
            None,
            &comptime.r#type.to_string(),
            &token,
            &[],
        ));
    }
}

// SystemVerilog requires constant bounds for part-selects: the width for
// indexed part-selects (`+:`/`-:`/`step`), and BOTH bounds for a `[msb:lsb]`
// range (`Colon`). A runtime bound is unsynthesizable, so reject it.
// The comptimes must already be evaluated (via check_select_type).
fn check_part_select_width(
    context: &mut Context,
    op: &VarSelectOp,
    base: (&ir::Expression, &Expression),
    bound: (&ir::Expression, &Expression),
) {
    let (base, base_ast) = base;
    let (bound, bound_ast) = bound;
    // `references_loop_var` only when the IR is const, so a runtime-for
    // body (loop var non-const) reports once, not twice.
    let bound_const = if bound.comptime().is_const {
        !references_loop_var(bound_ast)
    } else {
        false
    };
    if !bound_const
        && matches!(
            op,
            VarSelectOp::PlusColon
                | VarSelectOp::MinusColon
                | VarSelectOp::Step
                | VarSelectOp::Colon
        )
    {
        context.insert_error(AnalyzerError::non_constant_select_width(
            &bound.token_range(),
        ));
    }
    // A `[msb:lsb]` range also needs a constant base index (the msb).
    let base_const = if base.comptime().is_const {
        !references_loop_var(base_ast)
    } else {
        false
    };
    if matches!(op, VarSelectOp::Colon) && !base_const {
        context.insert_error(AnalyzerError::non_constant_select_width(
            &base.token_range(),
        ));
    }
}

/// Detects a reference to a statement-level for-loop induction variable:
/// const while the IR unrolls but runtime in the emitted SV `for`, so it
/// can't size a part-select or bound a `[msb:lsb]`. Genvars stay allowed
/// (elaboration constants); scans the source AST, before the IR is folded.
#[derive(Default)]
struct LoopVarFinder {
    found: bool,
}

impl VerylWalker for LoopVarFinder {
    fn scoped_identifier(&mut self, arg: &ScopedIdentifier) {
        if !self.found
            && let Ok(symbol) = crate::symbol_table::resolve(arg)
            && let crate::symbol::SymbolKind::Variable(x) = &symbol.found.kind
            && x.loop_variable
        {
            self.found = true;
        }
    }
}

fn references_loop_var(expr: &Expression) -> bool {
    let mut finder = LoopVarFinder::default();
    finder.expression(expr);
    finder.found
}

impl Conv<&ScopedIdentifier> for VarPathSelect {
    fn conv(context: &mut Context, value: &ScopedIdentifier) -> IrResult<Self> {
        let var_path: VarPath = Conv::conv(context, value)?;
        let token: TokenRange = value.into();
        Ok(VarPathSelect(var_path, VarSelect::default(), token))
    }
}

/// Resolves one hop segment of a hierarchical reference. Within a known `scope`
/// (the previous hop's inner namespace) the lookup is direct; the first hop
/// crosses an instance boundary the symbol table treats as invisible, so its
/// target is recovered from where that walk stopped.
fn resolve_hop_symbol(
    generic_path: &GenericSymbolPath,
    scope: Option<&Namespace>,
    base_token: &Token,
) -> Option<Symbol> {
    if let Some(scope) = scope {
        Some((*symbol_table::resolve((base_token.text, scope)).ok()?.found).clone())
    } else {
        let i = generic_path.paths.len() - 1;
        let symbol = match symbol_table::resolve_base_path(generic_path, i, base_token.id) {
            Ok(symbol) => (*symbol.found).clone(),
            Err(err) => *err.last_found?,
        };
        // `last_found` is wherever the invisible walk stopped; require it to be
        // this segment so a deeper hop is not read as the node it stopped at.
        (symbol.token.text == base_token.text).then_some(symbol)
    }
}

/// The inner namespace of the module an instance instantiates, so a plain
/// instance hop (`u_mid`) can be descended before resolving a generate block
/// below it (`u_mid.g_leaf[0]`).
fn instance_module_scope(inst: &Symbol) -> Option<Namespace> {
    let SymbolKind::Instance(prop) = &inst.kind else {
        return None;
    };
    let type_symbol =
        symbol_table::resolve((&prop.type_name.generic_path(), &inst.namespace)).ok()?;
    Some(type_symbol.found.inner_namespace())
}

/// Folds a `g_leaf[0]` generate-block hop into one `label[index]` segment, the
/// form the IR stores the block (and its genvar variable path) under.
fn fold_generate_block_index(
    context: &mut Context,
    block: &Symbol,
    base_token: &Token,
    selects: &[ExpressionIdentifierList0List],
) -> Option<StrId> {
    if !matches!(block.kind, SymbolKind::Block) {
        return None;
    }
    // A generate block has one index dimension and no range.
    let [select] = selects else {
        return None;
    };
    if select.select.select_opt.is_some() {
        return None;
    }

    // Generate elaboration is static, so the subscript must be constant.
    let mut index: ir::Expression = Conv::conv(context, select.select.expression.as_ref()).ok()?;
    let comptime = index.eval_comptime(context, None);
    if !comptime.is_const {
        return None;
    }
    let index = comptime.get_value().ok()?.to_usize()?;
    Some(generate_block_label(base_token.text, index))
}

impl Conv<&ExpressionIdentifier> for VarPathSelect {
    fn conv(context: &mut Context, value: &ExpressionIdentifier) -> IrResult<Self> {
        // Unwound here because the walk returns early on an invalid select.
        let select_paths = context.select_paths.len();
        let select_dims = context.select_dims.len();
        let ret = conv_expression_identifier(context, value);
        context.select_paths.truncate(select_paths);
        context.select_dims.truncate(select_dims);
        ret
    }
}

/// Whether `symbol` is declared as a scalar `logic`/`bit` (no width, no
/// array). A modport member stands for the interface variable behind it.
fn is_scalar_symbol(symbol: &Symbol) -> bool {
    let symbol = match &symbol.kind {
        SymbolKind::ModportVariableMember(x) => match symbol_table::get(x.variable) {
            Some(x) => x,
            None => return false,
        },
        _ => symbol.clone(),
    };
    symbol.kind.get_type().is_some_and(|x| x.is_scalar())
}

fn conv_expression_identifier(
    context: &mut Context,
    value: &ExpressionIdentifier,
) -> IrResult<VarPathSelect> {
    check_separator(context, value);

    let mut path: VarPath = Conv::conv(context, value.scoped_identifier.as_ref())?;
    let mut generic_path: GenericSymbolPath = value.scoped_identifier.as_ref().into();
    let mut select = VarSelect::default();
    let token: TokenRange = value.into();
    let mut end: Option<(VarSelectOp, ir::Expression)> = None;

    context.select_dims.push(0);

    // SV rejects a select on a scalar, and the IR cannot tell `logic` from
    // `logic<1>` (both carry a width of 1), so the declaration is checked here.
    if !value.expression_identifier_list.is_empty()
        && let Ok(symbol) = symbol_table::resolve(value.scoped_identifier.as_ref())
        && is_scalar_symbol(&symbol.found)
    {
        context.insert_error(AnalyzerError::invalid_select(
            &InvalidSelectKind::Scalar,
            &token,
            &[],
        ));
        return Err(ir_error!(token));
    }

    for x in &value.expression_identifier_list {
        if end.is_some() {
            context.insert_error(AnalyzerError::invalid_select(
                &InvalidSelectKind::SelectAfterRange,
                &token,
                &[],
            ));
            return Err(ir_error!(token));
        }
        context
            .select_paths
            .push((path.clone(), generic_path.clone()));
        let base_value = x.select.expression.as_ref();
        let mut base = Conv::conv(context, base_value)?;
        check_select_type(context, &mut base, base_value);
        if let Some(x) = &x.select.select_opt {
            let op = Conv::conv(context, x.select_operator.as_ref())?;
            let mut bound = Conv::conv(context, x.expression.as_ref())?;
            check_select_type(context, &mut bound, &x.expression);
            check_part_select_width(context, &op, (&base, base_value), (&bound, &x.expression));
            end = Some((op, bound));
        }
        select.push(base);
        context.select_paths.pop();
        context.inc_select_dim();
    }

    let mut current_scope: Option<Namespace> = None;
    for x in &value.expression_identifier_list0 {
        let base_token = x.identifier.identifier_token.token;
        path.push(base_token.text);
        generic_path.paths.push(GenericSymbol {
            base: base_token,
            arguments: vec![],
        });

        // Cross-instance hops only appear in test modules; gating the lookups
        // there keeps them off the hot path for ordinary RTL member accesses.
        let hop = if context.in_test_module {
            resolve_hop_symbol(&generic_path, current_scope.as_ref(), &base_token)
        } else {
            None
        };

        // Generate-block hop: absorb `[0]` into the segment, then descend so a
        // nested generate hop resolves in the block's scope.
        if let Some(symbol) = &hop
            && !x.expression_identifier_list0_list.is_empty()
            && let Some(folded) = fold_generate_block_index(
                context,
                symbol,
                &base_token,
                &x.expression_identifier_list0_list,
            )
        {
            *path.0.last_mut().unwrap() = folded;
            current_scope = Some(symbol.inner_namespace());
            continue;
        }

        // Plain-instance hop: descend into the instantiated module so a
        // following generate hop resolves there; any other node ends the chain.
        current_scope = hop.as_ref().and_then(instance_module_scope);

        // Same scalar rule for a selected member (`s.x[0]` on a scalar `x`).
        if !x.expression_identifier_list0_list.is_empty()
            && let Ok(symbol) = symbol_table::resolve_base_path(
                &generic_path,
                generic_path.paths.len() - 1,
                base_token.id,
            )
            && is_scalar_symbol(&symbol.found)
        {
            context.insert_error(AnalyzerError::invalid_select(
                &InvalidSelectKind::Scalar,
                &token,
                &[],
            ));
            return Err(ir_error!(token));
        }

        context
            .select_paths
            .push((path.clone(), generic_path.clone()));
        context.reset_select_dim();
        for x in &x.expression_identifier_list0_list {
            if end.is_some() {
                context.insert_error(AnalyzerError::invalid_select(
                    &InvalidSelectKind::SelectAfterRange,
                    &token,
                    &[],
                ));
                return Err(ir_error!(token));
            }
            let base_value = x.select.expression.as_ref();
            let mut base = Conv::conv(context, base_value)?;
            check_select_type(context, &mut base, base_value);
            if let Some(x) = &x.select.select_opt {
                let op = Conv::conv(context, x.select_operator.as_ref())?;
                let mut bound = Conv::conv(context, x.expression.as_ref())?;
                check_select_type(context, &mut bound, &x.expression);
                check_part_select_width(context, &op, (&base, base_value), (&bound, &x.expression));
                end = Some((op, bound));
            }
            select.push(base);
            context.inc_select_dim();
        }
        context.select_paths.pop();
    }

    context.select_dims.pop();

    select.1 = end;

    Ok(VarPathSelect(path, select, token))
}

impl Conv<&HierarchicalIdentifier> for VarPathSelect {
    fn conv(context: &mut Context, value: &HierarchicalIdentifier) -> IrResult<Self> {
        // Unwound here because the walk returns early on an invalid select.
        let select_paths = context.select_paths.len();
        let select_dims = context.select_dims.len();
        let ret = conv_hierarchical_identifier(context, value);
        context.select_paths.truncate(select_paths);
        context.select_dims.truncate(select_dims);
        ret
    }
}

fn conv_hierarchical_identifier(
    context: &mut Context,
    value: &HierarchicalIdentifier,
) -> IrResult<VarPathSelect> {
    let mut path: VarPath = Conv::conv(context, value.identifier.as_ref())?;
    let mut generic_path: GenericSymbolPath = value.identifier.as_ref().into();
    let mut select = VarSelect::default();
    let token: TokenRange = value.into();
    let mut end: Option<(VarSelectOp, ir::Expression)> = None;

    context.select_dims.push(0);

    // An assignment target reaches here rather than through
    // `ExpressionIdentifier`; a select on a scalar is rejected the same way.
    if !value.hierarchical_identifier_list.is_empty()
        && let Ok(symbol) = symbol_table::resolve(value.identifier.as_ref())
        && is_scalar_symbol(&symbol.found)
    {
        context.insert_error(AnalyzerError::invalid_select(
            &InvalidSelectKind::Scalar,
            &token,
            &[],
        ));
        return Err(ir_error!(token));
    }

    for x in &value.hierarchical_identifier_list {
        if end.is_some() {
            context.insert_error(AnalyzerError::invalid_select(
                &InvalidSelectKind::SelectAfterRange,
                &token,
                &[],
            ));
            return Err(ir_error!(token));
        }
        context
            .select_paths
            .push((path.clone(), generic_path.clone()));
        let base_value = x.select.expression.as_ref();
        let mut base = Conv::conv(context, base_value)?;
        check_select_type(context, &mut base, base_value);
        if let Some(x) = &x.select.select_opt {
            let op = Conv::conv(context, x.select_operator.as_ref())?;
            let mut bound = Conv::conv(context, x.expression.as_ref())?;
            check_select_type(context, &mut bound, &x.expression);
            check_part_select_width(context, &op, (&base, base_value), (&bound, &x.expression));
            end = Some((op, bound));
        }
        select.push(base);
        context.select_paths.pop();
        context.inc_select_dim();
    }

    for x in &value.hierarchical_identifier_list0 {
        path.push(x.identifier.identifier_token.token.text);
        let member_token = x.identifier.identifier_token.token;
        generic_path.paths.push(GenericSymbol {
            base: x.identifier.identifier_token.token,
            arguments: vec![],
        });

        // Same rule for a selected member as an assignment target.
        if !x.hierarchical_identifier_list0_list.is_empty()
            && let Ok(symbol) = symbol_table::resolve_base_path(
                &generic_path,
                generic_path.paths.len() - 1,
                member_token.id,
            )
            && is_scalar_symbol(&symbol.found)
        {
            context.insert_error(AnalyzerError::invalid_select(
                &InvalidSelectKind::Scalar,
                &token,
                &[],
            ));
            return Err(ir_error!(token));
        }

        context
            .select_paths
            .push((path.clone(), generic_path.clone()));
        context.reset_select_dim();
        for x in &x.hierarchical_identifier_list0_list {
            if end.is_some() {
                context.insert_error(AnalyzerError::invalid_select(
                    &InvalidSelectKind::SelectAfterRange,
                    &token,
                    &[],
                ));
                return Err(ir_error!(token));
            }
            let base_value = x.select.expression.as_ref();
            let mut base = Conv::conv(context, base_value)?;
            check_select_type(context, &mut base, base_value);
            if let Some(x) = &x.select.select_opt {
                let op = Conv::conv(context, x.select_operator.as_ref())?;
                let mut bound = Conv::conv(context, x.expression.as_ref())?;
                check_select_type(context, &mut bound, &x.expression);
                check_part_select_width(context, &op, (&base, base_value), (&bound, &x.expression));
                end = Some((op, bound));
            }
            select.push(base);
            context.inc_select_dim();
        }
        context.select_paths.pop();
    }

    context.select_dims.pop();

    select.1 = end;

    Ok(VarPathSelect(path, select, token))
}

impl Conv<&Expression> for Vec<VarPathSelect> {
    fn conv(context: &mut Context, value: &Expression) -> IrResult<Self> {
        let mut ret = vec![];

        // An anonymous loop variable is also registered as `_`.
        if value.is_anonymous_expression() {
            return Ok(ret);
        }

        if let Some(x) = value.unwrap_factor() {
            match x {
                Factor::IdentifierFactor(x) => {
                    let x: VarPathSelect =
                        Conv::conv(context, x.identifier_factor.expression_identifier.as_ref())?;
                    ret.push(x);
                }
                Factor::LBraceConcatenationListRBrace(x) => {
                    let items: Vec<_> = x.concatenation_list.as_ref().into();
                    for item in items {
                        let mut x: Vec<VarPathSelect> =
                            Conv::conv(context, item.expression.as_ref())?;
                        ret.append(&mut x);
                    }
                }
                _ => (),
            }
        }

        Ok(ret)
    }
}