tree-parser 0.1.4

An asynchronous Rust library for parsing source code and searching constructs.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
//! Core parsing functionality

use crate::{
    languages::*, CodeConstruct, ConstructMetadata, Error, ErrorType, FileError, Language,
    LanguageDetection, ParseOptions, ParsedFile, ParsedProject,
};
use std::collections::HashMap;
use std::path::{Path, PathBuf};

use tokio::fs;
use tree_sitter::{Node, Parser, Tree};
use walkdir::WalkDir;

/// Parse a single source code file and extract code constructs
/// 
/// This function reads a source code file, parses it using tree-sitter,
/// and extracts all identifiable code constructs (functions, classes, etc.).
/// 
/// # Arguments
/// 
/// * `file_path` - Path to the source code file to parse
/// * `language` - The programming language of the file
/// 
/// # Returns
/// 
/// Returns a `ParsedFile` containing all extracted constructs and metadata,
/// or an `Error` if parsing fails.
/// 
/// # Examples
/// 
/// ```rust
/// use tree_parser::{parse_file, Language};
/// 
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
///     let result = parse_file("src/main.rs", Language::Rust).await?;
///     println!("Found {} constructs", result.constructs.len());
///     Ok(())
/// }
/// ```
/// 
/// # Errors
/// 
/// This function will return an error if:
/// - The file cannot be read (I/O error)
/// - The file content cannot be parsed (syntax error)
/// - The specified language is not supported
pub async fn parse_file(file_path: &str, language: Language) -> Result<ParsedFile, Error> {
    // Read file content
    let content = fs::read_to_string(file_path)
        .await
        .map_err(|e| Error::Io(e.to_string()))?;
    
    let file_size_bytes = content.len();
    
    // Get tree-sitter language
    let ts_language = get_tree_sitter_language(&language)?;
    
    // Create parser
    let mut parser = Parser::new();
    parser
        .set_language(&ts_language)
        .map_err(|e| Error::Parse(e.to_string()))?;
    
    // Parse the content
    let tree = parser
        .parse(&content, None)
        .ok_or_else(|| Error::Parse("Failed to parse file".to_string()))?;
    
    // Extract code constructs
    let constructs = extract_constructs(&tree, &content, &language);
    
    let path = Path::new(file_path);
    let relative_path = path
        .file_name()
        .unwrap_or_default()
        .to_string_lossy()
        .to_string();
    
    Ok(ParsedFile {
        file_path: file_path.to_string(),
        relative_path,
        language,
        constructs,
        syntax_tree: Some(tree),
        file_size_bytes,

    })
}

/// Parse an entire project directory recursively
/// 
/// This function traverses a directory structure, identifies source code files,
/// and parses them concurrently to extract code constructs from all supported files.
/// 
/// # Arguments
/// 
/// * `dir_path` - Path to the root directory to parse
/// * `options` - Configuration options controlling parsing behavior
/// 
/// # Returns
/// 
/// Returns a `ParsedProject` containing results from all parsed files,
/// including statistics and error information.
/// 
/// # Examples
/// 
/// ```rust
/// use tree_parser::{parse_directory, ParseOptions};
/// 
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
///     let options = ParseOptions::default();
///     let project = parse_directory("./src", options).await?;
///     
///     println!("Parsed {} files", project.total_files_processed);
///     for (language, count) in &project.language_distribution {
///         println!("{:?}: {} files", language, count);
///     }
///     Ok(())
/// }
/// ```
/// 
/// # Performance
/// 
/// This function uses concurrent processing to parse multiple files simultaneously.
/// The concurrency level is controlled by `options.max_concurrent_files`.
pub async fn parse_directory(
    dir_path: &str,
    options: ParseOptions,
) -> Result<ParsedProject, Error> {
    let root_path = PathBuf::from(dir_path);
    
    if !root_path.exists() {
        return Err(Error::Io(format!("Directory does not exist: {}", dir_path)));
    }
    
    // Collect files to parse
    let files_to_parse = collect_files(&root_path, &options)?;
    
    // Parse files in parallel
    let (parsed_files, error_files) = parse_files_parallel(files_to_parse, &options).await;
    
    // Calculate statistics
    let total_files_processed = parsed_files.len();
    let mut language_distribution = HashMap::new();
    for file in &parsed_files {
        *language_distribution.entry(file.language.clone()).or_insert(0) += 1;
    }
    
    Ok(ParsedProject {
        root_path: dir_path.to_string(),
        files: parsed_files,
        total_files_processed,
        language_distribution,
        error_files,
    })
}

/// Parse a project directory with custom file filtering
/// 
/// This function provides advanced filtering capabilities for selecting which files
/// to parse within a directory structure. It combines the standard parsing options
/// with custom filtering criteria.
/// 
/// # Arguments
/// 
/// * `dir_path` - Path to the root directory to parse
/// * `file_filter` - Custom filter criteria for file selection
/// * `options` - Configuration options controlling parsing behavior
/// 
/// # Returns
/// 
/// Returns a `ParsedProject` containing results from all files that match
/// the filter criteria.
/// 
/// # Examples
/// 
/// ```rust
/// use tree_parser::{parse_directory_with_filter, ParseOptions, FileFilter, Language};
/// use std::sync::Arc;
/// 
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
///     let filter = FileFilter {
///         languages: Some(vec![Language::Rust, Language::Python]),
///         extensions: None,
///         min_size_bytes: Some(100),
///         max_size_bytes: Some(100_000),
///         custom_predicate: Some(Arc::new(|path| {
///             !path.to_string_lossy().contains("test")
///         })),
///     };
///     
///     let options = ParseOptions::default();
///     let project = parse_directory_with_filter("./src", &filter, options).await?;
///     
///     println!("Parsed {} filtered files", project.total_files_processed);
///     Ok(())
/// }
/// ```
pub async fn parse_directory_with_filter(
    dir_path: &str,
    file_filter: &crate::FileFilter,
    options: ParseOptions,
) -> Result<ParsedProject, Error> {
    let root_path = PathBuf::from(dir_path);
    
    if !root_path.exists() {
        return Err(Error::Io(format!("Directory does not exist: {}", dir_path)));
    }
    
    // Collect files to parse with custom filter
    let files_to_parse = collect_files_with_filter(&root_path, &options, file_filter)?;
    
    // Parse files in parallel
    let (parsed_files, error_files) = parse_files_parallel(files_to_parse, &options).await;
    
    // Calculate statistics
    let total_files_processed = parsed_files.len();
    let mut language_distribution = HashMap::new();
    for file in &parsed_files {
        *language_distribution.entry(file.language.clone()).or_insert(0) += 1;
    }
    
    Ok(ParsedProject {
        root_path: dir_path.to_string(),
        files: parsed_files,
        total_files_processed,

        language_distribution,
        error_files,
    })
}

/// Collect files to parse from directory based on parsing options
/// 
/// This internal function traverses a directory structure and collects all files
/// that should be parsed according to the provided options.
/// 
/// # Arguments
/// 
/// * `root_path` - Root directory path to start collection from
/// * `options` - Parsing options that control file selection
/// 
/// # Returns
/// 
/// A vector of file paths that should be parsed, or an error if directory
/// traversal fails.
fn collect_files(root_path: &Path, options: &ParseOptions) -> Result<Vec<PathBuf>, Error> {
    let mut files = Vec::new();
    
    let walker = if options.recursive {
        WalkDir::new(root_path)
    } else {
        WalkDir::new(root_path).max_depth(1)
    };
    
    for entry in walker {
        let entry = entry.map_err(|e| Error::Io(e.to_string()))?;
        let path = entry.path();
        
        // Skip directories
        if path.is_dir() {
            continue;
        }
        
        // Skip hidden files if not included
        if !options.include_hidden_files && is_hidden_file(path) {
            continue;
        }
        
        // Check ignore patterns
        if should_ignore_file(path, &options.ignore_patterns) {
            continue;
        }
        
        // Check file size
        if let Ok(metadata) = path.metadata() {
            let size_mb = metadata.len() as usize / (1024 * 1024);
            if size_mb > options.max_file_size_mb {
                continue;
            }
        }
        
        // Check if we can detect the language
        if detect_language_by_extension(&path.to_string_lossy()).is_some() {
            files.push(path.to_path_buf());
        }
    }
    
    Ok(files)
}

/// Collect files with custom filter criteria
/// 
/// This internal function extends the basic file collection with additional
/// filtering capabilities provided by a `FileFilter`.
/// 
/// # Arguments
/// 
/// * `root_path` - Root directory path to start collection from
/// * `options` - Parsing options that control file selection
/// * `filter` - Custom filter criteria for more precise file selection
/// 
/// # Returns
/// 
/// A vector of file paths that match both the parsing options and the custom
/// filter criteria.
fn collect_files_with_filter(
    root_path: &Path,
    options: &ParseOptions,
    filter: &crate::FileFilter,
) -> Result<Vec<PathBuf>, Error> {
    let mut files = collect_files(root_path, options)?;
    
    // Apply custom filter
    files.retain(|path| {
        // Check extensions
        if let Some(ref extensions) = filter.extensions {
            if let Some(ext) = path.extension() {
                if !extensions.contains(&ext.to_string_lossy().to_lowercase()) {
                    return false;
                }
            } else {
                return false;
            }
        }
        
        // Check languages
        if let Some(ref languages) = filter.languages {
            if let Some(detected_lang) = detect_language_by_extension(&path.to_string_lossy()) {
                if !languages.contains(&detected_lang) {
                    return false;
                }
            } else {
                return false;
            }
        }
        
        // Check file size
        if let Ok(metadata) = path.metadata() {
            let size = metadata.len() as usize;
            
            if let Some(min_size) = filter.min_size_bytes {
                if size < min_size {
                    return false;
                }
            }
            
            if let Some(max_size) = filter.max_size_bytes {
                if size > max_size {
                    return false;
                }
            }
        }
        
        // Apply custom predicate
        if let Some(ref predicate) = filter.custom_predicate {
            if !predicate(path) {
                return false;
            }
        }
        
        true
    });
    
    Ok(files)
}

/// Parse files in parallel
async fn parse_files_parallel(
    files: Vec<PathBuf>,
    options: &ParseOptions,
) -> (Vec<ParsedFile>, Vec<FileError>) {
    let chunk_size = std::cmp::max(1, files.len() / options.max_concurrent_files);
    let mut parsed_files = Vec::new();
    let mut error_files = Vec::new();
    
    for chunk in files.chunks(chunk_size) {
        let chunk_results: Vec<_> = chunk
            .iter()
            .map(|path| async move {
                let path_str = path.to_string_lossy().to_string();
                
                // Detect language
                let language = match options.language_detection {
                    LanguageDetection::ByExtension => detect_language_by_extension(&path_str),
                    LanguageDetection::Combined => {
                        // Try to read content for better detection
                        if let Ok(content) = tokio::fs::read_to_string(path).await {
                            detect_language(&path_str, Some(&content))
                        } else {
                            detect_language_by_extension(&path_str)
                        }
                    }
                    _ => detect_language_by_extension(&path_str), // Fallback
                };
                
                if let Some(lang) = language {
                    match parse_file(&path_str, lang).await {
                        Ok(parsed) => Ok(parsed),
                        Err(e) => Err(FileError {
                            file_path: path_str,
                            error_type: ErrorType::ParseError,
                            message: e.to_string(),
                        }),
                    }
                } else {
                    Err(FileError {
                        file_path: path_str,
                        error_type: ErrorType::UnsupportedLanguage,
                        message: "Could not detect language".to_string(),
                    })
                }
            })
            .collect();
        
        // Await all tasks in this chunk
        for result in futures::future::join_all(chunk_results).await {
            match result {
                Ok(parsed_file) => parsed_files.push(parsed_file),
                Err(error) => error_files.push(error),
            }
        }
    }
    
    (parsed_files, error_files)
}

/// Extract code constructs from syntax tree
fn extract_constructs(tree: &Tree, source: &str, language: &Language) -> Vec<CodeConstruct> {
    let root_node = tree.root_node();
    let mut root_constructs = Vec::new();
    
    // Extract constructs with proper parent-child relationships
    extract_constructs_hierarchical(root_node, source, language, &mut root_constructs, None);
    
    // Flatten the hierarchy for the final result while preserving relationships
    let mut all_constructs = Vec::new();
    flatten_constructs(&root_constructs, &mut all_constructs);
    
    all_constructs
}

/// Recursively extract constructs from nodes with proper hierarchy
fn extract_constructs_hierarchical(
    node: Node,
    source: &str,
    language: &Language,
    constructs: &mut Vec<CodeConstruct>,
    parent_construct: Option<&CodeConstruct>,
) {
    let node_type = node.kind();
    let supported_types = get_supported_node_types(language);
    
    if supported_types.contains(&node_type.to_string()) {
        let mut construct = create_code_construct_with_parent(node, source, language, parent_construct);
        
        // Recursively process children and add them to this construct
        let mut child_constructs = Vec::new();
        for i in 0..node.child_count() {
            if let Some(child) = node.child(i) {
                extract_constructs_hierarchical(child, source, language, &mut child_constructs, Some(&construct));
            }
        }
        
        construct.children = child_constructs;
        constructs.push(construct);
    } else {
        // If this node is not a supported construct, continue searching in its children
        for i in 0..node.child_count() {
            if let Some(child) = node.child(i) {
                extract_constructs_hierarchical(child, source, language, constructs, parent_construct);
            }
        }
    }
}

/// Flatten hierarchical constructs into a single vector while preserving relationships
fn flatten_constructs(constructs: &[CodeConstruct], flattened: &mut Vec<CodeConstruct>) {
    for construct in constructs {
        flattened.push(construct.clone());
        flatten_constructs(&construct.children, flattened);
    }
}

/// Create a CodeConstruct from a tree-sitter node with proper parent relationship
fn create_code_construct_with_parent(
    node: Node, 
    source: &str, 
    language: &Language,
    parent_construct: Option<&CodeConstruct>
) -> CodeConstruct {
    let start_byte = node.start_byte();
    let end_byte = node.end_byte();
    let source_code = source[start_byte..end_byte].to_string();
    
    let start_point = node.start_position();
    let end_point = node.end_position();
    
    // Extract name if possible
    let name = extract_construct_name(node, source);
    
    // Create metadata
    let metadata = extract_metadata(node, source, language);
    
    // Set parent if provided
    let parent = parent_construct.map(|p| Box::new(p.clone()));
    
    CodeConstruct {
        node_type: node.kind().to_string(),
        name,
        source_code,
        start_line: start_point.row + 1, // Convert to 1-based
        end_line: end_point.row + 1,
        start_byte,
        end_byte,
        parent,
        children: Vec::new(), // Will be populated by the caller
        metadata,
    }
}

/// Extract construct name from node
fn extract_construct_name(node: Node, source: &str) -> Option<String> {
    // Try to find identifier child
    for i in 0..node.child_count() {
        if let Some(child) = node.child(i) {
            if child.kind() == "identifier" || child.kind() == "name" {
                let start = child.start_byte();
                let end = child.end_byte();
                return Some(source[start..end].to_string());
            }
        }
    }
    None
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::Language;

    #[test]
    fn test_parent_child_relationships() {
        // Simple Python code with nested structure
        let source = "class TestClass:\n    def test_method(self):\n        pass";
        
        // Create a simple tree-sitter parser for testing
        let mut parser = Parser::new();
        let language = crate::languages::get_tree_sitter_language(&Language::Python).unwrap();
        parser.set_language(&language).unwrap();
        
        let tree = parser.parse(source, None).unwrap();
        let constructs = extract_constructs(&tree, source, &Language::Python);
        
        // Find class and method constructs
        let class_construct = constructs.iter().find(|c| c.node_type == "class_definition");
        let method_construct = constructs.iter().find(|c| c.node_type == "function_definition");
        
        assert!(class_construct.is_some(), "Should find class construct");
        assert!(method_construct.is_some(), "Should find method construct");
        
        let method = method_construct.unwrap();
        
        // Check that method has a parent
        assert!(method.parent.is_some(), "Method should have a parent");
        
        if let Some(parent) = &method.parent {
            assert_eq!(parent.node_type, "class_definition", "Method's parent should be the class");
        }
        
        // Check that class has children
        let class = class_construct.unwrap();
        assert!(!class.children.is_empty(), "Class should have children");
        
        let child_method = class.children.iter().find(|c| c.node_type == "function_definition");
        assert!(child_method.is_some(), "Class should contain the method as a child");
    }
}

/// Extract metadata from node
fn extract_metadata(_node: Node, _source: &str, _language: &Language) -> ConstructMetadata {
    ConstructMetadata {
        visibility: None,
        modifiers: Vec::new(),
        parameters: Vec::new(),
        return_type: None,
        inheritance: Vec::new(),
        annotations: Vec::new(),
        documentation: None,
    }
}

/// Check if file is hidden
fn is_hidden_file(path: &Path) -> bool {
    path.file_name()
        .and_then(|name| name.to_str())
        .map(|name| name.starts_with('.'))
        .unwrap_or(false)
}

/// Check if file should be ignored based on patterns
fn should_ignore_file(path: &Path, ignore_patterns: &[String]) -> bool {
    let path_str = path.to_string_lossy();
    
    for pattern in ignore_patterns {
        if path_str.contains(pattern) {
            return true;
        }
    }
    
    false
}