如何为 C 常量结构设置 ANTLR 语法?

How to setup ANTLR grammar for a C constant structure?

我正在尝试在 C# 控制台应用程序中使用 ANTLR4 从自动生成的 C 文件(使用 IAR 编译)中解析出版本号。出于某种原因,它似乎不喜欢我不断的声明。

我得到的 ANTLR 错误是 'mismatched input '=' expecting {'(', '*', '^', ':', ';', Identifier}

//Declared in another file...
typedef struct
{
    uint16_t major;
    uint16_t minor;
    uint16_t build;
    uint16_t revision;
} 
VERSION;

//In the C file I'm trying to parse
const VERSION version =
{
    .major = 1,
    .minor = 2,
    .build = 3000,
    .revision = 40000,
};

这是我正在使用的 C# 代码,用于尝试解析它。我很确定 StructDeclaration 是错误的,但在初始化 Lexer 后我仍然没有得到任何标记。

using (FileStream stream = new FileStream(path, FileMode.Open))
{
     AntlrInputStream inputStream = new AntlrInputStream(stream);
     CLexer cLexer = new CLexer(inputStream);
     CommonTokenStream commonTokenStream = new CommonTokenStream(cLexer);
     CParser cParser = new CParser(commonTokenStream);

     CParser.StructDeclarationContext decl = cParser.structDeclaration();
}

这是我正在使用的g4文件。 https://github.com/antlr/grammars-v4/blob/master/c/C.g4

我需要添加什么规则才能支持此功能?

CParser.StructDeclarationContext decl = cParser.structDeclaration();

structDeclaration 规则可以解析 struct ... VERSION; 部分,但它不能处理它前面的 typedef 关键字,也不能处理它后面的变量定义,因为那些不是结构声明的一部分。

解析整个文件时,compilationUnit 是您要调用的规则(事实上,它实际上是唯一一个要从外部调用的规则 - 这就是它以 [=15= 结尾的原因) ]).