Skip to content

armgit / Ix

Public Imported from GitHub
0

Understand any codebase instantly. System intelligence for codebases, built for humans and AI.

feat: add Go parser and fix Go query error that blocked all .go ingestion

Tanner Kocher387f4abf6545
diff --git a/build.sbt b/build.sbt
index 21817676..4ccc51e6 100644
--- a/build.sbt
+++ b/build.sbt
@@ -33,6 +33,7 @@ lazy val memoryLayer = (project in file("memory-layer"))
"io.github.bonede" % "tree-sitter" % "0.26.6",
"io.github.bonede" % "tree-sitter-scala" % "0.24.0",
"io.github.bonede" % "tree-sitter-typescript" % "0.23.2",
+ "io.github.bonede" % "tree-sitter-go" % "0.23.3",
// Logging
"org.typelevel" %% "log4cats-slf4j" % "2.7.0",
diff --git a/core-ingestion/dist/queries.d.ts b/core-ingestion/dist/queries.d.ts
index 66c86e9f..6642ee57 100644
--- a/core-ingestion/dist/queries.d.ts
+++ b/core-ingestion/dist/queries.d.ts
@@ -4,7 +4,7 @@ export declare const JAVASCRIPT_QUERIES = "\n(class_declaration\n name: (identi
export declare const PYTHON_QUERIES = "\n(class_definition\n name: (identifier) @name) @definition.class\n\n(function_definition\n name: (identifier) @name) @definition.function\n\n(import_statement\n name: (dotted_name) @import.source) @import\n\n(import_from_statement\n module_name: (dotted_name) @import.source) @import\n\n(import_from_statement\n module_name: (relative_import) @import.source) @import\n\n; from . import utils / from .models import User \u2014 also capture the imported symbol names\n(import_from_statement\n module_name: (relative_import)\n name: (dotted_name (identifier) @import.name)) @import.names\n\n(call\n function: (identifier) @call.name) @call\n\n(call\n function: (attribute\n attribute: (identifier) @call.name)) @call\n\n; Heritage queries - Python class inheritance\n(class_definition\n name: (identifier) @heritage.class\n superclasses: (argument_list\n (identifier) @heritage.extends)) @heritage\n\n; Type references \u2014 captures types used in type annotations / hints\n(typed_parameter type: (type (identifier) @reference.type))\n(typed_default_parameter type: (type (identifier) @reference.type))\n";
export declare const JAVA_QUERIES = "\n; Classes, Interfaces, Enums, Annotations\n(class_declaration name: (identifier) @name) @definition.class\n(interface_declaration name: (identifier) @name) @definition.interface\n(enum_declaration name: (identifier) @name) @definition.enum\n(annotation_type_declaration name: (identifier) @name) @definition.annotation\n\n; Methods & Constructors\n(method_declaration name: (identifier) @name) @definition.method\n(constructor_declaration name: (identifier) @name) @definition.constructor\n\n; Imports - capture any import declaration child as source\n(import_declaration (_) @import.source) @import\n\n; Calls\n(method_invocation name: (identifier) @call.name) @call\n(method_invocation object: (_) name: (identifier) @call.name) @call\n\n; Constructor calls: new Foo()\n(object_creation_expression type: (type_identifier) @call.name) @call\n\n; Heritage - extends class\n(class_declaration name: (identifier) @heritage.class\n (superclass (type_identifier) @heritage.extends)) @heritage\n\n; Heritage - implements interfaces\n(class_declaration name: (identifier) @heritage.class\n (super_interfaces (type_list (type_identifier) @heritage.implements))) @heritage.impl\n\n; Type references \u2014 captures types used in field/param/return-type positions\n(field_declaration type: (type_identifier) @reference.type)\n(formal_parameter type: (type_identifier) @reference.type)\n(local_variable_declaration type: (type_identifier) @reference.type)\n(method_declaration type: (type_identifier) @reference.type)\n";
export declare const C_QUERIES = "\n; Functions (direct declarator)\n(function_definition declarator: (function_declarator declarator: (identifier) @name)) @definition.function\n(declaration declarator: (function_declarator declarator: (identifier) @name)) @definition.function\n\n; Functions returning pointers (pointer_declarator wraps function_declarator)\n(function_definition declarator: (pointer_declarator declarator: (function_declarator declarator: (identifier) @name))) @definition.function\n(declaration declarator: (pointer_declarator declarator: (function_declarator declarator: (identifier) @name))) @definition.function\n\n; Functions returning double pointers (nested pointer_declarator)\n(function_definition declarator: (pointer_declarator declarator: (pointer_declarator declarator: (function_declarator declarator: (identifier) @name)))) @definition.function\n\n; Structs, Unions, Enums, Typedefs\n(struct_specifier name: (type_identifier) @name) @definition.struct\n(union_specifier name: (type_identifier) @name) @definition.union\n(enum_specifier name: (type_identifier) @name) @definition.enum\n(type_definition declarator: (type_identifier) @name) @definition.typedef\n\n; Macros\n(preproc_function_def name: (identifier) @name) @definition.macro\n(preproc_def name: (identifier) @name) @definition.macro\n\n; Includes\n(preproc_include path: (_) @import.source) @import\n\n; Calls\n(call_expression function: (identifier) @call.name) @call\n(call_expression function: (field_expression field: (field_identifier) @call.name)) @call\n\n; Type references \u2014 captures types used in declaration/parameter positions\n(declaration type: (type_identifier) @reference.type)\n(parameter_declaration type: (type_identifier) @reference.type)\n";
-export declare const GO_QUERIES = "\n; Functions & Methods\n(function_declaration name: (identifier) @name) @definition.function\n(method_declaration name: (field_identifier) @name) @definition.method\n\n; Types\n(type_declaration (type_spec name: (type_identifier) @name type: (struct_type))) @definition.struct\n(type_declaration (type_spec name: (type_identifier) @name type: (interface_type))) @definition.interface\n\n; Imports\n(import_declaration (import_spec path: (interpreted_string_literal) @import.source)) @import\n(import_declaration (import_spec_list (import_spec path: (interpreted_string_literal) @import.source))) @import\n\n; Struct embedding (anonymous fields = inheritance)\n(type_declaration\n (type_spec\n name: (type_identifier) @heritage.class\n type: (struct_type\n (field_declaration_list\n (field_declaration\n type: (type_identifier) @heritage.extends))))) @definition.struct\n\n; Calls\n(call_expression function: (identifier) @call.name) @call\n(call_expression function: (selector_expression field: (field_identifier) @call.name)) @call\n\n; Struct literal construction: User{Name: \"Alice\"}\n(composite_literal type: (type_identifier) @call.name) @call\n\n; Type references \u2014 captures types used in field/param/return-type positions\n(field_declaration type: (type_identifier) @reference.type)\n(parameter_declaration type: (type_identifier) @reference.type)\n(result type: (type_identifier) @reference.type)\n";
+export declare const GO_QUERIES = "\n; Functions & Methods\n(function_declaration name: (identifier) @name) @definition.function\n(method_declaration name: (field_identifier) @name) @definition.method\n\n; Types\n(type_declaration (type_spec name: (type_identifier) @name type: (struct_type))) @definition.struct\n(type_declaration (type_spec name: (type_identifier) @name type: (interface_type))) @definition.interface\n\n; Imports\n(import_declaration (import_spec path: (interpreted_string_literal) @import.source)) @import\n(import_declaration (import_spec_list (import_spec path: (interpreted_string_literal) @import.source))) @import\n\n; Struct embedding (anonymous fields = inheritance)\n(type_declaration\n (type_spec\n name: (type_identifier) @heritage.class\n type: (struct_type\n (field_declaration_list\n (field_declaration\n type: (type_identifier) @heritage.extends))))) @definition.struct\n\n; Calls\n(call_expression function: (identifier) @call.name) @call\n(call_expression function: (selector_expression field: (field_identifier) @call.name)) @call\n\n; Struct literal construction: User{Name: \"Alice\"}\n(composite_literal type: (type_identifier) @call.name) @call\n\n; Type references \u2014 captures types used in field/param/return-type positions\n(field_declaration type: (type_identifier) @reference.type)\n(parameter_declaration type: (type_identifier) @reference.type)\n; Return types: in tree-sitter-go, return type is a direct type_identifier child of function/method\n(function_declaration result: (type_identifier) @reference.type)\n(method_declaration result: (type_identifier) @reference.type)\n";
export declare const CPP_QUERIES = "\n; Classes, Structs, Namespaces\n(class_specifier name: (type_identifier) @name) @definition.class\n(struct_specifier name: (type_identifier) @name) @definition.struct\n(namespace_definition name: (namespace_identifier) @name) @definition.namespace\n(enum_specifier name: (type_identifier) @name) @definition.enum\n\n; Typedefs and unions (common in C-style headers and mixed C/C++ code)\n(type_definition declarator: (type_identifier) @name) @definition.typedef\n(union_specifier name: (type_identifier) @name) @definition.union\n\n; Macros\n(preproc_function_def name: (identifier) @name) @definition.macro\n(preproc_def name: (identifier) @name) @definition.macro\n\n; Functions & Methods (direct declarator)\n(function_definition declarator: (function_declarator declarator: (identifier) @name)) @definition.function\n(function_definition declarator: (function_declarator declarator: (qualified_identifier name: (identifier) @name))) @definition.method\n\n; Functions/methods returning pointers (pointer_declarator wraps function_declarator)\n(function_definition declarator: (pointer_declarator declarator: (function_declarator declarator: (identifier) @name))) @definition.function\n(function_definition declarator: (pointer_declarator declarator: (function_declarator declarator: (qualified_identifier name: (identifier) @name)))) @definition.method\n\n; Functions/methods returning double pointers (nested pointer_declarator)\n(function_definition declarator: (pointer_declarator declarator: (pointer_declarator declarator: (function_declarator declarator: (identifier) @name)))) @definition.function\n(function_definition declarator: (pointer_declarator declarator: (pointer_declarator declarator: (function_declarator declarator: (qualified_identifier name: (identifier) @name))))) @definition.method\n\n; Functions/methods returning references (reference_declarator wraps function_declarator)\n(function_definition declarator: (reference_declarator (function_declarator declarator: (identifier) @name))) @definition.function\n(function_definition declarator: (reference_declarator (function_declarator declarator: (qualified_identifier name: (identifier) @name)))) @definition.method\n\n; Destructors (destructor_name is distinct from identifier in tree-sitter-cpp)\n(function_definition declarator: (function_declarator declarator: (qualified_identifier name: (destructor_name) @name))) @definition.method\n\n; Function declarations / prototypes (common in headers)\n(declaration declarator: (function_declarator declarator: (identifier) @name)) @definition.function\n(declaration declarator: (pointer_declarator declarator: (function_declarator declarator: (identifier) @name))) @definition.function\n\n; Inline class method declarations (inside class body, no body: void Foo();)\n(field_declaration declarator: (function_declarator declarator: (identifier) @name)) @definition.method\n\n; Inline class method definitions (inside class body, with body: void Foo() { ... })\n(field_declaration_list\n (function_definition\n declarator: (function_declarator\n declarator: [(field_identifier) (identifier) (operator_name) (destructor_name)] @name)) @definition.method)\n\n; Templates\n(template_declaration (class_specifier name: (type_identifier) @name)) @definition.template\n(template_declaration (function_definition declarator: (function_declarator declarator: (identifier) @name))) @definition.template\n\n; Includes\n(preproc_include path: (_) @import.source) @import\n\n; Calls\n(call_expression function: (identifier) @call.name) @call\n(call_expression function: (field_expression field: (field_identifier) @call.name)) @call\n(call_expression function: (qualified_identifier name: (identifier) @call.name)) @call\n(call_expression function: (template_function name: (identifier) @call.name)) @call\n\n; Constructor calls: new User()\n(new_expression type: (type_identifier) @call.name) @call\n\n; Heritage\n(class_specifier name: (type_identifier) @heritage.class\n (base_class_clause (type_identifier) @heritage.extends)) @heritage\n(class_specifier name: (type_identifier) @heritage.class\n (base_class_clause (access_specifier) (type_identifier) @heritage.extends)) @heritage\n\n; Type references \u2014 captures types used in declaration/parameter positions\n(declaration type: (type_identifier) @reference.type)\n(parameter_declaration type: (type_identifier) @reference.type)\n";
export declare const CSHARP_QUERIES = "\n; Types\n(class_declaration name: (identifier) @name) @definition.class\n(interface_declaration name: (identifier) @name) @definition.interface\n(struct_declaration name: (identifier) @name) @definition.struct\n(enum_declaration name: (identifier) @name) @definition.enum\n(record_declaration name: (identifier) @name) @definition.record\n(delegate_declaration name: (identifier) @name) @definition.delegate\n\n; Namespaces (block form and C# 10+ file-scoped form)\n(namespace_declaration name: (identifier) @name) @definition.namespace\n(namespace_declaration name: (qualified_name) @name) @definition.namespace\n(file_scoped_namespace_declaration name: (identifier) @name) @definition.namespace\n(file_scoped_namespace_declaration name: (qualified_name) @name) @definition.namespace\n\n; Methods & Properties\n(method_declaration name: (identifier) @name) @definition.method\n(local_function_statement name: (identifier) @name) @definition.function\n(constructor_declaration name: (identifier) @name) @definition.constructor\n(property_declaration name: (identifier) @name) @definition.property\n\n; Primary constructors (C# 12): class User(string name, int age) { }\n(class_declaration name: (identifier) @name (parameter_list) @definition.constructor)\n(record_declaration name: (identifier) @name (parameter_list) @definition.constructor)\n\n; Using\n(using_directive (qualified_name) @import.source) @import\n(using_directive (identifier) @import.source) @import\n\n; Calls\n(invocation_expression function: (identifier) @call.name) @call\n(invocation_expression function: (member_access_expression name: (identifier) @call.name)) @call\n\n; Null-conditional method calls: user?.Save()\n; Parses as: invocation_expression \u2192 conditional_access_expression \u2192 member_binding_expression \u2192 identifier\n(invocation_expression\n function: (conditional_access_expression\n (member_binding_expression\n (identifier) @call.name))) @call\n\n; Constructor calls: new Foo() and new Foo { Props }\n(object_creation_expression type: (identifier) @call.name) @call\n\n; Target-typed new (C# 9): User u = new(\"x\", 5)\n(variable_declaration type: (identifier) @call.name (variable_declarator (implicit_object_creation_expression) @call))\n\n; Heritage\n(class_declaration name: (identifier) @heritage.class\n (base_list (identifier) @heritage.extends)) @heritage\n(class_declaration name: (identifier) @heritage.class\n (base_list (generic_name (identifier) @heritage.extends))) @heritage\n\n; Type references \u2014 captures types used in field/param/return-type positions\n(parameter type: (identifier) @reference.type)\n(variable_declaration type: (identifier) @reference.type)\n(field_declaration type: (identifier) @reference.type)\n(method_declaration return_type: (identifier) @reference.type)\n";
export declare const RUST_QUERIES = "\n; Functions & Items\n(function_item name: (identifier) @name) @definition.function\n(struct_item name: (type_identifier) @name) @definition.struct\n(enum_item name: (type_identifier) @name) @definition.enum\n(trait_item name: (type_identifier) @name) @definition.trait\n(impl_item type: (type_identifier) @name !trait) @definition.impl\n(impl_item type: (generic_type type: (type_identifier) @name) !trait) @definition.impl\n(mod_item name: (identifier) @name) @definition.module\n\n; Type aliases, const, static, macros\n(type_item name: (type_identifier) @name) @definition.type\n(const_item name: (identifier) @name) @definition.const\n(static_item name: (identifier) @name) @definition.static\n(macro_definition name: (identifier) @name) @definition.macro\n\n; Use statements\n(use_declaration argument: (_) @import.source) @import\n\n; Calls\n(call_expression function: (identifier) @call.name) @call\n(call_expression function: (field_expression field: (field_identifier) @call.name)) @call\n(call_expression function: (scoped_identifier name: (identifier) @call.name)) @call\n(call_expression function: (generic_function function: (identifier) @call.name)) @call\n\n; Struct literal construction: User { name: value }\n(struct_expression name: (type_identifier) @call.name) @call\n\n; Type references \u2014 captures types used in field/param/return-type positions\n(field_declaration type: (type_identifier) @reference.type)\n(parameter pattern: (_) type: (type_identifier) @reference.type)\n(function_item return_type: (type_identifier) @reference.type)\n\n; Heritage (trait implementation) \u2014 all combinations of concrete/generic trait \u00D7 concrete/generic type\n(impl_item trait: (type_identifier) @heritage.trait type: (type_identifier) @heritage.class) @heritage\n(impl_item trait: (generic_type type: (type_identifier) @heritage.trait) type: (type_identifier) @heritage.class) @heritage\n(impl_item trait: (type_identifier) @heritage.trait type: (generic_type type: (type_identifier) @heritage.class)) @heritage\n(impl_item trait: (generic_type type: (type_identifier) @heritage.trait) type: (generic_type type: (type_identifier) @heritage.class)) @heritage\n";
diff --git a/core-ingestion/dist/queries.js b/core-ingestion/dist/queries.js
index 248b4d82..16490aa5 100644
--- a/core-ingestion/dist/queries.js
+++ b/core-ingestion/dist/queries.js
@@ -293,7 +293,9 @@ export const GO_QUERIES = `
; Type references — captures types used in field/param/return-type positions
(field_declaration type: (type_identifier) @reference.type)
(parameter_declaration type: (type_identifier) @reference.type)
-(result type: (type_identifier) @reference.type)
+; Return types: in tree-sitter-go, return type is a direct type_identifier child of function/method
+(function_declaration result: (type_identifier) @reference.type)
+(method_declaration result: (type_identifier) @reference.type)
`;
// C++ queries - works with tree-sitter-cpp
export const CPP_QUERIES = `
diff --git a/core-ingestion/src/queries.ts b/core-ingestion/src/queries.ts
index c3ecc2e1..1ae0446a 100644
--- a/core-ingestion/src/queries.ts
+++ b/core-ingestion/src/queries.ts
@@ -300,7 +300,9 @@ export const GO_QUERIES = `
; Type references — captures types used in field/param/return-type positions
(field_declaration type: (type_identifier) @reference.type)
(parameter_declaration type: (type_identifier) @reference.type)
-(result type: (type_identifier) @reference.type)
+; Return types: in tree-sitter-go, return type is a direct type_identifier child of function/method
+(function_declaration result: (type_identifier) @reference.type)
+(method_declaration result: (type_identifier) @reference.type)
`;
// C++ queries - works with tree-sitter-cpp
diff --git a/memory-layer/src/main/scala/ix/memory/ingestion/GraphPatchBuilder.scala b/memory-layer/src/main/scala/ix/memory/ingestion/GraphPatchBuilder.scala
index c11587ef..3a903acd 100644
--- a/memory-layer/src/main/scala/ix/memory/ingestion/GraphPatchBuilder.scala
+++ b/memory-layer/src/main/scala/ix/memory/ingestion/GraphPatchBuilder.scala
@@ -31,6 +31,7 @@ object GraphPatchBuilder {
val extractor = if (filePath.endsWith(".py")) "tree-sitter-python/1.0"
else if (filePath.endsWith(".ts") || filePath.endsWith(".tsx")) "typescript-parser/1.0"
else if (filePath.endsWith(".scala") || filePath.endsWith(".sc")) "scala-parser/1.0"
+ else if (filePath.endsWith(".go")) "tree-sitter-go/1.0"
else if (filePath.endsWith(".json") || filePath.endsWith(".yaml") || filePath.endsWith(".yml") || filePath.endsWith(".toml")) "config-parser/1.0"
else if (filePath.endsWith(".md")) "markdown-parser/1.0"
else "unknown-parser/1.0"
@@ -80,7 +81,7 @@ object GraphPatchBuilder {
val claimOps = relationshipClaims ++ attributeClaims
val allOps = nodeOps ++ edgeOps ++ claimOps
- val sourceType = if (filePath.endsWith(".py") || filePath.endsWith(".ts") || filePath.endsWith(".tsx") || filePath.endsWith(".scala") || filePath.endsWith(".sc")) SourceType.Code
+ val sourceType = if (filePath.endsWith(".py") || filePath.endsWith(".ts") || filePath.endsWith(".tsx") || filePath.endsWith(".scala") || filePath.endsWith(".sc") || filePath.endsWith(".go")) SourceType.Code
else if (filePath.endsWith(".json") || filePath.endsWith(".yaml") || filePath.endsWith(".yml") || filePath.endsWith(".toml")) SourceType.Config
else if (filePath.endsWith(".md")) SourceType.Doc
else SourceType.Code
diff --git a/memory-layer/src/main/scala/ix/memory/ingestion/IngestionService.scala b/memory-layer/src/main/scala/ix/memory/ingestion/IngestionService.scala
index ea66a6bb..61c4d9c4 100644
--- a/memory-layer/src/main/scala/ix/memory/ingestion/IngestionService.scala
+++ b/memory-layer/src/main/scala/ix/memory/ingestion/IngestionService.scala
@@ -41,6 +41,7 @@ class IngestionService(parserRouter: ParserRouter, writeApi: GraphWriteApi, quer
extractor = if (fp.endsWith(".py")) "tree-sitter-python/1.0"
else if (fp.endsWith(".ts") || fp.endsWith(".tsx")) "typescript-parser/1.0"
else if (fp.endsWith(".scala") || fp.endsWith(".sc")) "scala-parser/1.0"
+ else if (fp.endsWith(".go")) "tree-sitter-go/1.0"
else if (fp.endsWith(".json") || fp.endsWith(".yaml") || fp.endsWith(".yml") || fp.endsWith(".toml") || fp.endsWith(".ini") || fp.endsWith(".conf") || fp.endsWith(".properties") || fp.endsWith(".env")) "config-parser/1.0"
else if (fp.endsWith(".md") || fp.endsWith(".mdx") || fp.endsWith(".rst") || fp.endsWith(".txt")) "markdown-parser/1.0"
else "text-parser/1.0"
diff --git a/memory-layer/src/main/scala/ix/memory/ingestion/ParserRouter.scala b/memory-layer/src/main/scala/ix/memory/ingestion/ParserRouter.scala
index a5d24632..74639975 100644
--- a/memory-layer/src/main/scala/ix/memory/ingestion/ParserRouter.scala
+++ b/memory-layer/src/main/scala/ix/memory/ingestion/ParserRouter.scala
@@ -1,6 +1,6 @@
package ix.memory.ingestion
-import ix.memory.ingestion.parsers.{ConfigParser, MarkdownParser, ScalaParser, TreeSitterPythonParser, TypeScriptParser}
+import ix.memory.ingestion.parsers.{ConfigParser, MarkdownParser, ScalaParser, TreeSitterGoParser, TreeSitterPythonParser, TypeScriptParser}
/**
* Routes file paths to the appropriate language parser.
@@ -13,11 +13,13 @@ class ParserRouter {
private val configParser = new ConfigParser()
private val markdownParser = new MarkdownParser()
private val scalaParser = new ScalaParser()
+ private val goParser = new TreeSitterGoParser()
def parserFor(filePath: String): Option[Parser] = {
if (filePath.endsWith(".py")) Some(pythonParser)
else if (filePath.endsWith(".ts") || filePath.endsWith(".tsx")) Some(tsParser)
else if (filePath.endsWith(".scala") || filePath.endsWith(".sc")) Some(scalaParser)
+ else if (filePath.endsWith(".go")) Some(goParser)
else if (filePath.endsWith(".json") || filePath.endsWith(".yaml") || filePath.endsWith(".yml") || filePath.endsWith(".toml")) Some(configParser)
else if (filePath.endsWith(".md")) Some(markdownParser)
else None
diff --git a/memory-layer/src/main/scala/ix/memory/ingestion/parsers/GoParser.scala b/memory-layer/src/main/scala/ix/memory/ingestion/parsers/GoParser.scala
new file mode 100644
index 00000000..2abd19ae
--- /dev/null
+++ b/memory-layer/src/main/scala/ix/memory/ingestion/parsers/GoParser.scala
@@ -0,0 +1,485 @@
+package ix.memory.ingestion.parsers
+
+import ix.memory.ingestion.{Fingerprint, Parser, ParseResult, ParsedEntity, ParsedRelationship}
+import ix.memory.model.NodeKind
+import io.circe.Json
+
+import scala.util.matching.Regex
+
+/**
+ * Regex-based Go source parser (fallback for when tree-sitter is unavailable).
+ * Extracts: functions, methods, structs, interfaces, type declarations,
+ * imports, const/var declarations, and basic call edges.
+ */
+class GoParser extends Parser {
+
+ private val PackagePattern: Regex = """^\s*package\s+(\w+)""".r
+ private val FuncPattern: Regex = """^\s*func\s+(\w+)\s*(?:\[.*?\])?\s*\(""".r
+ private val MethodPattern: Regex = """^\s*func\s+\(\s*\w+\s+\*?(\w+)\s*\)\s+(\w+)\s*(?:\[.*?\])?\s*\(""".r
+ private val StructPattern: Regex = """^\s*type\s+(\w+)\s+struct\s*\{""".r
+ private val InterfacePattern: Regex = """^\s*type\s+(\w+)\s+interface\s*\{""".r
+ private val TypeAliasPattern: Regex = """^\s*type\s+(\w+)\s*=\s*(.+)""".r
+ private val NamedTypePattern: Regex = """^\s*type\s+(\w+)\s+(\w+)""".r
+ private val ImportSinglePattern: Regex = """^\s*import\s+"([^"]+)"""".r
+ private val ImportGroupStart: Regex = """^\s*import\s*\(""".r
+ private val ImportSpecPattern: Regex = """^\s*(?:(\w+|\.)\s+)?"([^"]+)"""".r
+ private val ConstPattern: Regex = """^\s*const\s+(\w+)\s""".r
+ private val VarPattern: Regex = """^\s*var\s+(\w+)\s""".r
+ private val ConstGroupStart: Regex = """^\s*const\s*\(""".r
+ private val VarGroupStart: Regex = """^\s*var\s*\(""".r
+ private val ConstSpecPattern: Regex = """^\s*(\w+)""".r
+ private val CallPattern: Regex = """\b(\w+)\s*\(""".r
+
+ private val GoBuiltins: Set[String] = Set(
+ "make", "len", "cap", "append", "copy", "close", "delete",
+ "complex", "real", "imag", "new", "panic", "recover",
+ "print", "println", "error", "string", "int", "float64",
+ "bool", "byte", "rune", "nil", "true", "false", "iota",
+ "int8", "int16", "int32", "int64",
+ "uint", "uint8", "uint16", "uint32", "uint64", "uintptr",
+ "float32", "complex64", "complex128", "any", "comparable"
+ )
+
+ private val GoKeywords: Set[String] = Set(
+ "break", "case", "chan", "const", "continue", "default", "defer",
+ "else", "fallthrough", "for", "func", "go", "goto", "if",
+ "import", "interface", "map", "package", "range", "return",
+ "select", "struct", "switch", "type", "var"
+ )
+
+ def parse(fileName: String, source: String): ParseResult = {
+ val lines = source.split("\n", -1)
+
+ var fileAttrs: Map[String, Json] = Map("language" -> Json.fromString("go"))
+ var entities = Vector.empty[ParsedEntity]
+ var relationships = Vector.empty[ParsedRelationship]
+
+ // Track type ranges for containment
+ var typeRanges = Vector.empty[(String, Int, Int)]
+
+ var i = 0
+ while (i < lines.length) {
+ val line = lines(i)
+ val lineNum = i + 1
+ val trimmed = line.trim
+
+ // Skip comments
+ if (trimmed.startsWith("//") || trimmed.startsWith("/*") || trimmed.startsWith("*")) {
+ i += 1
+ } else {
+ var handled = false
+
+ // Package
+ if (!handled) {
+ PackagePattern.findFirstMatchIn(line).foreach { m =>
+ fileAttrs = fileAttrs + ("package" -> Json.fromString(m.group(1)))
+ handled = true
+ }
+ }
+
+ // Method (must check before function)
+ if (!handled) {
+ MethodPattern.findFirstMatchIn(line).foreach { m =>
+ val receiverType = m.group(1)
+ val methodName = m.group(2)
+ val endLine = findBraceBlockEnd(lines, i).getOrElse(lineNum)
+ val sig = trimmed.replaceAll("""\s*\{\s*$""", "").trim.take(120)
+ val bodyText = lines.slice(i, endLine).mkString("\n")
+ val fp = Fingerprint.compute(sig, bodyText)
+ val exported = methodName.nonEmpty && methodName.head.isUpper
+
+ entities = entities :+ ParsedEntity(
+ name = methodName,
+ kind = NodeKind.Method,
+ attrs = Map(
+ "language" -> Json.fromString("go"),
+ "summary" -> Json.fromString(sig),
+ "signature" -> Json.fromString(sig),
+ "visibility" -> Json.fromString(if (exported) "exported" else "unexported"),
+ "exported" -> Json.fromBoolean(exported),
+ "receiver" -> Json.fromString(receiverType)
+ ),
+ lineStart = lineNum,
+ lineEnd = endLine,
+ contentFingerprint = Some(fp)
+ )
+ relationships = relationships :+ ParsedRelationship(receiverType, methodName, "CONTAINS")
+
+ // Extract calls
+ relationships = relationships ++ extractCalls(lines, i, endLine, methodName)
+
+ i = endLine
+ handled = true
+ }
+ }
+
+ // Function
+ if (!handled) {
+ FuncPattern.findFirstMatchIn(line).foreach { m =>
+ val funcName = m.group(1)
+ val endLine = findBraceBlockEnd(lines, i).getOrElse(lineNum)
+ val sig = trimmed.replaceAll("""\s*\{\s*$""", "").trim.take(120)
+ val bodyText = lines.slice(i, endLine).mkString("\n")
+ val fp = Fingerprint.compute(sig, bodyText)
+ val exported = funcName.nonEmpty && funcName.head.isUpper
+
+ entities = entities :+ ParsedEntity(
+ name = funcName,
+ kind = NodeKind.Function,
+ attrs = Map(
+ "language" -> Json.fromString("go"),
+ "summary" -> Json.fromString(sig),
+ "signature" -> Json.fromString(sig),
+ "visibility" -> Json.fromString(if (exported) "exported" else "unexported"),
+ "exported" -> Json.fromBoolean(exported)
+ ),
+ lineStart = lineNum,
+ lineEnd = endLine,
+ contentFingerprint = Some(fp)
+ )
+ relationships = relationships :+ ParsedRelationship(fileName, funcName, "CONTAINS")
+
+ // Extract calls
+ relationships = relationships ++ extractCalls(lines, i, endLine, funcName)
+
+ i = endLine
+ handled = true
+ }
+ }
+
+ // Struct
+ if (!handled) {
+ StructPattern.findFirstMatchIn(line).foreach { m =>
+ val name = m.group(1)
+ val endLine = findBraceBlockEnd(lines, i).getOrElse(lineNum)
+ val sig = trimmed.replaceAll("""\s*\{\s*$""", "").trim.take(120)
+ val bodyText = lines.slice(i, endLine).mkString("\n")
+ val fp = Fingerprint.compute(sig, bodyText)
+ val exported = name.nonEmpty && name.head.isUpper
+
+ entities = entities :+ ParsedEntity(
+ name = name,
+ kind = NodeKind.Class,
+ attrs = Map(
+ "language" -> Json.fromString("go"),
+ "go_kind" -> Json.fromString("struct"),
+ "signature" -> Json.fromString(sig),
+ "summary" -> Json.fromString(sig),
+ "visibility" -> Json.fromString(if (exported) "exported" else "unexported"),
+ "exported" -> Json.fromBoolean(exported)
+ ),
+ lineStart = lineNum,
+ lineEnd = endLine,
+ contentFingerprint = Some(fp)
+ )
+ relationships = relationships :+ ParsedRelationship(fileName, name, "CONTAINS")
+ typeRanges = typeRanges :+ (name, lineNum, endLine)
+
+ i = endLine
+ handled = true
+ }
+ }
+
+ // Interface
+ if (!handled) {
+ InterfacePattern.findFirstMatchIn(line).foreach { m =>
+ val name = m.group(1)
+ val endLine = findBraceBlockEnd(lines, i).getOrElse(lineNum)
+ val sig = trimmed.replaceAll("""\s*\{\s*$""", "").trim.take(120)
+ val bodyText = lines.slice(i, endLine).mkString("\n")
+ val fp = Fingerprint.compute(sig, bodyText)
+ val exported = name.nonEmpty && name.head.isUpper
+
+ entities = entities :+ ParsedEntity(
+ name = name,
+ kind = NodeKind.Interface,
+ attrs = Map(
+ "language" -> Json.fromString("go"),
+ "go_kind" -> Json.fromString("interface"),
+ "signature" -> Json.fromString(sig),
+ "summary" -> Json.fromString(sig),
+ "visibility" -> Json.fromString(if (exported) "exported" else "unexported"),
+ "exported" -> Json.fromBoolean(exported)
+ ),
+ lineStart = lineNum,
+ lineEnd = endLine,
+ contentFingerprint = Some(fp)
+ )
+ relationships = relationships :+ ParsedRelationship(fileName, name, "CONTAINS")
+ typeRanges = typeRanges :+ (name, lineNum, endLine)
+
+ i = endLine
+ handled = true
+ }
+ }
+
+ // Type alias
+ if (!handled) {
+ TypeAliasPattern.findFirstMatchIn(line).foreach { m =>
+ val name = m.group(1)
+ val exported = name.nonEmpty && name.head.isUpper
+ val sig = trimmed.take(120)
+ val fp = Fingerprint.compute(sig, sig)
+
+ entities = entities :+ ParsedEntity(
+ name = name,
+ kind = NodeKind.Class,
+ attrs = Map(
+ "language" -> Json.fromString("go"),
+ "go_kind" -> Json.fromString("type_alias"),
+ "signature" -> Json.fromString(sig),
+ "summary" -> Json.fromString(sig),
+ "visibility" -> Json.fromString(if (exported) "exported" else "unexported"),
+ "exported" -> Json.fromBoolean(exported)
+ ),
+ lineStart = lineNum,
+ lineEnd = lineNum,
+ contentFingerprint = Some(fp)
+ )
+ relationships = relationships :+ ParsedRelationship(fileName, name, "CONTAINS")
+ handled = true
+ }
+ }
+
+ // Named type (must be after struct/interface/alias checks)
+ if (!handled) {
+ NamedTypePattern.findFirstMatchIn(line).foreach { m =>
+ val name = m.group(1)
+ val baseType = m.group(2)
+ if (baseType != "struct" && baseType != "interface") {
+ val exported = name.nonEmpty && name.head.isUpper
+ val sig = trimmed.take(120)
+ val fp = Fingerprint.compute(sig, sig)
+
+ entities = entities :+ ParsedEntity(
+ name = name,
+ kind = NodeKind.Class,
+ attrs = Map(
+ "language" -> Json.fromString("go"),
+ "go_kind" -> Json.fromString("named_type"),
+ "signature" -> Json.fromString(sig),
+ "summary" -> Json.fromString(sig),
+ "visibility" -> Json.fromString(if (exported) "exported" else "unexported"),
+ "exported" -> Json.fromBoolean(exported)
+ ),
+ lineStart = lineNum,
+ lineEnd = lineNum,
+ contentFingerprint = Some(fp)
+ )
+ relationships = relationships :+ ParsedRelationship(fileName, name, "CONTAINS")
+ handled = true
+ }
+ }
+ }
+
+ // Import group
+ if (!handled) {
+ ImportGroupStart.findFirstMatchIn(line).foreach { _ =>
+ i += 1
+ while (i < lines.length && !lines(i).trim.startsWith(")")) {
+ ImportSpecPattern.findFirstMatchIn(lines(i)).foreach { m =>
+ val importPath = m.group(2)
+ if (!entities.exists(e => e.name == importPath && e.kind == NodeKind.Module)) {
+ entities = entities :+ ParsedEntity(
+ name = importPath,
+ kind = NodeKind.Module,
+ attrs = Map.empty,
+ lineStart = i + 1,
+ lineEnd = i + 1
+ )
+ }
+ relationships = relationships :+ ParsedRelationship(fileName, importPath, "IMPORTS")
+ }
+ i += 1
+ }
+ handled = true
+ }
+ }
+
+ // Single import
+ if (!handled) {
+ ImportSinglePattern.findFirstMatchIn(line).foreach { m =>
+ val importPath = m.group(1)
+ if (!entities.exists(e => e.name == importPath && e.kind == NodeKind.Module)) {
+ entities = entities :+ ParsedEntity(
+ name = importPath,
+ kind = NodeKind.Module,
+ attrs = Map.empty,
+ lineStart = lineNum,
+ lineEnd = lineNum
+ )
+ }
+ relationships = relationships :+ ParsedRelationship(fileName, importPath, "IMPORTS")
+ handled = true
+ }
+ }
+
+ // Const (single)
+ if (!handled) {
+ ConstGroupStart.findFirstMatchIn(line).foreach { _ =>
+ i += 1
+ while (i < lines.length && !lines(i).trim.startsWith(")")) {
+ ConstSpecPattern.findFirstMatchIn(lines(i).trim).foreach { m =>
+ val name = m.group(1)
+ if (name != "//" && name != "/*" && name != "_") {
+ val exported = name.nonEmpty && name.head.isUpper
+ entities = entities :+ ParsedEntity(
+ name = name,
+ kind = NodeKind.Variable,
+ attrs = Map(
+ "language" -> Json.fromString("go"),
+ "go_kind" -> Json.fromString("const"),
+ "visibility" -> Json.fromString(if (exported) "exported" else "unexported"),
+ "exported" -> Json.fromBoolean(exported)
+ ),
+ lineStart = i + 1,
+ lineEnd = i + 1
+ )
+ relationships = relationships :+ ParsedRelationship(fileName, name, "CONTAINS")
+ }
+ }
+ i += 1
+ }
+ handled = true
+ }
+ }
+
+ if (!handled) {
+ ConstPattern.findFirstMatchIn(line).foreach { m =>
+ val name = m.group(1)
+ if (name != "(" && name != "_") {
+ val exported = name.nonEmpty && name.head.isUpper
+ entities = entities :+ ParsedEntity(
+ name = name,
+ kind = NodeKind.Variable,
+ attrs = Map(
+ "language" -> Json.fromString("go"),
+ "go_kind" -> Json.fromString("const"),
+ "visibility" -> Json.fromString(if (exported) "exported" else "unexported"),
+ "exported" -> Json.fromBoolean(exported)
+ ),
+ lineStart = lineNum,
+ lineEnd = lineNum
+ )
+ relationships = relationships :+ ParsedRelationship(fileName, name, "CONTAINS")
+ handled = true
+ }
+ }
+ }
+
+ // Var group
+ if (!handled) {
+ VarGroupStart.findFirstMatchIn(line).foreach { _ =>
+ i += 1
+ while (i < lines.length && !lines(i).trim.startsWith(")")) {
+ val varLine = lines(i).trim
+ if (varLine.nonEmpty && !varLine.startsWith("//") && !varLine.startsWith("/*")) {
+ varLine.split("\\s+").headOption.foreach { name =>
+ if (name != "_" && name.matches("\\w+")) {
+ val exported = name.nonEmpty && name.head.isUpper
+ entities = entities :+ ParsedEntity(
+ name = name,
+ kind = NodeKind.Variable,
+ attrs = Map(
+ "language" -> Json.fromString("go"),
+ "go_kind" -> Json.fromString("var"),
+ "visibility" -> Json.fromString(if (exported) "exported" else "unexported"),
+ "exported" -> Json.fromBoolean(exported)
+ ),
+ lineStart = i + 1,
+ lineEnd = i + 1
+ )
+ relationships = relationships :+ ParsedRelationship(fileName, name, "CONTAINS")
+ }
+ }
+ }
+ i += 1
+ }
+ handled = true
+ }
+ }
+
+ if (!handled) {
+ VarPattern.findFirstMatchIn(line).foreach { m =>
+ val name = m.group(1)
+ if (name != "(" && name != "_") {
+ val exported = name.nonEmpty && name.head.isUpper
+ entities = entities :+ ParsedEntity(
+ name = name,
+ kind = NodeKind.Variable,
+ attrs = Map(
+ "language" -> Json.fromString("go"),
+ "go_kind" -> Json.fromString("var"),
+ "visibility" -> Json.fromString(if (exported) "exported" else "unexported"),
+ "exported" -> Json.fromBoolean(exported)
+ ),
+ lineStart = lineNum,
+ lineEnd = lineNum
+ )
+ relationships = relationships :+ ParsedRelationship(fileName, name, "CONTAINS")
+ handled = true
+ }
+ }
+ }
+
+ if (!handled) i += 1
+ else if (i == lineNum - 1) i += 1 // advance if we didn't already
+ }
+ }
+
+ val fileEntity = ParsedEntity(
+ name = fileName,
+ kind = NodeKind.File,
+ attrs = fileAttrs,
+ lineStart = 1,
+ lineEnd = lines.length
+ )
+
+ ParseResult(fileEntity +: entities, relationships)
+ }
+
+ private def findBraceBlockEnd(lines: Array[String], startIdx: Int): Option[Int] = {
+ var braceCount = 0
+ var foundOpen = false
+ var i = startIdx
+
+ while (i < lines.length) {
+ val line = lines(i)
+ for (ch <- line) {
+ ch match {
+ case '{' =>
+ braceCount += 1
+ foundOpen = true
+ case '}' =>
+ braceCount -= 1
+ if (foundOpen && braceCount == 0) {
+ return Some(i + 1)
+ }
+ case _ =>
+ }
+ }
+ i += 1
+ }
+
+ if (foundOpen) Some(lines.length) else None
+ }
+
+ private def extractCalls(lines: Array[String], startIdx: Int, endIdx: Int, callerName: String): Vector[ParsedRelationship] = {
+ var calls = Vector.empty[ParsedRelationship]
+ val seen = scala.collection.mutable.Set.empty[String]
+ for (i <- (startIdx + 1) until endIdx.min(lines.length)) {
+ val line = lines(i).trim
+ if (!line.startsWith("//") && !line.startsWith("/*")) {
+ CallPattern.findAllMatchIn(line).foreach { m =>
+ val callee = m.group(1)
+ if (callee != callerName && !GoBuiltins.contains(callee) &&
+ !GoKeywords.contains(callee) && !seen.contains(callee)) {
+ seen += callee
+ calls = calls :+ ParsedRelationship(callerName, callee, "CALLS")
+ }
+ }
+ }
+ }
+ calls
+ }
+}
diff --git a/memory-layer/src/main/scala/ix/memory/ingestion/parsers/TreeSitterGoParser.scala b/memory-layer/src/main/scala/ix/memory/ingestion/parsers/TreeSitterGoParser.scala
new file mode 100644
index 00000000..39b94b57
--- /dev/null
+++ b/memory-layer/src/main/scala/ix/memory/ingestion/parsers/TreeSitterGoParser.scala
@@ -0,0 +1,523 @@
+package ix.memory.ingestion.parsers
+
+import ix.memory.ingestion.{Fingerprint, Parser, ParseResult, ParsedEntity, ParsedRelationship}
+import ix.memory.model.NodeKind
+import io.circe.Json
+import org.treesitter.{TSNode, TreeSitterGo}
+
+/**
+ * Tree-sitter AST-based Go parser with regex fallback.
+ * Extracts packages, functions, methods, structs, interfaces, type aliases,
+ * const/var declarations, imports, call edges, and struct embedding (EXTENDS).
+ */
+class TreeSitterGoParser extends Parser {
+
+ private val regexFallback = new GoParser()
+
+ def parse(fileName: String, source: String): ParseResult = {
+ try treeSitterParse(fileName, source)
+ catch { case _: Throwable => regexFallback.parse(fileName, source) }
+ }
+
+ private def treeSitterParse(fileName: String, source: String): ParseResult = {
+ TreeSitterUtils.withParse(new TreeSitterGo(), source) { root =>
+ val ctx = new GoExtractionContext(fileName, source, root)
+ ctx.result()
+ }
+ }
+
+ // -------------------------------------------------------------------------
+ // Extraction context
+ // -------------------------------------------------------------------------
+
+ private class GoExtractionContext(
+ fileName: String,
+ source: String,
+ root: TSNode
+ ) {
+ import TreeSitterUtils._
+
+ var entities = Vector.empty[ParsedEntity]
+ var relationships = Vector.empty[ParsedRelationship]
+
+ private val lines = source.split("\n", -1)
+
+ // Initialize with file entity
+ entities = entities :+ ParsedEntity(
+ name = fileName,
+ kind = NodeKind.File,
+ attrs = Map("language" -> Json.fromString("go")),
+ lineStart = 1,
+ lineEnd = lines.length
+ )
+
+ // Walk the program
+ walkProgram(root)
+
+ def result(): ParseResult = ParseResult(entities, relationships)
+
+ private def walkProgram(node: TSNode): Unit = {
+ for (child <- namedChildren(node)) {
+ child.getType() match {
+ case "package_clause" =>
+ handlePackageClause(child)
+
+ case "import_declaration" =>
+ handleImportDeclaration(child)
+
+ case "function_declaration" =>
+ handleFunctionDeclaration(child)
+
+ case "method_declaration" =>
+ handleMethodDeclaration(child)
+
+ case "type_declaration" =>
+ handleTypeDeclaration(child)
+
+ case "const_declaration" =>
+ handleConstDeclaration(child)
+
+ case "var_declaration" =>
+ handleVarDeclaration(child)
+
+ case _ =>
+ // Ignore other top-level nodes (comments, etc.)
+ }
+ }
+ }
+
+ // --- Package handling ---
+
+ private def handlePackageClause(node: TSNode): Unit = {
+ fieldChild(node, "name").orElse(findChild(node, "package_identifier")).foreach { nameNode =>
+ val pkgName = nodeText(nameNode, source)
+ // Set package as attribute on the File entity
+ entities = entities.map { e =>
+ if (e.name == fileName && e.kind == NodeKind.File) {
+ e.copy(attrs = e.attrs + ("package" -> Json.fromString(pkgName)))
+ } else e
+ }
+ }
+ }
+
+ // --- Import handling ---
+
+ private def handleImportDeclaration(node: TSNode): Unit = {
+ // Single import: import "fmt"
+ findChild(node, "import_spec").foreach(handleImportSpec)
+
+ // Grouped import: import ( "fmt"; "os" )
+ findChild(node, "import_spec_list").foreach { specList =>
+ for (spec <- childrenOfType(specList, "import_spec")) {
+ handleImportSpec(spec)
+ }
+ }
+ }
+
+ private def handleImportSpec(spec: TSNode): Unit = {
+ // import_spec has optional name (alias) and path (interpreted_string_literal)
+ val pathOpt = fieldChild(spec, "path")
+ .orElse(findChild(spec, "interpreted_string_literal"))
+ .map(n => nodeText(n, source).stripPrefix("\"").stripSuffix("\""))
+
+ pathOpt.foreach { importPath =>
+ val aliasOpt = fieldChild(spec, "name")
+ .map(n => nodeText(n, source))
+
+ val entityName = aliasOpt match {
+ case Some(".") => importPath // dot import
+ case Some("_") => importPath // side-effect import
+ case Some(alias) => alias // named import
+ case None => importPath // bare import
+ }
+
+ if (!entities.exists(e => e.name == importPath && e.kind == NodeKind.Module)) {
+ entities = entities :+ ParsedEntity(
+ name = importPath,
+ kind = NodeKind.Module,
+ attrs = Map.empty,
+ lineStart = lineStart(spec),
+ lineEnd = lineEnd(spec)
+ )
+ }
+ relationships = relationships :+ ParsedRelationship(fileName, importPath, "IMPORTS")
+ }
+ }
+
+ // --- Function handling ---
+
+ private def handleFunctionDeclaration(node: TSNode): Unit = {
+ val nameOpt = extractName(node, source)
+ nameOpt.foreach { funcName =>
+ val start = lineStart(node)
+ val end = lineEnd(node)
+ val sig = extractFirstLine(node).replaceAll("""\s*\{\s*$""", "").trim.take(120)
+ val bodyText = nodeText(node, source)
+ val fp = Fingerprint.compute(sig, bodyText)
+ val exported = funcName.nonEmpty && funcName.head.isUpper
+
+ entities = entities :+ ParsedEntity(
+ name = funcName,
+ kind = NodeKind.Function,
+ attrs = Map(
+ "language" -> Json.fromString("go"),
+ "summary" -> Json.fromString(sig),
+ "signature" -> Json.fromString(sig),
+ "visibility" -> Json.fromString(if (exported) "exported" else "unexported"),
+ "exported" -> Json.fromBoolean(exported)
+ ),
+ lineStart = start,
+ lineEnd = end,
+ contentFingerprint = Some(fp)
+ )
+ relationships = relationships :+ ParsedRelationship(fileName, funcName, "CONTAINS")
+
+ // Extract calls from function body
+ fieldChild(node, "body").foreach { body =>
+ extractCallsFromBody(body, funcName)
+ }
+ }
+ }
+
+ // --- Method handling ---
+
+ private def handleMethodDeclaration(node: TSNode): Unit = {
+ val nameOpt = extractName(node, source)
+ nameOpt.foreach { methodName =>
+ val start = lineStart(node)
+ val end = lineEnd(node)
+ val sig = extractFirstLine(node).replaceAll("""\s*\{\s*$""", "").trim.take(120)
+ val bodyText = nodeText(node, source)
+ val fp = Fingerprint.compute(sig, bodyText)
+ val exported = methodName.nonEmpty && methodName.head.isUpper
+
+ // Extract receiver type name
+ val receiverType = fieldChild(node, "receiver")
+ .orElse(findChild(node, "parameter_list"))
+ .flatMap(extractReceiverType)
+
+ val attrs = Map(
+ "language" -> Json.fromString("go"),
+ "summary" -> Json.fromString(sig),
+ "signature" -> Json.fromString(sig),
+ "visibility" -> Json.fromString(if (exported) "exported" else "unexported"),
+ "exported" -> Json.fromBoolean(exported)
+ ) ++ receiverType.map(r => "receiver" -> Json.fromString(r))
+
+ entities = entities :+ ParsedEntity(
+ name = methodName,
+ kind = NodeKind.Method,
+ attrs = attrs,
+ lineStart = start,
+ lineEnd = end,
+ contentFingerprint = Some(fp)
+ )
+
+ // Method belongs to receiver type, not file
+ val containsSrc = receiverType.getOrElse(fileName)
+ relationships = relationships :+ ParsedRelationship(containsSrc, methodName, "CONTAINS")
+
+ // Extract calls from method body
+ fieldChild(node, "body").foreach { body =>
+ extractCallsFromBody(body, methodName)
+ }
+ }
+ }
+
+ private def extractReceiverType(paramList: TSNode): Option[String] = {
+ // The receiver parameter list contains a single parameter_declaration
+ // e.g., (r *Receiver) or (r Receiver)
+ val params = namedChildren(paramList)
+ params.headOption.flatMap { param =>
+ // Look for type_identifier or pointer_type → type_identifier
+ val typeNode = fieldChild(param, "type").getOrElse(param)
+ extractTypeName(typeNode)
+ }
+ }
+
+ private def extractTypeName(node: TSNode): Option[String] = {
+ node.getType() match {
+ case "type_identifier" =>
+ Some(nodeText(node, source))
+ case "pointer_type" =>
+ // *Type — recurse to get the type name
+ namedChildren(node).headOption.flatMap(extractTypeName)
+ case "parameter_declaration" =>
+ // Get the type field
+ fieldChild(node, "type").flatMap(extractTypeName)
+ case "generic_type" =>
+ // Type[T] — extract the base type
+ fieldChild(node, "type").flatMap(extractTypeName)
+ case _ =>
+ // Fallback: try to find a type_identifier descendant
+ findChild(node, "type_identifier").map(n => nodeText(n, source))
+ }
+ }
+
+ // --- Type declaration handling ---
+
+ private def handleTypeDeclaration(node: TSNode): Unit = {
+ // Single type: type Foo struct { ... }
+ findChild(node, "type_spec").foreach(handleTypeSpec)
+
+ // Grouped type: type ( Foo struct {}; Bar interface {} )
+ for (child <- namedChildren(node)) {
+ if (child.getType() == "type_spec") {
+ handleTypeSpec(child)
+ }
+ }
+ }
+
+ private def handleTypeSpec(spec: TSNode): Unit = {
+ val nameOpt = extractName(spec, source)
+ nameOpt.foreach { typeName =>
+ val start = lineStart(spec)
+ val end = lineEnd(spec)
+ val exported = typeName.nonEmpty && typeName.head.isUpper
+ val bodyText = nodeText(spec, source)
+
+ // Determine the type kind from the type expression
+ val typeNode = fieldChild(spec, "type")
+ val typeKind = typeNode.map(_.getType()).getOrElse("")
+
+ typeKind match {
+ case "struct_type" =>
+ val sig = extractFirstLine(spec).replaceAll("""\s*\{\s*$""", "").trim.take(120)
+ val fp = Fingerprint.compute(sig, bodyText)
+ entities = entities :+ ParsedEntity(
+ name = typeName,
+ kind = NodeKind.Class,
+ attrs = Map(
+ "language" -> Json.fromString("go"),
+ "go_kind" -> Json.fromString("struct"),
+ "signature" -> Json.fromString(sig),
+ "summary" -> Json.fromString(sig),
+ "visibility" -> Json.fromString(if (exported) "exported" else "unexported"),
+ "exported" -> Json.fromBoolean(exported)
+ ),
+ lineStart = start,
+ lineEnd = end,
+ contentFingerprint = Some(fp)
+ )
+ relationships = relationships :+ ParsedRelationship(fileName, typeName, "CONTAINS")
+
+ // Extract struct embedding (EXTENDS)
+ typeNode.foreach(extractStructEmbedding(_, typeName))
+
+ case "interface_type" =>
+ val sig = extractFirstLine(spec).replaceAll("""\s*\{\s*$""", "").trim.take(120)
+ val fp = Fingerprint.compute(sig, bodyText)
+ entities = entities :+ ParsedEntity(
+ name = typeName,
+ kind = NodeKind.Interface,
+ attrs = Map(
+ "language" -> Json.fromString("go"),
+ "go_kind" -> Json.fromString("interface"),
+ "signature" -> Json.fromString(sig),
+ "summary" -> Json.fromString(sig),
+ "visibility" -> Json.fromString(if (exported) "exported" else "unexported"),
+ "exported" -> Json.fromBoolean(exported)
+ ),
+ lineStart = start,
+ lineEnd = end,
+ contentFingerprint = Some(fp)
+ )
+ relationships = relationships :+ ParsedRelationship(fileName, typeName, "CONTAINS")
+
+ // Extract interface embedding
+ typeNode.foreach(extractInterfaceEmbedding(_, typeName))
+
+ case _ =>
+ // Type alias (type Foo = Bar) or named type (type Foo int)
+ val isAlias = allChildren(spec).exists(c => nodeText(c, source) == "=")
+ val goKind = if (isAlias) "type_alias" else "named_type"
+ val sig = nodeText(spec, source).trim.take(120)
+ val fp = Fingerprint.compute(sig, bodyText)
+
+ entities = entities :+ ParsedEntity(
+ name = typeName,
+ kind = NodeKind.Class,
+ attrs = Map(
+ "language" -> Json.fromString("go"),
+ "go_kind" -> Json.fromString(goKind),
+ "signature" -> Json.fromString(sig),
+ "summary" -> Json.fromString(sig),
+ "visibility" -> Json.fromString(if (exported) "exported" else "unexported"),
+ "exported" -> Json.fromBoolean(exported)
+ ),
+ lineStart = start,
+ lineEnd = end,
+ contentFingerprint = Some(fp)
+ )
+ relationships = relationships :+ ParsedRelationship(fileName, typeName, "CONTAINS")
+ }
+ }
+ }
+
+ private def extractStructEmbedding(structType: TSNode, typeName: String): Unit = {
+ // Walk field_declaration_list for embedded fields (no field name)
+ findChild(structType, "field_declaration_list").foreach { fieldList =>
+ for (field <- childrenOfType(fieldList, "field_declaration")) {
+ // An embedded field has a type but no name field
+ val hasName = fieldChild(field, "name").isDefined
+ if (!hasName) {
+ // The type is the embedded type
+ fieldChild(field, "type").foreach { typeNode =>
+ extractTypeName(typeNode).foreach { embeddedName =>
+ if (embeddedName != typeName && !GoBuiltins.contains(embeddedName)) {
+ relationships = relationships :+ ParsedRelationship(typeName, embeddedName, "EXTENDS")
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ private def extractInterfaceEmbedding(ifaceType: TSNode, typeName: String): Unit = {
+ // Walk interface body for bare type identifiers (embedded interfaces)
+ for (child <- namedChildren(ifaceType)) {
+ child.getType() match {
+ case "type_identifier" =>
+ val embeddedName = nodeText(child, source)
+ if (embeddedName != typeName && !GoBuiltins.contains(embeddedName)) {
+ relationships = relationships :+ ParsedRelationship(typeName, embeddedName, "EXTENDS")
+ }
+ case "qualified_type" =>
+ // pkg.Type embedded
+ fieldChild(child, "name")
+ .orElse(namedChildren(child).lastOption)
+ .foreach { nameNode =>
+ val embeddedName = nodeText(nameNode, source)
+ if (embeddedName != typeName) {
+ relationships = relationships :+ ParsedRelationship(typeName, embeddedName, "EXTENDS")
+ }
+ }
+ case _ => // method specs, etc. — skip
+ }
+ }
+ }
+
+ // --- Const/Var handling ---
+
+ private def handleConstDeclaration(node: TSNode): Unit = {
+ // Single const or grouped const ( ... )
+ val specs = childrenOfType(node, "const_spec")
+ if (specs.isEmpty) {
+ // May have a single const_spec as direct structure
+ handleConstOrVarSpecs(namedChildren(node).filter(_.getType() == "const_spec"), "const")
+ } else {
+ handleConstOrVarSpecs(specs, "const")
+ }
+ }
+
+ private def handleVarDeclaration(node: TSNode): Unit = {
+ val specs = childrenOfType(node, "var_spec")
+ if (specs.isEmpty) {
+ handleConstOrVarSpecs(namedChildren(node).filter(_.getType() == "var_spec"), "var")
+ } else {
+ handleConstOrVarSpecs(specs, "var")
+ }
+ }
+
+ private def handleConstOrVarSpecs(specs: Vector[TSNode], declKind: String): Unit = {
+ for (spec <- specs) {
+ // Each spec may have multiple names: const a, b = 1, 2
+ val names = fieldChild(spec, "name")
+ .map(Vector(_))
+ .getOrElse(childrenOfType(spec, "identifier"))
+
+ for (nameNode <- names) {
+ val varName = nodeText(nameNode, source)
+ if (varName.nonEmpty && varName != "_") {
+ val start = lineStart(spec)
+ val end = lineEnd(spec)
+ val exported = varName.head.isUpper
+ val sig = nodeText(spec, source).trim.take(120)
+ val fp = Fingerprint.compute(sig, sig)
+
+ entities = entities :+ ParsedEntity(
+ name = varName,
+ kind = NodeKind.Variable,
+ attrs = Map(
+ "language" -> Json.fromString("go"),
+ "go_kind" -> Json.fromString(declKind),
+ "signature" -> Json.fromString(sig),
+ "visibility" -> Json.fromString(if (exported) "exported" else "unexported"),
+ "exported" -> Json.fromBoolean(exported)
+ ),
+ lineStart = start,
+ lineEnd = end,
+ contentFingerprint = Some(fp)
+ )
+ relationships = relationships :+ ParsedRelationship(fileName, varName, "CONTAINS")
+ }
+ }
+ }
+ }
+
+ // --- CALLS extraction ---
+
+ private def extractCallsFromBody(bodyNode: TSNode, callerName: String): Unit = {
+ val seen = scala.collection.mutable.Set.empty[String]
+ val callExprs = collectDescendants(bodyNode, _.getType() == "call_expression")
+
+ for (callExpr <- callExprs) {
+ fieldChild(callExpr, "function").foreach { funcNode =>
+ val callee = resolveCalleeName(funcNode)
+ callee.foreach { name =>
+ if (name != callerName && !GoBuiltins.contains(name) &&
+ !GoKeywords.contains(name) && !seen.contains(name) && name != fileName) {
+ seen += name
+ relationships = relationships :+ ParsedRelationship(callerName, name, "CALLS")
+ }
+ }
+ }
+ }
+ }
+
+ private def resolveCalleeName(funcNode: TSNode): Option[String] = {
+ funcNode.getType() match {
+ case "identifier" =>
+ Some(nodeText(funcNode, source))
+ case "selector_expression" =>
+ // e.g., pkg.Func() or obj.Method() — extract the field (rightmost)
+ fieldChild(funcNode, "field").map(n => nodeText(n, source))
+ case "call_expression" =>
+ // Chained calls — recurse
+ fieldChild(funcNode, "function").flatMap(resolveCalleeName)
+ case "parenthesized_expression" =>
+ // (func)() — recurse into the inner expression
+ namedChildren(funcNode).headOption.flatMap(resolveCalleeName)
+ case _ =>
+ None
+ }
+ }
+
+ // --- Helpers ---
+
+ private def extractFirstLine(node: TSNode): String = {
+ val text = nodeText(node, source)
+ text.split("\n").head
+ }
+ }
+
+ // --- Shared constants ---
+
+ private val GoKeywords: Set[String] = Set(
+ "break", "case", "chan", "const", "continue", "default", "defer",
+ "else", "fallthrough", "for", "func", "go", "goto", "if",
+ "import", "interface", "map", "package", "range", "return",
+ "select", "struct", "switch", "type", "var"
+ )
+
+ private val GoBuiltins: Set[String] = Set(
+ "make", "len", "cap", "append", "copy", "close", "delete",
+ "complex", "real", "imag", "new", "panic", "recover",
+ "print", "println", "error", "string", "int", "float64",
+ "bool", "byte", "rune", "nil", "true", "false", "iota",
+ "int8", "int16", "int32", "int64",
+ "uint", "uint8", "uint16", "uint32", "uint64", "uintptr",
+ "float32", "complex64", "complex128", "any", "comparable"
+ )
+}