antlr-kotlin
antlr-kotlin copied to clipboard
Issue when accessing $variable.property inside grammar actions
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 ?
Is this superseded my your PR (now accepted)?
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.
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.
Do you have a small sample grammar I can use to reproduce?
I've solved this issue, will open a PR soon.