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
//! Semantic validation for instruction definitions.
//!
//! Validates a parsed definition for:
//! - Name uniqueness
//! - Type resolution
//! - Bit coverage completeness
//! - Pattern conflicts between instructions
use std::collections::{HashMap, HashSet};
use crate::error::{Error, ErrorKind, Span};
use crate::parser::dsl_to_hardware;
use crate::types::*;
/// Validate a decoder definition and convert to a validated IR.
///
/// This performs multiple checks and transformations:
/// - Converts bit ranges from DSL notation to hardware notation
/// - Checks for duplicate names
/// - Resolves field types
/// - Validates bit coverage and patterns
pub fn validate(def: &DecoderDef) -> Result<ValidatedDef, Vec<Error>> {
let mut errors = Vec::new();
// Phase 0: Convert all bit ranges from DSL notation to hardware notation
let instructions = convert_bit_ranges(def, &mut errors);
// Phase 1: Name uniqueness
check_name_uniqueness(&instructions, &def.type_aliases, &mut errors);
// Phase 2: Type resolution
resolve_types(&instructions, &def.type_aliases, &mut errors);
// Phase 3: Bit coverage
check_bit_coverage(&instructions, def.config.width, &mut errors);
// Phase 3b: Max units check (if configured)
if def.config.max_units.is_some() {
check_max_units(&instructions, &def.config, &mut errors);
}
// Phase 4: Pattern conflicts
check_pattern_conflicts(&instructions, &mut errors);
// Phase 5: Map validation
check_maps(&def.maps, &mut errors);
// Phase 6: Format validation
check_formats(&instructions, &def.maps, &mut errors);
if !errors.is_empty() {
return Err(errors);
}
// Build validated instructions
let validated_instructions = instructions
.into_iter()
.map(|instr| {
let resolved_fields = instr
.segments
.iter()
.filter_map(|seg| {
if let Segment::Field {
name,
field_type,
ranges,
..
} = seg
{
let resolved = resolve_field_type(field_type, &def.type_aliases);
Some(ResolvedField {
name: name.clone(),
ranges: ranges.clone(),
resolved_type: resolved,
})
} else {
None
}
})
.collect();
ValidatedInstruction {
name: instr.name.clone(),
segments: instr.segments.clone(),
resolved_fields,
format_lines: instr.format_lines.clone(),
span: instr.span.clone(),
}
})
.collect();
Ok(ValidatedDef {
imports: def.imports.clone(),
config: def.config.clone(),
type_aliases: def.type_aliases.clone(),
maps: def.maps.clone(),
instructions: validated_instructions,
})
}
/// Convert all DSL bit ranges to hardware (LSB=0) notation.
/// Now supports cross-unit fields by splitting them into multiple BitRange objects.
fn convert_bit_ranges(def: &DecoderDef, _errors: &mut Vec<Error>) -> Vec<InstructionDef> {
let width = def.config.width;
let order = def.config.bit_order;
def.instructions
.iter()
.map(|instr| {
let segments = instr
.segments
.iter()
.map(|seg| match seg {
Segment::Fixed {
ranges,
pattern,
span,
} => {
// Convert each DSL range to hardware notation
// Since ranges is already vec![range], we just need to convert it
let hw_ranges = dsl_to_hardware(ranges[0].start, ranges[0].end, width, order);
Segment::Fixed {
ranges: hw_ranges,
pattern: pattern.clone(),
span: span.clone(),
}
}
Segment::Field {
name,
field_type,
ranges,
span,
} => {
// Convert each DSL range to hardware notation
let hw_ranges = dsl_to_hardware(ranges[0].start, ranges[0].end, width, order);
Segment::Field {
name: name.clone(),
field_type: field_type.clone(),
ranges: hw_ranges,
span: span.clone(),
}
}
})
.collect();
InstructionDef {
name: instr.name.clone(),
segments,
format_lines: instr.format_lines.clone(),
span: instr.span.clone(),
}
})
.collect()
}
fn check_name_uniqueness(
instructions: &[InstructionDef],
type_aliases: &[TypeAlias],
errors: &mut Vec<Error>,
) {
let mut seen_instructions: HashMap<&str, &Span> = HashMap::new();
for instr in instructions {
if let Some(prev_span) = seen_instructions.get(instr.name.as_str()) {
errors.push(
Error::new(
ErrorKind::DuplicateInstructionName(instr.name.clone()),
instr.span.clone(),
)
.with_help(format!("first defined at line {}", prev_span.line)),
);
} else {
seen_instructions.insert(&instr.name, &instr.span);
}
}
let mut seen_types: HashMap<&str, &Span> = HashMap::new();
for ta in type_aliases {
if let Some(prev_span) = seen_types.get(ta.name.as_str()) {
errors.push(
Error::new(
ErrorKind::DuplicateTypeAlias(ta.name.clone()),
ta.span.clone(),
)
.with_help(format!("first defined at line {}", prev_span.line)),
);
} else {
seen_types.insert(&ta.name, &ta.span);
}
}
}
fn resolve_types(
instructions: &[InstructionDef],
type_aliases: &[TypeAlias],
errors: &mut Vec<Error>,
) {
let alias_names: HashSet<&str> = type_aliases.iter().map(|ta| ta.name.as_str()).collect();
for instr in instructions {
for seg in &instr.segments {
if let Segment::Field {
field_type, span, ..
} = seg
{
if let FieldType::Alias(alias_name) = field_type {
if !alias_names.contains(alias_name.as_str())
&& !is_builtin_type(alias_name)
{
errors.push(Error::new(
ErrorKind::UnresolvedType(alias_name.clone()),
span.clone(),
));
}
}
}
}
}
}
fn check_bit_coverage(
instructions: &[InstructionDef],
width: u32,
errors: &mut Vec<Error>,
) {
for instr in instructions {
// Group ranges by unit (flattening all segment ranges)
let mut units_map: HashMap<u32, Vec<BitRange>> = HashMap::new();
for seg in &instr.segments {
match seg {
Segment::Fixed { ranges, pattern, span, .. } => {
// Check pattern length matches total range width
let total_width: u32 = ranges.iter().map(|r| r.width()).sum();
if pattern.len() as u32 != total_width {
errors.push(Error::new(
ErrorKind::PatternLengthMismatch {
instruction: instr.name.clone(),
expected: total_width,
got: pattern.len() as u32,
},
span.clone(),
));
}
for range in ranges {
units_map.entry(range.unit).or_default().push(*range);
}
}
Segment::Field { ranges, .. } => {
for range in ranges {
units_map.entry(range.unit).or_default().push(*range);
}
}
};
}
// For unit 0: require full coverage
if let Some(unit0_ranges) = units_map.get(&0) {
let mut covered = vec![false; width as usize];
for range in unit0_ranges {
for bit in range.end..=range.start {
let idx = bit as usize;
if covered[idx] {
errors.push(Error::new(
ErrorKind::OverlappingBits {
instruction: instr.name.clone(),
bit,
},
instr.span.clone(),
));
}
covered[idx] = true;
}
}
let missing: Vec<u32> = covered
.iter()
.enumerate()
.filter(|&(_, c)| !c)
.map(|(i, _)| i as u32)
.collect();
if !missing.is_empty() {
errors.push(Error::new(
ErrorKind::BitCoverageGap {
instruction: instr.name.clone(),
missing_bits: missing,
},
instr.span.clone(),
));
}
}
// For units 1+: only check for overlaps, gaps are allowed
for (unit_idx, ranges) in &units_map {
if *unit_idx == 0 {
continue;
}
let mut covered = vec![false; width as usize];
for range in ranges {
for bit in range.end..=range.start {
let idx = bit as usize;
if covered[idx] {
errors.push(Error::new(
ErrorKind::OverlappingBits {
instruction: instr.name.clone(),
bit,
},
instr.span.clone(),
));
}
covered[idx] = true;
}
}
}
}
}
/// Check that instructions don't exceed the configured max_units limit.
fn check_max_units(
instructions: &[InstructionDef],
config: &DecoderConfig,
errors: &mut Vec<Error>,
) {
let max_units = config.max_units.expect("check_max_units called without max_units configured");
for instr in instructions {
// Find the maximum unit index across all segments
let max_unit = instr.segments
.iter()
.flat_map(|seg| match seg {
Segment::Fixed { ranges, .. } | Segment::Field { ranges, .. } => ranges.iter(),
})
.map(|range| range.unit)
.max()
.unwrap_or(0);
let required_units = max_unit + 1;
if required_units > max_units {
errors.push(Error::new(
ErrorKind::ExceedsMaxUnits {
instruction: instr.name.clone(),
required: required_units,
max_units,
},
instr.span.clone(),
).with_help(format!(
"set max_units = {} in the decoder block or remove max_units to allow any length",
required_units
)));
}
}
}
fn check_pattern_conflicts(instructions: &[InstructionDef], errors: &mut Vec<Error>) {
// O(n²) check: two instructions conflict if all their shared fixed bit positions
// have compatible (identical) values.
for i in 0..instructions.len() {
for j in (i + 1)..instructions.len() {
if patterns_conflict(&instructions[i], &instructions[j]) {
errors.push(Error::new(
ErrorKind::PatternConflict {
a: instructions[i].name.clone(),
b: instructions[j].name.clone(),
},
instructions[j].span.clone(),
));
}
}
}
}
/// Check if two instructions have conflicting fixed bit patterns.
/// A conflict occurs when both instructions have identical fixed bits at the same positions.
fn patterns_conflict(a: &InstructionDef, b: &InstructionDef) -> bool {
let a_fixed = fixed_bit_map(a);
let b_fixed = fixed_bit_map(b);
for (&bit, &a_val) in &a_fixed {
if let Some(&b_val) = b_fixed.get(&bit) {
if a_val != b_val {
return false;
}
}
}
if a_fixed.len() != b_fixed.len() {
return false;
}
true
}
fn fixed_bit_map(instr: &InstructionDef) -> HashMap<(u32, u32), Bit> {
let mut map = HashMap::new();
for seg in &instr.segments {
if let Segment::Fixed {
ranges, pattern, ..
} = seg
{
let mut bit_idx = 0;
for range in ranges {
for i in 0..range.width() as usize {
if bit_idx < pattern.len() {
let hw_bit = range.start - i as u32;
// Key is (unit, hw_bit) to avoid collisions between units
map.insert((range.unit, hw_bit), pattern[bit_idx]);
bit_idx += 1;
}
}
}
}
}
map
}
fn check_maps(maps: &[MapDef], errors: &mut Vec<Error>) {
let mut seen_names: HashMap<&str, &Span> = HashMap::new();
for map in maps {
// Duplicate map names
if let Some(prev) = seen_names.get(map.name.as_str()) {
errors.push(
Error::new(
ErrorKind::DuplicateMapName(map.name.clone()),
map.span.clone(),
)
.with_help(format!("first defined at line {}", prev.line)),
);
} else {
seen_names.insert(&map.name, &map.span);
}
// Check for duplicate entries (same key pattern)
let mut seen_keys: Vec<&Vec<MapKey>> = Vec::new();
for entry in &map.entries {
if seen_keys.iter().any(|k| *k == &entry.keys) {
errors.push(Error::new(
ErrorKind::DuplicateMapEntry {
map: map.name.clone(),
},
entry.span.clone(),
));
} else {
seen_keys.push(&entry.keys);
}
}
// Check param uniqueness within map
let mut seen_params: HashSet<&str> = HashSet::new();
for param in &map.params {
if !seen_params.insert(param.as_str()) {
errors.push(Error::new(
ErrorKind::InvalidFormatString(format!(
"duplicate parameter '{}' in map '{}'",
param, map.name
)),
map.span.clone(),
));
}
}
}
}
fn check_formats(
instructions: &[InstructionDef],
maps: &[MapDef],
errors: &mut Vec<Error>,
) {
let map_names: HashMap<&str, &MapDef> = maps.iter().map(|m| (m.name.as_str(), m)).collect();
for instr in instructions {
if instr.format_lines.is_empty() {
continue;
}
let field_names: HashSet<String> = instr
.segments
.iter()
.filter_map(|seg| {
if let Segment::Field { name, .. } = seg {
Some(name.clone())
} else {
None
}
})
.collect();
// Check guard ordering: all non-last format lines must have guards
for (i, fl) in instr.format_lines.iter().enumerate() {
if i < instr.format_lines.len() - 1 && fl.guard.is_none() {
errors.push(Error::new(
ErrorKind::UnguardedNonLastFormatLine {
instruction: instr.name.clone(),
},
fl.span.clone(),
));
}
// Check guard field references
if let Some(guard) = &fl.guard {
for cond in &guard.conditions {
check_guard_operand_field(&cond.left, &field_names, &instr.name, &fl.span, errors);
check_guard_operand_field(&cond.right, &field_names, &instr.name, &fl.span, errors);
}
}
// Check format string field references
for piece in &fl.pieces {
if let FormatPiece::FieldRef { expr, .. } = piece {
check_format_expr_fields(
expr,
&field_names,
&instr.name,
&fl.span,
&map_names,
errors,
);
}
}
}
}
}
fn check_guard_operand_field(
operand: &GuardOperand,
field_names: &HashSet<String>,
instr_name: &str,
span: &Span,
errors: &mut Vec<Error>,
) {
match operand {
GuardOperand::Field(name) => {
if !field_names.contains(name.as_str()) {
errors.push(Error::new(
ErrorKind::UndefinedFieldInGuard {
instruction: instr_name.to_string(),
field: name.clone(),
},
span.clone(),
));
}
}
GuardOperand::Expr { left, right, .. } => {
check_guard_operand_field(left, field_names, instr_name, span, errors);
check_guard_operand_field(right, field_names, instr_name, span, errors);
}
GuardOperand::Literal(_) => {}
}
}
fn check_format_expr_fields(
expr: &FormatExpr,
field_names: &HashSet<String>,
instr_name: &str,
span: &Span,
maps: &HashMap<&str, &MapDef>,
errors: &mut Vec<Error>,
) {
match expr {
FormatExpr::Field(name) => {
if !field_names.contains(name.as_str()) {
errors.push(Error::new(
ErrorKind::UndefinedFieldInFormat {
instruction: instr_name.to_string(),
field: name.clone(),
},
span.clone(),
));
}
}
FormatExpr::Ternary { field, .. } => {
if !field_names.contains(field.as_str()) {
errors.push(Error::new(
ErrorKind::UndefinedFieldInFormat {
instruction: instr_name.to_string(),
field: field.clone(),
},
span.clone(),
));
}
}
FormatExpr::Arithmetic { left, right, .. } => {
check_format_expr_fields(left, field_names, instr_name, span, maps, errors);
check_format_expr_fields(right, field_names, instr_name, span, maps, errors);
}
FormatExpr::IntLiteral(_) => {}
FormatExpr::MapCall {
map_name, args, ..
} => {
if let Some(map_def) = maps.get(map_name.as_str()) {
if args.len() != map_def.params.len() {
errors.push(Error::new(
ErrorKind::MapArgCountMismatch {
map: map_name.clone(),
expected: map_def.params.len(),
got: args.len(),
},
span.clone(),
));
}
} else {
errors.push(Error::new(
ErrorKind::UndefinedMap(map_name.clone()),
span.clone(),
));
}
for arg in args {
check_format_expr_fields(arg, field_names, instr_name, span, maps, errors);
}
}
FormatExpr::BuiltinCall { args, .. } => {
// Builtins are already validated during parsing
for arg in args {
check_format_expr_fields(arg, field_names, instr_name, span, maps, errors);
}
}
}
}
fn resolve_field_type(field_type: &FieldType, type_aliases: &[TypeAlias]) -> ResolvedFieldType {
match field_type {
FieldType::Alias(name) => {
if let Some(alias) = type_aliases.iter().find(|ta| ta.name == *name) {
ResolvedFieldType {
base_type: alias.base_type.clone(),
wrapper_type: alias.wrapper_type.clone(),
transforms: alias.transforms.clone(),
display_format: alias.display_format,
}
} else {
// Built-in type used as alias
ResolvedFieldType {
base_type: resolve_builtin(name),
wrapper_type: None,
transforms: Vec::new(),
display_format: None,
}
}
}
FieldType::Inline {
base_type,
transforms,
} => ResolvedFieldType {
base_type: resolve_builtin(base_type),
wrapper_type: None,
transforms: transforms.clone(),
display_format: None,
},
}
}
fn is_builtin_type(name: &str) -> bool {
matches!(
name,
"u1" | "u2" | "u3" | "u4" | "u5" | "u6" | "u7" | "u8" | "u16" | "u32" | "i8" | "i16" | "i32" | "bool"
)
}
fn resolve_builtin(name: &str) -> String {
match name {
"u1" | "u2" | "u3" | "u4" | "u5" | "u6" | "u7" => "u8".to_string(),
"bool" => "bool".to_string(),
other => other.to_string(),
}
}