From e1cda08149f490b0a668add153d379259531896d Mon Sep 17 00:00:00 2001 From: Phodal Huang Date: Sat, 3 Feb 2024 10:04:57 +0800 Subject: [PATCH] feat(c): add support for parsing #include directives This commit adds support for parsing #include directives in C code. The `CAnalyser` class now uses a regular expression to extract the included file paths and stores them in the `includesDirective` property. This allows for better analysis of code dependencies. Additionally, a test case in `CFullIdentListenerTest` has been updated to reflect the new behavior. --- chapi-ast-c/src/main/kotlin/chapi/ast/cast/CAnalyser.kt | 6 ++++++ .../test/kotlin/chapi/ast/cast/CFullIdentListenerTest.kt | 6 +++--- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/chapi-ast-c/src/main/kotlin/chapi/ast/cast/CAnalyser.kt b/chapi-ast-c/src/main/kotlin/chapi/ast/cast/CAnalyser.kt index 4ba42926..d366194d 100644 --- a/chapi-ast-c/src/main/kotlin/chapi/ast/cast/CAnalyser.kt +++ b/chapi-ast-c/src/main/kotlin/chapi/ast/cast/CAnalyser.kt @@ -30,7 +30,13 @@ open class CAnalyser : Analyser { pp.addInput(LexerSource(InputStreamReader(code.byteInputStream()), true)) } + private val importRegex = Regex("""#include\s+(<[^>]+>|\"[^\"]+\")""") + override fun analysis(code: String, filePath: String): CodeContainer { + includesDirective = importRegex.findAll(code).map { + it.groupValues[1] + }.toMutableList() + val output = preProcessing(code) val context = this.parse(output).compilationUnit() diff --git a/chapi-ast-c/src/test/kotlin/chapi/ast/cast/CFullIdentListenerTest.kt b/chapi-ast-c/src/test/kotlin/chapi/ast/cast/CFullIdentListenerTest.kt index 2c4b176e..b28b0063 100644 --- a/chapi-ast-c/src/test/kotlin/chapi/ast/cast/CFullIdentListenerTest.kt +++ b/chapi-ast-c/src/test/kotlin/chapi/ast/cast/CFullIdentListenerTest.kt @@ -61,8 +61,8 @@ static RedisModuleType *MemAllocType; """ val codeFile = CAnalyser().analysis(code, "helloworld.c") - assertEquals(codeFile.Imports.size, 0) -// assertEquals(codeFile.Imports[0].Source, "stdio.h") + assertEquals(codeFile.Imports.size, 1) + assertEquals(codeFile.Imports[0].Source, "stdio.h") } @Test @@ -300,7 +300,7 @@ typedef struct { """.trimIndent() val codeFile = CAnalyser().analysis(code, "helloworld.c") - assertEquals(codeFile.Imports.size, 0) + assertEquals(codeFile.Imports.size, 6) } @Test