Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -790,6 +790,11 @@ private RegexNode ReduceAtomic()
start = endExclusive;
}

// Force a re-reduction if we know we've exposed new opportunities that'll be handled.
reordered |=
child.ChildCount() == 2 &&
(child.Child(0).Kind is RegexNodeKind.Empty || child.Child(1).Kind is RegexNodeKind.Empty); // can be transformed into a ? or ??

// If anything was reordered, there may be new optimization opportunities inside
// of the alternation, so reduce it again.
if (reordered)
Expand Down Expand Up @@ -1032,6 +1037,22 @@ private RegexNode ReduceAlternation()
if (node.Kind == RegexNodeKind.Alternate)
{
node = RemoveRedundantEmptiesAndNothings(node);

// If the alternation is actually just a ? or ?? in disguise, transform it accordingly.
// (a|) becomes a?
// (|a) becomes a??
// Such "optional" nodes are processed more efficiently, including being able to be better coalesced with surrounding nodes.
if (node.Kind is RegexNodeKind.Alternate && node.ChildCount() == 2)
{
if (node.Child(1).Kind is RegexNodeKind.Empty)
{
node = node.Child(0).MakeQuantifier(lazy: false, min: 0, max: 1);
}
else if (node.Child(0).Kind is RegexNodeKind.Empty)
{
node = node.Child(1).MakeQuantifier(lazy: true, min: 0, max: 1);
}
}
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -306,6 +306,12 @@ public class RegexReductionTests
[InlineData("abcd|aefg", "a(?>bcd|efg)")]
[InlineData("abcd|abc|ab|a", "a(?>bcd|bc|b|)")]
[InlineData("^abcd|^abce", "^(?:abc[de])")]
[InlineData("abc|", "(?:abc)?")]
[InlineData("a|", "a?")]
[InlineData("(?:abc|)d", "(?>(?:abc)?)d")]
[InlineData("(?:a|)a", "a{1,2}")]
[InlineData("(?:a|)a*", "a*")]
[InlineData("a+(?:a|)", "a+")]
// [InlineData("abcde|abcdef", "abcde(?>|f)")] // TODO https://github.com/dotnet/runtime/issues/66031: Need to reorganize optimizations to avoid an extra Empty being left at the end of the tree
[InlineData("abcdef|abcde", "abcde(?>f|)")]
[InlineData("abcdef|abcdeg|abcdeh|abcdei|abcdej|abcdek|abcdel", "abcde[f-l]")]
Expand Down
Loading