diff --git a/src/libraries/System.Text.RegularExpressions/src/System.Text.RegularExpressions.csproj b/src/libraries/System.Text.RegularExpressions/src/System.Text.RegularExpressions.csproj
index 0034d373563a96..d12444426c2b8f 100644
--- a/src/libraries/System.Text.RegularExpressions/src/System.Text.RegularExpressions.csproj
+++ b/src/libraries/System.Text.RegularExpressions/src/System.Text.RegularExpressions.csproj
@@ -54,9 +54,11 @@
+
+
diff --git a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Regex.cs b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Regex.cs
index d07f3440de4b8a..c23f309c9f34db 100644
--- a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Regex.cs
+++ b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Regex.cs
@@ -117,21 +117,10 @@ private void Init(string pattern, RegexOptions options, TimeSpan matchTimeout, C
// and is used as input into RegexOptions.Compiled and RegexOptions.NonBacktracking.
_code = RegexWriter.Write(tree, culture);
- if ((options & RegexOptions.NonBacktracking) != 0)
- {
- // NonBacktracking doesn't support captures (other than the implicit top-level capture).
- capnames = null;
- capslist = null;
- caps = null;
- capsize = 1;
- }
- else
- {
- capnames = tree.CapNames;
- capslist = tree.CapsList;
- caps = _code.Caps;
- capsize = _code.CapSize;
- }
+ capnames = tree.CapNames;
+ capslist = tree.CapsList;
+ caps = _code.Caps;
+ capsize = _code.CapSize;
}
internal static void ValidatePattern(string pattern)
diff --git a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexParser.cs b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexParser.cs
index b81e9d88e86b24..43a62f3ca1621b 100644
--- a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexParser.cs
+++ b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexParser.cs
@@ -533,17 +533,6 @@ private RegexNode ScanReplacement()
if (RightCharMoveRight() == '$')
{
RegexNode node = ScanDollar();
-
- // NonBacktracking does not support capture groups, so any replacement patterns that refer to
- // groups are unsupported. However, the replacement patterns that refer to the left/right portion
- // or all of the input as well as referring to group 0 (i.e. the whole match) are supported.
- if ((_options & RegexOptions.NonBacktracking) != 0 &&
- node.Kind == RegexNodeKind.Backreference &&
- node.M is not (0 or RegexReplacement.LeftPortion or RegexReplacement.RightPortion or RegexReplacement.WholeString))
- {
- throw new NotSupportedException(SR.NotSupported_NonBacktrackingAndReplacementsWithSubstitutionsOfGroups);
- }
-
AddUnitNode(node);
}
@@ -1409,7 +1398,6 @@ private RegexNode ScanDollar()
int capnum = -1;
int newcapnum = ch - '0';
MoveRight();
- CheckUnsupportedNonBacktrackingNumericRef(newcapnum);
if (IsCaptureSlot(newcapnum))
{
capnum = newcapnum;
@@ -1427,7 +1415,6 @@ private RegexNode ScanDollar()
newcapnum = newcapnum * 10 + digit;
MoveRight();
- CheckUnsupportedNonBacktrackingNumericRef(newcapnum);
if (IsCaptureSlot(newcapnum))
{
capnum = newcapnum;
@@ -1445,7 +1432,6 @@ private RegexNode ScanDollar()
int capnum = ScanDecimal();
if (!angled || CharsRight() > 0 && RightCharMoveRight() == '}')
{
- CheckUnsupportedNonBacktrackingNumericRef(capnum);
if (IsCaptureSlot(capnum))
{
return new RegexNode(RegexNodeKind.Backreference, _options, capnum);
@@ -1458,13 +1444,6 @@ private RegexNode ScanDollar()
string capname = ScanCapname();
if (CharsRight() > 0 && RightCharMoveRight() == '}')
{
- // Throw unconditionally for non-backtracking, even if not a valid capture name,
- // as information to determine whether a name is valid or not isn't tracked.
- if ((_options & RegexOptions.NonBacktracking) != 0)
- {
- throw new NotSupportedException(SR.NotSupported_NonBacktrackingAndReplacementsWithSubstitutionsOfGroups);
- }
-
if (IsCaptureName(capname))
{
return new RegexNode(RegexNodeKind.Backreference, _options, CaptureSlotFromName(capname));
@@ -1515,16 +1494,6 @@ private RegexNode ScanDollar()
return RegexNode.CreateOneWithCaseConversion('$', _options, _culture);
}
- /// Throws on unsupported capture references for NonBacktracking in replacement patterns.
- private void CheckUnsupportedNonBacktrackingNumericRef(int capnum)
- {
- // Throw for non-backtracking on non-zero group, even if not a valid capture number, as information to determine whether a name is valid or not isn't tracked
- if ((_options & RegexOptions.NonBacktracking) != 0 && capnum != 0)
- {
- throw new NotSupportedException(SR.NotSupported_NonBacktrackingAndReplacementsWithSubstitutionsOfGroups);
- }
- }
-
/*
* Scans a capture name: consumes word chars
*/
diff --git a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Symbolic/DerivativeEffect.cs b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Symbolic/DerivativeEffect.cs
new file mode 100644
index 00000000000000..164b5f55c6111b
--- /dev/null
+++ b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Symbolic/DerivativeEffect.cs
@@ -0,0 +1,33 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+
+namespace System.Text.RegularExpressions.Symbolic
+{
+ ///
+ /// Describes effects to record capture start and end points.
+ ///
+ ///
+ /// These are applied into registers (arrays of positions for all capture starts and ends) and amount to assignments
+ /// of the current input position. Effects are generated and associated with transitions in effect-aware versions
+ /// of MkDerivative in SymbolicRegexNode.
+ ///
+ internal struct DerivativeEffect
+ {
+ public enum EffectKind
+ {
+ /// Effect to assign the current input position to an index in the capture starts array.
+ CaptureStart,
+ /// Effect to assign the current input position to an index in the capture ends array.
+ CaptureEnd,
+ };
+
+ public EffectKind Kind;
+ public int CaptureNumber;
+
+ public DerivativeEffect(EffectKind kind, int captureNumber)
+ {
+ Kind = kind;
+ CaptureNumber = captureNumber;
+ }
+ }
+}
diff --git a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Symbolic/DfaMatchingState.cs b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Symbolic/DfaMatchingState.cs
index 254a7fd94407d2..3e8d1bc45156f5 100644
--- a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Symbolic/DfaMatchingState.cs
+++ b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Symbolic/DfaMatchingState.cs
@@ -4,6 +4,7 @@
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Net;
+using System.Collections.Generic;
namespace System.Text.RegularExpressions.Symbolic
{
@@ -55,18 +56,22 @@ internal int WatchDog
internal bool StartsWithLineAnchor => Node._info.StartsWithLineAnchor;
///
- /// Compute the target state for the given input minterm.
- /// If is False this means that this is \n and it is the last character of the input.
+ /// Translates a minterm predicate to a character kind, which is a general categorization of characters used
+ /// for cheaply deciding the nullability of anchors.
///
- /// minterm corresponding to some input character or False corresponding to last \n
- internal DfaMatchingState Next(T minterm)
+ ///
+ /// A False predicate is handled as a special case to indicate the very last \n.
+ ///
+ /// the minterm to translate
+ /// the character kind of the minterm
+ private uint GetNextCharKind(ref T minterm)
{
ICharAlgebra alg = Node._builder._solver;
T wordLetterPredicate = Node._builder._wordLetterPredicateForAnchors;
T newLinePredicate = Node._builder._newLinePredicate;
// minterm == solver.False is used to represent the very last \n
- uint nextCharKind = 0;
+ uint nextCharKind = CharKind.General;
if (alg.False.Equals(minterm))
{
nextCharKind = CharKind.NewLineS;
@@ -85,12 +90,23 @@ internal DfaMatchingState Next(T minterm)
{
nextCharKind = CharKind.WordLetter;
}
+ return nextCharKind;
+ }
+
+ ///
+ /// Compute the target state for the given input minterm.
+ /// If is False this means that this is \n and it is the last character of the input.
+ ///
+ /// minterm corresponding to some input character or False corresponding to last \n
+ internal DfaMatchingState Next(T minterm)
+ {
+ uint nextCharKind = GetNextCharKind(ref minterm);
// Combined character context
uint context = CharKind.Context(PrevCharKind, nextCharKind);
// Compute the derivative of the node for the given context
- SymbolicRegexNode derivative = Node.MkDerivative(minterm, context);
+ SymbolicRegexNode derivative = Node.MkDerivativeWithEffects(eager: true).TransitionOrdered(minterm, context);
// nextCharKind will be the PrevCharKind of the target state
// use an existing state instead if one exists already
@@ -98,6 +114,31 @@ internal DfaMatchingState Next(T minterm)
return Node._builder.MkState(derivative, nextCharKind);
}
+ ///
+ /// Compute a set of transitions for the given minterm.
+ ///
+ /// minterm corresponding to some input character or False corresponding to last \n
+ /// an enumeration of the transitions as pairs of the target state and a list of effects to be applied
+ internal IEnumerable<(DfaMatchingState, List)> AntimirovEagerNextWithEffects(T minterm)
+ {
+ uint nextCharKind = GetNextCharKind(ref minterm);
+
+ // Combined character context
+ uint context = CharKind.Context(PrevCharKind, nextCharKind);
+
+ // Compute the transitions for the given context
+ IEnumerable<(SymbolicRegexNode, List)> derivativesAndEffects =
+ Node.MkDerivativeWithEffects(eager: true).TransitionsWithEffects(minterm, context);
+
+ foreach (var (derivative, effects) in derivativesAndEffects)
+ {
+ // nextCharKind will be the PrevCharKind of the target state
+ // use an existing state instead if one exists already
+ // otherwise create a new new id for it
+ yield return (Node._builder.MkState(derivative, nextCharKind), effects);
+ }
+ }
+
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal bool IsNullable(uint nextCharKind)
{
diff --git a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Symbolic/RegexNodeToSymbolicConverter.cs b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Symbolic/RegexNodeToSymbolicConverter.cs
index cdafb9114882aa..0e8fe48890f00e 100644
--- a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Symbolic/RegexNodeToSymbolicConverter.cs
+++ b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Symbolic/RegexNodeToSymbolicConverter.cs
@@ -1,6 +1,7 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
+using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
@@ -15,14 +16,16 @@ internal sealed class RegexNodeToSymbolicConverter
internal readonly SymbolicRegexBuilder _builder;
private readonly CultureInfo _culture;
private readonly Dictionary<(bool, string), BDD> _createConditionFromSet_Cache = new();
+ private readonly Hashtable? _caps;
/// Constructs a regex to symbolic finite automata converter
- public RegexNodeToSymbolicConverter(Unicode.UnicodeCategoryTheory categorizer, CultureInfo culture)
+ public RegexNodeToSymbolicConverter(Unicode.UnicodeCategoryTheory categorizer, CultureInfo culture, Hashtable? caps)
{
_categorizer = categorizer;
_culture = culture;
Solver = categorizer._solver;
_builder = new SymbolicRegexBuilder(Solver);
+ _caps = caps;
}
/// The character solver associated with the regex converter
@@ -220,7 +223,7 @@ public SymbolicRegexNode Convert(RegexNode node, bool topLevel)
{
nested[i] = Convert(node.Child(i), topLevel);
}
- return _builder.MkOr(nested);
+ return _builder.MkOrderedOr(nested);
}
case RegexNodeKind.Beginning:
@@ -231,15 +234,17 @@ public SymbolicRegexNode Convert(RegexNode node, bool topLevel)
return _builder._bolAnchor;
case RegexNodeKind.Capture when node.N == -1:
- return Convert(node.Child(0), topLevel); // treat as non-capturing group (...)
+ int captureNum;
+ if (_caps == null || !_caps.TryGetValue(node.M, out captureNum))
+ captureNum = node.M;
+ return _builder.MkCapture(Convert(node.Child(0), topLevel: false), captureNum);
case RegexNodeKind.Concatenate:
{
- List nested = FlattenNestedConcatenations(node);
- var converted = new SymbolicRegexNode[nested.Count];
- for (int i = 0; i < converted.Length; i++)
+ var converted = new SymbolicRegexNode[node.ChildCount()];
+ for (int i = 0; i < node.ChildCount(); ++i)
{
- converted[i] = Convert(nested[i], topLevel: false);
+ converted[i] = Convert(node.Child(i), topLevel: false);
}
return _builder.MkConcat(converted, topLevel);
}
@@ -371,45 +376,6 @@ void EnsureWordLetterPredicateInitialized()
}
}
- List FlattenNestedConcatenations(RegexNode concat)
- {
- var results = new List();
-
- var todo = new Stack();
- todo.Push(concat);
-
- while (todo.TryPop(out RegexNode? node))
- {
- if (node.Kind == RegexNodeKind.Concatenate)
- {
- // Flatten nested concatenations
- for (int i = node.ChildCount() - 1; i >= 0; i--)
- {
- todo.Push(node.Child(i));
- }
- }
- else if (node.Kind == RegexNodeKind.Capture)
- {
- if (node.N == -1)
- {
- // Unwrap nonbalancing capture groups
- todo.Push(node.Child(0));
- }
- else
- {
- // Balancing groups are not supported
- throw new NotSupportedException(SR.Format(SR.NotSupported_NonBacktrackingConflictingExpression, SR.ExpressionDescription_BalancingGroup));
- }
- }
- else
- {
- results.Add(node);
- }
- }
-
- return results;
- }
-
SymbolicRegexNode ConvertMulti(RegexNode node, bool topLevel)
{
Debug.Assert(node.Kind == RegexNodeKind.Multi);
diff --git a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Symbolic/SparseIntMap.cs b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Symbolic/SparseIntMap.cs
new file mode 100644
index 00000000000000..8078d39ccc9169
--- /dev/null
+++ b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Symbolic/SparseIntMap.cs
@@ -0,0 +1,95 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+
+using System.Collections.Generic;
+using System.Diagnostics;
+
+namespace System.Text.RegularExpressions.Symbolic
+{
+ /// An insertion-ordered map that supports small int keys.
+ /// Uses a sparse array of the same size as the space of keys for efficient lookups.
+ internal sealed class SparseIntMap where T : struct
+ {
+ private const int InitialCapacity = 16;
+ private readonly List> _dense = new();
+ private int[] _sparse = new int[InitialCapacity];
+
+ private void Grow(int maxValue)
+ {
+ int newLength = maxValue + 1;
+ Debug.Assert(newLength > _sparse.Length);
+ // At least double the size to amortize memory allocations
+ newLength = Math.Max(2 * _sparse.Length, newLength);
+ Array.Resize(ref _sparse, newLength);
+ // Using GC.AllocateUninitializedArray(newLength) and copying would also be valid
+ }
+
+ /// Remove all entries. Does not decrease capacity.
+ public void Clear() => _dense.Clear();
+
+ /// Number of entries in the map.
+ public int Count => _dense.Count;
+
+ /// Get the internal list of entries. Do not modify.
+ public List> Values => _dense;
+
+ /// Return the index of the entry with the key, or -1 if none exists.
+ public int Find(int key)
+ {
+ int[] sparse = _sparse;
+ if ((uint)key < (uint)sparse.Length)
+ {
+ List> dense = _dense;
+ int idx = sparse[key];
+ if (idx < dense.Count)
+ {
+ int entryKey = dense[idx].Key;
+ Debug.Assert(entryKey < _sparse.Length);
+ if (key == entryKey)
+ {
+ return idx;
+ }
+ }
+ }
+
+ return -1;
+ }
+
+ /// Find or add an entry matching the key.
+ /// the key to find or add
+ /// will be set to the index of the matching entry
+ /// whether a new entry was added
+ public bool Add(int key, out int index)
+ {
+ index = Find(key);
+ if (index >= 0)
+ {
+ return false;
+ }
+ if (key >= _sparse.Length)
+ {
+ Grow(key);
+ }
+ index = _dense.Count;
+ _sparse[key] = index;
+ _dense.Add(new KeyValuePair(key, default(T)));
+ return true;
+ }
+
+ /// Find or add an entry matching a key and then set the value of the entry.
+ public bool Add(int key, T value)
+ {
+ bool added = Add(key, out int index);
+ Update(index, key, value);
+ return added;
+ }
+
+ /// Set the value of the entry at the index.
+ public void Update(int index, int key, T value)
+ {
+ Debug.Assert(0 <= index && index < _dense.Count);
+ Debug.Assert(_dense[index].Key == key);
+ _dense[index] = new KeyValuePair(key, value);
+ }
+ }
+}
diff --git a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Symbolic/SymbolicMatch.cs b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Symbolic/SymbolicMatch.cs
index 5ba715c25ef4c8..df781471f06664 100644
--- a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Symbolic/SymbolicMatch.cs
+++ b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Symbolic/SymbolicMatch.cs
@@ -13,10 +13,12 @@ namespace System.Text.RegularExpressions.Symbolic
/// Indicates a match was found but without meaningful details about where.
internal static SymbolicMatch QuickMatch => new SymbolicMatch(0, 0);
- public SymbolicMatch(int index, int length)
+ public SymbolicMatch(int index, int length, int[]? captureStarts = null, int[]? captureEnds = null)
{
Index = index;
Length = length;
+ CaptureStarts = captureStarts;
+ CaptureEnds = captureEnds;
}
public int Index { get; }
@@ -25,6 +27,18 @@ public SymbolicMatch(int index, int length)
public bool Success => Index >= 0;
+ ///
+ /// Array of capture start indices for each capture group. Each is a valid index into the input if the group
+ /// was captured, or -1 otherwise.
+ ///
+ public readonly int[]? CaptureStarts;
+
+ ///
+ /// Array of capture end indices for each capture group. Each is a valid index into the input and greater than
+ /// the corresponding start position if the group was captured, or -1 otherwise.
+ ///
+ public readonly int[]? CaptureEnds;
+
public static bool operator ==(SymbolicMatch left, SymbolicMatch right) =>
left.Equals(right);
diff --git a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Symbolic/SymbolicNFA.cs b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Symbolic/SymbolicNFA.cs
index 1448ed8c6e580a..12ca744905e1d0 100644
--- a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Symbolic/SymbolicNFA.cs
+++ b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Symbolic/SymbolicNFA.cs
@@ -347,6 +347,7 @@ private class Transition
break;
case TransitionRegexKind.Union:
+ case TransitionRegexKind.OrderedUnion:
Debug.Assert(_first is not null && _second is not null);
foreach ((S, SymbolicRegexNode?, int) path in _first.EnumeratePaths(solver, pathCondition))
{
diff --git a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Symbolic/SymbolicRegexBuilder.cs b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Symbolic/SymbolicRegexBuilder.cs
index 1fec095c54b105..343706b1caf101 100644
--- a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Symbolic/SymbolicRegexBuilder.cs
+++ b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Symbolic/SymbolicRegexBuilder.cs
@@ -54,7 +54,8 @@ internal sealed class SymbolicRegexBuilder where TElement : notnull
TElement?, // _test
TransitionRegex?, // _first
TransitionRegex?, // _second
- SymbolicRegexNode?), // _leaf
+ SymbolicRegexNode?, // _leaf
+ DerivativeEffect?), // _effect
TransitionRegex> _trCache = new();
///
@@ -63,6 +64,7 @@ internal sealed class SymbolicRegexBuilder where TElement : notnull
///
internal DfaMatchingState[]? _statearray;
internal DfaMatchingState[]? _delta;
+ internal List<(DfaMatchingState, List)>[]? _capturingDelta;
private const int InitialStateLimit = 1024;
///
@@ -112,6 +114,7 @@ internal SymbolicRegexBuilder(ICharAlgebra solver)
}
_mintermsCount = mintermsCount;
_delta = new DfaMatchingState[InitialStateLimit << _mintermsCount];
+ _capturingDelta = new List<(DfaMatchingState, List)>[InitialStateLimit << _mintermsCount];
}
// initialized to False but updated later to the actual condition ony if \b or \B occurs anywhere in the regex
@@ -138,6 +141,26 @@ internal SymbolicRegexBuilder(ICharAlgebra solver)
internal SymbolicRegexNode MkOr(params SymbolicRegexNode[] regexes) =>
SymbolicRegexNode.MkOr(this, regexes);
+ ///
+ /// Make an ordered disjunction of given regexes, simplify by eliminating any regex that accepts no inputs
+ ///
+ internal SymbolicRegexNode MkOrderedOr(params SymbolicRegexNode[] regexes)
+ {
+ SymbolicRegexNode? or = null;
+ foreach (SymbolicRegexNode elem in regexes)
+ {
+ if (elem.IsNothing)
+ continue;
+
+ or = or is null ? elem : SymbolicRegexNode.MkOrderedOr(this, or, elem);
+
+ if (elem.IsAnyStar)
+ break; // .* is the absorbing element
+ }
+
+ return or ?? _nothing;
+ }
+
///
/// Make a conjunction of given regexes, simplify by eliminating regexes that accept everything
///
@@ -227,7 +250,7 @@ internal SymbolicRegexNode MkLoop(SymbolicRegexNode regex, b
if (lower == 0 && upper == 0)
{
- return isLazy ? _epsilon : _eagerEmptyLoop;
+ return _epsilon;
}
if (!isLazy && lower == 0 && upper == int.MaxValue && regex._kind == SymbolicRegexKind.Singleton)
@@ -294,6 +317,12 @@ internal SymbolicRegexNode MkSequence(TElement[] seq, bool topLevel)
///
internal SymbolicRegexNode MkNot(SymbolicRegexNode node) => SymbolicRegexNode.MkNot(this, node);
+ internal SymbolicRegexNode MkCapture(SymbolicRegexNode child, int captureNum) => MkConcat(MkCaptureStart(captureNum), MkConcat(child, MkCaptureEnd(captureNum)));
+
+ internal SymbolicRegexNode MkCaptureStart(int captureNum) => SymbolicRegexNode.MkCaptureStart(this, captureNum);
+
+ internal SymbolicRegexNode MkCaptureEnd(int captureNum) => SymbolicRegexNode.MkCaptureEnd(this, captureNum);
+
internal SymbolicRegexNode Transform(SymbolicRegexNode sr, SymbolicRegexBuilder builderT, Func predicateTransformer) where T : notnull
{
if (!StackHelper.TryEnsureSufficientExecutionStack())
@@ -345,10 +374,20 @@ internal SymbolicRegexNode Transform(SymbolicRegexNode sr, Symbo
Debug.Assert(sr._alts is not null);
return builderT.MkOr(sr._alts.Transform(builderT, predicateTransformer));
+ case SymbolicRegexKind.OrderedOr:
+ Debug.Assert(sr._left is not null && sr._right is not null);
+ return builderT.MkOrderedOr(Transform(sr._left, builderT, predicateTransformer), Transform(sr._right, builderT, predicateTransformer));
+
case SymbolicRegexKind.And:
Debug.Assert(sr._alts is not null);
return builderT.MkAnd(sr._alts.Transform(builderT, predicateTransformer));
+ case SymbolicRegexKind.CaptureStart:
+ return builderT.MkCaptureStart(sr._lower);
+
+ case SymbolicRegexKind.CaptureEnd:
+ return builderT.MkCaptureEnd(sr._lower);
+
case SymbolicRegexKind.Concat:
{
List> sr_elems = sr.ToList();
@@ -414,6 +453,7 @@ private DfaMatchingState MakeNewState(DfaMatchingState state
int newsize = _statearray.Length + 1024;
Array.Resize(ref _statearray, newsize);
Array.Resize(ref _delta, newsize << _mintermsCount);
+ Array.Resize(ref _capturingDelta, newsize << _mintermsCount);
}
_statearray[state.Id] = state;
return state;
diff --git a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Symbolic/SymbolicRegexInfo.cs b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Symbolic/SymbolicRegexInfo.cs
index 4e60696eb07174..52f28a8b186a96 100644
--- a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Symbolic/SymbolicRegexInfo.cs
+++ b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Symbolic/SymbolicRegexInfo.cs
@@ -86,7 +86,7 @@ internal static SymbolicRegexInfo Mk(bool isAlwaysNullable = false, bool canBeNu
public bool IsLazy => (_info & IsLazyMask) != 0;
- public static SymbolicRegexInfo Or(SymbolicRegexInfo[] infos)
+ public static SymbolicRegexInfo Or(params SymbolicRegexInfo[] infos)
{
uint isLazy = IsLazyMask;
uint i = 0;
diff --git a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Symbolic/SymbolicRegexKind.cs b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Symbolic/SymbolicRegexKind.cs
index f012d0559e9e8a..ece9e1ea627bfc 100644
--- a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Symbolic/SymbolicRegexKind.cs
+++ b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Symbolic/SymbolicRegexKind.cs
@@ -23,5 +23,8 @@ internal enum SymbolicRegexKind
EndAnchorZ = 0x4000,
/// Anchor for very first line or start-line after very first \n arises as the reverse of EndAnchorZ
EndAnchorZRev = 0x8000,
+ CaptureStart = 0x10000,
+ CaptureEnd = 0x20000,
+ OrderedOr = 0x40000,
}
}
diff --git a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Symbolic/SymbolicRegexMatcher.cs b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Symbolic/SymbolicRegexMatcher.cs
index 1d1f9f30a4942c..53432d5373536a 100644
--- a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Symbolic/SymbolicRegexMatcher.cs
+++ b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Symbolic/SymbolicRegexMatcher.cs
@@ -138,6 +138,9 @@ internal sealed class SymbolicRegexMatcher : ISymbolicRegexMatcher whe
/// Non-null iff the pattern contains anchors; otherwise, it's unused.
private readonly uint[]? _asciiCharKinds;
+ /// Number of capture groups.
+ private readonly int _capsize;
+
/// Get the minterm of .
/// character code
[MethodImpl(MethodImplOptions.AggressiveInlining)]
@@ -162,6 +165,7 @@ internal SymbolicRegexMatcher(SymbolicRegexNode sr, RegexCode code, Ch
BVAlgebra bv => bv._classifier,
_ => new MintermClassifier((CharSetSolver)(object)_builder._solver, minterms),
};
+ _capsize = code.CapSize;
if (code.FindOptimizations.FindMode != FindNextStartingPositionMode.NoSearch &&
code.FindOptimizations.LeadingAnchor == 0) // If there are any anchors, we're better off letting the DFA quickly do its job of determining whether there's a match.
@@ -183,7 +187,8 @@ internal SymbolicRegexMatcher(SymbolicRegexNode sr, RegexCode code, Ch
// Create the dot-star pattern (a concatenation of any* with the original pattern)
// and all of its initial states.
- _dotStarredPattern = _builder.MkConcat(_builder._anyStar, _pattern);
+ SymbolicRegexNode unorderedPattern = _pattern.IgnoreOrOrderAndLazyness();
+ _dotStarredPattern = _builder.MkConcat(_builder._anyStar, unorderedPattern);
var dotstarredInitialStates = new DfaMatchingState[statesCount];
for (uint i = 0; i < dotstarredInitialStates.Length; i++)
{
@@ -199,7 +204,7 @@ internal SymbolicRegexMatcher(SymbolicRegexNode sr, RegexCode code, Ch
// Create the reverse pattern (the original pattern in reverse order) and all of its
// initial states.
- _reversePattern = _pattern.Reverse();
+ _reversePattern = unorderedPattern.Reverse();
var reverseInitialStates = new DfaMatchingState[statesCount];
for (uint i = 0; i < reverseInitialStates.Length; i++)
{
@@ -235,6 +240,36 @@ internal SymbolicRegexMatcher(SymbolicRegexNode sr, RegexCode code, Ch
}
}
+ ///
+ /// Per thread data to be held by the regex runner and passed into every call to FindMatch. This is used to
+ /// avoid repeated memory allocation.
+ ///
+ internal struct PerThreadData
+ {
+ /// Maps used for the capturing third phase.
+ public SparseIntMap? Current, Next;
+ /// Registers used for the capturing third phase.
+ public Registers InitialRegisters;
+
+ public PerThreadData(int capsize)
+ {
+ // Only create data used for capturing mode if there are subcaptures
+ bool capturing = capsize > 1;
+ Current = capturing ? new() : null;
+ Next = capturing ? new() : null;
+ InitialRegisters = capturing ? new Registers
+ {
+ CaptureStarts = new int[capsize],
+ CaptureEnds = new int[capsize],
+ } : default(Registers);
+ }
+ }
+
+ ///
+ /// Create a PerThreadData with the appropriate parts initialized for this matcher's pattern.
+ ///
+ internal PerThreadData CreatePerThreadData() => new PerThreadData(_capsize);
+
/// Interface for transitions used by the method.
private interface ITransition
{
@@ -265,6 +300,80 @@ private DfaMatchingState Delta(ReadOnlySpan input,
return default(TTransition).TakeTransition(this, sourceState, mintermId, minterm);
}
+ ///
+ /// Stores additional data for tracking capture start and end positions.
+ ///
+ ///
+ /// The NFA simulation based third phase has one of these for each current state in the current set of live states.
+ ///
+ internal struct Registers
+ {
+ public int[] CaptureStarts;
+ public int[] CaptureEnds;
+
+ ///
+ /// Applies a list of effects in order to these registers at the provided input position. The order of effects
+ /// should not matter though, as multiple effects to the same capture start or end do not arise.
+ ///
+ /// list of effects to be applied
+ /// the current input position to record
+ public void ApplyEffects(List effects, int pos)
+ {
+ foreach (DerivativeEffect effect in effects)
+ {
+ ApplyEffect(effect, pos);
+ }
+ }
+
+ ///
+ /// Apply a single effect to these registers at the provided input position.
+ ///
+ /// the effecto to be applied
+ /// the current input position to record
+ public void ApplyEffect(DerivativeEffect effect, int pos)
+ {
+ switch (effect.Kind)
+ {
+ case DerivativeEffect.EffectKind.CaptureStart:
+ CaptureStarts[effect.CaptureNumber] = pos;
+ break;
+ case DerivativeEffect.EffectKind.CaptureEnd:
+ CaptureEnds[effect.CaptureNumber] = pos;
+ break;
+ }
+ }
+
+ ///
+ /// Make a copy of this set of registers.
+ ///
+ /// Registers pointing to copies of this set of registers
+ public Registers Clone() => new Registers
+ {
+ CaptureStarts = (int[])CaptureStarts.Clone(),
+ CaptureEnds = (int[])CaptureEnds.Clone(),
+ };
+
+ ///
+ /// Copy register values from another set of registers, possibly allocating new arrays if they were not yet allocated.
+ ///
+ /// the registers to copy from
+ public void Assign(Registers other)
+ {
+ if (CaptureStarts is not null && CaptureEnds is not null)
+ {
+ Debug.Assert(CaptureStarts.Length == other.CaptureStarts.Length);
+ Array.Copy(other.CaptureStarts, CaptureStarts, CaptureStarts.Length);
+ Debug.Assert(CaptureEnds.Length == other.CaptureEnds.Length);
+ Array.Copy(other.CaptureEnds, CaptureEnds, CaptureEnds.Length);
+ }
+ else
+ {
+ CaptureStarts = (int[])other.CaptureStarts.Clone();
+ CaptureEnds = (int[])other.CaptureEnds.Clone();
+ }
+ }
+ }
+
/// Transition for Brzozowski-style derivatives (i.e. a DFA).
private readonly struct BrzozowskiTransition : ITransition
{
@@ -343,6 +452,24 @@ private DfaMatchingState CreateNewTransition(DfaMatchingState, List)> CreateNewCapturingTransitions(DfaMatchingState state, TSetType minterm, int offset)
+ {
+ Debug.Assert(_builder._capturingDelta is not null);
+ lock (this)
+ {
+ // check if meanwhile delta[offset] has become defined possibly by another thread
+ List<(DfaMatchingState, List)> p = _builder._capturingDelta[offset];
+ if (p is null)
+ {
+ // this is the only place in code where the Next method is called in the matcher
+ p = new List<(DfaMatchingState, List)>(state.AntimirovEagerNextWithEffects(minterm));
+ Volatile.Write(ref _builder._capturingDelta[offset], p);
+ }
+
+ return p;
+ }
+ }
+
private void DoCheckTimeout(int timeoutOccursAt)
{
// This logic is identical to RegexRunner.DoCheckTimeout, with the exception of check skipping. RegexRunner calls
@@ -358,7 +485,8 @@ private void DoCheckTimeout(int timeoutOccursAt)
/// Whether to return once we know there's a match without determining where exactly it matched.
/// The input span
/// The position to start search in the input span.
- public SymbolicMatch FindMatch(bool isMatch, ReadOnlySpan input, int startat)
+ /// Per thread data reused between calls.
+ public SymbolicMatch FindMatch(bool isMatch, ReadOnlySpan input, int startat, PerThreadData perThreadData)
{
int timeoutOccursAt = 0;
if (_checkTimeout)
@@ -398,12 +526,9 @@ public SymbolicMatch FindMatch(bool isMatch, ReadOnlySpan input, int start
}
int i_start;
- int i_end;
-
if (watchdog >= 0)
{
i_start = i - watchdog + 1;
- i_end = i;
}
else
{
@@ -411,16 +536,24 @@ public SymbolicMatch FindMatch(bool isMatch, ReadOnlySpan input, int start
i_start = i < startat ?
startat :
FindStartPosition(input, i, i_q0_A1); // Walk in reverse to locate the start position of the match
- i_end = FindEndPosition(input, i_start);
}
- return new SymbolicMatch(i_start, i_end + 1 - i_start);
+ if (_capsize <= 1)
+ {
+ int i_end = FindEndPosition(input, i_start);
+ return new SymbolicMatch(i_start, i_end + 1 - i_start);
+ }
+ else
+ {
+ int i_end = FindEndPositionCapturing(input, i_start, out Registers endRegisters, perThreadData);
+ return new SymbolicMatch(i_start, i_end + 1 - i_start, endRegisters.CaptureStarts, endRegisters.CaptureEnds);
+ }
}
/// Find match end position using the original pattern, end position is known to exist.
/// input span
/// inclusive start position
- ///
+ /// the match end position
private int FindEndPosition(ReadOnlySpan input, int i)
{
int i_end = input.Length;
@@ -433,12 +566,6 @@ private int FindEndPosition(ReadOnlySpan input, int i)
{
// Empty match exists because the initial state is accepting.
i_end = i - 1;
-
- // Stop here if q is lazy.
- if (state.IsLazy)
- {
- return i_end;
- }
}
while (i < input.Length)
@@ -470,12 +597,6 @@ private bool FindEndPositionDeltas(ReadOnlySpan input, ref in
{
// Accepting state has been reached. Record the position.
i_end = i;
-
- // Stop here if q is lazy.
- if (q.IsLazy)
- {
- return true;
- }
}
else if (q.IsDeadend)
{
@@ -491,6 +612,125 @@ private bool FindEndPositionDeltas(ReadOnlySpan input, ref in
return false;
}
+ /// Find match end position using the original pattern, end position is known to exist. This version also produces captures.
+ /// input span
+ /// inclusive start position
+ /// out parameter for the final register values, which indicate capture starts and ends
+ /// Per thread data reused between calls.
+ /// the match end position
+ private int FindEndPositionCapturing(ReadOnlySpan input, int i, out Registers resultRegisters, PerThreadData perThreadData)
+ {
+ int i_end = input.Length;
+ Registers endRegisters = default(Registers);
+ DfaMatchingState? endState = null;
+
+ // Pick the correct start state based on previous character kind.
+ uint prevCharKind = GetCharKind(input, i - 1);
+ DfaMatchingState state = _initialStates[prevCharKind];
+
+ Registers initialRegisters = perThreadData.InitialRegisters;
+ // Initialize registers with -1, which means "not seen yet"
+ Array.Fill(initialRegisters.CaptureStarts, -1);
+ Array.Fill(initialRegisters.CaptureEnds, -1);
+
+ if (state.IsNullable(GetCharKind(input, i)))
+ {
+ // Empty match exists because the initial state is accepting.
+ i_end = i - 1;
+ endRegisters.Assign(initialRegisters);
+ endState = state;
+ }
+
+ // Use two maps from state IDs to register values for the current and next set of states.
+ // Note that these maps use insertion order, which is used to maintain priorities between states in a way
+ // that matches the order the backtracking engines visit paths.
+ Debug.Assert(perThreadData.Current is not null && perThreadData.Next is not null);
+ SparseIntMap current = perThreadData.Current, next = perThreadData.Next;
+ current.Clear();
+ next.Clear();
+ current.Add(state.Id, initialRegisters);
+
+ while ((uint)i < (uint)input.Length)
+ {
+ Debug.Assert(next.Count == 0);
+
+ TSetType[]? minterms = _builder._minterms;
+ Debug.Assert(minterms is not null);
+
+ int c = input[i];
+ int normalMintermId = _partitions.GetMintermID(c);
+
+ foreach (var (sourceId, sourceRegisters) in current.Values)
+ {
+ Debug.Assert(_builder._statearray is not null);
+ DfaMatchingState sourceState = _builder._statearray[sourceId];
+
+ // Find the minterm, handling the special case for the last \n
+ int mintermId = c == '\n' && i == input.Length - 1 && sourceState.StartsWithLineAnchor ?
+ minterms.Length : normalMintermId; // mintermId = minterms.Length represents \Z (last \n)
+ TSetType minterm = (uint)mintermId < (uint)minterms.Length ?
+ minterms[mintermId] :
+ _builder._solver.False; // minterm=False represents \Z
+
+ // Get or create the transitions
+ int offset = (sourceId << _builder._mintermsCount) | mintermId;
+ Debug.Assert(_builder._capturingDelta is not null);
+ var transitions = Volatile.Read(ref _builder._capturingDelta[offset])
+ ?? CreateNewCapturingTransitions(sourceState, minterm, offset);
+
+ // Take the transitions in their prioritized order
+ for (int j = 0; j < transitions.Count; ++j)
+ {
+ var (targetState, effects) = transitions[j];
+ if (targetState.IsDeadend)
+ continue;
+
+ // Try to add the state and handle the case where it didn't exist before. If the state already
+ // exists, then the transition can be safely ignored, as the existing state was generated by a
+ // higher priority transition.
+ if (next.Add(targetState.Id, out int index))
+ {
+ // Avoid copying the registers on the last transition from this state, reusing the registers instead
+ Registers newRegisters = j != transitions.Count - 1 ? sourceRegisters.Clone() : sourceRegisters;
+ newRegisters.ApplyEffects(effects, i);
+ next.Update(index, targetState.Id, newRegisters);
+ if (targetState.IsNullable(GetCharKind(input, i + 1)))
+ {
+ // Accepting state has been reached. Record the position.
+ i_end = i;
+ endRegisters.Assign(newRegisters);
+ endState = targetState;
+ // No lower priority transitions from this or other source states are taken because the
+ // backtracking engines would return the match ending here.
+ goto BREAK_NULLABLE;
+ }
+ }
+ }
+ }
+ BREAK_NULLABLE:
+ if (next.Count == 0)
+ {
+ // If all states died out some nullable state must have been seen before
+ goto FINISH;
+ }
+
+ // Swap the state sets and prepare for the next character
+ var tmp = current;
+ current = next;
+ next = tmp;
+ next.Clear();
+ i++;
+ }
+
+ FINISH:
+ Debug.Assert(i_end != input.Length && endState is not null);
+ // Apply effects for finishing at the stored end state
+ endState.Node.ApplyEffects(effect => endRegisters.ApplyEffect(effect, i_end + 1),
+ CharKind.Context(endState.PrevCharKind, GetCharKind(input, i_end + 1)));
+ resultRegisters = endRegisters;
+ return i_end;
+ }
+
/// Walk back in reverse using the reverse pattern to find the start position of match, start position is known to exist.
/// the input span
/// position to start walking back from, i points at the last character of the match
diff --git a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Symbolic/SymbolicRegexNode.cs b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Symbolic/SymbolicRegexNode.cs
index f7992bf43950d3..edeac320a461bd 100644
--- a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Symbolic/SymbolicRegexNode.cs
+++ b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Symbolic/SymbolicRegexNode.cs
@@ -132,28 +132,32 @@ internal bool CanBeNullable
private readonly int _hashcode;
- /// Converts a concatenation into an array, returns a non-concatenation in a singleton array.
- public List> ToList()
+ /// Converts a Concat or OrderdOr into an array, returns anything else in a singleton array.
+ /// a list to insert the elements into, or null to return results in a new list
+ /// kind of node to consider as the list builder
+ public List> ToList(List>? list = null, SymbolicRegexKind listKind = SymbolicRegexKind.Concat)
{
- var list = new List>();
- AppendToList(this, list);
+ Debug.Assert(listKind == SymbolicRegexKind.Concat || listKind == SymbolicRegexKind.OrderedOr);
+ if (list is null)
+ list = new List>();
+ AppendToList(this, list, listKind);
return list;
- static void AppendToList(SymbolicRegexNode concat, List> list)
+ static void AppendToList(SymbolicRegexNode concat, List> list, SymbolicRegexKind listKind)
{
if (!StackHelper.TryEnsureSufficientExecutionStack())
{
- StackHelper.CallOnEmptyStack(AppendToList, concat, list);
+ StackHelper.CallOnEmptyStack(AppendToList, concat, list, listKind);
return;
}
SymbolicRegexNode node = concat;
- while (node._kind == SymbolicRegexKind.Concat)
+ while (node._kind == listKind)
{
Debug.Assert(node._left is not null && node._right is not null);
- if (node._left._kind == SymbolicRegexKind.Concat)
+ if (node._left._kind == listKind)
{
- AppendToList(node._left, list);
+ AppendToList(node._left, list, listKind);
}
else
{
@@ -220,6 +224,11 @@ bool WithCache(uint context)
is_nullable = _alts.IsNullableFor(context);
break;
+ case SymbolicRegexKind.OrderedOr:
+ Debug.Assert(_left is not null && _right is not null);
+ is_nullable = _left.IsNullableFor(context) || _right.IsNullableFor(context);
+ break;
+
case SymbolicRegexKind.Not:
Debug.Assert(_left is not null);
is_nullable = !_left.IsNullableFor(context);
@@ -261,6 +270,11 @@ bool WithCache(uint context)
is_nullable = (CharKind.Next(context) & CharKind.StartStop) != 0;
break;
+ case SymbolicRegexKind.CaptureStart:
+ case SymbolicRegexKind.CaptureEnd:
+ is_nullable = true;
+ break;
+
default: // SymbolicRegexKind.EndAnchorZRev:
// EndAnchorZRev (rev(\Z)) anchor is nullable when the prev character is either the first Newline or Start
// note: CharKind.NewLineS == CharKind.Newline|CharKind.StartStop
@@ -436,6 +450,12 @@ internal static SymbolicRegexNode MkAnd(SymbolicRegexBuilder builder, Symb
return MkCollection(builder, SymbolicRegexKind.And, conjuncts, SymbolicRegexInfo.And(GetInfos(conjuncts)));
}
+ internal static SymbolicRegexNode MkCaptureStart(SymbolicRegexBuilder builder, int captureNum) =>
+ Create(builder, SymbolicRegexKind.CaptureStart, null, null, captureNum, -1, default, null, SymbolicRegexInfo.Mk(isAlwaysNullable: true));
+
+ internal static SymbolicRegexNode MkCaptureEnd(SymbolicRegexBuilder builder, int captureNum) =>
+ Create(builder, SymbolicRegexKind.CaptureEnd, null, null, captureNum, -1, default, null, SymbolicRegexInfo.Mk(isAlwaysNullable: true));
+
private static SymbolicRegexNode MkCollection(SymbolicRegexBuilder builder, SymbolicRegexKind kind, SymbolicRegexSet alts, SymbolicRegexInfo info) =>
alts.IsNothing ? builder._nothing :
alts.IsEverything ? builder._anyStar :
@@ -494,6 +514,125 @@ internal static SymbolicRegexNode MkConcat(SymbolicRegexBuilder builder, S
return concat;
}
+ ///
+ /// Make an ordered or of given regexes, eliminate nothing regexes and treat .* as consuming element.
+ /// Keep the or flat, assuming both right and left are flat.
+ /// Apply a counber subsumption/combining optimization, such that e.g. a{2,5}|a{3,10} will be combined to a{2,10}.
+ ///
+ internal static SymbolicRegexNode MkOrderedOr(SymbolicRegexBuilder builder, SymbolicRegexNode left, SymbolicRegexNode right)
+ {
+ if (left.IsAnyStar || right == builder._nothing || left == right)
+ return left;
+ if (left == builder._nothing)
+ return right;
+
+ if (left._kind != SymbolicRegexKind.OrderedOr)
+ {
+ // Apply the counter subsumption/combining optimization if possible
+ var (loop, rest) = left.FirstCounterInfo();
+ if (loop != builder._nothing)
+ {
+ Debug.Assert(loop._kind == SymbolicRegexKind.Loop && loop._left is not null);
+ var (otherLoop, otherRest) = right.FirstCounterInfo();
+ if (otherLoop != builder._nothing && rest == otherRest)
+ {
+ // Found two adjacent counters with the same continuation, check that the loops are equivalent apart from bounds
+ // and that the bounds form a contiguous interval. Two integer intervals [x1,x2] and [y1,y2] overlap when
+ // x1 <= y2 and y1 <= x2. The union of intervals that just touch is still contiguous, e.g. [2,5] and [6,10] make
+ // [2,10], so the lower bounds are decremented by 1 in the check.
+ Debug.Assert(otherLoop._kind == SymbolicRegexKind.Loop && otherLoop._left is not null);
+ if (loop._left == otherLoop._left && loop.IsLazy == otherLoop.IsLazy &&
+ loop._lower - 1 <= otherLoop._upper && otherLoop._lower - 1 <= loop._upper)
+ {
+ // Loops are equivalent apart from bounds, and the union of the bounds is a contiguous interval
+ // Build a new counter for the union of the ranges
+ SymbolicRegexNode newCounter = MkConcat(builder, MkLoop(builder, loop._left,
+ Math.Min(loop._lower, otherLoop._lower), Math.Max(loop._upper, otherLoop._upper), loop.IsLazy), rest);
+ if (right._kind == SymbolicRegexKind.OrderedOr)
+ {
+ // The right counter came from an or, so include the rest of that or
+ Debug.Assert(right._right is not null);
+ return MkOrderedOr(builder, newCounter, right._right);
+ }
+ else
+ {
+ return newCounter;
+ }
+ }
+ }
+ }
+ // No need for flattening and counter optimization did not apply, just build the or
+ return Create(builder, SymbolicRegexKind.OrderedOr, left, right, -1, -1, default, null, SymbolicRegexInfo.Or(left._info, right._info));
+ }
+
+ // If the left side was an or, then it has to be flattened, gather the elements from both sides
+ List> elems = left.ToList(listKind: SymbolicRegexKind.OrderedOr);
+ int firstRightElem = elems.Count;
+ right.ToList(elems, listKind: SymbolicRegexKind.OrderedOr);
+
+ // Eliminate any duplicate elements, keeping the leftmost element
+ HashSet> seenElems = new();
+ // Keep track of if any elements from the right side need to be eliminated
+ bool rightChanged = false;
+ for (int i = 0; i < elems.Count; i++)
+ {
+ if (!seenElems.Contains(elems[i]))
+ {
+ seenElems.Add(elems[i]);
+ }
+ else
+ {
+ // Nothing will be eliminated in the next step
+ elems[i] = builder._nothing;
+ rightChanged |= i >= firstRightElem;
+ }
+ }
+
+ // Build the flattened or, avoiding rebuilding the right side if possible
+ if (rightChanged)
+ {
+ SymbolicRegexNode or = builder._nothing;
+ for (int i = elems.Count - 1; i >= 0; i--)
+ {
+ or = MkOrderedOr(builder, elems[i], or);
+ }
+ return or;
+ }
+ else
+ {
+ SymbolicRegexNode or = right;
+ for (int i = firstRightElem - 1; i >= 0; i--)
+ {
+ or = MkOrderedOr(builder, elems[i], or);
+ }
+ return or;
+ }
+ }
+
+ ///
+ /// Extract a counter as a loop followed by its continuation. For example, a*b returns (a*,b).
+ /// Also look into the first element of an or, so a+|xyz returns (a+,()).
+ /// If no counter is found returns ([],[]).
+ ///
+ /// a tuple of the loop and its continuation
+ private (SymbolicRegexNode, SymbolicRegexNode) FirstCounterInfo()
+ {
+ if (_kind == SymbolicRegexKind.Loop)
+ return (this, _builder._epsilon);
+ if (_kind == SymbolicRegexKind.Concat)
+ {
+ Debug.Assert(_left is not null && _right is not null);
+ if (_left.Kind == SymbolicRegexKind.Loop)
+ return (_left, _right);
+ }
+ if (_kind == SymbolicRegexKind.OrderedOr)
+ {
+ Debug.Assert(_left is not null);
+ return _left.FirstCounterInfo();
+ }
+ return (_builder._nothing, _builder._nothing);
+ }
+
internal static SymbolicRegexNode MkNot(SymbolicRegexBuilder builder, SymbolicRegexNode root)
{
// Instead of just creating a negated root node
@@ -607,6 +746,8 @@ public int GetFixedLength()
case SymbolicRegexKind.EndAnchorZRev:
case SymbolicRegexKind.WBAnchor:
case SymbolicRegexKind.NWBAnchor:
+ case SymbolicRegexKind.CaptureStart:
+ case SymbolicRegexKind.CaptureEnd:
return 0;
case SymbolicRegexKind.Singleton:
@@ -644,6 +785,21 @@ public int GetFixedLength()
case SymbolicRegexKind.Or:
Debug.Assert(_alts is not null);
return _alts.GetFixedLength();
+
+ case SymbolicRegexKind.OrderedOr:
+ {
+ Debug.Assert(_left is not null && _right is not null);
+ int left_length = _left.GetFixedLength();
+ if (left_length >= 0)
+ {
+ int right_length = _right.GetFixedLength();
+ if (right_length == left_length)
+ {
+ return right_length;
+ }
+ }
+ break;
+ }
}
return -1;
@@ -778,6 +934,17 @@ internal SymbolicRegexNode MkDerivative(S elem, uint context)
#endregion
}
+ case SymbolicRegexKind.OrderedOr:
+ {
+ #region d(a,A|B) = d(a,A)|d(a,B)
+ Debug.Assert(_left is not null && _right is not null);
+ SymbolicRegexNode leftd = _left.MkDerivative(elem, context);
+ SymbolicRegexNode rightd = _right.MkDerivative(elem, context);
+ deriv = _builder.MkOrderedOr(leftd, rightd);
+ break;
+ #endregion
+ }
+
case SymbolicRegexKind.And:
{
#region d(a,A & B) = d(a,A) & d(a,B)
@@ -809,7 +976,10 @@ internal SymbolicRegexNode MkDerivative(S elem, uint context)
}
private TransitionRegex? _transitionRegex;
- /// Computes the symbolic derivative as a transition regex
+ ///
+ /// Computes the symbolic derivative as a transition regex.
+ /// Transitions are in the tree left to right in the order the backtracking engine would explore them.
+ ///
internal TransitionRegex MkDerivative()
{
if (_transitionRegex is not null)
@@ -892,6 +1062,11 @@ internal TransitionRegex MkDerivative()
}
break;
+ case SymbolicRegexKind.OrderedOr:
+ Debug.Assert(_left is not null && _right is not null);
+ _transitionRegex = _left.MkDerivative() | _right.MkDerivative();
+ break;
+
case SymbolicRegexKind.And:
Debug.Assert(_alts is not null);
_transitionRegex = TransitionRegex.Leaf(_builder._anyStar);
@@ -913,6 +1088,384 @@ internal TransitionRegex MkDerivative()
return _transitionRegex;
}
+ // These are the cache for transition regexes with effects
+ private TransitionRegex? _transitionRegexWithEffectsEager;
+ private TransitionRegex? _transitionRegexWithEffectsAny;
+ private ref TransitionRegex? TransitionRegexWithEffects(bool eager) => ref eager ? ref _transitionRegexWithEffectsEager : ref _transitionRegexWithEffectsAny;
+
+ ///
+ /// Computes the symbolic derivative as a transition regex.
+ /// Transitions are in the tree left to right in the order the backtracking engine would explore them.
+ /// The transitions also include the effects (e.g. capture starts and ends) along their paths.
+ ///
+ /// whether to only include paths before the first time the backtracking matchers would hit nullability
+ /// the derivative as a TransitionRegex/>
+ internal TransitionRegex MkDerivativeWithEffects(bool eager)
+ {
+ // Get a reference to the correct variable to cache on based on eagerness
+ ref TransitionRegex? transition = ref TransitionRegexWithEffects(eager);
+ if (transition is not null)
+ {
+ return transition;
+ }
+
+ if (IsNothing || IsEpsilon)
+ {
+ transition = TransitionRegex.Leaf(_builder._nothing);
+ return transition;
+ }
+
+ if (IsAnyStar || IsAnyPlus)
+ {
+ transition = TransitionRegex.Leaf(_builder._anyStar);
+ return transition;
+ }
+
+ if (!StackHelper.TryEnsureSufficientExecutionStack())
+ {
+ return StackHelper.CallOnEmptyStack(MkDerivativeWithEffects, eager);
+ }
+
+ switch (_kind)
+ {
+ case SymbolicRegexKind.Singleton:
+ Debug.Assert(_set is not null);
+ transition = TransitionRegex.Conditional(_set, TransitionRegex.Leaf(_builder._epsilon), TransitionRegex.Leaf(_builder._nothing));
+ break;
+
+ case SymbolicRegexKind.Concat:
+ {
+ // The Concat case below explicitly handles cases where the left side is an alternation or a loop.
+ // This is required for properly maintaining transition ordering and handling eagerness.
+
+ Debug.Assert(_left is not null && _right is not null);
+
+ TransitionRegex leftTransition = _left.MkDerivativeWithEffects(eager).Concat(_right);
+ if (!_left.CanBeNullable)
+ {
+ // If the left side can't be nullable then the character must be consumed there
+ transition = leftTransition;
+ }
+ else if (_left._kind == SymbolicRegexKind.OrderedOr)
+ {
+ Debug.Assert(_left._left is not null && _left._right is not null);
+
+ // This pattern is for the path where the backtracking matcher would find the match from the first alternative
+ SymbolicRegexNode leftLeftPath = _builder.MkConcat(_left._left, _right);
+ // The eager derivative of that path will be used when the pattern is nullable, i.e., the backtracking matcher
+ // would end the match rather than go onto paths in the second alternative.
+ TransitionRegex leftLeftTransition = leftLeftPath.MkDerivativeWithEffects(eager);
+ // When the path through the first alternative is not nullable, this transition that includes all derivatives from
+ // it is used.
+ TransitionRegex orTransition = TransitionRegex.Union(leftLeftPath.MkDerivativeWithEffects(false),
+ _builder.MkConcat(_left._right, _right).MkDerivativeWithEffects(eager), ordered: true);
+
+ // Based on the nullability of the path thorugh the first alternative, select or construct the transition for when
+ // the left side of the concatenation is nullable.
+ TransitionRegex leftNullableTransition = eager && leftLeftPath.CanBeNullable ?
+ (leftLeftPath.IsNullable ?
+ leftLeftTransition :
+ TransitionRegex.Lookaround(leftLeftPath.ExtractNullabilityTest(),
+ leftLeftTransition,
+ orTransition)) :
+ orTransition;
+ // Select or construct the transition based on whether the left side is nullable
+ transition = _left.IsNullable ?
+ leftNullableTransition :
+ TransitionRegex.Lookaround(_left.ExtractNullabilityTest(),
+ leftNullableTransition,
+ leftTransition);
+ }
+ else
+ {
+ // The full derivative through the left side is used when the right side is not nullable or the derivative is not eager
+ TransitionRegex leftAnyTransition = _left.MkDerivativeWithEffects(false).Concat(_right);
+ // Select or construct the case where the left side consumes the character
+ TransitionRegex mainTransition = eager ?
+ (_right.CanBeNullable ?
+ (_right.IsNullable ?
+ leftTransition :
+ TransitionRegex.Lookaround(_right.ExtractNullabilityTest(),
+ leftTransition,
+ leftAnyTransition)) :
+ leftAnyTransition) :
+ leftAnyTransition;
+ // Construct the case where the right side consumes the character. Any effects from the left side are applied
+ TransitionRegex nullTransition = _left.WrapEffects(_right.MkDerivativeWithEffects(eager));
+ // Order the transitions. If the left side is a lazy loop that is nullable due to its lower bound then prefer the right side
+ TransitionRegex orTransition = _left._kind == SymbolicRegexKind.Loop && _left.IsLazy && _left._lower == 0 ?
+ TransitionRegex.Union(nullTransition, mainTransition, ordered: true) :
+ TransitionRegex.Union(mainTransition, nullTransition, ordered: true);
+
+ // Select or construct the transition based on whether the left side is nullable
+ transition = _left.IsNullable ?
+ orTransition :
+ TransitionRegex.Lookaround(_left.ExtractNullabilityTest(),
+ orTransition,
+ leftTransition);
+ }
+ break;
+ }
+
+ case SymbolicRegexKind.Loop:
+ // d(R*) = d(R+) = d(R)R*
+ Debug.Assert(_left is not null);
+ Debug.Assert(_upper > 0);
+
+ if (eager && IsLazy && _lower == 0)
+ {
+ // This is nothing because the backtracking matcher would prefer to exit the loop
+ transition = TransitionRegex.Leaf(_builder._nothing);
+ }
+ else
+ {
+ TransitionRegex step = _left.MkDerivativeWithEffects(eager);
+ if (IsStar || IsPlus)
+ {
+ transition = step.Concat(_builder.MkLoop(_left, IsLazy));
+ }
+ else
+ {
+ int newupper = _upper == int.MaxValue ? int.MaxValue : _upper - 1;
+ int newlower = _lower == 0 ? 0 : _lower - 1;
+ SymbolicRegexNode rest = _builder.MkLoop(_left, IsLazy, newlower, newupper);
+ transition = step.Concat(rest);
+ }
+ }
+ break;
+
+ case SymbolicRegexKind.OrderedOr:
+ {
+ Debug.Assert(_left is not null && _right is not null);
+ // The transition when the first alternative is nullable
+ TransitionRegex leftTransition = _left.MkDerivativeWithEffects(eager);
+ // The transition when the backtracking engines could continue to the second alternative
+ TransitionRegex orTransition = TransitionRegex.Union(_left.MkDerivativeWithEffects(false),
+ _right.MkDerivativeWithEffects(eager), ordered: true);
+ // Select or construct the transition based on whether the first alternative is nullable
+ transition = eager && _left.CanBeNullable ?
+ (_left.IsNullable ?
+ leftTransition :
+ TransitionRegex.Lookaround(_left.ExtractNullabilityTest(),
+ leftTransition,
+ orTransition)) :
+ orTransition;
+ break;
+ }
+
+ case SymbolicRegexKind.Or:
+ Debug.Assert(_alts is not null);
+ transition = TransitionRegex.Leaf(_builder._nothing);
+ foreach (SymbolicRegexNode elem in _alts)
+ {
+ transition = transition | elem.MkDerivativeWithEffects(eager);
+ }
+ break;
+
+ case SymbolicRegexKind.And:
+ Debug.Assert(_alts is not null);
+ transition = TransitionRegex.Leaf(_builder._anyStar);
+ foreach (SymbolicRegexNode elem in _alts)
+ {
+ transition = transition & elem.MkDerivativeWithEffects(eager);
+ }
+ break;
+
+ case SymbolicRegexKind.Not:
+ Debug.Assert(_left is not null);
+ transition = ~_left.MkDerivativeWithEffects(eager);
+ break;
+
+ default:
+ transition = TransitionRegex.Leaf(_builder._nothing);
+ break;
+ }
+ return transition;
+ }
+
+ ///
+ /// Wrap a TransitionRegex with the effects under this node. The effects are valid when this node is nullable.
+ ///
+ ///
+ /// The construction follows the paths that the backtracking matcher would take. For example in ()|() only the effects for the first
+ /// alternative will be included.
+ ///
+ internal TransitionRegex WrapEffects(TransitionRegex transition)
+ {
+ if (!StackHelper.TryEnsureSufficientExecutionStack())
+ {
+ return StackHelper.CallOnEmptyStack(WrapEffects, transition);
+ }
+
+ switch (_kind)
+ {
+ case SymbolicRegexKind.Concat:
+ Debug.Assert(_left is not null && _right is not null);
+ Debug.Assert(_left.CanBeNullable && _right.CanBeNullable);
+ transition = _left.WrapEffects(transition);
+ transition = _right.WrapEffects(transition);
+ break;
+
+ case SymbolicRegexKind.Loop:
+ Debug.Assert(_left is not null);
+ // Apply effect when backtracking engine would enter loop
+ if (_lower != 0)
+ {
+ Debug.Assert(_left.CanBeNullable);
+ transition = _left.WrapEffects(transition);
+ }
+ else if (_upper != 0 && !IsLazy && _left.CanBeNullable)
+ {
+ TransitionRegex bodyTransition = _left.WrapEffects(transition);
+ transition = _left.IsNullable ?
+ bodyTransition :
+ TransitionRegex.Lookaround(_left.ExtractNullabilityTest(),
+ bodyTransition,
+ transition);
+ }
+ break;
+
+ case SymbolicRegexKind.OrderedOr:
+ Debug.Assert(_left is not null && _right is not null);
+ if (!_left.CanBeNullable)
+ {
+ // Left can't be nullable so right must be visited
+ Debug.Assert(_right.CanBeNullable);
+ transition = _right.WrapEffects(transition);
+ }
+ else if (!_right.CanBeNullable)
+ {
+ // Right can't be nullable so left must be visited
+ Debug.Assert(_left.CanBeNullable);
+ transition = _left.WrapEffects(transition);
+ }
+ else
+ {
+ // Prefer left side if it is nullable, otherwise right side
+ TransitionRegex leftTransition = _left.WrapEffects(transition);
+ transition = _left.IsNullable ?
+ leftTransition :
+ TransitionRegex.Lookaround(_left.ExtractNullabilityTest(),
+ leftTransition,
+ _right.WrapEffects(transition));
+ }
+ break;
+
+ case SymbolicRegexKind.CaptureStart:
+ // Add the effect to record the capture start
+ transition = TransitionRegex.Effect(transition,
+ new DerivativeEffect(DerivativeEffect.EffectKind.CaptureStart, _lower));
+ break;
+
+ case SymbolicRegexKind.CaptureEnd:
+ // Add the effect to record the capture start
+ transition = TransitionRegex.Effect(transition,
+ new DerivativeEffect(DerivativeEffect.EffectKind.CaptureEnd, _lower));
+ break;
+
+ case SymbolicRegexKind.Or:
+ Debug.Assert(_alts is not null);
+ foreach (SymbolicRegexNode elem in _alts)
+ {
+ if (elem.CanBeNullable)
+ transition = elem.IsNullable ?
+ elem.WrapEffects(transition) :
+ TransitionRegex.Lookaround(elem.ExtractNullabilityTest(),
+ elem.WrapEffects(transition),
+ transition);
+ }
+ break;
+
+ case SymbolicRegexKind.And:
+ Debug.Assert(_alts is not null);
+ foreach (SymbolicRegexNode elem in _alts)
+ {
+ Debug.Assert(elem.CanBeNullable);
+ transition = elem.WrapEffects(transition);
+ }
+ break;
+ }
+ return transition;
+ }
+
+ ///
+ /// Find all effects under this node and supply them to the callback.
+ ///
+ ///
+ /// The construction is similar to WrapEffects.
+ ///
+ /// action called for each effect
+ /// the current context to determine nullability
+ internal void ApplyEffects(Action apply, uint context)
+ {
+ if (!StackHelper.TryEnsureSufficientExecutionStack())
+ {
+ StackHelper.CallOnEmptyStack(ApplyEffects, apply, context);
+ return;
+ }
+
+ switch (_kind)
+ {
+ case SymbolicRegexKind.Concat:
+ Debug.Assert(_left is not null && _right is not null);
+ Debug.Assert(_left.IsNullableFor(context) && _right.IsNullableFor(context));
+ _left.ApplyEffects(apply, context);
+ _right.ApplyEffects(apply, context);
+ break;
+
+ case SymbolicRegexKind.Loop:
+ Debug.Assert(_left is not null);
+ // Apply effect when backtracking engine would enter loop
+ if (_lower != 0 || (_upper != 0 && !IsLazy && _left.IsNullableFor(context)))
+ {
+ Debug.Assert(_left.IsNullableFor(context));
+ _left.ApplyEffects(apply, context);
+ }
+ break;
+
+ case SymbolicRegexKind.OrderedOr:
+ Debug.Assert(_left is not null && _right is not null);
+ if (_left.IsNullableFor(context))
+ {
+ // Prefer the left side
+ _left.ApplyEffects(apply, context);
+ }
+ else
+ {
+ // Otherwise right side must be nullable
+ Debug.Assert(_right.IsNullableFor(context));
+ _right.ApplyEffects(apply, context);
+ }
+ break;
+
+ case SymbolicRegexKind.CaptureStart:
+ apply(new DerivativeEffect(DerivativeEffect.EffectKind.CaptureStart, _lower));
+ break;
+
+ case SymbolicRegexKind.CaptureEnd:
+ apply(new DerivativeEffect(DerivativeEffect.EffectKind.CaptureEnd, _lower));
+ break;
+
+ case SymbolicRegexKind.Or:
+ Debug.Assert(_alts is not null);
+ foreach (SymbolicRegexNode elem in _alts)
+ {
+ if (elem.IsNullableFor(context))
+ elem.ApplyEffects(apply, context);
+ }
+ break;
+
+ case SymbolicRegexKind.And:
+ Debug.Assert(_alts is not null);
+ foreach (SymbolicRegexNode elem in _alts)
+ {
+ Debug.Assert(elem.IsNullableFor(context));
+ elem.ApplyEffects(apply, context);
+ }
+ break;
+ }
+ }
+
///
/// Computes the closure of MkDerivative, by exploring all the leaves
/// of the transition regex until no more new leaves are found.
@@ -962,6 +1515,9 @@ public SymbolicRegexNode ExtractNullabilityTest()
disjunction = _builder.MkOr(disjunction, elem.ExtractNullabilityTest());
}
return disjunction;
+ case SymbolicRegexKind.OrderedOr:
+ Debug.Assert(_left is not null && _right is not null);
+ return _builder.MkOrderedOr(_left.ExtractNullabilityTest(), _right.ExtractNullabilityTest());
case SymbolicRegexKind.And:
Debug.Assert(_alts is not null);
SymbolicRegexNode conjunction = _builder._anyStar;
@@ -1002,6 +1558,8 @@ private int ComputeHashCode()
return HashCode.Combine(_kind, _info);
case SymbolicRegexKind.WatchDog:
+ case SymbolicRegexKind.CaptureStart:
+ case SymbolicRegexKind.CaptureEnd:
return HashCode.Combine(_kind, _lower);
case SymbolicRegexKind.Loop:
@@ -1011,6 +1569,7 @@ private int ComputeHashCode()
return HashCode.Combine(_kind, _alts, _info);
case SymbolicRegexKind.Concat:
+ case SymbolicRegexKind.OrderedOr:
return HashCode.Combine(_left, _right, _info);
case SymbolicRegexKind.Singleton:
@@ -1133,6 +1692,13 @@ internal void ToString(StringBuilder sb)
_alts.ToString(sb);
return;
+ case SymbolicRegexKind.OrderedOr:
+ Debug.Assert(_left is not null && _right is not null);
+ _left.ToString(sb);
+ sb.Append('|');
+ _right.ToString(sb);
+ return;
+
case SymbolicRegexKind.Concat:
Debug.Assert(_left is not null && _right is not null);
_left.ToString(sb);
@@ -1208,6 +1774,14 @@ internal void ToString(StringBuilder sb)
}
return;
+ case SymbolicRegexKind.CaptureStart:
+ sb.Append('('); // The group number may be wrong
+ return;
+
+ case SymbolicRegexKind.CaptureEnd:
+ sb.Append(')');
+ return;
+
default:
// Using the operator ~ for complement
Debug.Assert(_kind == SymbolicRegexKind.Not);
@@ -1254,6 +1828,8 @@ private void CollectPredicates_helper(HashSet predicates)
case SymbolicRegexKind.EndAnchor:
case SymbolicRegexKind.Epsilon:
case SymbolicRegexKind.WatchDog:
+ case SymbolicRegexKind.CaptureStart:
+ case SymbolicRegexKind.CaptureEnd:
return;
case SymbolicRegexKind.Singleton:
@@ -1275,6 +1851,12 @@ private void CollectPredicates_helper(HashSet predicates)
}
return;
+ case SymbolicRegexKind.OrderedOr:
+ Debug.Assert(_left is not null && _right is not null);
+ _left.CollectPredicates_helper(predicates);
+ _right.CollectPredicates_helper(predicates);
+ return;
+
case SymbolicRegexKind.Concat:
// avoid deep nested recursion over long concat nodes
SymbolicRegexNode conc = this;
@@ -1354,6 +1936,10 @@ public SymbolicRegexNode Reverse()
Debug.Assert(_alts is not null);
return _builder.MkOr(_alts.Reverse());
+ case SymbolicRegexKind.OrderedOr:
+ Debug.Assert(_left is not null && _right is not null);
+ return _builder.MkOrderedOr(_left.Reverse(), _right.Reverse());
+
case SymbolicRegexKind.And:
Debug.Assert(_alts is not null);
return _builder.MkAnd(_alts.Reverse());
@@ -1389,6 +1975,12 @@ public SymbolicRegexNode Reverse()
// Thus, this case is unreachable here, but included for completeness.
return _builder._endAnchorZ;
+ case SymbolicRegexKind.CaptureStart:
+ return MkCaptureEnd(_builder, _lower);
+
+ case SymbolicRegexKind.CaptureEnd:
+ return MkCaptureStart(_builder, _lower);
+
default:
// Remaining cases map to themselves:
// SymbolicRegexKind.Epsilon
@@ -1399,6 +1991,83 @@ public SymbolicRegexNode Reverse()
}
}
+ ///
+ /// Transform OrderdOr to Or nodes and any lazy loops to eager ones.
+ ///
+ ///
+ /// This transformation allows the second reverse pass to use the same derivative function as the third pass,
+ /// which must respect the backtracking engines alternation and lazyness semantics.
+ ///
+ public SymbolicRegexNode IgnoreOrOrderAndLazyness()
+ {
+ // Guard against stack overflow due to deep recursion
+ if (!StackHelper.TryEnsureSufficientExecutionStack())
+ {
+ return StackHelper.CallOnEmptyStack(IgnoreOrOrderAndLazyness);
+ }
+
+ switch (_kind)
+ {
+ case SymbolicRegexKind.Loop:
+ {
+ Debug.Assert(_left is not null);
+ SymbolicRegexNode body = _left.IgnoreOrOrderAndLazyness();
+ return body == _left && !IsLazy?
+ this :
+ MkLoop(_builder, body, _lower, _upper, isLazy: false);
+ }
+
+ case SymbolicRegexKind.Concat:
+ {
+ Debug.Assert(_left is not null && _right is not null);
+ SymbolicRegexNode left1 = _left.IgnoreOrOrderAndLazyness();
+ SymbolicRegexNode right1 = _right.IgnoreOrOrderAndLazyness();
+
+ Debug.Assert(left1 is not null && right1 is not null);
+ return left1 == _left && right1 == _right ?
+ this :
+ MkConcat(_builder, left1, right1);
+ }
+
+ case SymbolicRegexKind.Or:
+ case SymbolicRegexKind.And:
+ {
+ Debug.Assert(_alts != null);
+ var elements = new SymbolicRegexNode[_alts.Count];
+ int i = 0;
+ bool someChanged = false;
+ foreach (SymbolicRegexNode alt in _alts)
+ {
+ elements[i] = alt.IgnoreOrOrderAndLazyness();
+ someChanged |= alt != elements[i];
+ i += 1;
+ }
+ Debug.Assert(i == elements.Length);
+ return !someChanged ? this :
+ _kind == SymbolicRegexKind.Or ? MkOr(_builder, elements) :
+ MkAnd(_builder, elements);
+ }
+
+ case SymbolicRegexKind.Not:
+ {
+ Debug.Assert(_left is not null);
+ SymbolicRegexNode body = _left.IgnoreOrOrderAndLazyness();
+ return body == _left ?
+ this :
+ MkNot(_builder, body);
+ }
+
+ case SymbolicRegexKind.OrderedOr:
+ {
+ Debug.Assert(_left is not null && _right is not null);
+ return MkOr(_builder, _left.IgnoreOrOrderAndLazyness(), _right.IgnoreOrOrderAndLazyness());
+ }
+
+ default:
+ return this;
+ }
+ }
+
internal bool StartsWithLoop(int upperBoundLowestValue = 1)
{
if (!StackHelper.TryEnsureSufficientExecutionStack())
@@ -1419,6 +2088,10 @@ internal bool StartsWithLoop(int upperBoundLowestValue = 1)
Debug.Assert(_alts is not null);
return _alts.StartsWithLoop(upperBoundLowestValue);
+ case SymbolicRegexKind.OrderedOr:
+ Debug.Assert(_left is not null && _right is not null);
+ return _left.StartsWithLoop(upperBoundLowestValue) || _right.StartsWithLoop(upperBoundLowestValue);
+
default:
return false;
};
@@ -1444,6 +2117,8 @@ private S ComputeStartSet()
case SymbolicRegexKind.EndAnchorZ:
case SymbolicRegexKind.EndAnchorZRev:
case SymbolicRegexKind.BOLAnchor:
+ case SymbolicRegexKind.CaptureStart:
+ case SymbolicRegexKind.CaptureEnd:
return _builder._solver.False;
case SymbolicRegexKind.Singleton:
@@ -1472,6 +2147,12 @@ private S ComputeStartSet()
return startSet;
}
+ case SymbolicRegexKind.OrderedOr:
+ {
+ Debug.Assert(_left is not null && _right is not null);
+ return _builder._solver.Or(_left._startSet, _right._startSet);
+ }
+
case SymbolicRegexKind.And:
{
Debug.Assert(_alts is not null);
@@ -1545,14 +2226,16 @@ internal SymbolicRegexNode PruneAnchors(uint prevKind, bool contWithWL, bool
MkLoop(_builder, body, _lower, _upper, IsLazy);
case SymbolicRegexKind.Concat:
- Debug.Assert(_left is not null && _right is not null);
- SymbolicRegexNode left1 = _left.PruneAnchors(prevKind, contWithWL, contWithNWL);
- SymbolicRegexNode right1 = _left.IsNullable ? _right.PruneAnchors(prevKind, contWithWL, contWithNWL) : _right;
+ {
+ Debug.Assert(_left is not null && _right is not null);
+ SymbolicRegexNode left1 = _left.PruneAnchors(prevKind, contWithWL, contWithNWL);
+ SymbolicRegexNode right1 = _left.IsNullable ? _right.PruneAnchors(prevKind, contWithWL, contWithNWL) : _right;
- Debug.Assert(left1 is not null && right1 is not null);
- return left1 == _left && right1 == _right ?
- this :
- MkConcat(_builder, left1, right1);
+ Debug.Assert(left1 is not null && right1 is not null);
+ return left1 == _left && right1 == _right ?
+ this :
+ MkConcat(_builder, left1, right1);
+ }
case SymbolicRegexKind.Or:
{
@@ -1567,6 +2250,18 @@ internal SymbolicRegexNode PruneAnchors(uint prevKind, bool contWithWL, bool
return MkOr(_builder, elements);
}
+ case SymbolicRegexKind.OrderedOr:
+ {
+ Debug.Assert(_left is not null && _right is not null);
+ SymbolicRegexNode left1 = _left.PruneAnchors(prevKind, contWithWL, contWithNWL);
+ SymbolicRegexNode right1 = _right.PruneAnchors(prevKind, contWithWL, contWithNWL);
+
+ Debug.Assert(left1 is not null && right1 is not null);
+ return left1 == _left && right1 == _right ?
+ this :
+ MkOrderedOr(_builder, left1, right1);
+ }
+
default:
return this;
}
diff --git a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Symbolic/SymbolicRegexRunnerFactory.cs b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Symbolic/SymbolicRegexRunnerFactory.cs
index 780a2e7184d246..1abe7f9916077b 100644
--- a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Symbolic/SymbolicRegexRunnerFactory.cs
+++ b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Symbolic/SymbolicRegexRunnerFactory.cs
@@ -1,6 +1,8 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
+using System.Collections;
+using System.Diagnostics;
using System.Globalization;
using System.Text.RegularExpressions.Symbolic.Unicode;
@@ -26,7 +28,7 @@ public SymbolicRegexRunnerFactory(RegexCode code, RegexOptions options, TimeSpan
(options & RegexOptions.RightToLeft) != 0 ? nameof(RegexOptions.RightToLeft) : nameof(RegexOptions.ECMAScript)));
}
- var converter = new RegexNodeToSymbolicConverter(s_unicode, culture);
+ var converter = new RegexNodeToSymbolicConverter(s_unicode, culture, code.Caps);
var solver = (CharSetSolver)s_unicode._solver;
SymbolicRegexNode root = converter.Convert(code.Tree.Root, topLevel: true);
@@ -80,8 +82,14 @@ private sealed class Runner : RegexRunner where TSetType : notnull
{
/// The matching engine.
private readonly SymbolicRegexMatcher _matcher;
+ /// Per thread data available to the matching engine.
+ private readonly SymbolicRegexMatcher.PerThreadData _perThreadData;
- internal Runner(SymbolicRegexMatcher matcher) => _matcher = matcher;
+ internal Runner(SymbolicRegexMatcher matcher)
+ {
+ _matcher = matcher;
+ _perThreadData = _matcher.CreatePerThreadData();
+ }
protected override void InitTrackCount() { } // nop, no backtracking
@@ -93,7 +101,7 @@ protected override void Go()
ReadOnlySpan inputSpan = runtext.AsSpan(beginning, runtextend - beginning);
// Perform the match.
- SymbolicMatch pos = _matcher.FindMatch(quick, inputSpan, runtextpos - beginning);
+ SymbolicMatch pos = _matcher.FindMatch(quick, inputSpan, runtextpos - beginning, _perThreadData);
// Transfer the result back to the RegexRunner state.
if (pos.Success)
@@ -101,7 +109,23 @@ protected override void Go()
// If we successfully matched, capture the match, and then jump the current position to the end of the match.
int start = pos.Index + beginning;
int end = start + pos.Length;
- Capture(0, start, end);
+ if (!quick && pos.CaptureStarts != null)
+ {
+ Debug.Assert(pos.CaptureEnds != null);
+ Debug.Assert(pos.CaptureStarts.Length == pos.CaptureEnds.Length);
+ for (int cap = 0; cap < pos.CaptureStarts.Length; ++cap)
+ {
+ if (pos.CaptureStarts[cap] >= 0)
+ {
+ Debug.Assert(pos.CaptureEnds[cap] >= pos.CaptureStarts[cap]);
+ Capture(cap, pos.CaptureStarts[cap] + beginning, pos.CaptureEnds[cap] + beginning);
+ }
+ }
+ }
+ else
+ {
+ Capture(0, start, end);
+ }
runtextpos = end;
}
else
diff --git a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Symbolic/TransitionRegex.cs b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Symbolic/TransitionRegex.cs
index 5c3ccc6e3226f8..a1d04babed381c 100644
--- a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Symbolic/TransitionRegex.cs
+++ b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Symbolic/TransitionRegex.cs
@@ -18,6 +18,7 @@ internal class TransitionRegex : IEnumerable<(S, SymbolicRegexNode?, Symbo
public readonly TransitionRegex? _first;
public readonly TransitionRegex? _second;
public readonly SymbolicRegexNode? _node;
+ public readonly DerivativeEffect? _effect;
private readonly int _hashCode;
@@ -47,31 +48,34 @@ public bool IsAnyStar
}
}
- private TransitionRegex(SymbolicRegexBuilder builder, TransitionRegexKind kind, S? test, TransitionRegex? first, TransitionRegex? second, SymbolicRegexNode? node)
+ private TransitionRegex(SymbolicRegexBuilder builder, TransitionRegexKind kind, S? test, TransitionRegex? first, TransitionRegex? second, SymbolicRegexNode