octocode 0.11.0

AI-powered code indexer with semantic search, GraphRAG knowledge graphs, and MCP server for multi-language codebases
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
// Copyright 2025 Muvon Un Limited
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Svelte language implementation for the indexer

use crate::indexer::languages::Language;
use tree_sitter::Node;

pub struct Svelte {}

impl Language for Svelte {
	fn name(&self) -> &'static str {
		"svelte"
	}

	fn get_ts_language(&self) -> tree_sitter::Language {
		tree_sitter_svelte_ng::LANGUAGE.into()
	}

	fn get_meaningful_kinds(&self) -> Vec<&'static str> {
		vec![
			// Focus on script and style blocks which contain the meaningful code
			"script_element",
			"style_element",
			// Elements with meaningful attributes (components, events)
			"element", // But we'll filter this in extract_symbols
			           // Skip individual HTML tags as they create too much noise
		]
	}

	fn extract_symbols(&self, node: Node, contents: &str) -> Vec<String> {
		let mut symbols = Vec::new();

		match node.kind() {
			"script_element" => {
				// Extract JavaScript symbols from script content
				self.extract_script_content_symbols(node, contents, &mut symbols);
			}
			"style_element" => {
				// Extract CSS symbols from style content
				self.extract_style_content_symbols(node, contents, &mut symbols);
			}
			"element" => {
				// Only extract from elements that have meaningful Svelte-specific attributes
				self.extract_meaningful_element_symbols(node, contents, &mut symbols);
			}
			_ => self.extract_identifiers(node, contents, &mut symbols),
		}

		// Deduplicate and sort symbols
		symbols.sort();
		symbols.dedup();
		symbols
	}

	fn extract_identifiers(&self, node: Node, contents: &str, symbols: &mut Vec<String>) {
		let kind = node.kind();

		// Extract meaningful identifiers, avoiding noise
		if (kind.contains("identifier") || kind.contains("name"))
			&& !kind.contains("property")
			&& kind != "tag_name"
		{
			if let Ok(text) = node.utf8_text(contents.as_bytes()) {
				let text = text.trim();
				if !text.is_empty() && !symbols.contains(&text.to_string()) {
					// Filter out common Svelte keywords and HTML tags
					if !self.is_svelte_keyword(text) && !self.is_html_tag(text) {
						symbols.push(text.to_string());
					}
				}
			}
		}

		// Recursively process children
		let mut cursor = node.walk();
		if cursor.goto_first_child() {
			loop {
				self.extract_identifiers(cursor.node(), contents, symbols);
				if !cursor.goto_next_sibling() {
					break;
				}
			}
		}
	}

	fn are_node_types_equivalent(&self, type1: &str, type2: &str) -> bool {
		// Direct match
		if type1 == type2 {
			return true;
		}

		// Svelte-specific semantic groups
		let semantic_groups = [
			// Functions and methods
			&[
				"function_declaration",
				"method_definition",
				"arrow_function",
			] as &[&str],
			// Variable declarations
			&[
				"variable_declaration",
				"lexical_declaration",
				"reactive_declaration",
			],
			// Reactive statements
			&["reactive_statement", "reactive_declaration"],
			// Components and elements
			&["component", "element"],
			// Script and style blocks
			&["script_element", "style_element"],
		];

		// Check if both types belong to the same semantic group
		for group in &semantic_groups {
			let contains_type1 = group.contains(&type1);
			let contains_type2 = group.contains(&type2);

			if contains_type1 && contains_type2 {
				return true;
			}
		}

		false
	}

	fn get_node_type_description(&self, node_type: &str) -> &'static str {
		match node_type {
			"function_declaration" | "method_definition" | "arrow_function" => {
				"function declarations"
			}
			"variable_declaration" | "lexical_declaration" => "variable declarations",
			"reactive_statement" | "reactive_declaration" => "reactive declarations",
			"class_declaration" => "class declarations",
			"component" | "element" => "component declarations",
			"script_element" => "script blocks",
			"style_element" => "style blocks",
			_ => "declarations",
		}
	}

	fn extract_imports_exports(&self, node: Node, contents: &str) -> (Vec<String>, Vec<String>) {
		let mut imports = Vec::new();
		let mut exports = Vec::new();

		if node.kind() == "script_element" {
			// Extract JavaScript imports/exports from script content
			let script_content = self.get_script_text_content(node, contents);
			let (script_imports, script_exports) = Self::parse_js_imports_exports(&script_content);
			imports.extend(script_imports);
			exports.extend(script_exports);
		}

		(imports, exports)
	}

	fn resolve_import(
		&self,
		import_path: &str,
		source_file: &str,
		all_files: &[String],
	) -> Option<String> {
		// Svelte uses JavaScript import resolution
		let js = super::javascript::JavaScript {};
		js.resolve_import(import_path, source_file, all_files)
	}

	fn get_file_extensions(&self) -> Vec<&'static str> {
		vec!["svelte"]
	}
}

impl Svelte {
	/// Extract JavaScript symbols from script element content
	fn extract_script_content_symbols(
		&self,
		node: Node,
		contents: &str,
		symbols: &mut Vec<String>,
	) {
		// Look for the raw_text content inside script element
		for child in node.children(&mut node.walk()) {
			if child.kind() == "raw_text" {
				// Get the script content
				if let Ok(script_content) = child.utf8_text(contents.as_bytes()) {
					// Parse common JavaScript patterns manually since we can't re-parse with JS parser
					self.extract_js_patterns_from_text(script_content, symbols);
				}
			}
		}
	}

	/// Extract CSS symbols from style element content
	fn extract_style_content_symbols(&self, node: Node, contents: &str, symbols: &mut Vec<String>) {
		// Look for the raw_text content inside style element
		for child in node.children(&mut node.walk()) {
			if child.kind() == "raw_text" {
				// Get the style content
				if let Ok(style_content) = child.utf8_text(contents.as_bytes()) {
					// Extract CSS selectors and meaningful patterns
					self.extract_css_patterns_from_text(style_content, symbols);
				}
			}
		}
	}

	/// Extract symbols from meaningful Svelte elements (components, event handlers)
	fn extract_meaningful_element_symbols(
		&self,
		node: Node,
		contents: &str,
		symbols: &mut Vec<String>,
	) {
		// Only extract from elements that have Svelte-specific attributes
		let mut has_svelte_attributes = false;

		// Check for Svelte-specific attributes
		for child in node.children(&mut node.walk()) {
			if child.kind() == "start_tag" {
				for tag_child in child.children(&mut child.walk()) {
					if tag_child.kind() == "attribute" {
						for attr_child in tag_child.children(&mut tag_child.walk()) {
							if attr_child.kind() == "attribute_name" {
								if let Ok(attr_name) = attr_child.utf8_text(contents.as_bytes()) {
									// Check for Svelte directives
									if attr_name.starts_with("on:")
										|| attr_name.starts_with("bind:")
										|| attr_name.starts_with("use:")
										|| attr_name.starts_with("transition:")
									{
										has_svelte_attributes = true;
										// Extract the directive name
										symbols.push(attr_name.to_string());
									}
								}
							}
						}
					}
					// Extract component names (capitalized elements)
					else if tag_child.kind() == "tag_name" {
						if let Ok(tag_name) = tag_child.utf8_text(contents.as_bytes()) {
							// Svelte components are typically capitalized
							if tag_name.chars().next().is_some_and(|c| c.is_uppercase())
								&& !self.is_html_tag(tag_name)
							{
								symbols.push(tag_name.to_string());
								has_svelte_attributes = true;
							}
						}
					}
				}
			}
		}

		// Only recurse if this element has meaningful Svelte content
		if !has_svelte_attributes {}
	}

	/// Extract JavaScript patterns from text content
	fn extract_js_patterns_from_text(&self, text: &str, symbols: &mut Vec<String>) {
		// Simple regex-like pattern matching for common JS constructs
		let lines: Vec<&str> = text.lines().collect();

		for line in lines {
			let line = line.trim();

			// Extract function declarations: function name() or const name =
			if line.starts_with("function ") {
				if let Some(name) = self.extract_function_name(line) {
					symbols.push(name);
				}
			}
			// Extract variable declarations: let/const/var name =
			else if line.starts_with("let ")
				|| line.starts_with("const ")
				|| line.starts_with("var ")
			{
				if let Some(name) = self.extract_variable_name(line) {
					symbols.push(name);
				}
			}
			// Extract export declarations: export let name =
			else if line.starts_with("export let ") || line.starts_with("export const ") {
				if let Some(name) = self.extract_export_name(line) {
					symbols.push(name);
				}
			}
			// Extract reactive statements: $: name =
			else if line.trim_start().starts_with("$:") {
				if let Some(name) = self.extract_reactive_name(line) {
					symbols.push(name);
				}
			}
		}
	}

	/// Extract CSS patterns from text content
	fn extract_css_patterns_from_text(&self, text: &str, symbols: &mut Vec<String>) {
		let lines: Vec<&str> = text.lines().collect();

		for line in lines {
			let line = line.trim();

			// Extract CSS selectors (simple approach)
			if line.contains('{') && !line.trim_start().starts_with("/*") {
				let selector_part = line.split('{').next().unwrap_or("").trim();
				if !selector_part.is_empty() && !selector_part.contains(':') {
					// Simple selector extraction
					for selector in selector_part.split(',') {
						let selector = selector.trim();
						if !selector.is_empty() {
							symbols.push(selector.to_string());
						}
					}
				}
			}
		}
	}

	/// Extract function name from function declaration line
	fn extract_function_name(&self, line: &str) -> Option<String> {
		// function name() or function name(
		if let Some(start) = line.find("function ") {
			let after_function = &line[start + 9..];
			if let Some(end) = after_function.find('(') {
				let name = after_function[..end].trim();
				if !name.is_empty() && !self.is_svelte_keyword(name) {
					return Some(name.to_string());
				}
			}
		}
		None
	}

	/// Extract variable name from variable declaration line
	fn extract_variable_name(&self, line: &str) -> Option<String> {
		// let name = or const name = or var name =
		let parts: Vec<&str> = line.split_whitespace().collect();
		if parts.len() >= 4 && (parts[0] == "let" || parts[0] == "const" || parts[0] == "var") {
			let name = parts[1].trim_end_matches('=').trim_end_matches(',').trim();
			if !name.is_empty() && !self.is_svelte_keyword(name) {
				return Some(name.to_string());
			}
		}
		None
	}

	/// Extract export name from export declaration line
	fn extract_export_name(&self, line: &str) -> Option<String> {
		// export let name = or export const name =
		let parts: Vec<&str> = line.split_whitespace().collect();
		if parts.len() >= 5 && parts[0] == "export" && (parts[1] == "let" || parts[1] == "const") {
			let name = parts[2].trim_end_matches('=').trim_end_matches(',').trim();
			if !name.is_empty() && !self.is_svelte_keyword(name) {
				return Some(name.to_string());
			}
		}
		None
	}

	/// Extract reactive variable name from reactive statement
	fn extract_reactive_name(&self, line: &str) -> Option<String> {
		// $: name = something or $: if (condition)
		if let Some(colon_pos) = line.find(':') {
			let after_colon = &line[colon_pos + 1..].trim();

			// Handle $: name = value
			if let Some(eq_pos) = after_colon.find('=') {
				let name = after_colon[..eq_pos].trim();
				if !name.is_empty() && !self.is_svelte_keyword(name) {
					return Some(name.to_string());
				}
			}
			// Handle $: if (condition) - extract the reactive dependency
			else if after_colon.starts_with("if ") {
				// This is a reactive statement, could extract condition variables
				// For now, just mark it as a reactive statement
				return Some("reactive_if".to_string());
			}
		}
		None
	}

	/// Check if a string is a Svelte keyword
	fn is_svelte_keyword(&self, text: &str) -> bool {
		matches!(
			text,
			"export" | "import" | "let" | "const" | "var" | "function" | "class" | "if" | "else"
			| "for" | "while" | "do" | "switch" | "case" | "default" | "break" | "continue"
			| "return" | "try" | "catch" | "finally" | "throw" | "new" | "this" | "super"
			| "true" | "false" | "null" | "undefined" | "typeof" | "instanceof" | "in" | "of"
			// Svelte-specific keywords
			| "bind" | "on" | "use" | "transition" | "out" | "animate"
		)
	}

	/// Check if a string is a common HTML tag
	fn is_html_tag(&self, text: &str) -> bool {
		matches!(
			text.to_lowercase().as_str(),
			"div"
				| "span" | "p"
				| "a" | "img"
				| "h1" | "h2"
				| "h3" | "h4"
				| "h5" | "h6"
				| "ul" | "ol"
				| "li" | "table"
				| "tr" | "td"
				| "th" | "thead"
				| "tbody" | "tfoot"
				| "form" | "input"
				| "button" | "select"
				| "option" | "textarea"
				| "label" | "header"
				| "footer" | "nav"
				| "main" | "section"
				| "article" | "aside"
				| "html" | "head"
				| "body" | "title"
				| "meta" | "link"
				| "script" | "style"
		)
	}

	// Svelte components can have imports in script blocks and exports

	// Helper to extract text content from script element
	fn get_script_text_content(&self, node: Node, contents: &str) -> String {
		if let Ok(text) = node.utf8_text(contents.as_bytes()) {
			// Remove <script> and </script> tags, return inner content
			let text = text.trim();
			if text.starts_with("<script") && text.ends_with("</script>") {
				// Find the end of the opening tag
				if let Some(tag_end) = text.find('>') {
					let inner = &text[tag_end + 1..];
					if let Some(closing_start) = inner.rfind("</script>") {
						return inner[..closing_start].trim().to_string();
					}
				}
			}
			text.to_string()
		} else {
			String::new()
		}
	}

	// Helper function to parse JavaScript imports/exports from script content
	fn parse_js_imports_exports(content: &str) -> (Vec<String>, Vec<String>) {
		let mut imports = Vec::new();
		let mut exports = Vec::new();

		// Simple regex-based parsing for import/export statements
		for line in content.lines() {
			let trimmed = line.trim();

			// Handle import statements
			if trimmed.starts_with("import ") {
				if let Some(from_pos) = trimmed.find(" from ") {
					let import_path = &trimmed[from_pos + 6..].trim();
					if let Some(path) = Self::extract_quoted_string(import_path) {
						imports.push(path);
					}
				}
			}

			// Handle export statements
			if let Some(export_content) = trimmed.strip_prefix("export ") {
				if trimmed.contains("export default") {
					exports.push("default".to_string());
				} else {
					// Handle export let/const/var statements
					let export_part = export_content.trim();

					// Check if it's a variable declaration export
					if let Some(var_part) = export_part
						.strip_prefix("let ")
						.or_else(|| export_part.strip_prefix("const "))
						.or_else(|| export_part.strip_prefix("var "))
					{
						// Extract the variable name (everything before = or ; or whitespace after trimming)
						let var_name = var_part
							.trim()
							.split(|c: char| c == '=' || c == ';' || c == ':' || c.is_whitespace())
							.next()
							.unwrap_or("")
							.trim();

						if !var_name.is_empty() {
							exports.push(var_name.to_string());
						}
					} else if let Some(func_part) = export_part.strip_prefix("function ") {
						// Handle export function name()
						if let Some(name_end) = func_part.find('(') {
							let func_name = func_part[..name_end].trim();
							if !func_name.is_empty() {
								exports.push(func_name.to_string());
							}
						}
					} else if let Some(class_part) = export_part.strip_prefix("class ") {
						// Handle export class Name
						if let Some(name) = class_part.split_whitespace().next() {
							let class_name = name.trim_end_matches('{');
							if !class_name.is_empty() {
								exports.push(class_name.to_string());
							}
						}
					} else {
						// Handle other export patterns (e.g., export { name })
						if let Some(name) = export_part.split_whitespace().next() {
							if !name.starts_with('{') {
								exports.push(name.to_string());
							}
						}
					}
				}
			}
		}

		(imports, exports)
	}

	// Helper to extract quoted strings
	fn extract_quoted_string(text: &str) -> Option<String> {
		let text = text.trim();
		if (text.starts_with('"') && text.ends_with('"'))
			|| (text.starts_with('\'') && text.ends_with('\''))
		{
			Some(text[1..text.len() - 1].to_string())
		} else {
			None
		}
	}
}