You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ANTLR4解析C头文件:区分函数指针与返回指针的函数

ANTLR4解析C头文件时无法区分返回指针的函数与返回函数指针的函数

我正在用ANTLR4解析C头文件(.h),目标是提取函数签名(函数名、返回类型、参数)和函数指针,后续还计划扩展支持结构体、枚举、typedef等,用来检查头文件之间的兼容性。

目前遇到几个问题:

  • int *fp(int,int);(返回数据指针的函数)和int *(*function2())(int, int);(返回函数指针的函数)被代码误判为同一类型,无法分别存入不同的字典。
  • 标注“Function returning a pointer (to data or array)”的else分支从未执行,导致指针相关声明被误判为普通函数。
  • int (*function4())[5];这类返回数组指针的函数声明完全未被识别,但void function5(int arr[5]);能被正确处理。
  • 当前把所有函数指针都存入function_pointer字典,仅通过字符串比对检查兼容性,方式过于简陋,需要修正分类逻辑提升准确性。

当前使用的代码如下:

from CListener import CListener
from CParser import CParser
class FileStructure(CListener) :
    def __init__(self) :
        self.function_signatures= {}
        self.function_pointer = {}

    def print_definitions(self) :
        print("Function Signatures :",self.function_signatures)
        print("Function Pointers :",self.function_pointer)
    def extractIdentifier(self, directDeclarator):
        """
        This function extracts the identifier name from a directDeclarator context.
        If the directDeclarator context contains an Identifier, it returns its text.
        If the context is wrapped in parentheses, it recursively looks for the Identifier.
        """
        # Base case: If the directDeclarator contains an Identifier, return its text
        if directDeclarator.directDeclarator():
            return directDeclarator.directDeclarator().getText()
        
        # Recursive case: If the directDeclarator is wrapped in parentheses, recurse into it
        nestedDeclarator = directDeclarator.declarator()
        if nestedDeclarator and nestedDeclarator.directDeclarator():
            return self.extractIdentifier(nestedDeclarator.directDeclarator())
        
        # If no identifier is found, return an empty string
        return ""

    def getParameters(self, parameterTypeListCtx):
        """
        This function extracts parameters and their types from a parameterTypeList context.
        It iterates over each parameterDeclaration context within the parameterTypeList.
        Each parameter's type specifier and name are extracted and added to a list.
        """
        parameters = []
        parameterListCtx = parameterTypeListCtx.parameterList()
        if parameterListCtx:
            for parameterDeclarationCtx in parameterListCtx.parameterDeclaration():
                # Extract the type specifier(s) for the parameter
                type_specifiers = [
                    token.getText() for token in parameterDeclarationCtx.declarationSpecifiers().children
                    if not isinstance(token, CParser.TypeQualifierContext)
                ]
                param_type = ' '.join(type_specifiers)

                # Extract the parameter name, if it exists
                param_name = ''
                if parameterDeclarationCtx.declarator():
                    param_name = parameterDeclarationCtx.declarator().directDeclarator().getText()

                parameters.append((param_type, param_name))
        return parameters 
    def enterDeclaration(self, ctx: CParser.DeclarationContext):
        if ctx.initDeclaratorList():
            for initDeclaration in ctx.initDeclaratorList().initDeclarator():
                declarator = initDeclaration.declarator()
                directDeclarator = declarator.directDeclarator()

                # Handle functions returning a pointer (to data, function, or array)
                if declarator.pointer():
                    # Function returning a pointer to a function
                    if directDeclarator and directDeclarator.parameterTypeList():
                        function_name = self.extractIdentifier(directDeclarator)
                        print("function" , function_name)
                        self.function_pointer[function_name] = True
                    else:
                        # Function returning a pointer (to data or array)
                        print("else statement")
                        if directDeclarator and hasattr(directDeclarator, 'directDeclarator'):
                            # Check for an array type after the pointer
                            if any(hasattr(child, 'typeQualifierList') or hasattr(child, 'assignmentExpression') for child in directDeclarator.children):
                                # Function returning a pointer to an array
                                function_name = self.extractIdentifier(directDeclarator)
                                self.function_pointer[function_name] = True
                            else:
                                # Function returning a pointer to data (not a function or array)
                                function_name = self.extractIdentifier(directDeclarator)
                                print(function_name)
                                self.function_pointer[function_name] = True
                else:
                    # Handle normal function definitions
                    if directDeclarator and directDeclarator.parameterTypeList():
                        function_name = directDeclarator.directDeclarator().getText()
                        print(function_name)
                        return_type = ctx.declarationSpecifiers().getText()
                        parameter_list = self.getParameters(directDeclarator.parameterTypeList())
                        self.function_signatures[function_name] = (return_type, parameter_list)

内容的提问来源于stack exchange,提问作者Aditya Kalhan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 00:47:03