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
//! Error types and reporting for parsing and validation.
use std::fmt;
/// Source location information for error reporting.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Span {
pub file: String,
pub line: usize,
pub col: usize,
pub len: usize,
}
impl Span {
/// Create a new span with file and position information.
pub fn new(file: &str, line: usize, col: usize, len: usize) -> Self {
Span {
file: file.to_string(),
line,
col,
len,
}
}
}
/// Kinds of errors that can occur during parsing and validation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ErrorKind {
// Lexer errors
/// Unexpected character in input
UnexpectedChar(char),
// Parser errors
/// Unexpected token
UnexpectedToken(String),
/// Invalid bit pattern syntax
InvalidBitPattern(String),
/// Expected token missing
ExpectedToken(String),
/// Invalid bit range specification
InvalidRange,
/// Invalid decoder width value
InvalidWidth(u32),
/// Missing decoder block in definition
MissingDecoderBlock,
// Validation errors
/// Two instructions have the same name
DuplicateInstructionName(String),
/// Two type aliases have the same name
DuplicateTypeAlias(String),
/// Instruction doesn't specify bits for all positions
BitCoverageGap {
instruction: String,
missing_bits: Vec<u32>,
},
/// Instruction specifies overlapping bits
OverlappingBits {
instruction: String,
bit: u32,
},
/// Field references an undefined type
UnresolvedType(String),
/// Two instructions have the same fixed bit pattern
PatternConflict {
a: String,
b: String,
},
/// Fixed bit pattern length doesn't match range width
PatternLengthMismatch {
instruction: String,
expected: u32,
got: u32,
},
/// An import statement is unused
UnusedImport(String),
// Format/map errors
/// Invalid format string syntax
InvalidFormatString(String),
/// Invalid guard condition syntax
InvalidGuard(String),
/// Format string references undefined field
UndefinedFieldInFormat { instruction: String, field: String },
/// Guard references undefined field
UndefinedFieldInGuard { instruction: String, field: String },
/// Map call references undefined map
UndefinedMap(String),
/// Map call has wrong number of arguments
MapArgCountMismatch { map: String, expected: usize, got: usize },
/// Duplicate entry in a map
DuplicateMapEntry { map: String },
/// Duplicate map name
DuplicateMapName(String),
/// Non-last format line without a guard condition
UnguardedNonLastFormatLine { instruction: String },
/// Unknown builtin function name
UnknownBuiltinFunction(String),
// Variable-length instruction errors
/// A bit range spans across unit boundaries
CrossUnitBoundary {
instruction: String,
range_start: u32,
range_end: u32,
width: u32,
},
/// Instruction requires more units than max_units allows
ExceedsMaxUnits {
instruction: String,
required: u32,
max_units: u32,
},
}
/// An error with location and optional help text.
#[derive(Debug, Clone)]
pub struct Error {
pub kind: ErrorKind,
pub span: Span,
pub help: Option<String>,
}
impl Error {
/// Create a new error with a kind and span.
pub fn new(kind: ErrorKind, span: Span) -> Self {
Error {
kind,
span,
help: None,
}
}
/// Add a help message to the error.
pub fn with_help(mut self, help: impl Into<String>) -> Self {
self.help = Some(help.into());
self
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let msg = match &self.kind {
ErrorKind::UnexpectedChar(c) => format!("unexpected character '{}'", c),
ErrorKind::UnexpectedToken(t) => format!("unexpected token '{}'", t),
ErrorKind::InvalidBitPattern(p) => format!("invalid bit pattern '{}'", p),
ErrorKind::ExpectedToken(t) => format!("expected {}", t),
ErrorKind::InvalidRange => "invalid bit range".to_string(),
ErrorKind::InvalidWidth(w) => format!("invalid decoder width: {}", w),
ErrorKind::MissingDecoderBlock => "missing decoder block".to_string(),
ErrorKind::DuplicateInstructionName(n) => {
format!("duplicate instruction name '{}'", n)
}
ErrorKind::DuplicateTypeAlias(n) => format!("duplicate type alias '{}'", n),
ErrorKind::BitCoverageGap {
instruction,
missing_bits,
} => {
format!(
"instruction '{}' has uncovered bits: {:?}",
instruction, missing_bits
)
}
ErrorKind::OverlappingBits { instruction, bit } => {
format!(
"instruction '{}' has overlapping coverage at bit {}",
instruction, bit
)
}
ErrorKind::UnresolvedType(t) => format!("unresolved type '{}'", t),
ErrorKind::PatternConflict { a, b } => {
format!(
"instructions '{}' and '{}' have conflicting fixed bit patterns",
a, b
)
}
ErrorKind::PatternLengthMismatch {
instruction,
expected,
got,
} => {
format!(
"instruction '{}': fixed pattern length {} doesn't match range width {}",
instruction, got, expected
)
}
ErrorKind::UnusedImport(path) => format!("unused import '{}'", path),
ErrorKind::InvalidFormatString(msg) => format!("invalid format string: {}", msg),
ErrorKind::InvalidGuard(msg) => format!("invalid guard condition: {}", msg),
ErrorKind::UndefinedFieldInFormat { instruction, field } => {
format!(
"format string in '{}' references undefined field '{}'",
instruction, field
)
}
ErrorKind::UndefinedFieldInGuard { instruction, field } => {
format!(
"guard in '{}' references undefined field '{}'",
instruction, field
)
}
ErrorKind::UndefinedMap(name) => format!("undefined map '{}'", name),
ErrorKind::MapArgCountMismatch { map, expected, got } => {
format!(
"map '{}' expects {} arguments but got {}",
map, expected, got
)
}
ErrorKind::DuplicateMapEntry { map } => {
format!("duplicate entry in map '{}'", map)
}
ErrorKind::DuplicateMapName(name) => format!("duplicate map name '{}'", name),
ErrorKind::UnguardedNonLastFormatLine { instruction } => {
format!(
"non-last format line in '{}' must have a guard condition",
instruction
)
}
ErrorKind::UnknownBuiltinFunction(name) => {
format!("unknown builtin function '{}'", name)
}
ErrorKind::CrossUnitBoundary {
instruction,
range_start,
range_end,
width,
} => {
format!(
"instruction '{}': bit range [{}:{}] spans across unit boundary (width={})",
instruction, range_start, range_end, width
)
}
ErrorKind::ExceedsMaxUnits {
instruction,
required,
max_units,
} => {
format!(
"instruction '{}' requires {} units but decoder max_units is {}",
instruction, required, max_units
)
}
};
write!(f, "error: {}", msg)?;
write!(
f,
"\n --> {}:{}",
self.span.file, self.span.line
)?;
if let Some(help) = &self.help {
write!(f, "\n = help: {}", help)?;
}
Ok(())
}
}
impl std::error::Error for Error {}
/// Multiple errors collected from parsing or validation.
#[derive(Debug)]
pub struct Errors(pub Vec<Error>);
impl fmt::Display for Errors {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
for (i, err) in self.0.iter().enumerate() {
if i > 0 {
writeln!(f)?;
}
write!(f, "{}", err)?;
}
Ok(())
}
}
impl std::error::Error for Errors {}