0
votes

I need an idea how to express a statement like the following:

Int<Double<Float>>

So, in an abstract form we should have:

1.(easiest case):  a<b>
2. case: a<a<b>> 
3. case: a<a<a<b>>>
4. ....and so on...

The thing is that I should enable the possibility to embed a statement of the form a < b > within the < .. > - signs such that I have a nested statement. In other words: I should replace the b with a< b >. The 2nd thing is that the number of the opening and closed <>-signs should be equal.

How can I do that in ANTLR ?

1
I forgot to write that I use the newest version, Antlr4user3097712

1 Answers

2
votes

A rule can refer to itself without any problem¹. Let's say we have a rule type which describes your case, in a minimalist approach:

type: typeLiteral ('<' type '>')?;
typeLiteral: 'Int' | 'Double' | 'Float';

Note the ('<' type '>') is optional, denoted by the ? symbol, so using only a typeLiteral is a valid type. Here are the synta trees generated by these rules in your example Int<Double<Float>>:

Syntax tree for Int<Double<Float>>

¹: As long some terminals (like '<' or '>') can diferentiate when the recursion stop.

Image generated by http://ironcreek.net/phpsyntaxtree/