Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what does getType do in antlr4?

Tags:

antlr4

This question is with reference to the Cymbol code from the book (~ page 143) :

int t = ctx.type().start.getType(); // in DefPhase.enterFunctionDecl()
Symbol.Type type = CheckSymbols.getType(t);

What does each component return: "ctx.type()", "start", "getType()" ? The book does not contain any explanation about these names.

I can "kind of" understand that "ctx.type()" refers to the "type" rule, and "getType()" returns the number associated with it. But what exactly does the "start" do?

Also, to generalize this question: what is the mechanism to get the value/structure returned by a rule - especially in the context of usage in a listener?

I can see that for an ID, it is:

String name = ctx.ID().getText();

And as in above, for an enumeration of keywords it is via "start.getType()". Any other special kinds of access that I should be aware of?

like image 948
R71 Avatar asked Nov 10 '22 13:11

R71


1 Answers

Lets disassemble problem step by step. Obviously, ctx is instance of CymbolParser.FunctionDeclContext. On page 98-99 you can see how grammar and ParseTree are implemented (at least the feeling - for real implementation please see th .g4 file).

Take a look at the figure of AST on page 99 - you can see that node FunctionDeclContext has a several children, one labeled type. Intuitively you see that it somehow correspond with function return-type. This is the node you retrieve when calling CymbolParser.FunctionDeclContext::type. The return type is probably sth like TypeContext.

Note that methods without 'get' at the beginning are usually children-getters - e.g. you can access the block by calling CymbolParser.FunctionDeclContext::block.

So you got the type context of the method you got passed. You can call either begin or end on any context to get first of last Token defining the context. Simply start gets you "the first word". In this case, the first Token is of course the function return-type itsef, e.g. int.

And the last call - Token::getType returns integral representation of Token.

You can find more information at API reference webpages - Context, Token. But the best way of understanding the behavior is reading through the generated ANTLR classes such as <GrammarName>Parser etc. And to be complete, I attach a link to the book.

like image 158
petrbel Avatar answered Dec 19 '22 18:12

petrbel