Skip to main content

defmt_parser/
lib.rs

1//! Parsing library for [`defmt`] format strings.
2//!
3//! This is an implementation detail of [`defmt`] and not meant to be consumed by other tools at the
4//! moment so all the API is unstable.
5//!
6//! [`defmt`]: https://github.com/knurling-rs/defmt
7
8#![cfg_attr(docsrs, feature(doc_cfg))]
9#![doc(html_logo_url = "https://knurling.ferrous-systems.com/knurling_logo_light_text.svg")]
10
11mod display_hint;
12#[cfg(test)]
13mod tests;
14mod types;
15
16use std::{borrow::Cow, ops::Range};
17
18pub use crate::{
19    display_hint::{DisplayHint, TimePrecision},
20    types::Type,
21};
22
23/// The kinds of error this library can return
24#[derive(thiserror::Error, Debug, PartialEq, Eq, Clone)]
25pub enum Error {
26    #[error("invalid type specifier `{0:?}`")]
27    InvalidTypeSpecifier(String),
28    #[error("unable to parse given integer")]
29    InvalidInteger(#[from] std::num::ParseIntError),
30    #[error("invalid array specifier (missing length)")]
31    InvalidArraySpecifierMissingLength,
32    #[error("invalid array specifier (missing `]`")]
33    InvalidArraySpecifierMissingBracket,
34    #[error("trailing data after bitfield range")]
35    TrailingDataAfterBitfieldRange,
36    #[error("malformed format string (missing display hint after ':')")]
37    MalformedFormatString,
38    #[error("unknown display hint: {0:?}")]
39    UnknownDisplayHint(String),
40    #[error("unexpected content `{0:?}` in format string")]
41    UnexpectedContentInFormatString(String),
42    #[error("unmatched `{{` in format string")]
43    UnmatchedOpenBracket,
44    #[error("unmatched `}}` in format string")]
45    UnmatchedCloseBracket,
46    #[error("conflicting types for argument {0}: used as {1:?} and {2:?}")]
47    ConflictingTypes(usize, Type, Type),
48    #[error("argument {0} is not used in this format string")]
49    UnusedArgument(usize),
50}
51
52/// A format string that a future release will reject.
53///
54/// This is *not* a part of the public API.
55#[doc(hidden)]
56#[derive(thiserror::Error, Debug, PartialEq, Eq, Clone)]
57#[non_exhaustive]
58pub enum Warning {
59    #[error("unmatched `{{` in format string, escape it as `{{{{`: this will be an error in a future release")]
60    UnmatchedOpenBracket,
61    #[error("unmatched `}}` in format string, escape it as `}}}}`: this will be an error in a future release")]
62    UnmatchedCloseBracket,
63}
64
65/// A parameter of the form `{{0=Type:hint}}` in a format string.
66#[derive(Clone, Debug, Eq, PartialEq)]
67pub struct Parameter {
68    /// The argument index to display at this position.
69    pub index: usize,
70    /// The type of the argument to display, e.g. '=u8', '=bool'.
71    pub ty: Type,
72    /// The display hint, e.g. ':x', ':b', ':a'.
73    pub hint: Option<DisplayHint>,
74}
75
76/// A part of a format string.
77#[derive(Clone, Debug, Eq, PartialEq)]
78pub enum Fragment<'f> {
79    /// A literal string (eg. `"literal "` in `"literal {:?}"`).
80    Literal(Cow<'f, str>),
81
82    /// A format parameter.
83    Parameter(Parameter),
84}
85
86/// A parsed formatting parameter (contents of `{` `}` block).
87///
88/// # Syntax
89///
90/// ```notrust
91/// param := '{' [ argument ] [ '=' argtype ] [ ':' format_spec ] '}'
92/// argument := integer
93///
94/// argtype := bitfield | '?' | format-array | '[?]' | byte-array | '[u8]' | 'istr' | 'str' |
95///     'bool' | 'char' | 'u8' | 'u16' | 'u32' | 'u64' | 'u128' | 'usize' | 'i8' | 'i16' | 'i32' |
96///     'i64' | 'i128 | 'isize' | 'f32' | 'f64'
97/// bitfield := integer '..' integer
98/// format-array := '[?;' spaces integer ']'
99/// byte-array := '[u8;' spaces integer ']'
100/// spaces := ' '*
101///
102/// format_spec := [ zero_pad ] type
103/// zero_pad := '0' integer
104/// type := 'a' | 'b' | 'o' | 'x' | 'X' | '?' | 'us'
105/// ```
106#[derive(Debug, PartialEq)]
107struct Param {
108    index: Option<usize>,
109    ty: Type,
110    hint: Option<DisplayHint>,
111}
112
113/// The log level
114#[derive(Clone, Copy, Debug, Eq, PartialEq, PartialOrd)]
115pub enum Level {
116    Trace,
117    Debug,
118    Info,
119    Warn,
120    Error,
121}
122
123impl Level {
124    pub fn as_str(self) -> &'static str {
125        match self {
126            Level::Trace => "trace",
127            Level::Debug => "debug",
128            Level::Info => "info",
129            Level::Warn => "warn",
130            Level::Error => "error",
131        }
132    }
133}
134
135fn parse_range(mut s: &str) -> Option<(Range<u8>, usize /* consumed */)> {
136    // consume first number
137    let start_digits = s
138        .as_bytes()
139        .iter()
140        .take_while(|b| (**b as char).is_ascii_digit())
141        .count();
142    let start = s[..start_digits].parse().ok()?;
143
144    // next two `char`s should be `..`
145    if s.get(start_digits..start_digits + 2) != Some("..") {
146        return None;
147    }
148    s = &s[start_digits + 2..];
149
150    // consume second number
151    let end_digits = s
152        .as_bytes()
153        .iter()
154        .take_while(|b| (**b as char).is_ascii_digit())
155        .count();
156    let end = s[..end_digits].parse().ok()?;
157
158    // check for faulty state
159    if end <= start || start >= 128 || end > 128 {
160        return None;
161    }
162
163    Some((start..end, start_digits + end_digits + 2))
164}
165
166/// Parse and consume an array at the beginning of `s`.
167///
168/// Return the length of the array.
169fn parse_array(mut s: &str) -> Result<usize, Error> {
170    // skip spaces
171    let len_pos = s
172        .find(|c: char| c != ' ')
173        .ok_or(Error::InvalidArraySpecifierMissingLength)?;
174    s = &s[len_pos..];
175
176    // consume length
177    let after_len = s
178        .find(|c: char| !c.is_ascii_digit())
179        .ok_or(Error::InvalidArraySpecifierMissingBracket)?;
180    let len = s[..after_len].parse::<usize>()?;
181    s = &s[after_len..];
182
183    // consume final `]`
184    if s != "]" {
185        return Err(Error::InvalidArraySpecifierMissingBracket);
186    }
187
188    Ok(len)
189}
190
191/// Parser mode
192#[derive(Clone, Copy, Debug, Eq, PartialEq)]
193pub enum ParserMode {
194    /// Rejects unknown display hints
195    Strict,
196    /// Accepts unknown display hints
197    ForwardsCompatible,
198}
199
200/// Parse `Param` from `&str`
201///
202/// * example `input`: `0=Type:hint` (note: no curly braces)
203fn parse_param(mut input: &str, mode: ParserMode) -> Result<Param, Error> {
204    const TYPE_PREFIX: &str = "=";
205    const HINT_PREFIX: &str = ":";
206
207    // First, optional argument index.
208    let mut index = None;
209    let index_end = input
210        .find(|c: char| !c.is_ascii_digit())
211        .unwrap_or(input.len());
212
213    if index_end != 0 {
214        index = Some(input[..index_end].parse::<usize>()?);
215    }
216
217    // Then, optional type
218    let mut ty = Type::default(); // when no explicit type; use the default one
219    input = &input[index_end..];
220
221    if input.starts_with(TYPE_PREFIX) {
222        // skip the prefix
223        input = &input[TYPE_PREFIX.len()..];
224
225        // type is delimited by `HINT_PREFIX` or end-of-string
226        let type_end = input.find(HINT_PREFIX).unwrap_or(input.len());
227        let type_fragment = &input[..type_end];
228
229        const FORMAT_ARRAY_START: &str = "[?;";
230        const U8_ARRAY_START: &str = "[u8;";
231
232        // what comes next is the type
233        ty = if let Ok(ty) = type_fragment.parse() {
234            Ok(ty)
235        } else if let Some(s) = type_fragment.strip_prefix(U8_ARRAY_START) {
236            Ok(Type::U8Array(parse_array(s)?))
237        } else if let Some(s) = type_fragment.strip_prefix(FORMAT_ARRAY_START) {
238            Ok(Type::FormatArray(parse_array(s)?))
239        } else if let Some((range, used)) = parse_range(type_fragment) {
240            // Check for bitfield syntax.
241            match used != type_fragment.len() {
242                true => Err(Error::TrailingDataAfterBitfieldRange),
243                false => Ok(Type::BitField(range)),
244            }
245        } else {
246            Err(Error::InvalidTypeSpecifier(input.to_owned()))
247        }?;
248
249        input = &input[type_end..];
250    }
251
252    // Then, optional hint
253    let mut hint = None;
254
255    if input.starts_with(HINT_PREFIX) {
256        // skip the prefix
257        input = &input[HINT_PREFIX.len()..];
258        if input.is_empty() {
259            return Err(Error::MalformedFormatString);
260        }
261
262        hint = match (DisplayHint::parse(input), mode) {
263            (Some(a), _) => Some(a),
264            (None, ParserMode::Strict) => return Err(Error::UnknownDisplayHint(input.to_owned())),
265            (None, ParserMode::ForwardsCompatible) => Some(DisplayHint::Unknown(input.to_owned())),
266        };
267    } else if !input.is_empty() {
268        return Err(Error::UnexpectedContentInFormatString(input.to_owned()));
269    }
270
271    Ok(Param { index, ty, hint })
272}
273
274/// Rejects a brace that is not doubled, matching what `format!` accepts.
275fn check_braces_by_pairing(unescaped_literal: &str) -> Result<(), Warning> {
276    let mut chars = unescaped_literal.chars().peekable();
277    while let Some(c) = chars.next() {
278        if (c == '{' || c == '}') && chars.next_if_eq(&c).is_none() {
279            return Err(if c == '{' {
280                Warning::UnmatchedOpenBracket
281            } else {
282                Warning::UnmatchedCloseBracket
283            });
284        }
285    }
286
287    Ok(())
288}
289
290/// Rejects a brace kind whose count is odd at a plain character or at the end.
291fn check_braces_by_parity(unescaped_literal: &str) -> Result<(), Error> {
292    let mut last_open = false;
293    let mut last_close = false;
294    for c in unescaped_literal.chars() {
295        match c {
296            '{' => last_open = !last_open,
297            '}' => last_close = !last_close,
298            _ if last_open => return Err(Error::UnmatchedOpenBracket),
299            _ if last_close => return Err(Error::UnmatchedCloseBracket),
300            _ => {}
301        }
302    }
303
304    // Handle trailing unescaped `{` or `}`.
305    if last_open {
306        return Err(Error::UnmatchedOpenBracket);
307    } else if last_close {
308        return Err(Error::UnmatchedCloseBracket);
309    }
310
311    Ok(())
312}
313
314fn push_literal<'f>(
315    frag: &mut Vec<Fragment<'f>>,
316    unescaped_literal: &'f str,
317    warnings: &mut Vec<Warning>,
318) -> Result<(), Error> {
319    // Replace `{{` with `{` and `}}` with `}`. Single braces are errors.
320
321    // Parity is what this parser has always shipped and accepts strings pairing rejects, such
322    // as `}{{}`. Rejecting those outright would break code that compiles today, so parity keeps
323    // deciding and pairing only warns until a future release swaps them.
324    check_braces_by_parity(unescaped_literal)?;
325    if let Err(warning) = check_braces_by_pairing(unescaped_literal) {
326        if !warnings.contains(&warning) {
327            warnings.push(warning);
328        }
329    }
330
331    // FIXME: This always allocates a `String`, so the `Cow` is useless.
332    let literal = unescaped_literal.replace("{{", "{").replace("}}", "}");
333    frag.push(Fragment::Literal(literal.into()));
334    Ok(())
335}
336
337/// Returns `Some(smallest_bit_index, largest_bit_index)` contained in `params` if
338/// `params` contains any bitfields. Otherwise `None`.
339pub fn get_max_bitfield_range<'a, I>(params: I) -> Option<(u8, u8)>
340where
341    I: Iterator<Item = &'a Parameter> + Clone,
342{
343    let largest_bit_index = params
344        .clone()
345        .map(|param| match &param.ty {
346            Type::BitField(range) => range.end,
347            _ => unreachable!(),
348        })
349        .max();
350
351    let smallest_bit_index = params
352        .map(|param| match &param.ty {
353            Type::BitField(range) => range.start,
354            _ => unreachable!(),
355        })
356        .min();
357
358    match (smallest_bit_index, largest_bit_index) {
359        (Some(smallest), Some(largest)) => Some((smallest, largest)),
360        (None, None) => None,
361        _ => unreachable!(),
362    }
363}
364
365pub fn parse(format_string: &str, mode: ParserMode) -> Result<Vec<Fragment<'_>>, Error> {
366    parse_with_warnings(format_string, mode).map(|(fragments, _warnings)| fragments)
367}
368
369/// Same as [`parse`], additionally reporting each warning once.
370///
371/// This is *not* a part of the public API.
372#[doc(hidden)]
373pub fn parse_with_warnings(
374    format_string: &str,
375    mode: ParserMode,
376) -> Result<(Vec<Fragment<'_>>, Vec<Warning>), Error> {
377    let mut fragments = Vec::new();
378    let mut warnings = Vec::new();
379
380    // Index after the `}` of the last format specifier.
381    let mut end_pos = 0;
382
383    // Next argument index assigned to a parameter without an explicit one.
384    let mut next_arg_index = 0;
385
386    let mut chars = format_string.char_indices();
387    while let Some((brace_pos, ch)) = chars.next() {
388        if ch != '{' {
389            // Part of a literal fragment.
390            continue;
391        }
392
393        // Peek at the next char.
394        if chars.as_str().starts_with('{') {
395            // Escaped `{{`, also part of a literal fragment.
396            chars.next(); // Move after both `{`s.
397            continue;
398        }
399
400        if brace_pos > end_pos {
401            // There's a literal fragment with at least 1 character before this parameter fragment.
402            let unescaped_literal = &format_string[end_pos..brace_pos];
403            push_literal(&mut fragments, unescaped_literal, &mut warnings)?;
404        }
405
406        // Else, this is a format specifier. It ends at the next `}`.
407        let len = chars
408            .as_str()
409            .find('}')
410            .ok_or(Error::UnmatchedOpenBracket)?;
411        end_pos = brace_pos + 1 + len + 1;
412
413        // Parse the contents inside the braces.
414        let param_str = &format_string[brace_pos + 1..][..len];
415        let param = parse_param(param_str, mode)?;
416        fragments.push(Fragment::Parameter(Parameter {
417            index: param.index.unwrap_or_else(|| {
418                // If there is no explicit index, assign the next one.
419                let idx = next_arg_index;
420                next_arg_index += 1;
421                idx
422            }),
423            ty: param.ty,
424            hint: param.hint,
425        }));
426    }
427
428    // Trailing literal.
429    if end_pos != format_string.len() {
430        push_literal(&mut fragments, &format_string[end_pos..], &mut warnings)?;
431    }
432
433    // Check for argument type conflicts.
434    let mut args = Vec::new();
435    for frag in &fragments {
436        if let Fragment::Parameter(Parameter { index, ty, .. }) = frag {
437            if args.len() <= *index {
438                args.resize(*index + 1, None);
439            }
440
441            match &args[*index] {
442                None => args[*index] = Some(ty.clone()),
443                Some(other_ty) => match (other_ty, ty) {
444                    (Type::BitField(_), Type::BitField(_)) => {} // FIXME: Bitfield range shouldn't be part of the type.
445                    (a, b) if a != b => {
446                        return Err(Error::ConflictingTypes(*index, a.clone(), b.clone()))
447                    }
448                    _ => {}
449                },
450            }
451        }
452    }
453
454    // Check that argument indices are dense (all arguments must be used).
455    for (index, arg) in args.iter().enumerate() {
456        if arg.is_none() {
457            return Err(Error::UnusedArgument(index));
458        }
459    }
460
461    Ok((fragments, warnings))
462}