简体   繁体   中英

How to setup ANTLR grammar for a C constant structure?

I'm trying to use ANTLR4 in a C# console application to parse out a version number out of an auto-generated C file (compiled with IAR). For some reason it doesn't seem to like my constant declaration.

The ANTLR error I'm getting is '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,
};

This is the C# code I am working with to try and parse this. I'm pretty sure StructDeclaration is wrong but I'm still not getting any tokens after initializing the 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();
}

This is the g4 file that I am using. https://github.com/antlr/grammars-v4/blob/master/c/C.g4

What rule(s) do I need to add to be able to support this?

 CParser.StructDeclarationContext decl = cParser.structDeclaration(); 

The structDeclaration rule would be able to parse the struct ... VERSION; part, but it can't handle the typedef keyword before it nor the variable definition that comes after it because those aren't part of struct declaration.

When parsing an entire file, compilationUnit is the rule you want to invoke (in fact, it's really the only one that's meant to be invoked from the outside - that's why it ends with EOF ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM