1use nom::{
2 branch::alt,
3 bytes::complete::tag,
4 character::complete::{alphanumeric1, one_of},
5 combinator::{map, recognize},
6 error::{Error, ErrorKind, ParseError},
7 multi::many1,
8 sequence::delimited,
9 IResult, Input, Parser,
10};
11
12use crate::{util::ws, KconfigInput};
13
14pub fn parse_string(input: KconfigInput) -> IResult<KconfigInput, String> {
15 map(
16 alt((
17 delimited(tag("'"), take_until_unbalanced('\''), tag("'")),
18 delimited(tag("\""), take_until_unbalanced('"'), tag("\"")),
19 )),
20 |d| d.fragment().to_string(),
21 )
22 .parse(input)
23}
24
25pub fn take_until_unbalanced(
26 delimiter: char,
27) -> impl Fn(KconfigInput) -> IResult<KconfigInput, KconfigInput> {
28 move |i: KconfigInput| {
29 let mut index: usize = 0;
30 let mut delimiter_counter = 0;
31
32 let end_of_line = match &i.find('\n') {
33 Some(e) => *e,
34 None => i.len(),
35 };
36
37 while let Some(n) = &i[index..end_of_line].find(delimiter) {
38 delimiter_counter += 1;
39 index += n + 1;
40 }
41
42 index -= 1;
44 delimiter_counter -= 1;
46
47 match delimiter_counter % 2 == 0 {
48 true => Ok(i.take_split(index)),
49 false => Err(nom::Err::Error(Error::from_error_kind(
50 i,
51 ErrorKind::TakeUntil,
52 ))),
53 }
54 }
55}
56
57pub fn parse_first_word(input: KconfigInput) -> IResult<KconfigInput, KconfigInput> {
59 alt((
60 recognize((tag("'"), take_until_unbalanced('\''), tag("'"))),
61 recognize((tag("\""), take_until_unbalanced('"'), tag("\""))),
62 recognize(ws(many1(alt((alphanumeric1, recognize(one_of("-._'\""))))))),
63 ))
64 .parse(input)
65}