1use crate::buffer::LineBuffer;
4use crate::cursor::Position;
5
6use tree_sitter::{InputEdit, Node, Parser, Tree};
7
8#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
10pub enum Language {
11 #[default]
12 Rust,
13 TypeScript,
14 JavaScript,
15 Python,
16 Json,
17 Markdown,
18 Html,
19 PlainText,
20}
21
22#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
24pub enum TokenType {
25 Keyword,
26 Type,
27 Function,
28 Identifier,
29 String,
30 Number,
31 Comment,
32 Operator,
33 Punctuation,
34 Tag,
35 Attribute,
36}
37
38#[derive(Debug, Clone, PartialEq, Eq)]
40pub struct SyntaxToken {
41 pub token_type: TokenType,
42 pub start_col: usize,
43 pub end_col: usize,
44 pub text: String,
45}
46
47#[derive(Debug, Clone, PartialEq, Eq)]
49pub struct FoldRange {
50 pub start_line: usize,
51 pub end_line: usize,
52 pub collapsed: bool,
53}
54
55fn create_parser_for_lang(lang: Language) -> Option<Parser> {
56 let mut parser = Parser::new();
57 match lang {
58 Language::Rust => {
59 parser
60 .set_language(&tree_sitter_rust::LANGUAGE.into())
61 .ok()?;
62 Some(parser)
63 }
64 Language::JavaScript | Language::TypeScript => {
65 parser
66 .set_language(&tree_sitter_javascript::LANGUAGE.into())
67 .ok()?;
68 Some(parser)
69 }
70 _ => None,
71 }
72}
73
74fn classify_tree_sitter_kind(kind: &str, parent_kind: &str) -> TokenType {
75 match kind {
76 "line_comment" | "block_comment" | "comment" => TokenType::Comment,
77
78 "string_literal" | "raw_string_literal" | "char_literal" | "string" | "template_string"
79 | "string_content" | "escape_sequence" => TokenType::String,
80
81 "integer_literal" | "float_literal" | "number" => TokenType::Number,
82
83 "primitive_type" | "type_identifier" => TokenType::Type,
84
85 "identifier"
86 if parent_kind == "call_expression"
87 || parent_kind == "function_item"
88 || parent_kind == "function_declaration"
89 || parent_kind == "function_declarator"
90 || parent_kind == "method_definition" =>
91 {
92 TokenType::Function
93 }
94
95 "fn" | "let" | "mut" | "pub" | "struct" | "enum" | "impl" | "trait" | "match" | "if"
96 | "else" | "return" | "for" | "in" | "while" | "loop" | "async" | "await" | "use"
97 | "mod" | "crate" | "const" | "static" | "type" | "where" | "as" | "ref" | "move"
98 | "unsafe" | "dyn" | "super" | "self" | "Self" | "function" | "var" | "import"
99 | "export" | "default" | "from" | "class" | "interface" | "extends" | "new" | "this"
100 | "try" | "catch" | "finally" | "switch" | "case" | "break" | "continue" | "throw"
101 | "typeof" | "instanceof" | "yield" | "debugger" => TokenType::Keyword,
102
103 "+" | "-" | "*" | "/" | "%" | "=" | "==" | "!=" | "<" | ">" | "<=" | ">=" | "&&" | "||"
104 | "!" | "&" | "|" | "^" | "<<" | ">>" | "+=" | "-=" | "*=" | "/=" | "%=" | "&=" | "|="
105 | "^=" | "=>" | "->" => TokenType::Operator,
106
107 "(" | ")" | "[" | "]" | "{" | "}" | ";" | ":" | "::" | "," | "." => TokenType::Punctuation,
108
109 "tag_name" | "jsx_opening_element" | "jsx_closing_element" => TokenType::Tag,
110 "property_identifier" | "field_identifier" | "shorthand_property_identifier" => {
111 TokenType::Attribute
112 }
113
114 _ => TokenType::Identifier,
115 }
116}
117
118fn collect_leaf_tokens(node: Node, line_idx: usize, out: &mut Vec<SyntaxToken>, line_text: &str) {
119 if node.start_position().row > line_idx || node.end_position().row < line_idx {
120 return;
121 }
122
123 if node.child_count() == 0 {
124 let kind = node.kind();
125 let start_pt = node.start_position();
126 let end_pt = node.end_position();
127
128 let start_col = if start_pt.row == line_idx {
129 start_pt.column
130 } else {
131 0
132 };
133 let end_col = if end_pt.row == line_idx {
134 end_pt.column
135 } else {
136 line_text.len()
137 };
138
139 if start_col < end_col && start_col < line_text.len() {
140 let clamped_end = end_col.min(line_text.len());
141 let text = line_text[start_col..clamped_end].to_string();
142 if !text.trim().is_empty() {
143 let parent_kind = node.parent().map(|p| p.kind()).unwrap_or("");
144 let token_type = classify_tree_sitter_kind(kind, parent_kind);
145 out.push(SyntaxToken {
146 token_type,
147 start_col,
148 end_col: clamped_end,
149 text,
150 });
151 }
152 }
153 return;
154 }
155
156 for i in 0..node.child_count() {
157 if let Some(child) = node.child(i) {
158 collect_leaf_tokens(child, line_idx, out, line_text);
159 }
160 }
161}
162
163fn collect_ast_fold_ranges(node: Node, out: &mut Vec<FoldRange>) {
164 let start_row = node.start_position().row;
165 let end_row = node.end_position().row;
166
167 if end_row > start_row {
168 let is_foldable = matches!(
169 node.kind(),
170 "block"
171 | "declaration_list"
172 | "match_block"
173 | "statement_block"
174 | "field_declaration_list"
175 | "enum_variant_list"
176 | "object"
177 | "array"
178 | "function_item"
179 | "impl_item"
180 | "struct_item"
181 | "enum_item"
182 | "function_declaration"
183 | "class_declaration"
184 );
185
186 if is_foldable {
187 out.push(FoldRange {
188 start_line: start_row,
189 end_line: end_row,
190 collapsed: false,
191 });
192 }
193 }
194
195 for i in 0..node.child_count() {
196 if let Some(child) = node.child(i) {
197 collect_ast_fold_ranges(child, out);
198 }
199 }
200}
201
202pub struct SyntaxHighlighter {
204 parser: Option<Parser>,
205 tree: Option<Tree>,
206 language: Language,
207}
208
209impl std::fmt::Debug for SyntaxHighlighter {
210 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
211 f.debug_struct("SyntaxHighlighter")
212 .field("has_parser", &self.parser.is_some())
213 .field("has_tree", &self.tree.is_some())
214 .field("language", &self.language)
215 .finish()
216 }
217}
218
219impl Clone for SyntaxHighlighter {
220 fn clone(&self) -> Self {
221 let mut cloned = Self::with_language(self.language);
222 cloned.tree = self.tree.clone();
223 cloned
224 }
225}
226
227impl Default for SyntaxHighlighter {
228 fn default() -> Self {
229 Self::new()
230 }
231}
232
233impl SyntaxHighlighter {
234 pub fn new() -> Self {
235 Self::with_language(Language::Rust)
236 }
237
238 pub fn with_language(lang: Language) -> Self {
239 let parser = create_parser_for_lang(lang);
240 Self {
241 parser,
242 tree: None,
243 language: lang,
244 }
245 }
246
247 pub fn set_language(&mut self, lang: Language) {
248 if self.language != lang {
249 self.language = lang;
250 self.parser = create_parser_for_lang(lang);
251 self.tree = None;
252 }
253 }
254
255 pub fn language(&self) -> Language {
256 self.language
257 }
258
259 pub fn tree(&self) -> Option<&Tree> {
261 self.tree.as_ref()
262 }
263
264 pub fn parse(&mut self, source: &str) {
266 if let Some(ref mut parser) = self.parser {
267 self.tree = parser.parse(source, None);
268 }
269 }
270
271 pub fn edit(&mut self, edit: &InputEdit) {
273 if let Some(ref mut tree) = self.tree {
274 tree.edit(edit);
275 }
276 }
277
278 pub fn parse_incremental(&mut self, source: &str) {
280 if let Some(ref mut parser) = self.parser {
281 self.tree = parser.parse(source, self.tree.as_ref());
282 }
283 }
284
285 pub fn highlight_line(&self, line: &str, lang: Language) -> Vec<SyntaxToken> {
287 if line.is_empty() {
288 return Vec::new();
289 }
290
291 Self::tokenize_line_lexical(line, lang)
292 }
293
294 pub fn highlight_line_ast(&self, line_idx: usize, line: &str) -> Vec<SyntaxToken> {
296 if line.is_empty() {
297 return Vec::new();
298 }
299
300 if let Some(ref tree) = self.tree {
301 let mut tokens = Vec::new();
302 collect_leaf_tokens(tree.root_node(), line_idx, &mut tokens, line);
303 if !tokens.is_empty() {
304 tokens.sort_by_key(|t| t.start_col);
305 return tokens;
306 }
307 }
308
309 Self::tokenize_line_lexical(line, self.language)
310 }
311
312 pub fn tokenize_line_lexical(line: &str, lang: Language) -> Vec<SyntaxToken> {
314 if line.is_empty() {
315 return Vec::new();
316 }
317
318 let mut tokens = Vec::new();
319 let chars: Vec<char> = line.chars().collect();
320 let mut idx = 0;
321
322 while idx < chars.len() {
323 let ch = chars[idx];
324
325 if ch.is_whitespace() {
327 idx += 1;
328 continue;
329 }
330
331 if (ch == '/' && idx + 1 < chars.len() && chars[idx + 1] == '/')
333 || (ch == '#' && (lang == Language::Python || lang == Language::Markdown))
334 {
335 let start = idx;
336 let text: String = chars[start..].iter().collect();
337 tokens.push(SyntaxToken {
338 token_type: TokenType::Comment,
339 start_col: start,
340 end_col: chars.len(),
341 text,
342 });
343 break;
344 }
345
346 if ch == '"' || ch == '\'' || ch == '`' {
348 let quote = ch;
349 let start = idx;
350 idx += 1;
351 while idx < chars.len() {
352 if chars[idx] == '\\' && idx + 1 < chars.len() {
353 idx += 2;
354 } else if chars[idx] == quote {
355 idx += 1;
356 break;
357 } else {
358 idx += 1;
359 }
360 }
361 let text: String = chars[start..idx].iter().collect();
362 tokens.push(SyntaxToken {
363 token_type: TokenType::String,
364 start_col: start,
365 end_col: idx,
366 text,
367 });
368 continue;
369 }
370
371 if ch.is_ascii_digit() {
373 let start = idx;
374 while idx < chars.len()
375 && (chars[idx].is_ascii_digit() || chars[idx] == '.' || chars[idx] == '_')
376 {
377 idx += 1;
378 }
379 let text: String = chars[start..idx].iter().collect();
380 tokens.push(SyntaxToken {
381 token_type: TokenType::Number,
382 start_col: start,
383 end_col: idx,
384 text,
385 });
386 continue;
387 }
388
389 if ch.is_alphabetic() || ch == '_' {
391 let start = idx;
392 while idx < chars.len() && (chars[idx].is_alphanumeric() || chars[idx] == '_') {
393 idx += 1;
394 }
395 let text: String = chars[start..idx].iter().collect();
396
397 let token_type = if Self::is_keyword(&text, lang) {
398 TokenType::Keyword
399 } else if Self::is_type(&text, lang) {
400 TokenType::Type
401 } else if idx < chars.len() && chars[idx] == '(' {
402 TokenType::Function
403 } else {
404 TokenType::Identifier
405 };
406
407 tokens.push(SyntaxToken {
408 token_type,
409 start_col: start,
410 end_col: idx,
411 text,
412 });
413 continue;
414 }
415
416 let start = idx;
418 idx += 1;
419 let token_type = match ch {
420 '+' | '-' | '*' | '/' | '%' | '=' | '<' | '>' | '!' | '&' | '|' | '^' => {
421 TokenType::Operator
422 }
423 _ => TokenType::Punctuation,
424 };
425
426 tokens.push(SyntaxToken {
427 token_type,
428 start_col: start,
429 end_col: idx,
430 text: ch.to_string(),
431 });
432 }
433
434 tokens
435 }
436
437 fn is_keyword(word: &str, lang: Language) -> bool {
438 match lang {
439 Language::Rust => matches!(
440 word,
441 "fn" | "let"
442 | "mut"
443 | "pub"
444 | "struct"
445 | "enum"
446 | "impl"
447 | "trait"
448 | "match"
449 | "if"
450 | "else"
451 | "return"
452 | "for"
453 | "in"
454 | "while"
455 | "loop"
456 | "async"
457 | "await"
458 | "use"
459 | "mod"
460 | "crate"
461 | "const"
462 | "static"
463 | "type"
464 ),
465 Language::TypeScript | Language::JavaScript => matches!(
466 word,
467 "function"
468 | "const"
469 | "let"
470 | "var"
471 | "return"
472 | "if"
473 | "else"
474 | "import"
475 | "export"
476 | "default"
477 | "from"
478 | "class"
479 | "interface"
480 | "type"
481 | "new"
482 | "this"
483 | "async"
484 | "await"
485 | "try"
486 | "catch"
487 | "switch"
488 | "case"
489 ),
490 Language::Python => matches!(
491 word,
492 "def"
493 | "class"
494 | "return"
495 | "if"
496 | "elif"
497 | "else"
498 | "for"
499 | "while"
500 | "import"
501 | "from"
502 | "as"
503 | "try"
504 | "except"
505 | "finally"
506 | "with"
507 | "lambda"
508 | "pass"
509 | "None"
510 | "True"
511 | "False"
512 ),
513 Language::Json => matches!(word, "true" | "false" | "null"),
514 _ => false,
515 }
516 }
517
518 fn is_type(word: &str, lang: Language) -> bool {
519 match lang {
520 Language::Rust => {
521 word.chars().next().is_some_and(|c| c.is_uppercase())
522 || matches!(
523 word,
524 "u8" | "u16"
525 | "u32"
526 | "u64"
527 | "u128"
528 | "usize"
529 | "i8"
530 | "i16"
531 | "i32"
532 | "i64"
533 | "i128"
534 | "isize"
535 | "f32"
536 | "f64"
537 | "bool"
538 | "char"
539 | "str"
540 | "String"
541 | "Vec"
542 | "Option"
543 | "Result"
544 )
545 }
546 Language::TypeScript => {
547 matches!(
548 word,
549 "string"
550 | "number"
551 | "boolean"
552 | "any"
553 | "void"
554 | "never"
555 | "unknown"
556 | "Record"
557 | "Array"
558 ) || word.chars().next().is_some_and(|c| c.is_uppercase())
559 }
560 _ => false,
561 }
562 }
563
564 pub fn root_node(&self) -> Option<Node<'_>> {
566 self.tree.as_ref().map(|t| t.root_node())
567 }
568
569 pub fn node_at_position(&self, line: usize, col: usize) -> Option<Node<'_>> {
571 let tree = self.tree.as_ref()?;
572 let pt = tree_sitter::Point {
573 row: line,
574 column: col,
575 };
576 tree.root_node().descendant_for_point_range(pt, pt)
577 }
578
579 pub fn enclosing_scope_range(&self, line: usize, col: usize) -> Option<(usize, usize)> {
581 let mut node = self.node_at_position(line, col)?;
582 loop {
583 let kind = node.kind();
584 if matches!(
585 kind,
586 "function_item"
587 | "impl_item"
588 | "struct_item"
589 | "enum_item"
590 | "block"
591 | "statement_block"
592 | "class_declaration"
593 | "function_declaration"
594 ) {
595 return Some((node.start_position().row, node.end_position().row));
596 }
597 node = node.parent()?;
598 }
599 }
600
601 pub fn find_matching_bracket(&self, buffer: &LineBuffer, pos: Position) -> Option<Position> {
603 let line = buffer.line(pos.line)?;
604 let ch = line.chars().nth(pos.col)?;
605
606 let (target, is_forward) = match ch {
607 '(' => (')', true),
608 '[' => (']', true),
609 '{' => ('}', true),
610 ')' => ('(', false),
611 ']' => ('[', false),
612 '}' => ('{', false),
613 _ => return None,
614 };
615
616 let mut depth = 0;
617
618 if is_forward {
619 for l in pos.line..buffer.line_count() {
620 if let Some(text) = buffer.line(l) {
621 let start_c = if l == pos.line { pos.col } else { 0 };
622 for (c, cur) in text.chars().enumerate().skip(start_c) {
623 if cur == ch {
624 depth += 1;
625 } else if cur == target {
626 depth -= 1;
627 if depth == 0 {
628 return Some(Position::new(l, c));
629 }
630 }
631 }
632 }
633 }
634 } else {
635 for l in (0..=pos.line).rev() {
636 if let Some(text) = buffer.line(l) {
637 let chars: Vec<char> = text.chars().collect();
638 let start_c = if l == pos.line {
639 pos.col
640 } else {
641 chars.len().saturating_sub(1)
642 };
643 for c in (0..=start_c).rev() {
644 let cur = chars[c];
645 if cur == ch {
646 depth += 1;
647 } else if cur == target {
648 depth -= 1;
649 if depth == 0 {
650 return Some(Position::new(l, c));
651 }
652 }
653 }
654 }
655 }
656 }
657
658 None
659 }
660
661 pub fn compute_fold_ranges(&self, buffer: &LineBuffer) -> Vec<FoldRange> {
663 if let Some(ref tree) = self.tree {
664 let mut ranges = Vec::new();
665 collect_ast_fold_ranges(tree.root_node(), &mut ranges);
666 if !ranges.is_empty() {
667 ranges.sort_by_key(|r| (r.start_line, r.end_line));
668 ranges.dedup_by_key(|r| (r.start_line, r.end_line));
669 return ranges;
670 }
671 }
672
673 let mut ranges = Vec::new();
674 let mut stack = Vec::new();
675
676 for l in 0..buffer.line_count() {
677 if let Some(text) = buffer.line(l) {
678 for ch in text.chars() {
679 if ch == '{' {
680 stack.push(l);
681 } else if ch == '}' {
682 if let Some(start_l) = stack.pop() {
683 if l > start_l {
684 ranges.push(FoldRange {
685 start_line: start_l,
686 end_line: l,
687 collapsed: false,
688 });
689 }
690 }
691 }
692 }
693 }
694 }
695
696 ranges
697 }
698
699 pub fn compute_auto_indent(&self, buffer: &LineBuffer, line_idx: usize) -> usize {
701 let prev_line = match buffer.line(line_idx) {
702 Some(l) => l,
703 None => return 0,
704 };
705
706 let current_indent = prev_line.chars().take_while(|c| *c == ' ').count();
707 let trimmed = prev_line.trim_end();
708
709 if let Some(ref tree) = self.tree {
710 let pt = tree_sitter::Point {
711 row: line_idx,
712 column: prev_line.len().saturating_sub(1),
713 };
714 if let Some(node) = tree.root_node().descendant_for_point_range(pt, pt) {
715 let kind = node.kind();
716 if kind == "{" || kind == ":" || kind == "(" || kind == "[" {
717 return current_indent + 4;
718 }
719 }
720 }
721
722 if trimmed.ends_with('{')
723 || trimmed.ends_with(':')
724 || trimmed.ends_with('(')
725 || trimmed.ends_with('[')
726 {
727 current_indent + 4
728 } else {
729 current_indent
730 }
731 }
732}