gix_config/parse/nom/
mod.rs

1use std::borrow::Cow;
2
3use bstr::{BStr, ByteSlice};
4use winnow::{
5    combinator::{alt, delimited, opt, preceded, repeat},
6    error::{ErrMode, InputError as NomError, ParserError as _},
7    prelude::*,
8    stream::Offset as _,
9    token::{one_of, take_till, take_while},
10};
11
12use crate::parse::{error::ParseNode, section, Comment, Error, Event};
13
14/// Attempt to zero-copy parse the provided bytes, passing results to `dispatch`.
15pub fn from_bytes<'i>(mut input: &'i [u8], dispatch: &mut dyn FnMut(Event<'i>)) -> Result<(), Error> {
16    let start = input.checkpoint();
17
18    let bom = unicode_bom::Bom::from(input);
19    input.next_slice(bom.len());
20
21    repeat(
22        0..,
23        alt((
24            comment.map(Event::Comment),
25            take_spaces1.map(|whitespace| Event::Whitespace(Cow::Borrowed(whitespace))),
26            |i: &mut &'i [u8]| {
27                let newline = take_newlines1.parse_next(i)?;
28                let o = Event::Newline(Cow::Borrowed(newline));
29                Ok(o)
30            },
31        )),
32    )
33    .fold(|| (), |_acc, event| dispatch(event))
34    .parse_next(&mut input)
35    // I don't think this can panic. many0 errors if the child parser returns
36    // a success where the input was not consumed, but alt will only return Ok
37    // if one of its children succeed. However, all of it's children are
38    // guaranteed to consume something if they succeed, so the Ok(i) == i case
39    // can never occur.
40    .expect("many0(alt(...)) panicked. Likely a bug in one of the children parsers.");
41
42    if input.is_empty() {
43        return Ok(());
44    }
45
46    let mut node = ParseNode::SectionHeader;
47
48    let res = repeat(1.., |i: &mut &'i [u8]| section(i, &mut node, dispatch))
49        .map(|()| ())
50        .parse_next(&mut input);
51    res.map_err(|_| {
52        let newlines = newlines_from(input, start);
53        Error {
54            line_number: newlines,
55            last_attempted_parser: node,
56            parsed_until: input.as_bstr().into(),
57        }
58    })?;
59
60    // This needs to happen after we collect sections, otherwise the line number
61    // will be off.
62    if !input.is_empty() {
63        let newlines = newlines_from(input, start);
64        return Err(Error {
65            line_number: newlines,
66            last_attempted_parser: node,
67            parsed_until: input.as_bstr().into(),
68        });
69    }
70
71    Ok(())
72}
73
74fn newlines_from(input: &[u8], start: winnow::stream::Checkpoint<&[u8], &[u8]>) -> usize {
75    let offset = input.offset_from(&start);
76    let mut start_input = input;
77    start_input.reset(&start);
78    start_input.next_slice(offset).iter().filter(|c| **c == b'\n').count()
79}
80
81fn comment<'i>(i: &mut &'i [u8]) -> ModalResult<Comment<'i>, NomError<&'i [u8]>> {
82    (
83        one_of([';', '#']),
84        take_till(0.., |c| c == b'\n').map(|text: &[u8]| Cow::Borrowed(text.as_bstr())),
85    )
86        .map(|(tag, text)| Comment { tag, text })
87        .parse_next(i)
88}
89
90#[cfg(test)]
91mod tests;
92
93fn section<'i>(
94    i: &mut &'i [u8],
95    node: &mut ParseNode,
96    dispatch: &mut dyn FnMut(Event<'i>),
97) -> ModalResult<(), NomError<&'i [u8]>> {
98    let start = i.checkpoint();
99    let header = section_header(i).map_err(|e| {
100        i.reset(&start);
101        e
102    })?;
103    dispatch(Event::SectionHeader(header));
104
105    // This would usually be a many0(alt(...)), the manual loop allows us to
106    // optimize vec insertions
107    loop {
108        let start = i.checkpoint();
109
110        if let Some(v) = opt(take_spaces1).parse_next(i)? {
111            dispatch(Event::Whitespace(Cow::Borrowed(v.as_bstr())));
112        }
113
114        if let Some(v) = opt(take_newlines1).parse_next(i)? {
115            dispatch(Event::Newline(Cow::Borrowed(v.as_bstr())));
116        }
117
118        key_value_pair(i, node, dispatch)?;
119
120        if let Some(comment) = opt(comment).parse_next(i)? {
121            dispatch(Event::Comment(comment));
122        }
123
124        if i.offset_from(&start) == 0 {
125            break;
126        }
127    }
128
129    Ok(())
130}
131
132fn section_header<'i>(i: &mut &'i [u8]) -> ModalResult<section::Header<'i>, NomError<&'i [u8]>> {
133    // No spaces must be between section name and section start
134    let name = preceded('[', take_while(1.., is_section_char).map(bstr::ByteSlice::as_bstr)).parse_next(i)?;
135
136    if opt(one_of::<_, _, ErrMode<NomError<&[u8]>>>(']'))
137        .parse_next(i)?
138        .is_some()
139    {
140        // Either section does not have a subsection or using deprecated
141        // subsection syntax at this point.
142        let header = match memchr::memrchr(b'.', name.as_bytes()) {
143            Some(index) => section::Header {
144                name: section::Name(Cow::Borrowed(name[..index].as_bstr())),
145                separator: name.get(index..=index).map(|s| Cow::Borrowed(s.as_bstr())),
146                subsection_name: name.get(index + 1..).map(|s| Cow::Borrowed(s.as_bstr())),
147            },
148            None => section::Header {
149                name: section::Name(Cow::Borrowed(name.as_bstr())),
150                separator: None,
151                subsection_name: None,
152            },
153        };
154
155        if header.name.is_empty() {
156            return Err(winnow::error::ErrMode::from_input(i));
157        }
158        return Ok(header);
159    }
160
161    // Section header must be using modern subsection syntax at this point.
162    (take_spaces1, delimited('"', opt(sub_section), "\"]"))
163        .map(|(whitespace, subsection_name)| section::Header {
164            name: section::Name(Cow::Borrowed(name)),
165            separator: Some(Cow::Borrowed(whitespace)),
166            subsection_name,
167        })
168        .parse_next(i)
169}
170
171fn is_section_char(c: u8) -> bool {
172    c.is_ascii_alphanumeric() || c == b'-' || c == b'.'
173}
174
175fn sub_section<'i>(i: &mut &'i [u8]) -> ModalResult<Cow<'i, BStr>, NomError<&'i [u8]>> {
176    let mut output = Cow::Borrowed(Default::default());
177    if let Some(sub) = opt(subsection_subset).parse_next(i)? {
178        output = Cow::Borrowed(sub.as_bstr());
179    }
180    while let Some(sub) = opt(subsection_subset).parse_next(i)? {
181        output.to_mut().extend(sub);
182    }
183
184    Ok(output)
185}
186
187fn subsection_subset<'i>(i: &mut &'i [u8]) -> ModalResult<&'i [u8], NomError<&'i [u8]>> {
188    alt((subsection_unescaped, subsection_escaped_char)).parse_next(i)
189}
190
191fn subsection_unescaped<'i>(i: &mut &'i [u8]) -> ModalResult<&'i [u8], NomError<&'i [u8]>> {
192    take_while(1.., is_subsection_unescaped_char).parse_next(i)
193}
194
195fn subsection_escaped_char<'i>(i: &mut &'i [u8]) -> ModalResult<&'i [u8], NomError<&'i [u8]>> {
196    preceded('\\', one_of(is_subsection_escapable_char).take()).parse_next(i)
197}
198
199fn is_subsection_escapable_char(c: u8) -> bool {
200    c != b'\n'
201}
202
203fn is_subsection_unescaped_char(c: u8) -> bool {
204    c != b'"' && c != b'\\' && c != b'\n' && c != 0
205}
206
207fn key_value_pair<'i>(
208    i: &mut &'i [u8],
209    node: &mut ParseNode,
210    dispatch: &mut dyn FnMut(Event<'i>),
211) -> ModalResult<(), NomError<&'i [u8]>> {
212    *node = ParseNode::Name;
213    if let Some(name) = opt(config_name).parse_next(i)? {
214        dispatch(Event::SectionValueName(section::ValueName(Cow::Borrowed(name))));
215
216        if let Some(whitespace) = opt(take_spaces1).parse_next(i)? {
217            dispatch(Event::Whitespace(Cow::Borrowed(whitespace)));
218        }
219
220        *node = ParseNode::Value;
221        config_value(i, dispatch)
222    } else {
223        Ok(())
224    }
225}
226
227/// Parses the config name of a config pair. Assumes the input has already been
228/// trimmed of any leading whitespace.
229fn config_name<'i>(i: &mut &'i [u8]) -> ModalResult<&'i BStr, NomError<&'i [u8]>> {
230    (
231        one_of(|c: u8| c.is_ascii_alphabetic()),
232        take_while(0.., |c: u8| c.is_ascii_alphanumeric() || c == b'-'),
233    )
234        .take()
235        .map(bstr::ByteSlice::as_bstr)
236        .parse_next(i)
237}
238
239fn config_value<'i>(i: &mut &'i [u8], dispatch: &mut dyn FnMut(Event<'i>)) -> ModalResult<(), NomError<&'i [u8]>> {
240    if opt('=').parse_next(i)?.is_some() {
241        dispatch(Event::KeyValueSeparator);
242        if let Some(whitespace) = opt(take_spaces1).parse_next(i)? {
243            dispatch(Event::Whitespace(Cow::Borrowed(whitespace)));
244        }
245        value_impl(i, dispatch)
246    } else {
247        // This is a special way of denoting 'empty' values which a lot of code depends on.
248        // Hence, rather to fix this everywhere else, leave it here and fix it where it matters, namely
249        // when it's about differentiating between a missing key-value separator, and one followed by emptiness.
250        dispatch(Event::Value(Cow::Borrowed("".into())));
251        Ok(())
252    }
253}
254
255/// Handles parsing of known-to-be values. This function handles both single
256/// line values as well as values that are continuations.
257fn value_impl<'i>(i: &mut &'i [u8], dispatch: &mut dyn FnMut(Event<'i>)) -> ModalResult<(), NomError<&'i [u8]>> {
258    let start_checkpoint = i.checkpoint();
259    let mut value_start_checkpoint = i.checkpoint();
260    let mut value_end = None;
261
262    // This is required to ignore comment markers if they're in a quote.
263    let mut is_in_quotes = false;
264    // Used to determine if we return a Value or Value{Not,}Done
265    let mut partial_value_found = false;
266
267    loop {
268        let _ = take_while(0.., |c| !matches!(c, b'\n' | b'\\' | b'"' | b';' | b'#')).parse_next(i)?;
269        if let Some(c) = i.next_token() {
270            match c {
271                b'\n' => {
272                    value_end = Some(i.offset_from(&value_start_checkpoint) - 1);
273                    break;
274                }
275                b';' | b'#' if !is_in_quotes => {
276                    value_end = Some(i.offset_from(&value_start_checkpoint) - 1);
277                    break;
278                }
279                b'\\' => {
280                    let escaped_index = i.offset_from(&value_start_checkpoint);
281                    let escape_index = escaped_index - 1;
282                    let Some(mut c) = i.next_token() else {
283                        i.reset(&start_checkpoint);
284                        return Err(winnow::error::ErrMode::from_input(i));
285                    };
286                    let mut consumed = 1;
287                    if c == b'\r' {
288                        c = i.next_token().ok_or_else(|| {
289                            i.reset(&start_checkpoint);
290                            winnow::error::ErrMode::from_input(i)
291                        })?;
292                        if c != b'\n' {
293                            i.reset(&start_checkpoint);
294                            return Err(winnow::error::ErrMode::from_input(i));
295                        }
296                        consumed += 1;
297                    }
298
299                    match c {
300                        b'\n' => {
301                            partial_value_found = true;
302
303                            i.reset(&value_start_checkpoint);
304
305                            let value = i.next_slice(escape_index).as_bstr();
306                            dispatch(Event::ValueNotDone(Cow::Borrowed(value)));
307
308                            i.next_token();
309
310                            let nl = i.next_slice(consumed).as_bstr();
311                            dispatch(Event::Newline(Cow::Borrowed(nl)));
312
313                            value_start_checkpoint = i.checkpoint();
314                            value_end = None;
315                        }
316                        b'n' | b't' | b'\\' | b'b' | b'"' => {}
317                        _ => {
318                            i.reset(&start_checkpoint);
319                            return Err(winnow::error::ErrMode::from_input(i));
320                        }
321                    }
322                }
323                b'"' => is_in_quotes = !is_in_quotes,
324                _ => {}
325            }
326        } else {
327            break;
328        }
329    }
330    if is_in_quotes {
331        i.reset(&start_checkpoint);
332        return Err(winnow::error::ErrMode::from_input(i));
333    }
334
335    let value_end = match value_end {
336        None => {
337            let last_value_index = i.offset_from(&value_start_checkpoint);
338            if last_value_index == 0 {
339                dispatch(Event::Value(Cow::Borrowed("".into())));
340                return Ok(());
341            } else {
342                last_value_index
343            }
344        }
345        Some(idx) => idx,
346    };
347
348    i.reset(&value_start_checkpoint);
349    let value_end_no_trailing_whitespace = i[..value_end]
350        .iter()
351        .enumerate()
352        .rev()
353        .find_map(|(idx, b)| (!b.is_ascii_whitespace()).then_some(idx + 1))
354        .unwrap_or(0);
355    let remainder_value = i.next_slice(value_end_no_trailing_whitespace);
356
357    if partial_value_found {
358        dispatch(Event::ValueDone(Cow::Borrowed(remainder_value.as_bstr())));
359    } else {
360        dispatch(Event::Value(Cow::Borrowed(remainder_value.as_bstr())));
361    }
362
363    Ok(())
364}
365
366fn take_spaces1<'i>(i: &mut &'i [u8]) -> ModalResult<&'i BStr, NomError<&'i [u8]>> {
367    take_while(1.., winnow::stream::AsChar::is_space)
368        .map(bstr::ByteSlice::as_bstr)
369        .parse_next(i)
370}
371
372fn take_newlines1<'i>(i: &mut &'i [u8]) -> ModalResult<&'i BStr, NomError<&'i [u8]>> {
373    repeat(1..1024, alt(("\r\n", "\n")))
374        .map(|()| ())
375        .take()
376        .map(bstr::ByteSlice::as_bstr)
377        .parse_next(i)
378}