Skip to main content

nom_kconfig/
kconfig.rs

1use nom::{
2    combinator::{eof, map},
3    multi::many0,
4    sequence::delimited,
5    IResult, Parser,
6};
7#[cfg(feature = "deserialize")]
8use serde::Deserialize;
9#[cfg(feature = "serialize")]
10use serde::Serialize;
11#[cfg(feature = "debug")]
12use tracing::debug;
13
14use crate::{
15    entry::{parse_entry, Entry},
16    error::Error,
17    util::{ws, ws_comment},
18    KconfigInput,
19};
20
21/// A Kconfig file.
22/// Field `file` is relative to the root directory defined in [KconfigFile](crate::KconfigFile).
23#[derive(Debug, Clone, PartialEq, Default)]
24#[cfg_attr(feature = "hash", derive(Hash))]
25#[cfg_attr(feature = "serialize", derive(Serialize))]
26#[cfg_attr(feature = "deserialize", derive(Deserialize))]
27pub struct Kconfig {
28    pub file: String,
29    pub entries: Vec<Entry>,
30}
31
32/// Parses a kconfig input.
33/// # Example
34/// ```
35/// use std::path::PathBuf;
36/// use nom_kconfig::{KconfigInput, KconfigFile, Entry, kconfig::parse_kconfig, Kconfig};
37///
38/// let kconfig_file = KconfigFile::new(PathBuf::from("path/to/root/dir"), PathBuf::from("Kconfig"));
39/// let content = "";
40/// let input = KconfigInput::new_extra(content, kconfig_file);
41/// assert_eq!(parse_kconfig(input).unwrap().1, Kconfig {file: "Kconfig".to_string(), entries: vec!() })
42/// ```
43pub fn parse_kconfig(input: KconfigInput) -> Result<(KconfigInput, Kconfig), Error> {
44    match private_parse_kconfig(input) {
45        Ok((input, result)) => Ok((input, result)),
46        Err(nom_error) => Err(Error::from(nom_error)),
47    }
48}
49
50pub(crate) fn private_parse_kconfig(input: KconfigInput) -> IResult<KconfigInput, Kconfig> {
51    #[cfg(feature = "debug")]
52    debug!("parsing '{}'", input.extra.full_path().display());
53    let file: std::path::PathBuf = input.extra.file.clone();
54    let (input, result) = map(delimited(ws_comment, many0(parse_entry), ws(eof)), |d| {
55        Kconfig {
56            file: file.display().to_string(),
57            entries: d,
58        }
59    })
60    .parse(input)?;
61    Ok((input, result))
62}