markt1964
markt1964

Reputation: 2836

Can antlr rule contexts be target independent

I would like to know if there is any way to make the following antlr grammar fragment target independent:

ifstatement locals [long condition = 0, long branch = 0, long end = 0]: ifpart[_localctx] thenpart[_localctx] (elifpart[_localctx] thenpart[_localctx])* (elsepart[_localctx])? 'fi';

ifpart [IfstatementContext base] : 'if' boolexpr ;

thenpart [IfstatementContext base] : 'then' statements ;

elifpart [IfstatementContext base] : 'elif' boolexpr ;

elsepart [IfstatementContext base] : 'else' statements ;

This seems to work fine in Java, but the code produced by antlr fails to compile when using the Cpp target. I do not have any actions or predicates in the grammar.

My intended target is C++, but I intended to have the actions for each rule implemented by a listener rather than putting them in the grammar directly so that the grammar could still be analyzed and used by the java-based development tools that come with antlr, and I do not want to have to maintain two separate grammar files. On the Cpp target for the above grammar fragment, the parameter types for each of the other rules need to each be changed to IfstatementContext * which is not valid syntax for Java.

In terms of intent and design, in case it is relevant to understand what I am trying to do, is for the listener for the parser to have pre and post methods for the various components of the if statement, updating the local fields in the ifstatement context as they go so that correct code is outputted to handle flow control correctly in one pass. I would be using the long values as references to points in the code that need to be patched later with updated address information as each of the various if statement fragments complete. Please note, I am not asking how to write the Listener code.

I would, however, very much like to know how to have these references to contexts in an antlr grammar in a target-independent way, if it is at all possible.

If any further details are required, please indicate so in the comments section and I shall try to address any and all specific questions.

Upvotes: 0

Views: 125

Answers (1)

Mike Lischke
Mike Lischke

Reputation: 53407

Action and predicate code is always written in the target language. There's no way around it. If you need platform agnostic behavior then don't use actions or predicates.

That being said, there is a way that you could go, by using only expressions that are supported in all possible target languages. For example simple variable names, if-then-else constructs with curly braces, function calls and things like that are pretty much the same in languages like C++, Java and C#. Python/PHP/Swift are significantly different and Javascript/Typescript often needs the this prefix (but are otherwise compatible).

Upvotes: 1

Related Questions