Skip to main content

ignis_db/code_parsing/
mod.rs

1//! Code parsing module for extracting table! macro definitions from Rust code
2
3use crate::schema::Table;
4use anyhow::{Context, Result};
5use std::path::Path;
6
7/// Parser for extracting table! macro definitions from Rust source code
8pub struct TableMacroParser {
9    source_dir: String,
10}
11
12impl TableMacroParser {
13    pub fn new(source_dir: impl Into<String>) -> Self {
14        Self {
15            source_dir: source_dir.into(),
16        }
17    }
18
19    pub fn parse_table_macros(&self) -> Result<Vec<ParsedTable>> {
20        let mut tables = Vec::new();
21        let source_path = Path::new(&self.source_dir);
22        
23        if !source_path.exists() {
24            return Err(anyhow::anyhow!("Source directory does not exist: {}", self.source_dir));
25        }
26
27        self.walk_directory(source_path, &mut tables)?;
28        Ok(tables)
29    }
30
31    fn walk_directory(&self, dir: &Path, tables: &mut Vec<ParsedTable>) -> Result<()> {
32        for entry in std::fs::read_dir(dir)? {
33            let entry = entry?;
34            let path = entry.path();
35            
36            if path.is_dir() && !self.should_skip_directory(&path) {
37                self.walk_directory(&path, tables)?;
38            } else if path.extension().and_then(|s| s.to_str()) == Some("rs") {
39                if let Ok(file_tables) = self.parse_rust_file(&path) {
40                    tables.extend(file_tables);
41                }
42            }
43        }
44        Ok(())
45    }
46
47    fn should_skip_directory(&self, path: &Path) -> bool {
48        let dir_name = path.file_name().and_then(|s| s.to_str()).unwrap_or("");
49        matches!(dir_name, "target" | "node_modules" | ".git" | ".cargo")
50    }
51
52    fn parse_rust_file(&self, file_path: &Path) -> Result<Vec<ParsedTable>> {
53        let content = std::fs::read_to_string(file_path)
54            .with_context(|| format!("Failed to read file: {}", file_path.display()))?;
55        self.parse_rust_content(&content, file_path)
56    }
57
58    fn parse_rust_content(&self, content: &str, file_path: &Path) -> Result<Vec<ParsedTable>> {
59        let mut tables = Vec::new();
60        let lines: Vec<&str> = content.lines().collect();
61
62        let mut i = 0;
63        while i < lines.len() {
64            let line = lines[i].trim();
65            if line.contains("table!") {
66                // Find the complete table! macro definition
67                let start_line = i + 1;
68                let mut macro_content = String::new();
69                let mut brace_count = 0;
70                let mut in_macro = false;
71                
72                // Find the opening brace
73                for j in i..lines.len() {
74                    let current_line = lines[j];
75                    if current_line.contains("{") && !in_macro {
76                        in_macro = true;
77                        macro_content.push_str(current_line);
78                        brace_count = current_line.matches('{').count() - current_line.matches('}').count();
79                    } else if in_macro {
80                        macro_content.push_str(" ");
81                        macro_content.push_str(current_line);
82                        brace_count += current_line.matches('{').count();
83                        brace_count -= current_line.matches('}').count();
84                        
85                        if brace_count == 0 {
86                            // Found the closing brace
87                            if let Some(table) = self.parse_table_macro_content(&macro_content, start_line, file_path)? {
88                                tables.push(table);
89                            }
90                            i = j;
91                            break;
92                        }
93                    }
94                    i = j;
95                }
96            }
97            i += 1;
98        }
99        Ok(tables)
100    }
101
102    fn parse_table_macro_content(&self, content: &str, line_num: usize, file_path: &Path) -> Result<Option<ParsedTable>> {
103        // Extract the content between the braces
104        let start = content.find('{').ok_or_else(|| {
105            anyhow::anyhow!("Invalid table! macro syntax at line {}: missing opening brace", line_num)
106        })?;
107        
108        let end = content.rfind('}').ok_or_else(|| {
109            anyhow::anyhow!("Invalid table! macro syntax at line {}: missing closing brace", line_num)
110        })?;
111        
112        let inner_content = &content[start + 1..end];
113        let (table_name, primary_key, columns) = self.parse_table_definition(inner_content, line_num)?;
114
115        Ok(Some(ParsedTable {
116            name: table_name,
117            primary_key,
118            columns,
119            file_path: file_path.to_path_buf(),
120            line_number: line_num,
121        }))
122    }
123
124    fn parse_table_macro_line(&self, line: &str, line_num: usize, file_path: &Path) -> Result<Option<ParsedTable>> {
125        let trimmed = line.trim();
126        if !trimmed.starts_with("table!") {
127            return Ok(None);
128        }
129
130        // Simple parsing for now - extract table name and basic structure
131        let start = trimmed.find('(').ok_or_else(|| {
132            anyhow::anyhow!("Invalid table! macro syntax at line {}: missing opening parenthesis", line_num)
133        })?;
134
135        let macro_content = &trimmed[start + 1..];
136        let end = self.find_matching_paren(macro_content).ok_or_else(|| {
137            anyhow::anyhow!("Invalid table! macro syntax at line {}: missing closing parenthesis", line_num)
138        })?;
139
140        let inner_content = &macro_content[..end];
141        let (table_name, primary_key, columns) = self.parse_table_definition(inner_content, line_num)?;
142
143        Ok(Some(ParsedTable {
144            name: table_name,
145            primary_key,
146            columns,
147            file_path: file_path.to_path_buf(),
148            line_number: line_num,
149        }))
150    }
151
152    fn find_matching_paren(&self, content: &str) -> Option<usize> {
153        let mut depth = 0;
154        for (i, ch) in content.char_indices() {
155            match ch {
156                '(' => depth += 1,
157                ')' => {
158                    if depth == 0 {
159                        return Some(i);
160                    }
161                    depth -= 1;
162                }
163                _ => {}
164            }
165        }
166        None
167    }
168
169    fn parse_table_definition(&self, content: &str, line_num: usize) -> Result<(String, String, Vec<ColumnDef>)> {
170        let parts: Vec<&str> = content.split_whitespace().collect();
171        
172        if parts.len() < 3 {
173            return Err(anyhow::anyhow!(
174                "Invalid table! macro syntax at line {}: expected 'table_name (pk) {{ columns }}'", 
175                line_num
176            ));
177        }
178
179        let table_name = parts[0].to_string();
180        
181        let pk_start = content.find('(').ok_or_else(|| {
182            anyhow::anyhow!("Invalid table! macro syntax at line {}: missing primary key", line_num)
183        })?;
184        
185        let pk_end = content[pk_start..].find(')').ok_or_else(|| {
186            anyhow::anyhow!("Invalid table! macro syntax at line {}: missing closing parenthesis for primary key", line_num)
187        })?;
188        
189        let primary_key = content[pk_start + 1..pk_start + pk_end].trim().to_string();
190        
191        let brace_start = content.find('{').ok_or_else(|| {
192            anyhow::anyhow!("Invalid table! macro syntax at line {}: missing opening brace for columns", line_num)
193        })?;
194        
195        let brace_end = content[brace_start..].rfind('}').ok_or_else(|| {
196            anyhow::anyhow!("Invalid table! macro syntax at line {}: missing closing brace for columns", line_num)
197        })?;
198        
199        let columns_content = &content[brace_start + 1..brace_start + brace_end];
200        let columns = self.parse_columns(columns_content, line_num)?;
201
202        Ok((table_name, primary_key, columns))
203    }
204
205    fn parse_columns(&self, content: &str, line_num: usize) -> Result<Vec<ColumnDef>> {
206        let mut columns = Vec::new();
207        let mut current = String::new();
208        let mut depth = 0;
209        
210        for ch in content.chars() {
211            match ch {
212                ',' if depth == 0 => {
213                    if !current.trim().is_empty() {
214                        if let Some(column) = self.parse_single_column(current.trim(), line_num)? {
215                            columns.push(column);
216                        }
217                    }
218                    current.clear();
219                }
220                '{' | '(' => {
221                    depth += 1;
222                    current.push(ch);
223                }
224                '}' | ')' => {
225                    depth -= 1;
226                    current.push(ch);
227                }
228                _ => {
229                    current.push(ch);
230                }
231            }
232        }
233        
234        if !current.trim().is_empty() {
235            if let Some(column) = self.parse_single_column(current.trim(), line_num)? {
236                columns.push(column);
237            }
238        }
239        
240        Ok(columns)
241    }
242
243    fn parse_single_column(&self, content: &str, line_num: usize) -> Result<Option<ColumnDef>> {
244        let content = content.trim();
245        if content.is_empty() {
246            return Ok(None);
247        }
248
249        if let Some(arrow_pos) = content.find("->") {
250            let name = content[..arrow_pos].trim().to_string();
251            let type_def = content[arrow_pos + 2..].trim().to_string();
252            
253            Ok(Some(ColumnDef {
254                name,
255                type_definition: type_def,
256            }))
257        } else {
258            Err(anyhow::anyhow!(
259                "Invalid column definition at line {}: expected 'name -> type', got '{}'", 
260                line_num, content
261            ))
262        }
263    }
264}
265
266#[derive(Debug, Clone)]
267pub struct ParsedTable {
268    pub name: String,
269    pub primary_key: String,
270    pub columns: Vec<ColumnDef>,
271    pub file_path: std::path::PathBuf,
272    pub line_number: usize,
273}
274
275#[derive(Debug, Clone)]
276pub struct ColumnDef {
277    pub name: String,
278    pub type_definition: String,
279}
280
281impl ParsedTable {
282    pub fn to_table(&self) -> Result<Table> {
283        use crate::builders::TableBuilder;
284        use crate::builders::SchemaBuilder;
285        
286        let mut builder = TableBuilder::new(&self.name);
287        builder = builder.add_column(&self.primary_key, "SERIAL PRIMARY KEY");
288        
289        for column in &self.columns {
290            if column.name != self.primary_key {
291                let sql_type = self.convert_type_to_sql(&column.type_definition);
292                builder = builder.add_column(&column.name, &sql_type);
293            }
294        }
295        
296        builder.build().map_err(|e| anyhow::anyhow!("Failed to build table from parsed definition: {}", e))
297    }
298
299    fn convert_type_to_sql(&self, rust_type: &str) -> String {
300        match rust_type {
301            "String" => "TEXT".to_string(),
302            "i32" => "INTEGER".to_string(),
303            "i64" => "BIGINT".to_string(),
304            "bool" => "BOOLEAN".to_string(),
305            "chrono::DateTime<chrono::Utc>" => "TIMESTAMPTZ".to_string(),
306            "uuid::Uuid" => "UUID".to_string(),
307            "serde_json::Value" => "JSONB".to_string(),
308            "Option<String>" => "TEXT".to_string(),
309            "Option<i32>" => "INTEGER".to_string(),
310            "Option<bool>" => "BOOLEAN".to_string(),
311            _ => {
312                if rust_type.starts_with("Option<") && rust_type.ends_with('>') {
313                    let inner_type = &rust_type[7..rust_type.len()-1];
314                    self.convert_type_to_sql(inner_type)
315                } else {
316                    "TEXT".to_string()
317                }
318            }
319        }
320    }
321}