Anthony Brien
Anthony Brien

Reputation: 6166

Is there a way to use one ANTLR grammar that targets multiple languages?

I am developing a language service in Visual Studio using an ANTLR grammar for a custom language. However, the grammar is filled with C++ code to handle preprocessor directives and for efficiency reasons for the compiler.

Language services for Visual Studio are a pain to write in C++, so I need a C# parser for the same language. That means I have to set language=CSharp2 and strip all the C++ code from the grammar.

I am thinking of writing a little exporter that strips away all the C++ code from the grammar, and converts simple statements like { $channel = HIDDEN; } to { $channel = TokenChannels.Hidden; }.

Is there a more clever method to do this? Like through templates, or little tricks to embed both languages in the grammar?

Upvotes: 4

Views: 1036

Answers (1)

kierans
kierans

Reputation: 2213

I'd break the problem up into two phases using an AST. Have your parser in a target language neutral grammar (that produces an AST) and use the -target option to the Antlr Tool to generate the parser in the target language of your choice (C++, C#, Java, etc).

Then implement AST walkers in the target language with your actions. The benefit of this is that once you get one AST walker finished you can copy it and just change the actions for another target language.

Upvotes: 1

Related Questions