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;
11use tracing::debug;
12
13use crate::{
14    entry::{parse_entry, Entry},
15    util::{ws, ws_comment},
16    KconfigInput,
17};
18
19/// A Kconfig file.
20/// Field `file` is relative to the root directory defined in [KconfigFile](crate::KconfigFile).
21#[derive(Debug, Clone, PartialEq, Default)]
22#[cfg_attr(feature = "hash", derive(Hash))]
23#[cfg_attr(feature = "serialize", derive(Serialize))]
24#[cfg_attr(feature = "deserialize", derive(Deserialize))]
25pub struct Kconfig {
26    pub file: String,
27    pub entries: Vec<Entry>,
28}
29
30/// Parses a kconfig input.
31/// # Example
32/// ```
33/// use std::path::PathBuf;
34/// use nom_kconfig::{KconfigInput, KconfigFile, Entry, kconfig::parse_kconfig, Kconfig};
35///
36/// let kconfig_file = KconfigFile::new(PathBuf::from("path/to/root/dir"), PathBuf::from("Kconfig"));
37/// let content = "";
38/// let input = KconfigInput::new_extra(content, kconfig_file);
39/// assert_eq!(parse_kconfig(input).unwrap().1, Kconfig {file: "Kconfig".to_string(), entries: vec!() })
40/// ```
41pub fn parse_kconfig(input: KconfigInput) -> IResult<KconfigInput, Kconfig> {
42    let file: std::path::PathBuf = input.extra.file.clone();
43    debug!("Parsing file '{}'", file.display());
44    let (input, result) = map(delimited(ws_comment, many0(parse_entry), ws(eof)), |d| {
45        Kconfig {
46            file: file.display().to_string(),
47            entries: d,
48        }
49    })
50    .parse(input)?;
51    Ok((input, result))
52}