Working on tree optimizer

This commit is contained in:
Youmu Liu
2026-02-11 18:02:45 +08:00
parent 4735b987f4
commit 39dd32992d
9 changed files with 193 additions and 63 deletions
@@ -174,24 +174,37 @@ namespace StgSharp.RegularAnalysis.TextRegex
{
// phase0: scan container and remove no parent nodes
_tree.AllNodes.RemoveWhere(node => node.Parent == null && node != _tree.Root);
HashSet<RegexAstNode>.Enumerator enumerator = _tree.AllNodes.GetEnumerator();
TreeEnumerator<RegexAstNode, RegexElementLabel> enumerator = new TreeEnumerator<RegexAstNode, RegexElementLabel>(_tree.Root);
RegexAstNode current;
// phase1: ALT flatten
// phase2: CONCAT normalize
while (enumerator.MoveNext())
{
RegexAstNode node = enumerator.Current;
if ((RegexElementLabel)node.NodeFlag == RegexElementLabel.ALT)
current = enumerator.Current;
if (current.EqualityTypeConvert == RegexElementLabel.ALT)
{
RegexAstNode list = FlattenAlt(node);
node.Left = list;
node.Right = RegexAstNode.Empty;
RegexAstNode union = FlattenAlt(current);
current.Right = union;
current.Left = RegexAstNode.Empty;
} else if (current.EqualityTypeConvert == RegexElementLabel.CONCAT) {
RotateConcat(current);
}
}
// phase2: ALT merge
// phase3: CONCAT merge
enumerator.Reset();
while (enumerator.MoveNext())
{
// suppose all concat is now in normalized form,
// we can merge adjacent unit nodes into a single unit node with string value
current = enumerator.Current;
if (current.EqualityTypeConvert == RegexElementLabel.CONCAT) {
MergeConcat(current);
}
}
// phase4: ALT union
}
private void ProcessOperator(