codegraph-go 0.1.5

Go parser for CodeGraph - extracts code entities and relationships from Go source files
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
//! AST visitor for extracting Go entities

use codegraph_parser_api::{
    ClassEntity, FunctionEntity, ImportRelation, ParserConfig, TraitEntity,
};
use tree_sitter::Node;

pub struct GoVisitor<'a> {
    pub source: &'a [u8],
    #[allow(dead_code)]
    pub config: ParserConfig,
    pub functions: Vec<FunctionEntity>,
    pub structs: Vec<ClassEntity>,
    pub interfaces: Vec<TraitEntity>,
    pub imports: Vec<ImportRelation>,
}

impl<'a> GoVisitor<'a> {
    pub fn new(source: &'a [u8], config: ParserConfig) -> Self {
        Self {
            source,
            config,
            functions: Vec::new(),
            structs: Vec::new(),
            interfaces: Vec::new(),
            imports: Vec::new(),
        }
    }

    fn node_text(&self, node: Node) -> String {
        node.utf8_text(self.source).unwrap_or("").to_string()
    }

    pub fn visit_node(&mut self, node: Node) {
        match node.kind() {
            "function_declaration" => self.visit_function(node),
            "method_declaration" => self.visit_method(node),
            "type_declaration" => self.visit_type_declaration(node),
            "import_declaration" => self.visit_import(node),
            _ => {}
        }

        let mut cursor = node.walk();
        for child in node.children(&mut cursor) {
            self.visit_node(child);
        }
    }

    fn visit_function(&mut self, node: Node) {
        let name = node
            .child_by_field_name("name")
            .map(|n| self.node_text(n))
            .unwrap_or_else(|| "anonymous".to_string());

        let func = FunctionEntity {
            name,
            signature: self
                .node_text(node)
                .lines()
                .next()
                .unwrap_or("")
                .to_string(),
            visibility: "public".to_string(),
            line_start: node.start_position().row + 1,
            line_end: node.end_position().row + 1,
            is_async: false,
            is_test: false,
            is_static: false,
            is_abstract: false,
            parameters: Vec::new(),
            return_type: None,
            doc_comment: None,
            attributes: Vec::new(),
            parent_class: None,
            complexity: None,
        };

        self.functions.push(func);
    }

    fn visit_method(&mut self, node: Node) {
        let name = node
            .child_by_field_name("name")
            .map(|n| self.node_text(n))
            .unwrap_or_else(|| "method".to_string());

        let func = FunctionEntity {
            name,
            signature: self
                .node_text(node)
                .lines()
                .next()
                .unwrap_or("")
                .to_string(),
            visibility: "public".to_string(),
            line_start: node.start_position().row + 1,
            line_end: node.end_position().row + 1,
            is_async: false,
            is_test: false,
            is_static: false,
            is_abstract: false,
            parameters: Vec::new(),
            return_type: None,
            doc_comment: None,
            attributes: Vec::new(),
            parent_class: None,
            complexity: None,
        };

        self.functions.push(func);
    }

    fn visit_type_declaration(&mut self, node: Node) {
        let mut cursor = node.walk();
        for child in node.children(&mut cursor) {
            if child.kind() == "type_spec" {
                let name = child
                    .child_by_field_name("name")
                    .map(|n| self.node_text(n))
                    .unwrap_or_else(|| "Type".to_string());
                let type_node = child.child_by_field_name("type");

                if let Some(type_node) = type_node {
                    match type_node.kind() {
                        "struct_type" => {
                            let struct_entity = ClassEntity {
                                name,
                                visibility: "public".to_string(),
                                line_start: child.start_position().row + 1,
                                line_end: child.end_position().row + 1,
                                is_abstract: false,
                                is_interface: false,
                                base_classes: Vec::new(),
                                implemented_traits: Vec::new(),
                                methods: Vec::new(),
                                fields: Vec::new(),
                                doc_comment: None,
                                attributes: Vec::new(),
                                type_parameters: Vec::new(),
                            };
                            self.structs.push(struct_entity);
                        }
                        "interface_type" => {
                            let interface_entity = TraitEntity {
                                name,
                                visibility: "public".to_string(),
                                line_start: child.start_position().row + 1,
                                line_end: child.end_position().row + 1,
                                required_methods: Vec::new(),
                                parent_traits: Vec::new(),
                                doc_comment: None,
                                attributes: Vec::new(),
                            };
                            self.interfaces.push(interface_entity);
                        }
                        _ => {}
                    }
                }
            }
        }
    }

    fn visit_import(&mut self, node: Node) {
        // Check if this is an import block or single import
        let mut cursor = node.walk();
        let mut found_specs = false;

        for child in node.children(&mut cursor) {
            match child.kind() {
                "import_spec_list" => {
                    // Import block: import ( ... )
                    found_specs = true;
                    let mut spec_cursor = child.walk();
                    for spec in child.children(&mut spec_cursor) {
                        if spec.kind() == "import_spec" {
                            self.extract_import_spec(spec);
                        }
                    }
                }
                "import_spec" => {
                    // Single import: import "fmt" or import f "fmt"
                    found_specs = true;
                    self.extract_import_spec(child);
                }
                _ => {}
            }
        }

        // Fallback for unexpected format
        if !found_specs {
            let import_text = self.node_text(node);
            let import = ImportRelation {
                importer: "current_package".to_string(),
                imported: import_text,
                symbols: Vec::new(),
                is_wildcard: false,
                alias: None,
            };
            self.imports.push(import);
        }
    }

    fn extract_import_spec(&mut self, node: Node) {
        let mut alias = None;
        let mut is_wildcard = false;
        let mut path = String::new();

        // Extract path and optional name (alias)
        let mut cursor = node.walk();
        for child in node.children(&mut cursor) {
            let kind = child.kind();
            let text = self.node_text(child);

            match kind {
                "interpreted_string_literal" => {
                    // This is the import path
                    // Remove quotes
                    path = text.trim_matches('"').to_string();
                }
                "package_identifier" | "identifier" | "dot" | "." => {
                    // This is the alias/name or special marker
                    if text == "." {
                        is_wildcard = true;
                    } else if text != "_" {
                        alias = Some(text);
                    }
                    // If it's "_", we ignore it (blank identifier)
                }
                _ => {
                    // Check text content for special cases
                    if text == "." {
                        is_wildcard = true;
                    } else if text != "_"
                        && !text.trim().is_empty()
                        && kind != "("
                        && kind != ")"
                        && kind != "\""
                    {
                        // Might be an unrecognized alias format
                        if !path.is_empty() {
                            // Only set alias if we haven't found the path yet would mean this comes before
                            // Actually in Go, alias comes before path
                        }
                    }
                }
            }
        }

        let import = ImportRelation {
            importer: "current_package".to_string(),
            imported: path,
            symbols: Vec::new(), // Go doesn't have named imports like TypeScript
            is_wildcard,
            alias,
        };
        self.imports.push(import);
    }
}

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

    #[test]
    fn test_visitor_basics() {
        let visitor = GoVisitor::new(b"package main", ParserConfig::default());
        assert_eq!(visitor.functions.len(), 0);
        assert_eq!(visitor.structs.len(), 0);
        assert_eq!(visitor.interfaces.len(), 0);
    }

    #[test]
    fn test_visitor_function_extraction() {
        use tree_sitter::Parser;

        let source = b"package main\nfunc greet(name string) string { return \"Hello\" }";
        let mut parser = Parser::new();
        parser.set_language(tree_sitter_go::language()).unwrap();
        let tree = parser.parse(source, None).unwrap();

        let mut visitor = GoVisitor::new(source, ParserConfig::default());
        visitor.visit_node(tree.root_node());

        assert_eq!(visitor.functions.len(), 1);
        assert_eq!(visitor.functions[0].name, "greet");
    }

    #[test]
    fn test_visitor_struct_extraction() {
        use tree_sitter::Parser;

        let source = b"package main\ntype Person struct { Name string }";
        let mut parser = Parser::new();
        parser.set_language(tree_sitter_go::language()).unwrap();
        let tree = parser.parse(source, None).unwrap();

        let mut visitor = GoVisitor::new(source, ParserConfig::default());
        visitor.visit_node(tree.root_node());

        assert_eq!(visitor.structs.len(), 1);
        assert_eq!(visitor.structs[0].name, "Person");
    }

    #[test]
    fn test_visitor_interface_extraction() {
        use tree_sitter::Parser;

        let source = b"package main\ntype Reader interface { Read() error }";
        let mut parser = Parser::new();
        parser.set_language(tree_sitter_go::language()).unwrap();
        let tree = parser.parse(source, None).unwrap();

        let mut visitor = GoVisitor::new(source, ParserConfig::default());
        visitor.visit_node(tree.root_node());

        assert_eq!(visitor.interfaces.len(), 1);
        assert_eq!(visitor.interfaces[0].name, "Reader");
    }

    #[test]
    fn test_visitor_method_extraction() {
        use tree_sitter::Parser;

        let source = b"package main\nfunc (p Person) String() string { return \"\" }";
        let mut parser = Parser::new();
        parser.set_language(tree_sitter_go::language()).unwrap();
        let tree = parser.parse(source, None).unwrap();

        let mut visitor = GoVisitor::new(source, ParserConfig::default());
        visitor.visit_node(tree.root_node());

        // Methods are extracted as functions
        assert_eq!(visitor.functions.len(), 1);
        assert_eq!(visitor.functions[0].name, "String");
    }

    #[test]
    fn test_visitor_import_extraction() {
        use tree_sitter::Parser;

        let source = b"package main\nimport \"fmt\"";
        let mut parser = Parser::new();
        parser.set_language(tree_sitter_go::language()).unwrap();
        let tree = parser.parse(source, None).unwrap();

        let mut visitor = GoVisitor::new(source, ParserConfig::default());
        visitor.visit_node(tree.root_node());

        assert_eq!(visitor.imports.len(), 1);
    }

    #[test]
    fn test_visitor_multiple_declarations() {
        use tree_sitter::Parser;

        let source = b"package main\ntype User struct {}\ntype Admin struct {}";
        let mut parser = Parser::new();
        parser.set_language(tree_sitter_go::language()).unwrap();
        let tree = parser.parse(source, None).unwrap();

        let mut visitor = GoVisitor::new(source, ParserConfig::default());
        visitor.visit_node(tree.root_node());

        assert_eq!(visitor.structs.len(), 2);
        assert_eq!(visitor.structs[0].name, "User");
        assert_eq!(visitor.structs[1].name, "Admin");
    }

    // TDD: New tests for individual import extraction
    #[test]
    fn test_visitor_import_block_multiple_imports() {
        use tree_sitter::Parser;

        let source = b"package main\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"io\"\n)";
        let mut parser = Parser::new();
        parser.set_language(tree_sitter_go::language()).unwrap();
        let tree = parser.parse(source, None).unwrap();

        let mut visitor = GoVisitor::new(source, ParserConfig::default());
        visitor.visit_node(tree.root_node());

        // Should extract 3 individual imports, not 1 block
        assert_eq!(
            visitor.imports.len(),
            3,
            "Should extract 3 individual imports"
        );
        assert_eq!(visitor.imports[0].imported, "fmt");
        assert_eq!(visitor.imports[1].imported, "os");
        assert_eq!(visitor.imports[2].imported, "io");
    }

    #[test]
    fn test_visitor_import_with_alias() {
        use tree_sitter::Parser;

        let source = b"package main\nimport f \"fmt\"";
        let mut parser = Parser::new();
        parser.set_language(tree_sitter_go::language()).unwrap();
        let tree = parser.parse(source, None).unwrap();

        let mut visitor = GoVisitor::new(source, ParserConfig::default());
        visitor.visit_node(tree.root_node());

        assert_eq!(visitor.imports.len(), 1);
        assert_eq!(visitor.imports[0].imported, "fmt");
        assert_eq!(visitor.imports[0].alias, Some("f".to_string()));
        assert!(!visitor.imports[0].is_wildcard);
    }

    #[test]
    fn test_visitor_import_with_dot_wildcard() {
        use tree_sitter::Parser;

        let source = b"package main\nimport . \"fmt\"";
        let mut parser = Parser::new();
        parser.set_language(tree_sitter_go::language()).unwrap();
        let tree = parser.parse(source, None).unwrap();

        let mut visitor = GoVisitor::new(source, ParserConfig::default());
        visitor.visit_node(tree.root_node());

        assert_eq!(visitor.imports.len(), 1);
        assert_eq!(visitor.imports[0].imported, "fmt");
        assert!(visitor.imports[0].is_wildcard);
        assert_eq!(visitor.imports[0].alias, None);
    }

    #[test]
    fn test_visitor_import_with_blank_identifier() {
        use tree_sitter::Parser;

        let source = b"package main\nimport _ \"database/sql\"";
        let mut parser = Parser::new();
        parser.set_language(tree_sitter_go::language()).unwrap();
        let tree = parser.parse(source, None).unwrap();

        let mut visitor = GoVisitor::new(source, ParserConfig::default());
        visitor.visit_node(tree.root_node());

        assert_eq!(visitor.imports.len(), 1);
        assert_eq!(visitor.imports[0].imported, "database/sql");
        assert_eq!(visitor.imports[0].alias, None); // _ is ignored
        assert!(!visitor.imports[0].is_wildcard);
    }

    #[test]
    fn test_visitor_import_block_with_aliases() {
        use tree_sitter::Parser;

        let source = b"package main\nimport (\n\tf \"fmt\"\n\t. \"os\"\n\t_ \"encoding/json\"\n)";
        let mut parser = Parser::new();
        parser.set_language(tree_sitter_go::language()).unwrap();
        let tree = parser.parse(source, None).unwrap();

        let mut visitor = GoVisitor::new(source, ParserConfig::default());
        visitor.visit_node(tree.root_node());

        assert_eq!(visitor.imports.len(), 3);

        // Import with alias
        assert_eq!(visitor.imports[0].imported, "fmt");
        assert_eq!(visitor.imports[0].alias, Some("f".to_string()));
        assert!(!visitor.imports[0].is_wildcard);

        // Import with dot (wildcard)
        assert_eq!(visitor.imports[1].imported, "os");
        assert!(visitor.imports[1].is_wildcard);
        assert_eq!(visitor.imports[1].alias, None);

        // Import with blank identifier
        assert_eq!(visitor.imports[2].imported, "encoding/json");
        assert_eq!(visitor.imports[2].alias, None);
        assert!(!visitor.imports[2].is_wildcard);
    }
}