1use crate::node::{CodeNode, NodeKind};
8
9pub const FALLBACK_EXTENSIONS: &[&str] = &[
17 "kt", "kts", "swift", "rb", "php", "phtml", "sh", "bash", "zsh", ];
23
24pub const MARKDOWN_EXTENSIONS: &[&str] = &["md", "markdown"];
29
30pub fn is_fallback_supported_extension(ext: &str) -> bool {
31 let ext = ext.to_ascii_lowercase();
32 FALLBACK_EXTENSIONS.iter().any(|e| *e == ext)
33}
34
35pub fn is_markdown_extension(ext: &str) -> bool {
37 let ext = ext.to_ascii_lowercase();
38 MARKDOWN_EXTENSIONS.iter().any(|e| *e == ext)
39}
40
41pub fn parse_fallback_source(source: &str, file_path: &str, ext: &str) -> Vec<CodeNode> {
42 let ext = ext.to_ascii_lowercase();
43 let is_markdown = is_markdown_extension(&ext);
44 let mut nodes = Vec::new();
45
46 for (idx, line) in source.lines().enumerate() {
47 let line_no = idx as u32 + 1;
48 let trimmed = line.trim_start();
49
50 if trimmed.is_empty()
56 || (!is_markdown && (trimmed.starts_with('#') || trimmed.starts_with("//")))
57 {
58 continue;
59 }
60
61 let candidate = match ext.as_str() {
62 "md" | "markdown" => parse_markdown_line(trimmed),
63 "kt" | "kts" => parse_kotlin_line(trimmed),
64 "swift" => parse_swift_line(trimmed),
65 "rb" => parse_ruby_line(trimmed),
66 "php" | "phtml" => parse_php_line(trimmed),
67 "sh" | "bash" | "zsh" => parse_shell_line(trimmed),
68 _ => None,
69 };
70
71 if let Some((name, kind)) = candidate {
72 let col = (line.len().saturating_sub(trimmed.len())) as u32;
73 let node = CodeNode::new(&name, &name, kind, file_path)
74 .with_lines(line_no, line_no)
75 .with_column(col)
76 .with_signature(trimmed.to_string());
77 nodes.push(node);
78 }
79 }
80
81 nodes
82}
83
84fn parse_kotlin_line(line: &str) -> Option<(String, NodeKind)> {
85 if let Some(rest) = line.strip_prefix("fun ") {
86 return take_ident(rest).map(|name| (name, NodeKind::Function));
87 }
88
89 if let Some(rest) = line.strip_prefix("class ") {
90 return take_ident(rest).map(|name| (name, NodeKind::Class));
91 }
92
93 if let Some(rest) = line.strip_prefix("data class ") {
94 return take_ident(rest).map(|name| (name, NodeKind::Class));
95 }
96
97 if let Some(rest) = line.strip_prefix("interface ") {
98 return take_ident(rest).map(|name| (name, NodeKind::Interface));
99 }
100
101 if let Some(rest) = line.strip_prefix("object ") {
102 return take_ident(rest).map(|name| (name, NodeKind::Class));
103 }
104
105 if let Some(rest) = line.strip_prefix("enum class ") {
106 return take_ident(rest).map(|name| (name, NodeKind::Enum));
107 }
108
109 None
110}
111
112fn parse_swift_line(line: &str) -> Option<(String, NodeKind)> {
113 if let Some(rest) = line.strip_prefix("func ") {
114 return take_ident(rest).map(|name| (name, NodeKind::Function));
115 }
116
117 if let Some(rest) = line.strip_prefix("class ") {
118 return take_ident(rest).map(|name| (name, NodeKind::Class));
119 }
120
121 if let Some(rest) = line.strip_prefix("struct ") {
122 return take_ident(rest).map(|name| (name, NodeKind::Struct));
123 }
124
125 if let Some(rest) = line.strip_prefix("enum ") {
126 return take_ident(rest).map(|name| (name, NodeKind::Enum));
127 }
128
129 if let Some(rest) = line.strip_prefix("protocol ") {
130 return take_ident(rest).map(|name| (name, NodeKind::Interface));
131 }
132
133 if let Some(rest) = line.strip_prefix("extension ") {
134 return take_ident(rest).map(|name| (name, NodeKind::Module));
135 }
136
137 None
138}
139
140fn parse_ruby_line(line: &str) -> Option<(String, NodeKind)> {
141 if let Some(rest) = line.strip_prefix("def ") {
142 return take_ident(rest.trim_start_matches("self.")).map(|name| (name, NodeKind::Function));
143 }
144
145 if let Some(rest) = line.strip_prefix("class ") {
146 return take_ident(rest).map(|name| (name, NodeKind::Class));
147 }
148
149 if let Some(rest) = line.strip_prefix("module ") {
150 return take_ident(rest).map(|name| (name, NodeKind::Module));
151 }
152
153 None
154}
155
156fn parse_php_line(line: &str) -> Option<(String, NodeKind)> {
157 if let Some(rest) = line.strip_prefix("function ") {
158 return take_ident(rest).map(|name| (name, NodeKind::Function));
159 }
160
161 if let Some(rest) = line.strip_prefix("class ") {
162 return take_ident(rest).map(|name| (name, NodeKind::Class));
163 }
164
165 if let Some(rest) = line.strip_prefix("interface ") {
166 return take_ident(rest).map(|name| (name, NodeKind::Interface));
167 }
168
169 if let Some(rest) = line.strip_prefix("trait ") {
170 return take_ident(rest).map(|name| (name, NodeKind::Interface));
171 }
172
173 None
174}
175
176fn parse_shell_line(line: &str) -> Option<(String, NodeKind)> {
177 if let Some(rest) = line.strip_prefix("function ") {
178 return take_ident(rest).map(|name| (name, NodeKind::Function));
179 }
180
181 if let Some(paren_idx) = line.find("()") {
183 let name = line[..paren_idx].trim();
184 if is_shell_identifier(name) {
188 return Some((name.to_string(), NodeKind::Function));
189 }
190 }
191
192 None
193}
194
195fn is_shell_identifier(s: &str) -> bool {
197 !s.is_empty()
198 && s.chars()
199 .next()
200 .is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
201 && s.chars()
202 .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
203}
204
205fn parse_markdown_line(line: &str) -> Option<(String, NodeKind)> {
206 let trimmed = line.trim_start();
207 if let Some(rest) = trimmed.strip_prefix("# ") {
208 return take_ident(rest).map(|name| (name, NodeKind::Section));
209 }
210 if let Some(rest) = trimmed.strip_prefix("## ") {
211 return take_ident(rest).map(|name| (name, NodeKind::Section));
212 }
213 if let Some(rest) = trimmed.strip_prefix("### ") {
214 return take_ident(rest).map(|name| (name, NodeKind::Section));
215 }
216 if trimmed.starts_with("#") && trimmed.contains(' ') {
218 let name = trimmed
219 .split_whitespace()
220 .nth(1)
221 .unwrap_or(trimmed)
222 .trim_start_matches('#')
223 .trim();
224 if !name.is_empty() {
225 return Some((name.to_string(), NodeKind::Section));
226 }
227 }
228 None
229}
230
231fn take_ident(input: &str) -> Option<String> {
232 let mut out = String::new();
233 for ch in input.chars() {
234 if ch.is_alphanumeric() || ch == '_' || ch == '-' {
235 out.push(ch);
236 } else {
237 break;
238 }
239 }
240
241 if out.is_empty() {
242 None
243 } else {
244 Some(out)
245 }
246}
247
248#[cfg(test)]
249mod tests {
250 use super::*;
251
252 #[test]
253 fn fallback_supports_requested_extensions() {
254 for ext in ["kt", "swift", "rb", "php", "sh"] {
255 assert!(is_fallback_supported_extension(ext));
256 }
257 assert!(!is_fallback_supported_extension("md"));
260 assert!(is_markdown_extension("md"));
261 }
262
263 #[test]
264 fn parses_kotlin_function() {
265 let source = "fun fetchUser(id: String): User = TODO()";
266 let nodes = parse_fallback_source(source, "sample.kt", "kt");
267 assert!(nodes.iter().any(|n| n.name == "fetchUser"));
268 }
269
270 #[test]
271 fn parses_shell_function() {
272 let source = "deploy_prod() { echo hi; }";
273 let nodes = parse_fallback_source(source, "deploy.sh", "sh");
274 assert!(nodes.iter().any(|n| n.name == "deploy_prod"));
275 }
276
277 #[test]
278 fn parses_swift_source() {
279 let source = r#"
280class UserManager {
281 func getUser() -> User {
282 return User()
283 }
284}
285
286struct Point {
287 var x: Double
288 var y: Double
289}
290
291enum Status {
292 case active
293 case inactive
294}
295"#;
296 let nodes = parse_fallback_source(source, "Users.swift", "swift");
297 assert!(nodes
298 .iter()
299 .any(|n| n.name == "UserManager" && matches!(n.kind, NodeKind::Class)));
300 assert!(nodes
301 .iter()
302 .any(|n| n.name == "getUser" && matches!(n.kind, NodeKind::Function)));
303 assert!(nodes
304 .iter()
305 .any(|n| n.name == "Point" && matches!(n.kind, NodeKind::Struct)));
306 assert!(nodes
307 .iter()
308 .any(|n| n.name == "Status" && matches!(n.kind, NodeKind::Enum)));
309 }
310
311 #[test]
312 fn parses_ruby_source() {
313 let source = r#"
314class ApplicationController
315 def index
316 render json: { status: "ok" }
317 end
318
319 def show
320 @user = User.find(params[:id])
321 end
322end
323
324module Authentication
325end
326"#;
327 let nodes = parse_fallback_source(source, "controller.rb", "rb");
328 assert!(nodes
329 .iter()
330 .any(|n| n.name == "ApplicationController" && matches!(n.kind, NodeKind::Class)));
331 assert!(nodes
332 .iter()
333 .any(|n| n.name == "index" && matches!(n.kind, NodeKind::Function)));
334 assert!(nodes
335 .iter()
336 .any(|n| n.name == "show" && matches!(n.kind, NodeKind::Function)));
337 assert!(nodes
338 .iter()
339 .any(|n| n.name == "Authentication" && matches!(n.kind, NodeKind::Module)));
340 }
341
342 #[test]
343 fn parses_php_source() {
344 let source = r#"
345class PaymentProcessor {
346 function processPayment($amount) {
347 return true;
348 }
349}
350
351interface Gateway {
352}
353
354function helper() {
355}
356"#;
357 let nodes = parse_fallback_source(source, "payment.php", "php");
358 assert!(nodes
359 .iter()
360 .any(|n| n.name == "PaymentProcessor" && matches!(n.kind, NodeKind::Class)));
361 assert!(nodes
362 .iter()
363 .any(|n| n.name == "processPayment" && matches!(n.kind, NodeKind::Function)));
364 assert!(nodes
365 .iter()
366 .any(|n| n.name == "Gateway" && matches!(n.kind, NodeKind::Interface)));
367 assert!(nodes
368 .iter()
369 .any(|n| n.name == "helper" && matches!(n.kind, NodeKind::Function)));
370 }
371
372 #[test]
373 fn fallback_ignores_comments() {
374 let source = r#"
376// class NotAClass
377# def not_a_function
378fun realFunction(x: Int): Int = x
379"#;
380 let nodes = parse_fallback_source(source, "test.kt", "kt");
381 assert!(!nodes.iter().any(|n| n.name == "NotAClass"));
382 assert!(!nodes.iter().any(|n| n.name == "not_a_function"));
383 assert!(nodes.iter().any(|n| n.name == "realFunction"));
384 }
385
386 #[test]
387 fn fallback_kotlin_class_and_data_class() {
388 let source = r#"
389class Repository {
390}
391data class UserDto(val name: String)
392object Singleton
393"#;
394 let nodes = parse_fallback_source(source, "models.kt", "kt");
395 assert!(nodes
396 .iter()
397 .any(|n| n.name == "Repository" && matches!(n.kind, NodeKind::Class)));
398 assert!(nodes
399 .iter()
400 .any(|n| n.name == "UserDto" && matches!(n.kind, NodeKind::Class)));
401 assert!(nodes
402 .iter()
403 .any(|n| n.name == "Singleton" && matches!(n.kind, NodeKind::Class)));
404 }
405
406 #[test]
407 fn fallback_empty_source_returns_empty() {
408 let nodes = parse_fallback_source("", "empty.kt", "kt");
409 assert!(nodes.is_empty());
410 }
411
412 #[test]
413 fn fallback_unsupported_extension_returns_empty() {
414 assert!(!is_fallback_supported_extension("xyz"));
416 assert!(!is_fallback_supported_extension("rs"));
417 }
418
419 #[test]
420 fn parses_shell_function_keyword() {
421 let source = "function deploy_staging { echo staging; }";
422 let nodes = parse_fallback_source(source, "deploy.bash", "bash");
423 assert!(nodes.iter().any(|n| n.name == "deploy_staging"));
424 }
425}
426
427#[cfg(test)]
428mod regression_tests {
429 use super::*;
430
431 #[test]
432 fn markdown_is_not_indexed_as_code() {
433 assert!(!is_fallback_supported_extension("md"));
437 assert!(!is_fallback_supported_extension("markdown"));
438 assert!(is_markdown_extension("md"));
439 }
440
441 #[test]
442 fn markdown_still_parses_when_asked_directly() {
443 let nodes = parse_fallback_source("# fetch benchmark\n## setup\n", "README.md", "md");
444 assert_eq!(nodes.len(), 2);
445 assert!(nodes.iter().all(|n| n.kind == NodeKind::Section));
446 }
447
448 #[test]
449 fn shell_comments_are_not_functions() {
450 let src = "#!/bin/bash\n# Compare app.fetch() between refs\nreal_fn() {\n echo hi\n}\n";
454 let nodes = parse_fallback_source(src, "compare.sh", "sh");
455
456 assert_eq!(nodes.len(), 1, "only the real function should be indexed");
457 assert_eq!(nodes[0].name, "real_fn");
458 }
459
460 #[test]
461 fn shell_names_must_be_identifiers() {
462 assert!(is_shell_identifier("deploy_app"));
463 assert!(is_shell_identifier("build-web"));
464 assert!(!is_shell_identifier("# Compare app.fetch"));
465 assert!(!is_shell_identifier("app.fetch"));
466 assert!(!is_shell_identifier(""));
467 assert!(!is_shell_identifier("2fast"));
468 }
469
470 #[test]
471 fn prose_containing_parens_is_not_a_function() {
472 let nodes = parse_fallback_source("echo \"call foo() now\"\n", "x.sh", "sh");
473 assert!(
474 nodes.is_empty(),
475 "a string mentioning foo() is not a definition"
476 );
477 }
478
479 #[test]
480 fn double_slash_comments_are_skipped() {
481 let nodes = parse_fallback_source("// fun notReal()\nfun real() {}\n", "a.kt", "kt");
482 assert_eq!(nodes.len(), 1);
483 assert_eq!(nodes[0].name, "real");
484 }
485}