Skip to main content

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 string;
38pub mod symbol;
39pub mod tristate;
40pub mod util;
41
42pub use self::attribute::Attribute;
43pub use self::entry::Entry;
44pub use self::kconfig::{parse_kconfig, Kconfig};
45pub use self::symbol::Symbol;
46
47/// [KconfigInput] is a struct gathering a [KconfigFile] and its associated content.
48pub type KconfigInput<'a> = LocatedSpan<&'a str, KconfigFile>;
49
50/// Represents a Kconfig file.
51/// 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.
52#[derive(Debug, Default, Clone)]
53pub struct KconfigFile {
54    /// 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.
55    root_dir: PathBuf,
56    /// The path the the Kconfig you want to parse.
57    file: PathBuf,
58    /// Externally-specified variables to use when including child source files
59    vars: HashMap<String, String>,
60}
61
62impl KconfigFile {
63    pub fn new(root_dir: PathBuf, file: PathBuf) -> Self {
64        Self {
65            root_dir,
66            file,
67            vars: HashMap::new(),
68        }
69    }
70
71    pub fn new_with_vars<S: AsRef<str>>(
72        root_dir: PathBuf,
73        file: PathBuf,
74        vars: &HashMap<S, S>,
75    ) -> Self {
76        Self {
77            root_dir,
78            file,
79            vars: vars
80                .iter()
81                .map(|(s1, s2)| (s1.as_ref().to_string(), s2.as_ref().to_string()))
82                .collect(),
83        }
84    }
85
86    pub fn full_path(&self) -> PathBuf {
87        match self.file.is_absolute() {
88            true => self.file.clone(),
89            false => self.root_dir.join(&self.file),
90        }
91    }
92
93    pub fn read_to_string(&self) -> io::Result<String> {
94        fs::read_to_string(self.full_path())
95    }
96
97    pub fn set_vars<S: AsRef<str>>(&mut self, vars: &[(S, S)]) {
98        self.vars = vars
99            .iter()
100            .map(|(s1, s2)| (s1.as_ref().to_string(), s2.as_ref().to_string()))
101            .collect();
102    }
103}
104
105#[cfg(test)]
106pub mod kconfig_test;
107#[cfg(test)]
108pub mod lib_test;
109mod number;
110#[cfg(test)]
111pub mod symbol_test;
112#[cfg(test)]
113pub mod util_test;
114
115#[macro_export]
116macro_rules! assert_parsing_eq {
117    ($fn:ident, $input:expr, $expected:expr) => {{
118        use $crate::KconfigInput;
119        let res = $fn(KconfigInput::new_extra($input, Default::default()))
120            .map(|r| (r.0.fragment().to_owned(), r.1));
121        assert_eq!(res, $expected)
122    }};
123}