I am writing a toy compiler. During the semantic passes, I want to add information to the AST. Which of the following is the best approach?Define 1 mutable AST type whose fields are updated with each pass Define multiple immutable ASTs, each of which are an input and output of a semantic passA mix of both?
Mutable AST vs. different immutable ASTs
data structures;compiler
It depends on what information you want to add, if your AST is self contained well, how many passes you'll make where you modify the AST, and a handful of other conditions which may or may not matter for you.In general, I would try to avoid modifying the AST. That can easily get you into the situation where your code needs to start caring what state the AST is in (is the added info missing, or just not added yet?). That sort of temporal coupling is troublesome in any software, along with the usual issues that accompany mutable state.