Skip to content

Commit 260d6ff

Browse files
committed
Add computed contexts
This was requested on the issue tracker and the answer was "do it yourself" so here I go doing it myself!
1 parent d83a900 commit 260d6ff

2 files changed

Lines changed: 15 additions & 5 deletions

File tree

src/parse/error.rs

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,9 @@ impl std::fmt::Display for MBusError {
6262
let mut level = 0;
6363
for context in ctx.context() {
6464
match context {
65-
MBusContext::Label(_) | MBusContext::Assertion(_) => {
65+
MBusContext::Label(_)
66+
| MBusContext::ComputedLabel(_)
67+
| MBusContext::Assertion(_) => {
6668
if first {
6769
first = false;
6870
} else {
@@ -138,6 +140,8 @@ impl ErrorConvert<MBusError> for ContextError<MBusContext> {
138140
pub enum MBusContext {
139141
/// Description of what is currently being parsed
140142
Label(&'static str),
143+
/// Computed description of what is currently being parsed
144+
ComputedLabel(String),
141145
/// Grammar item that was expected
142146
Expected(StrContextValue),
143147
/// Failed assertion
@@ -148,6 +152,7 @@ impl std::fmt::Display for MBusContext {
148152
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
149153
match self {
150154
Self::Label(name) => write!(f, "invalid {name}"),
155+
Self::ComputedLabel(name) => write!(f, "invalid {name}"),
151156
Self::Expected(value) => write!(f, "expected {value}"),
152157
Self::Assertion(text) => write!(f, "assertion failed: {text}"),
153158
}

src/parse/types/number.rs

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ use winnow::prelude::*;
88
use winnow::token::take;
99
use winnow::Bytes;
1010

11-
use crate::parse::error::{MBResult, MBusError};
11+
use crate::parse::error::{MBResult, MBusContext, MBusError};
1212

1313
use super::BitsInput;
1414

@@ -62,7 +62,12 @@ pub fn parse_bcd<'a>(bytes: usize) -> impl Parser<&'a Bytes, i64, MBusError> {
6262

6363
(peek(take(bytes)).void(), binary::bits::bits(parser))
6464
.map(|(_, n)| n)
65-
.context(StrContext::Label("signed BCD number"))
65+
.context_with(move || {
66+
[MBusContext::ComputedLabel(format!(
67+
"signed {bytes} byte BCD number"
68+
))]
69+
.into_iter()
70+
})
6671
}
6772

6873
#[cfg(test)]
@@ -161,7 +166,7 @@ mod test_parse_bcd {
161166

162167
let ctx = result.inner().context().next().unwrap().to_string();
163168

164-
assert_eq!(ctx, "invalid signed BCD number");
169+
assert_eq!(ctx, "invalid signed 3 byte BCD number");
165170
}
166171

167172
#[test]
@@ -172,7 +177,7 @@ mod test_parse_bcd {
172177

173178
let ctx = result.inner().context().next().unwrap().to_string();
174179

175-
assert_eq!(ctx, "invalid signed BCD number");
180+
assert_eq!(ctx, "invalid signed 2 byte BCD number");
176181
}
177182

178183
#[test]

0 commit comments

Comments
 (0)