rpu/
preprocessor.rs

1use crate::prelude::*;
2
3pub struct Preprocessor {
4    defines: FxHashMap<String, String>,
5}
6
7impl Default for Preprocessor {
8    fn default() -> Self {
9        Self::new()
10    }
11}
12
13impl Preprocessor {
14    fn new() -> Self {
15        Preprocessor {
16            defines: FxHashMap::default(),
17        }
18    }
19
20    /// Process a line of code and store any #define statements. This is very limited right now, only simple single line defines are supported.
21    fn process_line(&mut self, line: &str) -> String {
22        if line.trim_start().starts_with("#define") {
23            let parts: Vec<_> = line.split_whitespace().collect();
24            if parts.len() > 2 {
25                self.defines
26                    .insert(parts[1].to_string(), parts[2..].join(" "));
27            }
28            String::new() // Return an empty string for define lines
29        } else {
30            self.expand_macros(line)
31        }
32    }
33
34    /// Expand a line of code by replacing any defined macros
35    fn expand_macros(&self, line: &str) -> String {
36        let mut expanded_line = line.to_string();
37        for (key, value) in &self.defines {
38            expanded_line = expanded_line.replace(key, value);
39        }
40        expanded_line
41    }
42
43    /// Process a module of code, line by line
44    pub fn process_module(&mut self, module: &str) -> String {
45        let mut processed_file = String::new();
46        for line in module.lines() {
47            processed_file.push_str(&self.process_line(line));
48            processed_file.push('\n');
49        }
50        processed_file
51    }
52}