I'm designing a Tokenizer / Parser / AST. I'm wondering if this basic idea of an expression is good and if this way of implementing Simplification is good, or should I use something like the Visitor pattern? Is implementing it in the class itself a good idea?
public abstract class Expr
{
public Expr Left;
public Expr Right;
public abstract bool CanSimplify { get; set; }
public abstract Expr Simplify();
}
public class ConstExpr : Expr
{
public double Value;
public override bool CanSimplify { get; set; } = false;
public override Expr Simplify()
{
return this;
}
public override string ToString()
{
return Value.ToString(CultureInfo.InvariantCulture);
}
}
public class AddExpr : Expr
{
public override bool CanSimplify { get; set; } = true;
public override Expr Simplify()
{
while (Left.CanSimplify)
Left.Simplify();
while (Right.CanSimplify)
Right.Simplify();
var left = Left as ConstExpr;
var right = Right as ConstExpr;
if (left == null || right == null)
return this;
return new ConstExpr {Value = left.Value + right.Value};
}
}