Skip to content
Advertisement

ANTLR4 Return values from a function

Im making a programming language as a project at my University and I’ve run into a problem with adding a return statement in functions.

This is my grammar:

JavaScript

And here is the custom visitor

JavaScript

To help with transferring data I have made classes to carry values and function data.

JavaScript
JavaScript

The problem I have atm is when I make a function call I want to get a value in return if the function has a return statement. Here is a code example with functions, the function call testFunc has the return statement.

JavaScript

Advertisement

Answer

The first issue I see is that there is no visitReturnStatement in your Visitor class.

This method would need to be responsible for pulling the return value from the result of visiting its expr() child and getting it’s value.

The more interesting issue is that you might be anywhere within the functionDeclaration‘s statementBlock child sub-tree when the return is encountered. However, whenever it’s encountered, it needs to “return” immediately from the function, without bothering with any more of the logic in the statementBlock.

Off hand, a fairly simple solution it to use exception handling for this (even though it’s not really an exception, you need the “jump out of here up to the first place that’s ready to handle me” behavior that exceptions do well).

If you set up something like a FunctionReturnResultException that has a Value member in it’s definition, you could wrap your code to evaluate the statements in the statement block in visitFunctionCall:

JavaScript

in a try catch something like

JavaScript

Your visitReturnStatement method would contain something akin to:

JavaScript

——-

BTW, saw this in your code:

JavaScript

You might want to double-check docs on HashMap.put(). I suspect this is not doing what you intend.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement