Skip to main content

resrap_rs/core/
codebasegen.rs

1use std::path::{Path, PathBuf};
2
3use crate::Resrap;
4
5#[derive(Clone, Copy, Debug, PartialEq, Eq)]
6pub enum FileType {
7    Dir,
8    File,
9}
10
11/// Describes either a directory or file entry in a codebase specification.
12#[derive(Clone, Debug)]
13pub struct Node {
14    pub name: String,
15    pub typ: FileType,
16    /// E.g. `code_*.c`
17    pub pattern: String,
18    /// Number of files, e.g. 10.
19    pub count: usize,
20    /// Tokens per file, e.g. 20.
21    pub token_count: usize,
22    /// Language/type identifier, e.g. `C` or `sql`.
23    pub file_type: String,
24    pub children: Vec<Node>,
25}
26
27impl Node {
28    fn dir(name: String) -> Self {
29        Node {
30            name,
31            typ: FileType::Dir,
32            pattern: String::new(),
33            count: 0,
34            token_count: 0,
35            file_type: String::new(),
36            children: Vec::new(),
37        }
38    }
39
40    /// Creates the directory structure and files.
41    pub fn generate_structure(&self, resrap: &Resrap, root: &str) -> Result<(), String> {
42        self.generate_node(resrap, root)
43    }
44
45    fn generate_node(&self, resrap: &Resrap, root: &str) -> Result<(), String> {
46        let loc = if self.name.is_empty() {
47            PathBuf::from(root)
48        } else {
49            Path::new(root).join(&self.name)
50        };
51
52        match self.typ {
53            FileType::Dir => {
54                std::fs::create_dir_all(&loc).map_err(|err| {
55                    format!("failed to create directory '{}': {}", loc.display(), err)
56                })?;
57
58                for child in &self.children {
59                    child.generate_node(resrap, loc.to_str().unwrap_or(root))?;
60                }
61            }
62            FileType::File => {
63                if self.count == 0 {
64                    return Err(format!(
65                        "invalid file count {} for pattern '{}'",
66                        self.count, self.pattern
67                    ));
68                }
69
70                std::fs::create_dir_all(root).map_err(|err| {
71                    format!("failed to create parent directory '{}': {}", root, err)
72                })?;
73
74                for i in 1..=self.count {
75                    let file_name = self.pattern.replace('*', &i.to_string());
76                    let full_path = Path::new(root).join(&file_name);
77
78                    // Complete generation finishes the top-level rule instead
79                    // of cutting the file in the middle of a statement.
80                    let content =
81                        resrap.generate_complete(&self.file_type, "program", self.token_count);
82
83                    std::fs::write(&full_path, content).map_err(|err| {
84                        format!("failed to write file '{}': {}", full_path.display(), err)
85                    })?;
86
87                    println!(
88                        "Generated: {} ({} tokens)",
89                        full_path.display(),
90                        self.token_count
91                    );
92                }
93            }
94        }
95
96        Ok(())
97    }
98}
99
100/// Parses the directory DSL into a tree.
101pub fn parse_dsl(input: &str) -> Result<Node, String> {
102    let mut root = Node::dir(String::new());
103    let mut stack: Vec<(usize, Vec<usize>)> = Vec::new();
104
105    for (line_num, line) in input.lines().enumerate() {
106        if line.trim().is_empty() {
107            continue;
108        }
109
110        let indent = line.chars().take_while(|c| *c == ' ').count();
111        let name = line.trim();
112
113        let node = if let Some(open) = name.find('[') {
114            if !name.ends_with(']') {
115                return Err(format!(
116                    "line {}: invalid file spec format, expected 'type[countXtokens pattern]'",
117                    line_num + 1
118                ));
119            }
120
121            let file_type = name[..open].to_string();
122            let rest = &name[open + 1..name.len() - 1];
123            let parts: Vec<&str> = rest.split_whitespace().collect();
124
125            if parts.len() < 2 {
126                return Err(format!(
127                    "line {}: invalid file spec format, expected 'type[countXtokens pattern]'",
128                    line_num + 1
129                ));
130            }
131
132            let xparts: Vec<&str> = parts[0].split('x').collect();
133            if xparts.len() != 2 {
134                return Err(format!(
135                    "line {}: invalid count format '{}', expected 'NUMxNUM'",
136                    line_num + 1,
137                    parts[0]
138                ));
139            }
140
141            let count = xparts[0].parse::<usize>().map_err(|err| {
142                format!(
143                    "line {}: invalid file count '{}': {}",
144                    line_num + 1,
145                    xparts[0],
146                    err
147                )
148            })?;
149            let token_count = xparts[1].parse::<usize>().map_err(|err| {
150                format!(
151                    "line {}: invalid token count '{}': {}",
152                    line_num + 1,
153                    xparts[1],
154                    err
155                )
156            })?;
157
158            if count == 0 || token_count == 0 {
159                return Err(format!(
160                    "line {}: count and token count must be positive numbers",
161                    line_num + 1
162                ));
163            }
164
165            Node {
166                name: String::new(),
167                typ: FileType::File,
168                pattern: parts[1].to_string(),
169                count,
170                token_count,
171                file_type,
172                children: Vec::new(),
173            }
174        } else {
175            Node::dir(name.to_string())
176        };
177
178        while let Some((stack_indent, _)) = stack.last() {
179            if *stack_indent >= indent {
180                stack.pop();
181            } else {
182                break;
183            }
184        }
185
186        let parent_path = stack
187            .last()
188            .map(|(_, path)| path.clone())
189            .unwrap_or_default();
190        let parent = node_at_mut(&mut root, &parent_path)
191            .ok_or_else(|| format!("line {}: indentation error", line_num + 1))?;
192        parent.children.push(node);
193        let child_path = {
194            let mut path = parent_path;
195            path.push(parent.children.len() - 1);
196            path
197        };
198
199        if node_at_mut(&mut root, &child_path)
200            .map(|n| n.typ == FileType::Dir)
201            .unwrap_or(false)
202        {
203            stack.push((indent, child_path));
204        }
205    }
206
207    Ok(root)
208}
209
210fn node_at_mut<'a>(root: &'a mut Node, path: &[usize]) -> Option<&'a mut Node> {
211    let mut node = root;
212    for &index in path {
213        node = node.children.get_mut(index)?;
214    }
215    Some(node)
216}
217
218#[cfg(test)]
219mod tests {
220    use super::*;
221    use crate::Resrap;
222
223    #[test]
224    fn parses_simple_directory() {
225        let root = parse_dsl("src/").unwrap();
226        assert_eq!(root.typ, FileType::Dir);
227        assert!(root.name.is_empty());
228        assert_eq!(root.children.len(), 1);
229        assert_eq!(root.children[0].name, "src/");
230    }
231
232    #[test]
233    fn parses_nested_file_spec() {
234        let root = parse_dsl("src/\n  code/\n    c[10x20 code_*.c]").unwrap();
235        let code = &root.children[0].children[0];
236        assert_eq!(code.typ, FileType::Dir);
237        assert_eq!(code.name, "code/");
238        assert_eq!(code.children.len(), 1);
239        let file = &code.children[0];
240        assert_eq!(file.typ, FileType::File);
241        assert_eq!(file.file_type, "c");
242        assert_eq!(file.count, 10);
243        assert_eq!(file.token_count, 20);
244        assert_eq!(file.pattern, "code_*.c");
245    }
246
247    #[test]
248    fn rejects_bad_specs() {
249        for dsl in ["c[abc]", "c[10 code_*.c]", "c[ax20 *.c]", "c[0x20 *.c]"] {
250            assert!(parse_dsl(dsl).is_err(), "accepted {:?}", dsl);
251        }
252    }
253
254    #[test]
255    fn accepts_blank_lines() {
256        let root = parse_dsl("\n  \nsrc/\n\t\nmore/").unwrap();
257        assert_eq!(root.children.len(), 2);
258    }
259
260    #[test]
261    fn generates_files() {
262        let mut r = Resrap::new();
263        r.parse_grammar("c", "program:'int x;';\n").unwrap();
264        let dir = std::env::temp_dir().join(format!("resrap-dsl-{}", std::process::id()));
265        std::fs::create_dir_all(&dir).unwrap();
266        let dsl = "out/\n  c[2x10 code_*.c]\n";
267        let root = parse_dsl(dsl).unwrap();
268        root.generate_structure(&r, dir.to_str().unwrap()).unwrap();
269        for i in 1..=2 {
270            assert!(dir.join("out").join(format!("code_{}.c", i)).exists());
271        }
272        std::fs::remove_dir_all(&dir).ok();
273    }
274}