I'm working on something like a compiler that tran...
# announcements
t
I'm working on something like a compiler that transforms the ASTs of two different languages into a shared IR/AST. I have defined this IR as a deep hierarchy of sealed classes where the leaves are abstract. My plan was to make implementations of those abstract leaf classes for each of the two langauges (i.e. the
ClassElement
is implemented as
AClassElement
if it was converted from source langauge A or
BClassElement
if it was converted from source language B and the conversion happens mostly in the constructors). They are essentially data classes but many properties have to be computed lazily. My problem is how to reuse the construction code for related AST elements. For example,
ClassElement
and
InterfaceElement
both extend
ClassLikeElement
and share a lot of properties. Usually I could put the shared logic into
ClassLikeElement
and inherit it, but here it doesn't work because the implementations for
ClassLikeElement
need to be different for source languages
A
and
B
. My options are: 1. Put the shared logic into delegate objects and make two implementations of every AST element for the source languages
A
and
B
2. Make the AST classes pure data classes and do all the conversion in a factory. 3. Mix both options? Which approach is preferable?