Separating data structures from algorithms in Go

45 Views Asked by At

I'm currently building a compiler for a toy language in Go, to learn about Go and compilers in general. I have an AST that has heterogenous nodes (AssignStatement, BinaryExpression, IfStatement...) like,

type IfStatement struct {
    Meta           meta.Meta
    Condition      Expression
    IfBlock        []Statement 
    ElseBlock      []Statement 
}

To work with this data structure I was have been maintaining an interface which is implemented by all the nodes of the AST. For example,

type Statement interface {
    TypeCheck(state *TypeCheckState)
}

All statement nodes will implement their specific TypeCheck methods using metadata from state and calling the TypeCheck method on their children nodes. It has worked well enough but as I keep progressing in building my compiler this interface has become bloated and I don't feel like many of the methods belong there. Like I probably will have to add a TranslateToLLVMInstruction method on this interface when I get to backend. I want to decouple the AST data structure from these methods. I have looked at the Visitor pattern but it doesn't seem to fit very well in this recursive scenario where each visiting action might need different parameters and return values. With my current approach I can define whatever method signature I want for each action.

How are these situations usually handled in Go?

0

There are 0 best solutions below