Skip to content

Commit 42aaa64

Browse files
committed
feat(parser): add import extraction for multiple languages
Implement parseImports to extract import statements for Java, Kotlin, JavaScript, TypeScript, Python, and Go using language-specific queries.
1 parent 691e161 commit 42aaa64

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed

mpp-codegraph/src/wasmJsMain/kotlin/cc/unitmesh/codegraph/parser/wasm/WasmJsCodeParser.kt

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -563,6 +563,67 @@ class WasmJsCodeParser : CodeParser {
563563
}
564564
}
565565

566+
override suspend fun parseImports(
567+
sourceCode: String,
568+
filePath: String,
569+
language: Language
570+
): List<ImportInfo> {
571+
initialize()
572+
573+
val parser = getOrCreateParser(language)
574+
val tree = parser.parse(sourceCode)
575+
val lang = languages[language] ?: return emptyList()
576+
577+
val queryString = when (language) {
578+
Language.JAVA, Language.KOTLIN -> """
579+
(import_declaration (identifier) @import.path)
580+
(import_list (import_header (identifier) @import.path))
581+
""".trimIndent()
582+
583+
Language.JAVASCRIPT, Language.TYPESCRIPT -> """
584+
(import_statement source: (string) @import.path)
585+
""".trimIndent()
586+
587+
Language.PYTHON -> """
588+
(import_statement name: (dotted_name) @import.path)
589+
(import_from_statement module_name: (dotted_name) @import.path)
590+
""".trimIndent()
591+
592+
Language.GO -> """
593+
(import_declaration (import_spec path: (interpreted_string_literal) @import.path))
594+
""".trimIndent()
595+
596+
else -> return emptyList()
597+
}
598+
599+
return try {
600+
val query = lang.query(queryString)
601+
val captures = query.captures(tree.rootNode).toArray()
602+
val imports = captures
603+
.filter { it.name == "import.path" }
604+
.map { capture ->
605+
val importPath = capture.node.text.trim('"', '\'')
606+
ImportInfo(
607+
path = importPath,
608+
type = ImportType.MODULE,
609+
filePath = filePath,
610+
startLine = capture.node.startPosition.row + 1,
611+
endLine = capture.node.endPosition.row + 1,
612+
isStatic = false,
613+
alias = null,
614+
importedNames = emptyList(),
615+
rawText = capture.node.text
616+
)
617+
}
618+
.distinct()
619+
query.delete()
620+
imports
621+
} catch (e: Throwable) {
622+
console.warn("Failed to extract imports: ${e.message}")
623+
emptyList()
624+
}
625+
}
626+
566627
/**
567628
* Check if code contains syntax errors
568629
*/

0 commit comments

Comments
 (0)