Innovenergy_trunk/csharp/Lib/SrcGen/Trees/ForwardTree.cs

46 lines
1.4 KiB
C#
Raw Normal View History

2023-06-13 11:03:09 +00:00
using InnovEnergy.Lib.Utils;
using Sawmill;
namespace InnovEnergy.Lib.SrcGen.Trees;
public class ForwardTree<T> : IRewritable<ForwardTree<T>> where T : notnull
{
public T Node { get; }
public IReadOnlyList<ForwardTree<T>> Children { get; }
public Boolean IsLeaf => Children.Count == 0;
public ForwardTree(T node) : this(node, Array.Empty<ForwardTree<T>>())
{
}
public ForwardTree(T node, IReadOnlyList<ForwardTree<T>> children)
{
Node = node;
Children = children;
}
public ForwardTree<T> WithNode(T node) => new ForwardTree<T>(node, Children);
public ForwardTree<T> WithNode(Func<T, T> makeNode) => new ForwardTree<T>(makeNode(Node), Children);
public override String ToString()
{
var node = Node.ToString()!;
return Children.Aggregate(node, (s, c) => s + "\n" + c.ToString().Indent(node.Length));
}
Int32 IRewritable<ForwardTree<T>>.CountChildren() => Children.Count;
void IRewritable<ForwardTree<T>>.GetChildren(Span<ForwardTree<T>> childrenReceiver)
{
for (var i = 0; i < Children.Count; i++)
childrenReceiver[i] = Children[i];
}
ForwardTree<T> IRewritable<ForwardTree<T>>.SetChildren(ReadOnlySpan<ForwardTree<T>> newChildren)
{
return new ForwardTree<T>(Node, newChildren.ToArray());
}
}