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 let mut pending_annotations: Vec<String> = Vec::new();
46
47 for (idx, line) in source.lines().enumerate() {
48 let line_no = idx as u32 + 1;
49 let trimmed = line.trim_start();
50
51 if trimmed.is_empty() {
52 continue;
53 }
54
55 if !is_markdown && (trimmed.starts_with('#') || trimmed.starts_with("//")) {
61 pending_annotations.clear();
62 continue;
63 }
64
65 if !is_markdown && trimmed.starts_with('@') {
68 pending_annotations.push(trimmed.to_string());
69 continue;
70 }
71
72 let candidate = match ext.as_str() {
73 "md" | "markdown" => parse_markdown_line(trimmed),
74 "kt" | "kts" => parse_kotlin_line(trimmed),
75 "swift" => parse_swift_line(trimmed),
76 "rb" => parse_ruby_line(trimmed),
77 "php" | "phtml" => parse_php_line(trimmed),
78 "sh" | "bash" | "zsh" => parse_shell_line(trimmed),
79 _ => None,
80 };
81
82 if let Some((name, kind)) = candidate {
83 let col = (line.len().saturating_sub(trimmed.len())) as u32;
84 let signature = if pending_annotations.is_empty() {
85 trimmed.to_string()
86 } else {
87 let mut signature = pending_annotations.join(" ");
88 signature.push(' ');
89 signature.push_str(trimmed);
90 signature
91 };
92 pending_annotations.clear();
93 let node = CodeNode::new(&name, &name, kind, file_path)
94 .with_lines(line_no, line_no)
95 .with_column(col)
96 .with_signature(signature);
97 nodes.push(node);
98 } else {
99 pending_annotations.clear();
100 }
101 }
102
103 nodes
104}
105
106fn parse_kotlin_line(line: &str) -> Option<(String, NodeKind)> {
107 let line = strip_kotlin_modifiers(line);
108 if let Some(rest) = line.strip_prefix("fun ") {
109 return take_ident(rest).map(|name| (name, NodeKind::Function));
110 }
111
112 if let Some(rest) = line.strip_prefix("class ") {
113 return take_ident(rest).map(|name| (name, NodeKind::Class));
114 }
115
116 if let Some(rest) = line.strip_prefix("interface ") {
117 return take_ident(rest).map(|name| (name, NodeKind::Interface));
118 }
119
120 if let Some(rest) = line.strip_prefix("object ") {
121 return take_ident(rest).map(|name| (name, NodeKind::Class));
122 }
123
124 if let Some(rest) = line.strip_prefix("enum class ") {
125 return take_ident(rest).map(|name| (name, NodeKind::Enum));
126 }
127
128 None
129}
130
131fn strip_kotlin_modifiers(line: &str) -> &str {
132 let mut rest = line.trim_start();
133 loop {
134 let stripped = [
135 "public ",
136 "private ",
137 "protected ",
138 "internal ",
139 "open ",
140 "abstract ",
141 "sealed ",
142 "inner ",
143 "data ",
144 "override ",
145 "lateinit ",
146 ]
147 .iter()
148 .find_map(|prefix| rest.strip_prefix(prefix));
149 match stripped {
150 Some(next) => rest = next.trim_start(),
151 None => return rest,
152 }
153 }
154}
155
156fn parse_swift_line(line: &str) -> Option<(String, NodeKind)> {
157 if let Some(rest) = line.strip_prefix("func ") {
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("struct ") {
166 return take_ident(rest).map(|name| (name, NodeKind::Struct));
167 }
168
169 if let Some(rest) = line.strip_prefix("enum ") {
170 return take_ident(rest).map(|name| (name, NodeKind::Enum));
171 }
172
173 if let Some(rest) = line.strip_prefix("protocol ") {
174 return take_ident(rest).map(|name| (name, NodeKind::Interface));
175 }
176
177 if let Some(rest) = line.strip_prefix("extension ") {
178 return take_ident(rest).map(|name| (name, NodeKind::Module));
179 }
180
181 None
182}
183
184fn parse_ruby_line(line: &str) -> Option<(String, NodeKind)> {
185 if let Some(rest) = line.strip_prefix("def ") {
186 return take_ident(rest.trim_start_matches("self.")).map(|name| (name, NodeKind::Function));
187 }
188
189 if let Some(rest) = line.strip_prefix("class ") {
190 return take_ident(rest).map(|name| (name, NodeKind::Class));
191 }
192
193 if let Some(rest) = line.strip_prefix("module ") {
194 return take_ident(rest).map(|name| (name, NodeKind::Module));
195 }
196
197 None
198}
199
200fn parse_php_line(line: &str) -> Option<(String, NodeKind)> {
201 if let Some(rest) = line.strip_prefix("function ") {
202 return take_ident(rest).map(|name| (name, NodeKind::Function));
203 }
204
205 if let Some(rest) = line.strip_prefix("class ") {
206 return take_ident(rest).map(|name| (name, NodeKind::Class));
207 }
208
209 if let Some(rest) = line.strip_prefix("interface ") {
210 return take_ident(rest).map(|name| (name, NodeKind::Interface));
211 }
212
213 if let Some(rest) = line.strip_prefix("trait ") {
214 return take_ident(rest).map(|name| (name, NodeKind::Interface));
215 }
216
217 None
218}
219
220fn parse_shell_line(line: &str) -> Option<(String, NodeKind)> {
221 if let Some(rest) = line.strip_prefix("function ") {
222 return take_ident(rest).map(|name| (name, NodeKind::Function));
223 }
224
225 if let Some(paren_idx) = line.find("()") {
227 let name = line[..paren_idx].trim();
228 if is_shell_identifier(name) {
232 return Some((name.to_string(), NodeKind::Function));
233 }
234 }
235
236 None
237}
238
239fn is_shell_identifier(s: &str) -> bool {
241 !s.is_empty()
242 && s.chars()
243 .next()
244 .is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
245 && s.chars()
246 .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
247}
248
249fn parse_markdown_line(line: &str) -> Option<(String, NodeKind)> {
250 let trimmed = line.trim_start();
251 if let Some(rest) = trimmed.strip_prefix("# ") {
252 return take_ident(rest).map(|name| (name, NodeKind::Section));
253 }
254 if let Some(rest) = trimmed.strip_prefix("## ") {
255 return take_ident(rest).map(|name| (name, NodeKind::Section));
256 }
257 if let Some(rest) = trimmed.strip_prefix("### ") {
258 return take_ident(rest).map(|name| (name, NodeKind::Section));
259 }
260 if trimmed.starts_with("#") && trimmed.contains(' ') {
262 let name = trimmed
263 .split_whitespace()
264 .nth(1)
265 .unwrap_or(trimmed)
266 .trim_start_matches('#')
267 .trim();
268 if !name.is_empty() {
269 return Some((name.to_string(), NodeKind::Section));
270 }
271 }
272 None
273}
274
275fn take_ident(input: &str) -> Option<String> {
276 let mut out = String::new();
277 for ch in input.chars() {
278 if ch.is_alphanumeric() || ch == '_' || ch == '-' {
279 out.push(ch);
280 } else {
281 break;
282 }
283 }
284
285 if out.is_empty() {
286 None
287 } else {
288 Some(out)
289 }
290}
291
292#[cfg(test)]
293mod tests {
294 use super::*;
295
296 #[test]
297 fn fallback_supports_requested_extensions() {
298 for ext in ["kt", "swift", "rb", "php", "sh"] {
299 assert!(is_fallback_supported_extension(ext));
300 }
301 assert!(!is_fallback_supported_extension("md"));
304 assert!(is_markdown_extension("md"));
305 }
306
307 #[test]
308 fn parses_kotlin_function() {
309 let source = "fun fetchUser(id: String): User = TODO()";
310 let nodes = parse_fallback_source(source, "sample.kt", "kt");
311 assert!(nodes.iter().any(|n| n.name == "fetchUser"));
312 }
313
314 #[test]
315 fn parses_shell_function() {
316 let source = "deploy_prod() { echo hi; }";
317 let nodes = parse_fallback_source(source, "deploy.sh", "sh");
318 assert!(nodes.iter().any(|n| n.name == "deploy_prod"));
319 }
320
321 #[test]
322 fn parses_swift_source() {
323 let source = r#"
324class UserManager {
325 func getUser() -> User {
326 return User()
327 }
328}
329
330struct Point {
331 var x: Double
332 var y: Double
333}
334
335enum Status {
336 case active
337 case inactive
338}
339"#;
340 let nodes = parse_fallback_source(source, "Users.swift", "swift");
341 assert!(nodes
342 .iter()
343 .any(|n| n.name == "UserManager" && matches!(n.kind, NodeKind::Class)));
344 assert!(nodes
345 .iter()
346 .any(|n| n.name == "getUser" && matches!(n.kind, NodeKind::Function)));
347 assert!(nodes
348 .iter()
349 .any(|n| n.name == "Point" && matches!(n.kind, NodeKind::Struct)));
350 assert!(nodes
351 .iter()
352 .any(|n| n.name == "Status" && matches!(n.kind, NodeKind::Enum)));
353 }
354
355 #[test]
356 fn parses_ruby_source() {
357 let source = r#"
358class ApplicationController
359 def index
360 render json: { status: "ok" }
361 end
362
363 def show
364 @user = User.find(params[:id])
365 end
366end
367
368module Authentication
369end
370"#;
371 let nodes = parse_fallback_source(source, "controller.rb", "rb");
372 assert!(nodes
373 .iter()
374 .any(|n| n.name == "ApplicationController" && matches!(n.kind, NodeKind::Class)));
375 assert!(nodes
376 .iter()
377 .any(|n| n.name == "index" && matches!(n.kind, NodeKind::Function)));
378 assert!(nodes
379 .iter()
380 .any(|n| n.name == "show" && matches!(n.kind, NodeKind::Function)));
381 assert!(nodes
382 .iter()
383 .any(|n| n.name == "Authentication" && matches!(n.kind, NodeKind::Module)));
384 }
385
386 #[test]
387 fn parses_php_source() {
388 let source = r#"
389class PaymentProcessor {
390 function processPayment($amount) {
391 return true;
392 }
393}
394
395interface Gateway {
396}
397
398function helper() {
399}
400"#;
401 let nodes = parse_fallback_source(source, "payment.php", "php");
402 assert!(nodes
403 .iter()
404 .any(|n| n.name == "PaymentProcessor" && matches!(n.kind, NodeKind::Class)));
405 assert!(nodes
406 .iter()
407 .any(|n| n.name == "processPayment" && matches!(n.kind, NodeKind::Function)));
408 assert!(nodes
409 .iter()
410 .any(|n| n.name == "Gateway" && matches!(n.kind, NodeKind::Interface)));
411 assert!(nodes
412 .iter()
413 .any(|n| n.name == "helper" && matches!(n.kind, NodeKind::Function)));
414 }
415
416 #[test]
417 fn fallback_ignores_comments() {
418 let source = r#"
420// class NotAClass
421# def not_a_function
422fun realFunction(x: Int): Int = x
423"#;
424 let nodes = parse_fallback_source(source, "test.kt", "kt");
425 assert!(!nodes.iter().any(|n| n.name == "NotAClass"));
426 assert!(!nodes.iter().any(|n| n.name == "not_a_function"));
427 assert!(nodes.iter().any(|n| n.name == "realFunction"));
428 }
429
430 #[test]
431 fn fallback_kotlin_class_and_data_class() {
432 let source = r#"
433class Repository {
434}
435data class UserDto(val name: String)
436object Singleton
437"#;
438 let nodes = parse_fallback_source(source, "models.kt", "kt");
439 assert!(nodes
440 .iter()
441 .any(|n| n.name == "Repository" && matches!(n.kind, NodeKind::Class)));
442 assert!(nodes
443 .iter()
444 .any(|n| n.name == "UserDto" && matches!(n.kind, NodeKind::Class)));
445 assert!(nodes
446 .iter()
447 .any(|n| n.name == "Singleton" && matches!(n.kind, NodeKind::Class)));
448 }
449
450 #[test]
451 fn kotlin_annotation_stays_on_the_following_class() {
452 let source = r#"
453@HiltAndroidApp
454open class MyApplication : Application()
455
456@AndroidEntryPoint
457class MainActivity : AppCompatActivity()
458"#;
459 let nodes = parse_fallback_source(source, "app/MyApplication.kt", "kt");
460 let app = nodes.iter().find(|n| n.name == "MyApplication").unwrap();
461 assert!(app
462 .signature
463 .as_deref()
464 .unwrap()
465 .contains("@HiltAndroidApp"));
466 let activity = nodes.iter().find(|n| n.name == "MainActivity").unwrap();
467 assert!(activity
468 .signature
469 .as_deref()
470 .unwrap()
471 .contains("@AndroidEntryPoint"));
472 }
473
474 #[test]
475 fn fallback_empty_source_returns_empty() {
476 let nodes = parse_fallback_source("", "empty.kt", "kt");
477 assert!(nodes.is_empty());
478 }
479
480 #[test]
481 fn fallback_unsupported_extension_returns_empty() {
482 assert!(!is_fallback_supported_extension("xyz"));
484 assert!(!is_fallback_supported_extension("rs"));
485 }
486
487 #[test]
488 fn parses_shell_function_keyword() {
489 let source = "function deploy_staging { echo staging; }";
490 let nodes = parse_fallback_source(source, "deploy.bash", "bash");
491 assert!(nodes.iter().any(|n| n.name == "deploy_staging"));
492 }
493}
494
495#[cfg(test)]
496mod regression_tests {
497 use super::*;
498
499 #[test]
500 fn markdown_is_not_indexed_as_code() {
501 assert!(!is_fallback_supported_extension("md"));
505 assert!(!is_fallback_supported_extension("markdown"));
506 assert!(is_markdown_extension("md"));
507 }
508
509 #[test]
510 fn markdown_still_parses_when_asked_directly() {
511 let nodes = parse_fallback_source("# fetch benchmark\n## setup\n", "README.md", "md");
512 assert_eq!(nodes.len(), 2);
513 assert!(nodes.iter().all(|n| n.kind == NodeKind::Section));
514 }
515
516 #[test]
517 fn shell_comments_are_not_functions() {
518 let src = "#!/bin/bash\n# Compare app.fetch() between refs\nreal_fn() {\n echo hi\n}\n";
522 let nodes = parse_fallback_source(src, "compare.sh", "sh");
523
524 assert_eq!(nodes.len(), 1, "only the real function should be indexed");
525 assert_eq!(nodes[0].name, "real_fn");
526 }
527
528 #[test]
529 fn shell_names_must_be_identifiers() {
530 assert!(is_shell_identifier("deploy_app"));
531 assert!(is_shell_identifier("build-web"));
532 assert!(!is_shell_identifier("# Compare app.fetch"));
533 assert!(!is_shell_identifier("app.fetch"));
534 assert!(!is_shell_identifier(""));
535 assert!(!is_shell_identifier("2fast"));
536 }
537
538 #[test]
539 fn prose_containing_parens_is_not_a_function() {
540 let nodes = parse_fallback_source("echo \"call foo() now\"\n", "x.sh", "sh");
541 assert!(
542 nodes.is_empty(),
543 "a string mentioning foo() is not a definition"
544 );
545 }
546
547 #[test]
548 fn double_slash_comments_are_skipped() {
549 let nodes = parse_fallback_source("// fun notReal()\nfun real() {}\n", "a.kt", "kt");
550 assert_eq!(nodes.len(), 1);
551 assert_eq!(nodes[0].name, "real");
552 }
553}