libgrite-core 0.5.3

Core library for grite: event types, CRDT projections, hashing, and sled store
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
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
use streaming_iterator::StreamingIterator;
use tree_sitter::{Language, Parser, Query, QueryCursor};
use tree_sitter_language::LanguageFn;

use crate::types::event::SymbolInfo;

/// Attempt tree-sitter-based symbol extraction.
/// Returns None if language is unsupported or parsing fails (triggers regex fallback).
pub fn extract(content: &str, language: &str) -> Option<Vec<SymbolInfo>> {
    let (lang_fn, query_source, kinds) = language_config(language)?;
    let lang: Language = Language::from(lang_fn);

    let mut parser = Parser::new();
    parser.set_language(&lang).ok()?;

    let tree = parser.parse(content, None)?;
    let query = Query::new(&lang, query_source).ok()?;

    let name_idx = query.capture_index_for_name("name")?;
    let def_idx = query.capture_index_for_name("definition");

    let mut cursor = QueryCursor::new();
    let mut symbols = Vec::new();

    let mut matches = cursor.matches(&query, tree.root_node(), content.as_bytes());
    while let Some(m) = matches.next() {
        let mut name: Option<&str> = None;
        let mut def_start: u32 = 0;
        let mut def_end: u32 = 0;
        let mut name_start: u32 = 0;
        let mut name_end: u32 = 0;

        for capture in m.captures {
            if capture.index == name_idx {
                let start = capture.node.start_byte();
                let end = capture.node.end_byte();
                if start <= end && end <= content.len() {
                    name = Some(&content[start..end]);
                }
                name_start = capture.node.start_position().row as u32 + 1;
                name_end = capture.node.end_position().row as u32 + 1;
            }
            if let Some(di) = def_idx {
                if capture.index == di {
                    def_start = capture.node.start_position().row as u32 + 1;
                    def_end = capture.node.end_position().row as u32 + 1;
                }
            }
        }

        // Use definition span if available, otherwise use name node span
        let (line_start, line_end) = if def_idx.is_some() && def_start > 0 {
            (def_start, def_end)
        } else {
            (name_start, name_end)
        };

        if let Some(symbol_name) = name {
            let kind: &str = kinds.get(m.pattern_index).copied().unwrap_or("unknown");
            symbols.push(SymbolInfo {
                name: symbol_name.to_string(),
                kind: kind.to_string(),
                line_start,
                line_end,
            });
        }
    }

    // Sort by line, then by kind specificity (prefer struct/class/interface over generic "type")
    symbols.sort_by(|a, b| {
        a.line_start
            .cmp(&b.line_start)
            .then_with(|| kind_priority(&a.kind).cmp(&kind_priority(&b.kind)))
    });
    // Deduplicate: same name+line keeps the more specific kind (first after priority sort)
    symbols.dedup_by(|a, b| a.line_start == b.line_start && a.name == b.name);
    Some(symbols)
}

/// Priority for deduplication: lower = more specific, preferred.
fn kind_priority(kind: &str) -> u8 {
    match kind {
        "struct" | "class" | "interface" | "enum" | "trait" | "module" | "namespace" => 0,
        "function" | "method" | "impl" | "const" | "static" => 1,
        "type" => 2,
        _ => 3,
    }
}

/// Returns (LanguageFn, query_source, pattern_kinds) for a given language string.
fn language_config(language: &str) -> Option<(LanguageFn, &'static str, &'static [&'static str])> {
    match language {
        "rust" => Some((tree_sitter_rust::LANGUAGE, RUST_QUERY, RUST_KINDS)),
        "python" => Some((tree_sitter_python::LANGUAGE, PYTHON_QUERY, PYTHON_KINDS)),
        "typescript" => Some((
            tree_sitter_typescript::LANGUAGE_TYPESCRIPT,
            TYPESCRIPT_QUERY,
            TYPESCRIPT_KINDS,
        )),
        "typescriptreact" => Some((
            tree_sitter_typescript::LANGUAGE_TSX,
            TYPESCRIPT_QUERY,
            TYPESCRIPT_KINDS,
        )),
        "javascript" => Some((
            tree_sitter_javascript::LANGUAGE,
            JAVASCRIPT_QUERY,
            JAVASCRIPT_KINDS,
        )),
        "go" => Some((tree_sitter_go::LANGUAGE, GO_QUERY, GO_KINDS)),
        "java" => Some((tree_sitter_java::LANGUAGE, JAVA_QUERY, JAVA_KINDS)),
        "c" => Some((tree_sitter_c::LANGUAGE, C_QUERY, C_KINDS)),
        "cpp" => Some((tree_sitter_cpp::LANGUAGE, CPP_QUERY, CPP_KINDS)),
        "ruby" => Some((tree_sitter_ruby::LANGUAGE, RUBY_QUERY, RUBY_KINDS)),
        "elixir" => Some((tree_sitter_elixir::LANGUAGE, ELIXIR_QUERY, ELIXIR_KINDS)),
        _ => None,
    }
}

// --- Rust ---

const RUST_QUERY: &str = r#"
(function_item name: (identifier) @name) @definition
(struct_item name: (type_identifier) @name) @definition
(enum_item name: (type_identifier) @name) @definition
(trait_item name: (type_identifier) @name) @definition
(impl_item type: (type_identifier) @name) @definition
(const_item name: (identifier) @name) @definition
(type_item name: (type_identifier) @name) @definition
(static_item name: (identifier) @name) @definition
"#;

const RUST_KINDS: &[&str] = &[
    "function", // function_item
    "struct",   // struct_item
    "enum",     // enum_item
    "trait",    // trait_item
    "impl",     // impl_item
    "const",    // const_item
    "type",     // type_item
    "static",   // static_item
];

// --- Python ---

const PYTHON_QUERY: &str = r#"
(function_definition name: (identifier) @name) @definition
(class_definition name: (identifier) @name) @definition
"#;

const PYTHON_KINDS: &[&str] = &[
    "function", // function_definition
    "class",    // class_definition
];

// --- TypeScript (works for both TS and TSX grammars) ---

const TYPESCRIPT_QUERY: &str = r#"
(function_declaration name: (identifier) @name) @definition
(class_declaration name: (type_identifier) @name) @definition
(interface_declaration name: (type_identifier) @name) @definition
(type_alias_declaration name: (type_identifier) @name) @definition
(enum_declaration name: (identifier) @name) @definition
(lexical_declaration
  (variable_declarator
    name: (identifier) @name
    value: (arrow_function)) @definition)
"#;

const TYPESCRIPT_KINDS: &[&str] = &[
    "function",  // function_declaration
    "class",     // class_declaration
    "interface", // interface_declaration
    "type",      // type_alias_declaration
    "enum",      // enum_declaration
    "function",  // arrow function in variable
];

// --- JavaScript ---

const JAVASCRIPT_QUERY: &str = r#"
(function_declaration name: (identifier) @name) @definition
(class_declaration name: (identifier) @name) @definition
(lexical_declaration
  (variable_declarator
    name: (identifier) @name
    value: (arrow_function)) @definition)
"#;

const JAVASCRIPT_KINDS: &[&str] = &[
    "function", // function_declaration
    "class",    // class_declaration
    "function", // arrow function in variable
];

// --- Go ---

const GO_QUERY: &str = r#"
(function_declaration name: (identifier) @name) @definition
(method_declaration name: (field_identifier) @name) @definition
(type_declaration (type_spec name: (type_identifier) @name type: (struct_type))) @definition
(type_declaration (type_spec name: (type_identifier) @name type: (interface_type))) @definition
(type_declaration (type_spec name: (type_identifier) @name)) @definition
"#;

const GO_KINDS: &[&str] = &[
    "function",  // function_declaration
    "function",  // method_declaration
    "struct",    // struct type
    "interface", // interface type
    "type",      // other type alias
];

// --- Java ---

const JAVA_QUERY: &str = r#"
(method_declaration name: (identifier) @name) @definition
(class_declaration name: (identifier) @name) @definition
(interface_declaration name: (identifier) @name) @definition
(enum_declaration name: (identifier) @name) @definition
(constructor_declaration name: (identifier) @name) @definition
"#;

const JAVA_KINDS: &[&str] = &[
    "method",    // method_declaration
    "class",     // class_declaration
    "interface", // interface_declaration
    "enum",      // enum_declaration
    "method",    // constructor_declaration
];

// --- C ---

const C_QUERY: &str = r#"
(function_definition
  declarator: (function_declarator
    declarator: (identifier) @name)) @definition
(struct_specifier
  name: (type_identifier) @name) @definition
(enum_specifier
  name: (type_identifier) @name) @definition
(type_definition
  declarator: (type_identifier) @name) @definition
"#;

const C_KINDS: &[&str] = &[
    "function", // function_definition
    "struct",   // struct_specifier
    "enum",     // enum_specifier
    "type",     // type_definition (typedef)
];

// --- C++ ---

const CPP_QUERY: &str = r#"
(function_definition
  declarator: (function_declarator
    declarator: (identifier) @name)) @definition
(class_specifier
  name: (type_identifier) @name) @definition
(struct_specifier
  name: (type_identifier) @name) @definition
(enum_specifier
  name: (type_identifier) @name) @definition
(namespace_definition
  name: (namespace_identifier) @name) @definition
"#;

const CPP_KINDS: &[&str] = &[
    "function",  // function_definition
    "class",     // class_specifier
    "struct",    // struct_specifier
    "enum",      // enum_specifier
    "namespace", // namespace_definition
];

// --- Ruby ---

const RUBY_QUERY: &str = r#"
(method name: (identifier) @name) @definition
(class name: (constant) @name) @definition
(module name: (constant) @name) @definition
(singleton_method name: (identifier) @name) @definition
"#;

const RUBY_KINDS: &[&str] = &[
    "function", // method
    "class",    // class
    "module",   // module
    "function", // singleton_method
];

// --- Elixir ---

const ELIXIR_QUERY: &str = r#"
(call
  target: (identifier) @_kw
  (arguments
    (call target: (identifier) @name))
  (#match? @_kw "^(def|defp)$")) @definition

(call
  target: (identifier) @_kw
  (arguments
    (identifier) @name)
  (#match? @_kw "^(def|defp)$")) @definition

(call
  target: (identifier) @_kw
  (arguments
    (alias) @name)
  (#match? @_kw "^defmodule$")) @definition
"#;

const ELIXIR_KINDS: &[&str] = &[
    "function", // def/defp with call target (e.g. def foo(args))
    "function", // def/defp with simple identifier
    "module",   // defmodule
];

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_rust_extraction() {
        let content = r#"pub struct Config {
    pub name: String,
    pub value: u32,
}

pub enum State {
    Open,
    Closed,
}

pub trait Handler {
    fn handle(&self);
}

impl Config {
    pub fn new(name: String) -> Self {
        Self { name, value: 0 }
    }

    pub async fn load() -> Self {
        todo!()
    }
}

pub const MAX_SIZE: usize = 100;

pub type Result<T> = std::result::Result<T, Error>;
"#;

        let symbols = extract(content, "rust").unwrap();
        let names: Vec<&str> = symbols.iter().map(|s| s.name.as_str()).collect();

        assert!(
            names.contains(&"Config"),
            "missing Config, got: {:?}",
            names
        );
        assert!(names.contains(&"State"), "missing State, got: {:?}", names);
        assert!(
            names.contains(&"Handler"),
            "missing Handler, got: {:?}",
            names
        );
        assert!(names.contains(&"new"), "missing new, got: {:?}", names);
        assert!(names.contains(&"load"), "missing load, got: {:?}", names);
        assert!(
            names.contains(&"MAX_SIZE"),
            "missing MAX_SIZE, got: {:?}",
            names
        );

        // Check accurate line ranges
        let config = symbols
            .iter()
            .find(|s| s.name == "Config" && s.kind == "struct")
            .unwrap();
        assert_eq!(config.line_start, 1);
        assert_eq!(config.line_end, 4);
    }

    #[test]
    fn test_python_extraction() {
        let content = r#"class MyClass:
    def __init__(self):
        self.x = 0

    def method(self):
        return self.x

def standalone():
    pass

async def async_func():
    pass
"#;

        let symbols = extract(content, "python").unwrap();
        let names: Vec<&str> = symbols.iter().map(|s| s.name.as_str()).collect();

        assert!(
            names.contains(&"MyClass"),
            "missing MyClass, got: {:?}",
            names
        );
        assert!(
            names.contains(&"__init__"),
            "missing __init__, got: {:?}",
            names
        );
        assert!(
            names.contains(&"method"),
            "missing method, got: {:?}",
            names
        );
        assert!(
            names.contains(&"standalone"),
            "missing standalone, got: {:?}",
            names
        );
        assert!(
            names.contains(&"async_func"),
            "missing async_func, got: {:?}",
            names
        );

        // Check accurate line ranges
        let class = symbols.iter().find(|s| s.name == "MyClass").unwrap();
        assert_eq!(class.line_start, 1);
        assert_eq!(class.line_end, 6);
    }

    #[test]
    fn test_typescript_extraction() {
        let content = r#"export function greet(name: string): string {
    return `Hello, ${name}!`;
}

export class UserService {
    constructor() {}
    getName(): string { return ""; }
}

export interface Config {
    name: string;
    value: number;
}

type UserId = string;

enum Status {
    Active,
    Inactive
}

const fetchData = async (url: string) => {
    return fetch(url);
};
"#;

        let symbols = extract(content, "typescript").unwrap();
        let names: Vec<&str> = symbols.iter().map(|s| s.name.as_str()).collect();

        assert!(names.contains(&"greet"), "missing greet, got: {:?}", names);
        assert!(
            names.contains(&"UserService"),
            "missing UserService, got: {:?}",
            names
        );
        assert!(
            names.contains(&"Config"),
            "missing Config, got: {:?}",
            names
        );
        assert!(
            names.contains(&"UserId"),
            "missing UserId, got: {:?}",
            names
        );
        assert!(
            names.contains(&"Status"),
            "missing Status, got: {:?}",
            names
        );
        assert!(
            names.contains(&"fetchData"),
            "missing fetchData, got: {:?}",
            names
        );
    }

    #[test]
    fn test_javascript_extraction() {
        let content = r#"function hello(name) {
    console.log(`Hello, ${name}!`);
}

class Animal {
    constructor(name) {
        this.name = name;
    }
}

const greet = (name) => {
    return `Hi ${name}`;
};
"#;

        let symbols = extract(content, "javascript").unwrap();
        let names: Vec<&str> = symbols.iter().map(|s| s.name.as_str()).collect();

        assert!(names.contains(&"hello"), "missing hello, got: {:?}", names);
        assert!(
            names.contains(&"Animal"),
            "missing Animal, got: {:?}",
            names
        );
        assert!(names.contains(&"greet"), "missing greet, got: {:?}", names);
    }

    #[test]
    fn test_go_extraction() {
        let content = r#"package main

func main() {
    fmt.Println("hello")
}

func (s *Server) Start() error {
    return nil
}

type Config struct {
    Name string
    Port int
}

type Handler interface {
    Handle() error
}

type UserID string
"#;

        let symbols = extract(content, "go").unwrap();
        let names: Vec<&str> = symbols.iter().map(|s| s.name.as_str()).collect();

        assert!(names.contains(&"main"), "missing main, got: {:?}", names);
        assert!(names.contains(&"Start"), "missing Start, got: {:?}", names);
        assert!(
            names.contains(&"Config"),
            "missing Config, got: {:?}",
            names
        );
        assert!(
            names.contains(&"Handler"),
            "missing Handler, got: {:?}",
            names
        );
        assert!(
            names.contains(&"UserID"),
            "missing UserID, got: {:?}",
            names
        );

        // Check kinds
        let config = symbols.iter().find(|s| s.name == "Config").unwrap();
        assert_eq!(config.kind, "struct");
        let handler = symbols.iter().find(|s| s.name == "Handler").unwrap();
        assert_eq!(handler.kind, "interface");
    }

    #[test]
    fn test_java_extraction() {
        let content = r#"public class UserService {
    private String name;

    public UserService(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

public interface Repository {
    void save(Object entity);
    Object find(String id);
}

public enum Status {
    ACTIVE,
    INACTIVE
}
"#;

        let symbols = extract(content, "java").unwrap();
        let names: Vec<&str> = symbols.iter().map(|s| s.name.as_str()).collect();

        assert!(
            names.contains(&"UserService"),
            "missing UserService, got: {:?}",
            names
        );
        assert!(
            names.contains(&"getName"),
            "missing getName, got: {:?}",
            names
        );
        assert!(
            names.contains(&"setName"),
            "missing setName, got: {:?}",
            names
        );
        assert!(
            names.contains(&"Repository"),
            "missing Repository, got: {:?}",
            names
        );
        assert!(
            names.contains(&"Status"),
            "missing Status, got: {:?}",
            names
        );
    }

    #[test]
    fn test_c_extraction() {
        let content = r#"struct Point {
    int x;
    int y;
};

enum Color {
    RED,
    GREEN,
    BLUE
};

typedef unsigned long ulong;

int main(int argc, char** argv) {
    return 0;
}

void helper(int n) {
    printf("%d\n", n);
}
"#;

        let symbols = extract(content, "c").unwrap();
        let names: Vec<&str> = symbols.iter().map(|s| s.name.as_str()).collect();

        assert!(names.contains(&"Point"), "missing Point, got: {:?}", names);
        assert!(names.contains(&"Color"), "missing Color, got: {:?}", names);
        assert!(names.contains(&"main"), "missing main, got: {:?}", names);
        assert!(
            names.contains(&"helper"),
            "missing helper, got: {:?}",
            names
        );
    }

    #[test]
    fn test_cpp_extraction() {
        let content = r#"namespace mylib {

class Widget {
public:
    Widget();
    void draw();
};

struct Point {
    double x, y;
};

enum Color {
    Red, Green, Blue
};

}

void process(int n) {
    return;
}
"#;

        let symbols = extract(content, "cpp").unwrap();
        let names: Vec<&str> = symbols.iter().map(|s| s.name.as_str()).collect();

        assert!(names.contains(&"mylib"), "missing mylib, got: {:?}", names);
        assert!(
            names.contains(&"Widget"),
            "missing Widget, got: {:?}",
            names
        );
        assert!(names.contains(&"Point"), "missing Point, got: {:?}", names);
        assert!(names.contains(&"Color"), "missing Color, got: {:?}", names);
        assert!(
            names.contains(&"process"),
            "missing process, got: {:?}",
            names
        );
    }

    #[test]
    fn test_ruby_extraction() {
        let content = r#"module Authentication
  class User
    def initialize(name)
      @name = name
    end

    def self.find(id)
      new("user_#{id}")
    end

    def greet
      "Hello, #{@name}"
    end
  end
end
"#;

        let symbols = extract(content, "ruby").unwrap();
        let names: Vec<&str> = symbols.iter().map(|s| s.name.as_str()).collect();

        assert!(
            names.contains(&"Authentication"),
            "missing Authentication, got: {:?}",
            names
        );
        assert!(names.contains(&"User"), "missing User, got: {:?}", names);
        assert!(
            names.contains(&"initialize"),
            "missing initialize, got: {:?}",
            names
        );
        assert!(names.contains(&"greet"), "missing greet, got: {:?}", names);
    }

    #[test]
    fn test_elixir_extraction() {
        let content = r#"defmodule MyApp.Users do
  def get_user(id) do
    Repo.get(User, id)
  end

  defp validate(user) do
    # private function
    :ok
  end
end
"#;

        let symbols = extract(content, "elixir").unwrap();
        let names: Vec<&str> = symbols.iter().map(|s| s.name.as_str()).collect();

        assert!(
            names.contains(&"MyApp.Users"),
            "missing MyApp.Users, got: {:?}",
            names
        );
        assert!(
            names.contains(&"get_user"),
            "missing get_user, got: {:?}",
            names
        );
        assert!(
            names.contains(&"validate"),
            "missing validate, got: {:?}",
            names
        );
    }

    #[test]
    fn test_tsx_extraction() {
        let content = r#"interface Props {
    name: string;
}

export function Component(props: Props): JSX.Element {
    return <div>{props.name}</div>;
}

type Theme = "light" | "dark";
"#;

        let symbols = extract(content, "typescriptreact").unwrap();
        let names: Vec<&str> = symbols.iter().map(|s| s.name.as_str()).collect();

        assert!(names.contains(&"Props"), "missing Props, got: {:?}", names);
        assert!(
            names.contains(&"Component"),
            "missing Component, got: {:?}",
            names
        );
        assert!(names.contains(&"Theme"), "missing Theme, got: {:?}", names);
    }

    #[test]
    fn test_unknown_language_returns_none() {
        assert!(extract("anything", "brainfuck").is_none());
    }
}