Strumenta / antlr-kotlin

Support for Kotlin as a target for ANTLR 4
Apache License 2.0
221 stars 47 forks source link

sealed classes instead of multiple nullable values?! #178

Open andretietz opened 4 months ago

andretietz commented 4 months ago

Hey during using this awesome library, I noticed a thing that bugs me a bit.

a parser rule that has multiple options

document: rule EOF;
rule
  : OPTIONA
  | OPTIONB;

generates into:

val rule = document.rule()
rule.getOptiona() // nullable
rule.getOptionb() // nullable

I would very much prefer if that generates into:

sealed class Rule {
   data class Optiona(...) : Rule
   data class Optionb(...) : Rule
}

Would that be possible?

Can you hint me to the generation part where this part happening, may be I take a look myself?

ftomassetti commented 4 months ago

Hey during using this awesome library, I noticed a thing that bugs me a bit.

We just wanted to be sure it was not too awesome, so introduced a few problems on purpose :D

a parser rule that has multiple options

document: rule EOF;
rule
  : OPTIONA
  | OPTIONB;

generates into:

val rule = document.rule()
rule.getOptiona() // nullable
rule.getOptionb() // nullable

I would very much prefer if that generates into:

sealed class Rule {
   data class Optiona(...) : Rule
   data class Optionb(...) : Rule
}

Would that be possible?

I think this has been implemented in this way to reflect what was present in the Java runtime. Now, your approach is exactly what we do when mapping an ANTLR parse-tree to a Kolasu AST. We have an internal tool where we add annotations (in comments) in ANTLR grammars and when we use the annotation @oneOf we generate sealed classes and subclasses.

Personally I think that generating a more "kotlin-esque" AST would be nice, and perhaps we could control the generation through a flag: by default we could generate an AST in a more "standard" or "like-the-java-runtime" way (so that migration to the Kotlin target is very easy) and optionally, when a tag is specified, produce a different AST.

Can you hint me to the generation part where this part happening, may be I take a look myself?

Generation of code for all ANTLR targets is based on templates. Here there is the one for ANTLR Kotlin: https://github.com/Strumenta/antlr-kotlin/blob/master/antlr-kotlin-target/src/main/resources/org/antlr/v4/tool/templates/codegen/Kotlin/Kotlin.stg