Skip to main content

nom_kconfig/
kconfig_file.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//!         &HashMap::default(),
21//!     );
22//!     let input = kconfig_file.read_to_string().unwrap();
23//!     let kconfig = parse_kconfig(KconfigInput::new_extra(&input, kconfig_file));
24//!     println!("{:?}", kconfig);
25//!     Ok(())
26//! }
27//! ```
28
29use std::collections::HashMap;
30use std::path::PathBuf;
31use std::rc::Rc;
32use std::{fs, io};
33
34/// Represents a Kconfig file.
35/// 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.
36#[derive(Debug, Default, Clone, PartialEq, Eq)]
37pub struct KconfigFile {
38    /// 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.
39    pub root_dir: PathBuf,
40    /// The path the the Kconfig you want to parse.
41    pub file: PathBuf,
42    /// Externally-specified variables to use when including child source files
43    pub global_vars: Rc<HashMap<String, String>>,
44    pub local_vars: Rc<HashMap<String, String>>,
45    pub external_functions: Rc<HashMap<String, String>>,
46    pub depth: usize,
47    pub parent_file: Option<PathBuf>,
48}
49
50impl KconfigFile {
51    pub fn new(root_dir: PathBuf, file: PathBuf) -> Self {
52        Self {
53            root_dir,
54            file,
55            global_vars: Rc::new(HashMap::new()),
56            local_vars: Rc::new(HashMap::new()),
57            external_functions: Rc::new(HashMap::new()),
58            depth: 0,
59            parent_file: None,
60        }
61    }
62
63    pub fn new_with_vars<S: AsRef<str>>(
64        root_dir: PathBuf,
65        file: PathBuf,
66        global_vars: &HashMap<S, S>,
67        local_vars: &HashMap<S, S>,
68    ) -> Self {
69        Self {
70            root_dir,
71            file,
72            global_vars: Rc::new(
73                global_vars
74                    .iter()
75                    .map(|(s1, s2)| (s1.as_ref().to_string(), s2.as_ref().to_string()))
76                    .collect(),
77            ),
78            local_vars: Rc::new(
79                local_vars
80                    .iter()
81                    .map(|(s1, s2)| (s1.as_ref().to_string(), s2.as_ref().to_string()))
82                    .collect(),
83            ),
84            external_functions: Rc::new(HashMap::new()),
85            depth: 0,
86            parent_file: None,
87        }
88    }
89
90    pub fn with_external_functions(mut self, external_functions: &HashMap<String, String>) -> Self {
91        self.external_functions = Rc::new(external_functions.clone());
92        self
93    }
94
95    pub fn new_source_file(&self, path: PathBuf) -> Self {
96        let mut copied = self.clone();
97        copied.file = path;
98        copied.depth += 1;
99        copied.parent_file = Some(self.file.clone());
100        copied
101    }
102
103    pub fn vars(&self) -> HashMap<String, String> {
104        let mut variables = (*self.global_vars).clone();
105        variables.extend((*self.local_vars).clone());
106        variables
107    }
108
109    pub fn global_vars(&self) -> &HashMap<String, String> {
110        &self.global_vars
111    }
112
113    pub fn full_path(&self) -> PathBuf {
114        self.root_dir.join(&self.file)
115    }
116
117    pub fn read_to_string(&self) -> io::Result<String> {
118        fs::read_to_string(self.full_path()).map(|content| self.preprocess_content(content))
119    }
120
121    pub fn set_global_vars<S: AsRef<str>>(&mut self, vars: &[(S, S)]) {
122        self.global_vars = Rc::new(
123            vars.iter()
124                .map(|(s1, s2)| (s1.as_ref().to_string(), s2.as_ref().to_string()))
125                .collect(),
126        );
127    }
128
129    pub fn add_local_var<S: AsRef<str>>(&mut self, key: S, value: S) {
130        let mut new_map = (*self.local_vars).clone();
131        new_map.insert(key.as_ref().to_string(), value.as_ref().to_string());
132        self.local_vars = Rc::new(new_map);
133    }
134
135    pub fn add_local_vars(&mut self, new_vars: HashMap<String, String>) {
136        if new_vars.is_empty() {
137            return;
138        }
139        let mut new_map = (*self.local_vars).clone();
140        new_map.extend(new_vars);
141        self.local_vars = Rc::new(new_map);
142    }
143
144    pub fn preprocess_content(&self, content: String) -> String {
145        let variables = self.vars();
146        if variables.is_empty() {
147            return content;
148        }
149        let mut file_copy = content.clone();
150        for (var_name, var_value) in variables {
151            file_copy = file_copy.replace(&format!("$({var_name})"), &var_value);
152            file_copy = file_copy.replace(&format!("${{{var_name}}}"), &var_value);
153        }
154
155        file_copy
156    }
157}