c - 如何为 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
我需要添加哪些规则才能支持这一点?
解决方案
CParser.StructDeclarationContext decl = cParser.structDeclaration();
该structDeclaration
规则将能够解析该struct ... VERSION;
部分,但它不能处理它typedef
之前的关键字,也不能处理它之后的变量定义,因为它们不是结构声明的一部分。
解析整个文件时,compilationUnit
是您要调用的规则(事实上,它确实是唯一一个应该从外部调用的规则 - 这就是它以 结尾的原因EOF
)。
推荐阅读
- r - 替换值多列
- browser - 如果您使用 iframe,浏览器的自动播放策略是基于父站点还是嵌入站点?
- elasticsearch - fluentbit conf 帮助在 k8s 日志中进行堆栈跟踪
- gcc - 如何在 Windows 上使用 gcc -I?
- azure-devops - 我想跟踪我们在 Azure 板上调查工作项目所花费的时间
- html - 角度设置默认数值
- flutter - 在 Flutter 中将颜色从默认更改为自定义以实现暗模式?
- javascript - 如何在没有事件数据的情况下从 JavaScript 使用 dispatchEvent 函数到 Angular 12 应用程序
- kubernetes-helm - OCI 不推荐使用 Helm Chart 导出命令
- node.js - 如何使用 Node JS 提高 MongoDB 的性能?