Skip to main content

project_map_cli_rust/core/
parser.rs

1use tree_sitter::{Parser, Query, QueryCursor};
2use streaming_iterator::StreamingIterator;
3use std::fs;
4use std::path::Path;
5use crate::error::{AppError, Result};
6use serde::{Serialize, Deserialize};
7
8#[derive(Debug, Serialize, Deserialize, Clone)]
9pub struct Symbol {
10    pub name: String,
11    pub kind: String,
12    pub line: usize,
13    pub start_byte: usize,
14    pub end_byte: usize,
15    pub docstring: Option<String>,
16}
17
18#[derive(Debug, Serialize, Deserialize)]
19pub struct FileOutline {
20    pub path: String,
21    pub language: String,
22    pub symbols: Vec<Symbol>,
23    pub imports: Vec<String>,
24}
25
26pub struct CodeParser {
27    parser: Parser,
28}
29
30impl CodeParser {
31    pub fn new() -> Self {
32        Self {
33            parser: Parser::new(),
34        }
35    }
36
37    pub fn parse_file(&mut self, path: &Path) -> Result<FileOutline> {
38        let extension = path.extension()
39            .and_then(|s| s.to_str())
40            .unwrap_or("");
41
42        let (language, ts_language) = match extension {
43            "py" => ("python", tree_sitter_python::LANGUAGE.into()),
44            "rs" => ("rust", tree_sitter_rust::LANGUAGE.into()),
45            "ts" => ("typescript", tree_sitter_typescript::LANGUAGE_TYPESCRIPT.into()),
46            "tsx" => ("typescript", tree_sitter_typescript::LANGUAGE_TSX.into()),
47            "kt" => ("kotlin", tree_sitter_kotlin_ng::LANGUAGE.into()),
48            "sql" => ("sql", tree_sitter_sequel::LANGUAGE.into()),
49            "vue" => ("vue", tree_sitter_vue_updated::language().into()),
50            _ => return Err(AppError::Parser(format!("Unsupported extension: {}", extension))),
51        };
52
53        self.parser.set_language(&ts_language)
54            .map_err(|e| AppError::Parser(format!("Failed to set language: {}", e)))?;
55
56        let content = fs::read_to_string(path)?;
57        let tree = self.parser.parse(&content, None)
58            .ok_or_else(|| AppError::Parser("Failed to parse file".to_string()))?;
59
60        let query_str = match language {
61            "python" => "((class_definition name: (identifier) @name) @class)
62                         ((function_definition name: (identifier) @name) @function)
63                         (import_statement (dotted_name) @import)
64                         (import_from_statement module_name: (dotted_name) @import)
65                         (expression_statement (string) @doc)",
66            "rust" => "((struct_item name: (type_identifier) @name) @struct)
67                       ((enum_item name: (type_identifier) @name) @enum)
68                       ((function_item name: (identifier) @name) @function)
69                       ((trait_item name: (type_identifier) @name) @trait)
70                       ((impl_item type: (_) @name) @impl)
71                       (line_doc_comment) @doc
72                       (block_doc_comment) @doc",
73            "typescript" => "((class_declaration name: (type_identifier) @name) @class)
74                             ((function_declaration name: (identifier) @name) @function)
75                             ((generator_function_declaration name: (identifier) @name) @function)
76                             ((interface_declaration name: (type_identifier) @name) @interface)
77                             ((type_alias_declaration name: (type_identifier) @name) @type)
78                             ((enum_declaration name: (identifier) @name) @enum)
79                             ((method_definition name: (property_identifier) @name) @function)
80                             ((variable_declarator name: (identifier) @name value: (arrow_function)) @function)
81                             ((variable_declarator name: (identifier) @name value: (function_expression)) @function)
82                             ((variable_declarator name: (identifier) @name) @variable)
83                             (internal_module name: (identifier) @name) @module
84                             (import_statement source: (string (string_fragment) @import))
85                             (export_statement source: (string (string_fragment) @import))
86                             (export_statement (export_clause (export_specifier name: (identifier) @name)) @export)
87                             (comment) @doc",
88            "kotlin" => "((class_declaration name: (identifier) @name) @class)
89                         ((object_declaration name: (identifier) @name) @class)
90                         ((companion_object name: (identifier) @name) @class)
91                         ((function_declaration name: (identifier) @name) @function)
92                         (import (qualified_identifier) @import)
93                         (line_comment) @doc
94                         (block_comment) @doc",
95            "sql" => "((identifier) @name) @symbol",
96            "vue" => "((tag_name) @name) @component",
97            _ => unreachable!(),
98        };
99
100        let query = Query::new(&ts_language, query_str)
101            .map_err(|e| AppError::Parser(format!("Failed to create query: {}", e)))?;
102        
103        let mut cursor = QueryCursor::new();
104        let mut matches = cursor.matches(&query, tree.root_node(), content.as_bytes());
105
106        let mut symbols = Vec::new();
107        let mut imports = Vec::new();
108        let mut raw_docs = Vec::new();
109
110        while let Some(m) = matches.next() {
111            let mut name = String::new();
112            let mut kind = String::new();
113            let mut line = 0;
114            let mut start_byte = 0;
115            let mut end_byte = 0;
116            let mut is_import = false;
117            let mut is_doc = false;
118
119            for capture in m.captures {
120                let capture_name = query.capture_names()[capture.index as usize].to_string();
121                if capture_name == "import" {
122                    let imp = capture.node.utf8_text(content.as_bytes())
123                        .unwrap_or("")
124                        .to_string();
125                    if !imp.is_empty() {
126                        imports.push(imp);
127                    }
128                    is_import = true;
129                    break;
130                } else if capture_name == "doc" {
131                    let text = capture.node.utf8_text(content.as_bytes()).unwrap_or("");
132                    // For Python, only keep if it's a docstring (this is a heuristic)
133                    if language == "python" && !(text.starts_with("\"\"\"") || text.starts_with("'''")) {
134                        continue;
135                    }
136                    
137                    raw_docs.push((capture.node.start_position().row + 1, capture.node.start_byte(), capture.node.end_byte(), text.to_string()));
138                    is_doc = true;
139                    break;
140                } else if capture_name == "name" {
141                    name = capture.node.utf8_text(content.as_bytes())
142                        .unwrap_or("unknown")
143                        .to_string();
144                } else {
145                    kind = capture_name;
146                    line = capture.node.start_position().row + 1;
147                    start_byte = capture.node.start_byte();
148                    end_byte = capture.node.end_byte();
149                }
150            }
151            
152            if !is_import && !is_doc && !name.is_empty() && !kind.is_empty() {
153                let mut clean_name = name.replace("\n", " ")
154                    .split_whitespace()
155                    .collect::<Vec<_>>()
156                    .join(" ");
157                
158                if clean_name.chars().count() > 100 {
159                    clean_name = format!("{}...", clean_name.chars().take(97).collect::<String>());
160                }
161
162                symbols.push(Symbol {
163                    name: clean_name,
164                    kind,
165                    line,
166                    start_byte,
167                    end_byte,
168                    docstring: None,
169                });
170            }
171        }
172
173        // Second pass: Associate docstrings with symbols
174        for symbol in &mut symbols {
175            let mut attached_docs = Vec::new();
176            for (doc_line, doc_start, doc_end, doc_text) in &raw_docs {
177                // Case 1: Docstring is immediately before the symbol (within 2 lines)
178                if *doc_line < symbol.line && *doc_line >= symbol.line.saturating_sub(2) {
179                    attached_docs.push(doc_text.clone());
180                }
181                // Case 2: Docstring is inside the symbol's byte range
182                else if *doc_start >= symbol.start_byte && *doc_end <= symbol.end_byte {
183                    attached_docs.push(doc_text.clone());
184                }
185            }
186            if !attached_docs.is_empty() {
187                symbol.docstring = Some(attached_docs.join("\n\n"));
188            }
189        }
190
191        // Final filtering: remove noisy variables
192        symbols.retain(|s| s.kind != "variable" || s.docstring.is_some());
193
194        // For Vue, always add a component symbol based on the filename
195        if language == "vue" {
196            let file_name = path.file_name().and_then(|s| s.to_str()).unwrap_or("Component");
197            symbols.push(Symbol {
198                name: file_name.trim_end_matches(".vue").to_string(),
199                kind: "component".to_string(),
200                line: 1,
201                start_byte: 0,
202                end_byte: content.len(),
203                docstring: None,
204            });
205        }
206
207        Ok(FileOutline {
208            path: path.to_string_lossy().to_string(),
209            language: language.to_string(),
210            symbols,
211            imports,
212        })
213    }
214}