Strange artifacts with C++ target

22 views
Skip to first unread message

Martin Drasar

unread,
Jul 10, 2019, 10:18:09 AM7/10/19
to antlr-discussion
Hi,

I am particullary new to Antlr and I tried to generate C++ target, but the code does not compile, because there are some strange Java(?) artifacts, such as:

TESLALexer.h > StringBuilder buf = new StringBuilder(); // can't make locals in lexer rules
TESLALexer.cpp > case 6: setText(buf.toString()); buf.setLength(0); System.out.println(getText()); break;
TESLAParser.h > StringBuilder buf = new StringBuilder(); // can't make locals in lexer rules

Anybody have an idea, how they got inside?

I am attaching the grammar for anyone willing to test it.

Thank you,
Martin
TESLA.g4

Mike Lischke

unread,
Jul 10, 2019, 10:48:49 AM7/10/19
to antlr-discussion
Martin,
Have you actually looked at the grammar? I believe you didn't, otherwise you had seen that it contains Java action code, exactly what your C++ compiler complains about.

In order to use this grammar with the C++ target, you have to remove that action code (or convert it to C++). However, the only thing this code does is to convert escape codes and this is the perfect example why grammar writers should *not* deal with such conversions in their grammars (not your fault here, I know). It adds a language dependency to do something which is much better placed in the target code, e.g. when the text is retrieved for consumption by other parts of the application.

Alternatively, you can add a semantic phase after the parse run to process your parse result and convert such escape codes. That's also the place where you can do validity checks for the escape codes and show a proper error message if an invalid code was used.


Martin Drasar

unread,
Jul 10, 2019, 10:54:57 AM7/10/19
to antlr-discussion
Ooof... thanks Mike, I've read the grammar some time ago, when it was used with the Java target and I thought "hey, Java code, probably some internal Antlr stuff". And I did not connect the dots this time.

Thanks for your suggestions, I will see what I can do about it.

Martin
Reply all
Reply to author
Forward
0 new messages