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

Generated properties for non-nullable children should not be declared nullable

Open hakanai opened this issue 1 year ago • 6 comments

For a rule like this:

number: nested=(INTEGER | FLOAT | PI | INFINITY);

There is no way with that grammar that the nested token could be null, but the property you get after compiling the grammar is:

public final var nested: Token?

So now I have to put !! all over my code to assert something the grammar is already supposed to be doing for me.

The more insidious side of this issue is, I can't just put !! on all of them, because some of them really are nullable. And the nullability may change from time to time as the grammar evolves. So it would be nice if the generated code matched the actual grammar.

hakanai avatar Oct 18 '22 13:10 hakanai

Did you ever find a way to get this one solved?

lppedd avatar Dec 04 '23 11:12 lppedd

The real answer is this is not possible, as the engine that looks for template parts does not differentiate between nullable or non-nullable tokens.

You should open an issue upstream on the ANTLR4 repository, as other languages like Swift are affected.
@ftomassetti imo even this one can be closed as we can't do anything.

lppedd avatar Dec 06 '23 14:12 lppedd

To expand and add more context.
If we have a parser rule such as:

myRule
  : TagOpen tagName=Body? ... # Body

The Swift target will generate:

public class BodyContext: MyRuleContext {
    public var tagName: Token!

Note the !. I suppose that trying to access it without checking for nil will throw.
And the same concept doesn't exist in Kotlin, I'd have to use non-null delegates, but still, not entirely correct.

lppedd avatar Dec 06 '23 15:12 lppedd

Agreed, let's close this one

ftomassetti avatar Dec 06 '23 15:12 ftomassetti

@ftomassetti can we reopen? Working in this.

lppedd avatar Jan 09 '24 11:01 lppedd

Sure, reopening

ftomassetti avatar Jan 09 '24 12:01 ftomassetti