首页 > 解决方案 > 如何为 C 常量结构设置 ANTLR 语法?

问题描述

我正在尝试在 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

我需要添加哪些规则才能支持这一点?

标签: cantlr

解决方案


CParser.StructDeclarationContext decl = cParser.structDeclaration();

structDeclaration规则将能够解析该struct ... VERSION;部分,但它不能处理它typedef之前的关键字,也不能处理它之后的变量定义,因为它们不是结构声明的一部分。

解析整个文件时,compilationUnit是您要调用的规则(事实上,它确实是唯一一个应该从外部调用的规则 - 这就是它以 结尾的原因EOF)。


推荐阅读