antlr-kotlin icon indicating copy to clipboard operation
antlr-kotlin copied to clipboard

Issue when accessing $variable.property inside grammar actions

Open dooxe opened this issue 4 years ago • 3 comments

Hello,

As a workaround to the val/varissue, I created a simple class that is used instead primitive types in the grammar actions :

open class AssignableExpression<T:Any?> {
    var value : T? = null
}

then in the grammar I can use it to assign a "return value" from the action:

accessExpression
    returns [AssignableExpression<Any?> value = AssignableExpression<Any?>()]
    : v=variable {
            $value.value = $v.value
      }
    ;

The problem is that $v.value here causes the following error to occur during the java compilation:

e: ExpressionsParser.kt: (215, 80): Only safe (?.) or non-null asserted (!!.) calls are allowed on a nullable receiver of type ExpressionsParser.VariableContext?

To solve that I tried to add a safe call myself inside the grammar action:

accessExpression
    returns [AssignableExpression<Any?> value = AssignableExpression<Any?>()]
    : v=variable {
            $value.value = $v?.value
      }
    ;

But it generate the following error during the grammar compilation:

error(67): ExpressionsParser.g4:32:28: missing attribute access on rule reference v in $v

Does someone have an idea to solve this, or a workaround I can use to make my grammar / java compile well ?

dooxe avatar Aug 04 '21 11:08 dooxe

Is this superseded my your PR (now accepted)?

ftomassetti avatar Aug 04 '21 15:08 ftomassetti

Hi @ftomassetti , No, actually it's another problem: grammar actions expect the usage of context variables (therefore starting with $), to be directly followed by .something. So when one tries to use a safe call in a grammar action, e.g., $var?.value, the action parser doesn't understand and throw an error. At least that's what I understand from my yesterday investigations and digging into the code.

dooxe avatar Aug 05 '21 06:08 dooxe

I finally found a workaround to this problem, not much pretty, but it's working: this doesn't work

$value.value = $v?.value // action parser expect $value.value = $v.value

but this works:

$value.value = $ctx.v?.value

Even if it makes the code a bit less readable I'm quite fine with that.

dooxe avatar Aug 05 '21 07:08 dooxe

Do you have a small sample grammar I can use to reproduce?

lppedd avatar Dec 20 '23 10:12 lppedd

I've solved this issue, will open a PR soon.

lppedd avatar Jan 18 '24 22:01 lppedd