nom_kconfig/
lib.rs

1//! # nom-kconfig
2//!
3//! A parser for kconfig files. The parsing is done with [nom](https://github.com/rust-bakery/nom).
4//!
5//! ```no_run
6//! use std::path::PathBuf;
7//! use nom_kconfig::{parse_kconfig, KconfigInput, KconfigFile};
8//!
9//! // curl https://cdn.kernel.org/pub/linux/kernel/v6.x/linux-6.4.9.tar.xz | tar -xJ -C /tmp/
10//! fn main() -> Result<(), Box<dyn std::error::Error>> {
11//!     let kconfig_file = KconfigFile::new(
12//!         PathBuf::from("/tmp/linux-6.4.9"),
13//!         PathBuf::from("/tmp/linux-6.4.9/Kconfig")
14//!     );
15//!     let input = kconfig_file.read_to_string().unwrap();
16//!     let kconfig = parse_kconfig(KconfigInput::new_extra(&input, kconfig_file));
17//!     println!("{:?}", kconfig);
18//!     Ok(())
19//! }
20//! ```
21
22use nom_locate::LocatedSpan;
23
24use std::path::PathBuf;
25use std::{fs, io};
26
27pub mod attribute;
28pub mod entry;
29pub mod kconfig;
30pub mod symbol;
31pub mod util;
32
33pub use self::attribute::Attribute;
34pub use self::entry::Entry;
35pub use self::kconfig::{parse_kconfig, Kconfig};
36pub use self::symbol::Symbol;
37
38/// [KconfigInput] is a struct gathering a [KconfigFile] and its associated content.
39pub type KconfigInput<'a> = LocatedSpan<&'a str, KconfigFile>;
40
41/// Represents a Kconfig file.
42/// It stores the kernel root directory because we need this information when a [`source`](https://www.kernel.org/doc/html/next/kbuild/kconfig-language.html#kconfig-syntax) keyword is met.
43#[derive(Debug, Default, Clone)]
44pub struct KconfigFile {
45    /// The absolute path of the kernel root directory. This field is necessary to parse [`source`](https://www.kernel.org/doc/html/next/kbuild/kconfig-language.html#kconfig-syntax) entry.
46    root_dir: PathBuf,
47    /// The path the the Kconfig you want to parse.
48    file: PathBuf,
49}
50
51impl KconfigFile {
52    pub fn new(root_dir: PathBuf, file: PathBuf) -> Self {
53        Self { root_dir, file }
54    }
55
56    pub fn full_path(&self) -> PathBuf {
57        self.root_dir.join(&self.file)
58    }
59
60    pub fn read_to_string(&self) -> io::Result<String> {
61        fs::read_to_string(self.full_path())
62    }
63}
64
65#[cfg(test)]
66pub mod kconfig_test;
67#[cfg(test)]
68pub mod lib_test;
69#[cfg(test)]
70pub mod symbol_test;
71#[cfg(test)]
72pub mod util_test;
73
74#[macro_export]
75macro_rules! assert_parsing_eq {
76    ($fn:ident, $input:expr, $expected:expr) => {{
77        use $crate::KconfigInput;
78        let res = $fn(KconfigInput::new_extra($input, Default::default()))
79            .map(|r| (r.0.fragment().to_owned(), r.1));
80        assert_eq!(res, $expected)
81    }};
82}