nom_kconfig/
lib.rs

1#![allow(clippy::result_large_err)]
2
3//! # nom-kconfig
4//!
5//! A parser for kconfig files. The parsing is done with [nom](https://github.com/rust-bakery/nom).
6//!
7//! ```no_run
8//! use std::path::PathBuf;
9//! use nom_kconfig::{parse_kconfig, KconfigInput, KconfigFile};
10//! use std::collections::HashMap;
11//!
12//! // curl https://cdn.kernel.org/pub/linux/kernel/v6.x/linux-6.4.9.tar.xz | tar -xJ -C /tmp/
13//! fn main() -> Result<(), Box<dyn std::error::Error>> {
14//!     let mut variables = HashMap::new();
15//!     variables.insert("SRCARCH", "x86");
16//!     let kconfig_file = KconfigFile::new_with_vars(
17//!         PathBuf::from("/tmp/linux-6.4.9"),
18//!         PathBuf::from("/tmp/linux-6.4.9/Kconfig"),
19//!         &variables
20//!     );
21//!     let input = kconfig_file.read_to_string().unwrap();
22//!     let kconfig = parse_kconfig(KconfigInput::new_extra(&input, kconfig_file));
23//!     println!("{:?}", kconfig);
24//!     Ok(())
25//! }
26//! ```
27
28use nom_locate::LocatedSpan;
29
30use std::collections::HashMap;
31use std::path::PathBuf;
32use std::{fs, io};
33
34pub mod attribute;
35pub mod entry;
36pub mod kconfig;
37pub mod symbol;
38pub mod util;
39
40pub use self::attribute::Attribute;
41pub use self::entry::Entry;
42pub use self::kconfig::{parse_kconfig, Kconfig};
43pub use self::symbol::Symbol;
44
45/// [KconfigInput] is a struct gathering a [KconfigFile] and its associated content.
46pub type KconfigInput<'a> = LocatedSpan<&'a str, KconfigFile>;
47
48/// Represents a Kconfig file.
49/// 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.
50#[derive(Debug, Default, Clone)]
51pub struct KconfigFile {
52    /// 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.
53    root_dir: PathBuf,
54    /// The path the the Kconfig you want to parse.
55    file: PathBuf,
56    /// Externally-specified variables to use when including child source files
57    vars: HashMap<String, String>,
58}
59
60impl KconfigFile {
61    pub fn new(root_dir: PathBuf, file: PathBuf) -> Self {
62        Self {
63            root_dir,
64            file,
65            vars: HashMap::new(),
66        }
67    }
68
69    pub fn new_with_vars<S: AsRef<str>>(
70        root_dir: PathBuf,
71        file: PathBuf,
72        vars: &HashMap<S, S>,
73    ) -> Self {
74        Self {
75            root_dir,
76            file,
77            vars: vars
78                .iter()
79                .map(|(s1, s2)| (s1.as_ref().to_string(), s2.as_ref().to_string()))
80                .collect(),
81        }
82    }
83
84    pub fn full_path(&self) -> PathBuf {
85        self.root_dir.join(&self.file)
86    }
87
88    pub fn read_to_string(&self) -> io::Result<String> {
89        fs::read_to_string(self.full_path())
90    }
91
92    pub fn set_vars<S: AsRef<str>>(&mut self, vars: &[(S, S)]) {
93        self.vars = vars
94            .iter()
95            .map(|(s1, s2)| (s1.as_ref().to_string(), s2.as_ref().to_string()))
96            .collect();
97    }
98}
99
100#[cfg(test)]
101pub mod kconfig_test;
102#[cfg(test)]
103pub mod lib_test;
104#[cfg(test)]
105pub mod symbol_test;
106#[cfg(test)]
107pub mod util_test;
108
109#[macro_export]
110macro_rules! assert_parsing_eq {
111    ($fn:ident, $input:expr, $expected:expr) => {{
112        use $crate::KconfigInput;
113        let res = $fn(KconfigInput::new_extra($input, Default::default()))
114            .map(|r| (r.0.fragment().to_owned(), r.1));
115        assert_eq!(res, $expected)
116    }};
117}