From 21d2cd0fb7d9747e86c5e3df3c3d7371d98eb3b9 Mon Sep 17 00:00:00 2001 From: Olli Saarikivi Date: Tue, 7 Dec 2021 10:31:37 -0800 Subject: [PATCH 01/29] Initial version of captures in NonBacktracking --- .../src/System.Text.RegularExpressions.csproj | 1 + .../System/Text/RegularExpressions/Regex.cs | 2 +- .../Symbolic/DerivativeEffect.cs | 23 +++ .../Symbolic/DfaMatchingState.cs | 43 ++++ .../Symbolic/RegexNodeToSymbolicConverter.cs | 2 +- .../Symbolic/SymbolicMatch.cs | 6 +- .../Symbolic/SymbolicRegexBuilder.cs | 8 +- .../Symbolic/SymbolicRegexKind.cs | 2 + .../Symbolic/SymbolicRegexMatcher.cs | 185 +++++++++++++++++- .../Symbolic/SymbolicRegexNode.cs | 24 +++ .../Symbolic/SymbolicRegexRunnerFactory.cs | 20 +- .../Symbolic/TransitionRegex.cs | 96 ++++++++- .../Symbolic/TransitionRegexKind.cs | 3 +- 13 files changed, 393 insertions(+), 22 deletions(-) create mode 100644 src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Symbolic/DerivativeEffect.cs 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..3c4a90d6e8ed78 100644 --- a/src/libraries/System.Text.RegularExpressions/src/System.Text.RegularExpressions.csproj +++ b/src/libraries/System.Text.RegularExpressions/src/System.Text.RegularExpressions.csproj @@ -7,6 +7,7 @@ + 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..9ee7bc02862ea7 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 @@ -77,7 +77,7 @@ internal Regex(string pattern, RegexOptions options, TimeSpan matchTimeout, Cult if ((options & RegexOptions.NonBacktracking) != 0) { // If we're in non-backtracking mode, create the appropriate factory. - factory = new SymbolicRegexRunnerFactory(_code, options, matchTimeout, culture); + factory = new SymbolicRegexRunnerFactory(_code, options, matchTimeout, culture, capsize); _code = null; } else if (RuntimeFeature.IsDynamicCodeCompiled && UseOptionC()) 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..2f3092823a9c53 --- /dev/null +++ b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Symbolic/DerivativeEffect.cs @@ -0,0 +1,23 @@ +// 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 +{ + internal struct DerivativeEffect + { + public enum EffectKind + { + CaptureStart, + CaptureEnd, + }; + + public EffectKind Kind; + public int IntArg0; + + public DerivativeEffect(EffectKind kind, int intArg0) + { + Kind = kind; + IntArg0 = intArg0; + } + } +} 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..bf4efae1eee4ee 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 { @@ -98,6 +99,48 @@ internal DfaMatchingState Next(T minterm) return Node._builder.MkState(derivative, nextCharKind); } + internal IEnumerable<(DfaMatchingState, List)> AntimirovNextWithEffects(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; + if (alg.False.Equals(minterm)) + { + nextCharKind = CharKind.NewLineS; + minterm = newLinePredicate; + } + else if (newLinePredicate.Equals(minterm)) + { + // If the previous state was the start state, mark this as the very FIRST \n. + // Essentially, this looks the same as the very last \n and is used to nullify + // rev(\Z) in the conext of a reversed automaton. + nextCharKind = PrevCharKind == CharKind.StartStop ? + CharKind.NewLineS : + CharKind.Newline; + } + else if (alg.IsSatisfiable(alg.And(wordLetterPredicate, minterm))) + { + nextCharKind = CharKind.WordLetter; + } + + // Combined character context + uint context = CharKind.Context(PrevCharKind, nextCharKind); + + // Compute the derivative of the node for the given context + IEnumerable<(SymbolicRegexNode, List)> derivativesAndEffects = Node.MkDerivative().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..56c0f578dd3f4d 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 @@ -231,7 +231,7 @@ 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 (...) + return _builder.MkCapture(Convert(node.Child(0), topLevel: false), node.M); case RegexNodeKind.Concatenate: { 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..17a36a3af5887e 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; } @@ -24,6 +26,8 @@ public SymbolicMatch(int index, int length) public int Length { get; } public bool Success => Index >= 0; + public readonly int[]? CaptureStarts; + 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/SymbolicRegexBuilder.cs b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Symbolic/SymbolicRegexBuilder.cs index 1fec095c54b105..f09fb12a9654a0 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 @@ -294,6 +297,8 @@ internal SymbolicRegexNode MkSequence(TElement[] seq, bool topLevel) /// internal SymbolicRegexNode MkNot(SymbolicRegexNode node) => SymbolicRegexNode.MkNot(this, node); + internal SymbolicRegexNode MkCapture(SymbolicRegexNode child, int captureNum) => MkConcat(SymbolicRegexNode.MkCaptureStart(this, captureNum), MkConcat(child, SymbolicRegexNode.MkCaptureEnd(this, captureNum))); + internal SymbolicRegexNode Transform(SymbolicRegexNode sr, SymbolicRegexBuilder builderT, Func predicateTransformer) where T : notnull { if (!StackHelper.TryEnsureSufficientExecutionStack()) @@ -414,6 +419,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/SymbolicRegexKind.cs b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Symbolic/SymbolicRegexKind.cs index f012d0559e9e8a..54517f1f768f90 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,7 @@ 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, } } 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..06bf7e1094c6fe 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,8 @@ internal sealed class SymbolicRegexMatcher : ISymbolicRegexMatcher whe /// Non-null iff the pattern contains anchors; otherwise, it's unused. private readonly uint[]? _asciiCharKinds; + private readonly int _capsize; + /// Get the minterm of . /// character code [MethodImpl(MethodImplOptions.AggressiveInlining)] @@ -148,7 +150,7 @@ private TSetType GetMinterm(int c) } /// Constructs matcher for given symbolic regex. - internal SymbolicRegexMatcher(SymbolicRegexNode sr, RegexCode code, CharSetSolver css, BDD[] minterms, TimeSpan matchTimeout, CultureInfo culture) + internal SymbolicRegexMatcher(SymbolicRegexNode sr, RegexCode code, CharSetSolver css, BDD[] minterms, TimeSpan matchTimeout, CultureInfo culture, int capsize) { Debug.Assert(sr._builder._solver is BV64Algebra or BVAlgebra or CharSetSolver, $"Unsupported algebra: {sr._builder._solver}"); @@ -162,6 +164,7 @@ internal SymbolicRegexMatcher(SymbolicRegexNode sr, RegexCode code, Ch BVAlgebra bv => bv._classifier, _ => new MintermClassifier((CharSetSolver)(object)_builder._solver, minterms), }; + _capsize = 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. @@ -265,6 +268,73 @@ private DfaMatchingState Delta(ReadOnlySpan input, return default(TTransition).TakeTransition(this, sourceState, mintermId, minterm); } + private struct Registers + { + public int[] captureStarts; + public int[] captureEnds; + + public void ApplyEffects(List effects, int i) + { + foreach (DerivativeEffect effect in effects) + { + switch (effect.Kind) + { + case DerivativeEffect.EffectKind.CaptureStart: + captureStarts[effect.IntArg0] = i; + break; + case DerivativeEffect.EffectKind.CaptureEnd: + captureEnds[effect.IntArg0] = i; + break; + } + } + } + + public Registers Clone() => new Registers + { + captureStarts = (int[])captureStarts.Clone(), + captureEnds = (int[])captureEnds.Clone(), + }; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void CapturingDelta(string input, int i, Dictionary, Registers> sourceStates, Dictionary, Registers> targetStates) + { + Debug.Assert(targetStates.Count == 0); + + TSetType[]? minterms = _builder._minterms; + Debug.Assert(minterms is not null); + + int c = input[i]; + + foreach (var (sourceState, sourceRegisters) in sourceStates) + { + int mintermId = c == '\n' && i == input.Length - 1 && sourceState.StartsWithLineAnchor ? + minterms.Length : // mintermId = minterms.Length represents \Z (last \n) + _partitions.GetMintermID(c); + + TSetType minterm = (uint)mintermId < (uint)minterms.Length ? + minterms[mintermId] : + _builder._solver.False; // minterm=False represents \Z + + int offset = (sourceState.Id << _builder._mintermsCount) | mintermId; + Debug.Assert(_builder._capturingDelta is not null); + var transitions = Volatile.Read(ref _builder._capturingDelta[offset]) ?? CreateNewCapturingTransitions(sourceState, minterm, offset); + + foreach (var (targetState, effects) in transitions) { + if (!targetStates.TryGetValue(targetState, out Registers existingRegisters)) + { + // TODO: choose intelligently between registers + } + else + { + Registers newRegisters = sourceRegisters.Clone(); // TODO: avoid this the last time + newRegisters.ApplyEffects(effects, i); + targetStates.Add(targetState, newRegisters); + } + } + } + } + /// Transition for Brzozowski-style derivatives (i.e. a DFA). private readonly struct BrzozowskiTransition : ITransition { @@ -343,6 +413,23 @@ 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 + _builder._capturingDelta[offset] = p = new List<(DfaMatchingState, List)>(state.AntimirovNextWithEffects(minterm)); + } + + return p; + } + } + private void DoCheckTimeout(int timeoutOccursAt) { // This logic is identical to RegexRunner.DoCheckTimeout, with the exception of check skipping. RegexRunner calls @@ -398,12 +485,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,10 +495,26 @@ 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); + int i_end; + if (_capsize == 0) + { + if (watchdog >= 0) + { + i_end = i; + } + else + { + i_end = FindEndPosition(input, end, i_start); + } + return new SymbolicMatch(i_start, i_end + 1 - i_start); + } + else + { + i_end = FindEndPositionCapturing(input, end, i_start, out Registers endRegisters); + 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. @@ -491,6 +591,79 @@ private bool FindEndPositionDeltas(ReadOnlySpan input, ref in return false; } + private int FindEndPositionCapturing(string input, int exclusiveEnd, int i, out Registers endRegisters) + { + int i_end = exclusiveEnd; + + // Pick the correct start state based on previous character kind. + uint prevCharKind = GetCharKind(input, i - 1); + DfaMatchingState state = _initialStates[prevCharKind]; + Registers initialRegisters = new Registers + { + captureStarts = new int[_capsize], + captureEnds = new int[_capsize], + }; + 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; + + // Stop here if q is lazy. + if (state.IsLazy) + { + endRegisters = initialRegisters; + return i_end; + } + } + + Dictionary, Registers> current = new(), next = new(); + current.Add(state, initialRegisters); + + while (i < exclusiveEnd) + { + CapturingDelta(input, i, current, next); + var tmp = current; + current = next; + next = tmp; + next.Clear(); + + foreach (var (q, registers) in current) + { + if (q.IsNullable(GetCharKind(input, i + 1))) + { + // Accepting state has been reached. Record the position. + i_end = i; + + // Stop here if q is lazy. + if (q.IsLazy) + { + endRegisters = registers; + Debug.Assert(i_end != exclusiveEnd); + return i_end; + } + } + else if (q.IsDeadend) + { + // Non-accepting sink state (deadend) has been reached in the original pattern. + // So the match ended when the last i_end was updated. + endRegisters = registers; + Debug.Assert(i_end != exclusiveEnd); + return i_end; + } + } + + i++; + } + + // This should never happen, as a final state is already known to exist. + Debug.Assert(false); + endRegisters = default(Registers); + 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..eb64f8cf618273 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 @@ -436,6 +436,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()); + + internal static SymbolicRegexNode MkCaptureEnd(SymbolicRegexBuilder builder, int captureNum) => + Create(builder, SymbolicRegexKind.CaptureEnd, null, null, captureNum, -1, default, null, SymbolicRegexInfo.Mk()); + private static SymbolicRegexNode MkCollection(SymbolicRegexBuilder builder, SymbolicRegexKind kind, SymbolicRegexSet alts, SymbolicRegexInfo info) => alts.IsNothing ? builder._nothing : alts.IsEverything ? builder._anyStar : @@ -799,6 +805,14 @@ internal SymbolicRegexNode MkDerivative(S elem, uint context) #endregion } + case SymbolicRegexKind.CaptureStart: + case SymbolicRegexKind.CaptureEnd: + { + // Capture nodes are no-ops here since there's nothing to record their effect into + deriv = _builder._epsilon; + break; + } + default: deriv = _builder._nothing; break; @@ -906,6 +920,16 @@ internal TransitionRegex MkDerivative() _transitionRegex = ~_left.MkDerivative(); break; + case SymbolicRegexKind.CaptureStart: + _transitionRegex = TransitionRegex.Effect(TransitionRegex.Leaf(_builder._epsilon), + new DerivativeEffect(DerivativeEffect.EffectKind.CaptureStart, _lower)); + break; + + case SymbolicRegexKind.CaptureEnd: + _transitionRegex = TransitionRegex.Effect(TransitionRegex.Leaf(_builder._epsilon), + new DerivativeEffect(DerivativeEffect.EffectKind.CaptureEnd, _lower)); + break; + default: _transitionRegex = TransitionRegex.Leaf(_builder._nothing); break; 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..405469085ae4cd 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,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.Diagnostics; using System.Globalization; using System.Text.RegularExpressions.Symbolic.Unicode; @@ -16,7 +17,7 @@ internal sealed class SymbolicRegexRunnerFactory : RegexRunnerFactory internal readonly ISymbolicRegexMatcher _matcher; /// Initializes the factory. - public SymbolicRegexRunnerFactory(RegexCode code, RegexOptions options, TimeSpan matchTimeout, CultureInfo culture) + public SymbolicRegexRunnerFactory(RegexCode code, RegexOptions options, TimeSpan matchTimeout, CultureInfo culture, int capsize) { // RightToLeft and ECMAScript are currently not supported in conjunction with NonBacktracking. if ((options & (RegexOptions.RightToLeft | RegexOptions.ECMAScript)) != 0) @@ -45,7 +46,7 @@ public SymbolicRegexRunnerFactory(RegexCode code, RegexOptions options, TimeSpan // Convert the BDD-based AST to BV-based AST SymbolicRegexNode rootBV = converter._builder.Transform(root, builderBV, bdd => builderBV._solver.ConvertFromCharSet(solver, bdd)); - _matcher = new SymbolicRegexMatcher(rootBV, code, solver, minterms, matchTimeout, culture); + _matcher = new SymbolicRegexMatcher(rootBV, code, solver, minterms, matchTimeout, culture, capsize); } else { @@ -61,7 +62,7 @@ public SymbolicRegexRunnerFactory(RegexCode code, RegexOptions options, TimeSpan // Convert the BDD-based AST to ulong-based AST SymbolicRegexNode root64 = converter._builder.Transform(root, builder64, bdd => builder64._solver.ConvertFromCharSet(solver, bdd)); - _matcher = new SymbolicRegexMatcher(root64, code, solver, minterms, matchTimeout, culture); + _matcher = new SymbolicRegexMatcher(root64, code, solver, minterms, matchTimeout, culture, capsize); } } @@ -103,6 +104,19 @@ protected override void Go() int end = start + pos.Length; Capture(0, start, end); runtextpos = end; + if (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] >= 0); + runmatch!.AddMatch(cap, pos.CaptureStarts[cap], pos.CaptureEnds[cap]); + } + } + } } 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..f7d56dd2edb0f4 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,33 @@ 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? node, DerivativeEffect? effect) { Debug.Assert(builder is not null); Debug.Assert( - kind is TransitionRegexKind.Leaf && node is not null && Equals(test, default(S)) && first is null && second is null || - kind is TransitionRegexKind.Conditional && test is not null && first is not null && second is not null && node is null || - kind is TransitionRegexKind.Union && Equals(test, default(S)) && first is not null && second is not null && node is null || - kind is TransitionRegexKind.Lookaround && Equals(test, default(S)) && first is not null && second is not null && node is not null); + kind is TransitionRegexKind.Leaf && node is not null && Equals(test, default(S)) && first is null && second is null && effect is null || + kind is TransitionRegexKind.Conditional && test is not null && first is not null && second is not null && node is null && effect is null || + kind is TransitionRegexKind.Union && Equals(test, default(S)) && first is not null && second is not null && node is null && effect is null || + kind is TransitionRegexKind.Lookaround && Equals(test, default(S)) && first is not null && second is not null && node is not null && effect is null || + kind is TransitionRegexKind.Effect && Equals(test, default(S)) && first is not null && second is null && node is null && effect is not null); _builder = builder; _kind = kind; _test = test; _first = first; _second = second; _node = node; + _effect = effect; _hashCode = HashCode.Combine(kind, test, first, second, node); } - private static TransitionRegex Create(SymbolicRegexBuilder builder, TransitionRegexKind kind, S? test, TransitionRegex? one, TransitionRegex? two, SymbolicRegexNode? node) + private static TransitionRegex Create(SymbolicRegexBuilder builder, TransitionRegexKind kind, S? test, TransitionRegex? one, TransitionRegex? two, SymbolicRegexNode? node, DerivativeEffect? effect = null) { // Keep transition regexes internalized using the builder - (TransitionRegexKind, S?, TransitionRegex?, TransitionRegex?, SymbolicRegexNode?) key = (kind, test, one, two, node); + (TransitionRegexKind, S?, TransitionRegex?, TransitionRegex?, SymbolicRegexNode?, DerivativeEffect?) key = (kind, test, one, two, node, effect); TransitionRegex? tr; if (!builder._trCache.TryGetValue(key, out tr)) { - tr = new TransitionRegex(builder, kind, test, one, two, node); + tr = new TransitionRegex(builder, kind, test, one, two, node, effect); builder._trCache[key] = tr; } return tr; @@ -271,6 +274,9 @@ public static TransitionRegex Conditional(S test, TransitionRegex thencase public static TransitionRegex Lookaround(SymbolicRegexNode nullabilityTest, TransitionRegex thencase, TransitionRegex elsecase) => (thencase == elsecase) ? thencase : Create(thencase._builder, TransitionRegexKind.Lookaround, default(S), thencase, elsecase, nullabilityTest); + public static TransitionRegex Effect(TransitionRegex child, DerivativeEffect effect) => + Create(child._builder, TransitionRegexKind.Effect, default(S), child, null, null, effect); + /// Intersection of transition regexes public static TransitionRegex operator &(TransitionRegex one, TransitionRegex two) => Intersect(one, two); @@ -431,6 +437,12 @@ public SymbolicRegexNode Transition(S minterm, uint context) todo.Push(top._first); break; + case TransitionRegexKind.Effect: + // Effects are ignored here + Debug.Assert(top._first is not null && top._effect is not null); + todo.Push(top._first); + break; + default: Debug.Assert(top._kind is TransitionRegexKind.Lookaround && top._node is not null && top._first is not null && top._second is not null); // Branch according to the result of nullability @@ -453,5 +465,73 @@ public SymbolicRegexNode Transition(S minterm, uint context) } return target; } + + public IEnumerable<(SymbolicRegexNode, List)> TransitionsWithEffects(S minterm, uint context) + { + // Collect the union of all target leaves + Stack<(TransitionRegex, List)> todo = new(); + todo.Push((this, new List())); + while (todo.Count > 0) + { + (TransitionRegex top, List effects) = todo.Pop(); + switch (top._kind) + { + case TransitionRegexKind.Leaf: + Debug.Assert(top._node is not null); + yield return (top._node, effects); + break; + + case TransitionRegexKind.Conditional: + Debug.Assert(top._test is not null && top._first is not null && top._second is not null); + if (_builder._solver.IsSatisfiable(_builder._solver.And(minterm, top._test))) + { + if (!top._first.IsNothing) + { + todo.Push((top._first, new List(effects))); + } + } + else + { + if (!top._second.IsNothing) + { + todo.Push((top._second, effects)); + } + } + break; + + case TransitionRegexKind.Union: + // Observe that without Union Transition returns excatly one of the leaves + Debug.Assert(top._first is not null && top._second is not null); + todo.Push((top._second, new List(effects))); + todo.Push((top._first, effects)); + break; + + case TransitionRegexKind.Effect: + Debug.Assert(top._first is not null && top._effect is not null); + effects.Add((DerivativeEffect)top._effect); + todo.Push((top._first, effects)); + break; + + default: + Debug.Assert(top._kind is TransitionRegexKind.Lookaround && top._node is not null && top._first is not null && top._second is not null); + // Branch according to the result of nullability + if (top._node.IsNullableFor(context)) + { + if (!top._first.IsNothing) + { + todo.Push((top._first, new List(effects))); + } + } + else + { + if (!top._second.IsNothing) + { + todo.Push((top._second, effects)); + } + } + break; + } + } + } } } diff --git a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Symbolic/TransitionRegexKind.cs b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Symbolic/TransitionRegexKind.cs index 6be3c169a94093..c46c858bc2fa02 100644 --- a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Symbolic/TransitionRegexKind.cs +++ b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Symbolic/TransitionRegexKind.cs @@ -9,6 +9,7 @@ internal enum TransitionRegexKind Leaf, Conditional, Union, - Lookaround + Lookaround, + Effect } } From 998321ff072333ae3c08250f67aa4f3ad75e1899 Mon Sep 17 00:00:00 2001 From: Olli Saarikivi Date: Wed, 8 Dec 2021 13:41:01 -0800 Subject: [PATCH 02/29] Working version of captures in NonBacktracking --- .../System/Text/RegularExpressions/Regex.cs | 19 +--- .../Symbolic/RegexNodeToSymbolicConverter.cs | 46 +------- .../Symbolic/SymbolicRegexBuilder.cs | 12 +- .../Symbolic/SymbolicRegexMatcher.cs | 40 ++++--- .../Symbolic/SymbolicRegexNode.cs | 106 ++++++++++++++---- .../Symbolic/SymbolicRegexRunnerFactory.cs | 9 +- .../Symbolic/TransitionRegex.cs | 11 ++ 7 files changed, 146 insertions(+), 97 deletions(-) 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 9ee7bc02862ea7..6b795e9681bb40 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/Symbolic/RegexNodeToSymbolicConverter.cs b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Symbolic/RegexNodeToSymbolicConverter.cs index 56c0f578dd3f4d..4f5d4e25b2ba3c 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 @@ -235,11 +235,10 @@ public SymbolicRegexNode Convert(RegexNode node, bool topLevel) 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 +370,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/SymbolicRegexBuilder.cs b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Symbolic/SymbolicRegexBuilder.cs index f09fb12a9654a0..47d33a0430bb42 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 @@ -297,7 +297,11 @@ internal SymbolicRegexNode MkSequence(TElement[] seq, bool topLevel) /// internal SymbolicRegexNode MkNot(SymbolicRegexNode node) => SymbolicRegexNode.MkNot(this, node); - internal SymbolicRegexNode MkCapture(SymbolicRegexNode child, int captureNum) => MkConcat(SymbolicRegexNode.MkCaptureStart(this, captureNum), MkConcat(child, SymbolicRegexNode.MkCaptureEnd(this, captureNum))); + 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 { @@ -354,6 +358,12 @@ internal SymbolicRegexNode Transform(SymbolicRegexNode sr, Symbo 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(); 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 06bf7e1094c6fe..9b8ff42b7fb09d 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 @@ -277,15 +277,20 @@ public void ApplyEffects(List effects, int i) { foreach (DerivativeEffect effect in effects) { - switch (effect.Kind) - { - case DerivativeEffect.EffectKind.CaptureStart: - captureStarts[effect.IntArg0] = i; - break; - case DerivativeEffect.EffectKind.CaptureEnd: - captureEnds[effect.IntArg0] = i; - break; - } + ApplyEffect(effect, i); + } + } + + public void ApplyEffect(DerivativeEffect effect, int i) + { + switch (effect.Kind) + { + case DerivativeEffect.EffectKind.CaptureStart: + captureStarts[effect.IntArg0] = i; + break; + case DerivativeEffect.EffectKind.CaptureEnd: + captureEnds[effect.IntArg0] = i; + break; } } @@ -321,7 +326,7 @@ private void CapturingDelta(string input, int i, Dictionary(ReadOnlySpan input, ref in return false; } - private int FindEndPositionCapturing(string input, int exclusiveEnd, int i, out Registers endRegisters) + private int FindEndPositionCapturing(string input, int exclusiveEnd, int i, out Registers resultRegisters) { int i_end = exclusiveEnd; + Registers endRegisters = default(Registers); // Pick the correct start state based on previous character kind. uint prevCharKind = GetCharKind(input, i - 1); @@ -610,11 +616,13 @@ private int FindEndPositionCapturing(string input, int exclusiveEnd, int i, out { // Empty match exists because the initial state is accepting. i_end = i - 1; + endRegisters = initialRegisters.Clone(); + state.Node.ApplyEffects(effect => endRegisters.ApplyEffect(effect, i + 1)); // Stop here if q is lazy. if (state.IsLazy) { - endRegisters = initialRegisters; + resultRegisters = endRegisters; return i_end; } } @@ -636,12 +644,14 @@ private int FindEndPositionCapturing(string input, int exclusiveEnd, int i, out { // Accepting state has been reached. Record the position. i_end = i; + endRegisters = registers.Clone(); + q.Node.ApplyEffects(effect => endRegisters.ApplyEffect(effect, i + 1)); // Stop here if q is lazy. if (q.IsLazy) { - endRegisters = registers; Debug.Assert(i_end != exclusiveEnd); + resultRegisters = endRegisters; return i_end; } } @@ -649,8 +659,8 @@ private int FindEndPositionCapturing(string input, int exclusiveEnd, int i, out { // Non-accepting sink state (deadend) has been reached in the original pattern. // So the match ended when the last i_end was updated. - endRegisters = registers; Debug.Assert(i_end != exclusiveEnd); + resultRegisters = endRegisters; return i_end; } } @@ -660,7 +670,7 @@ private int FindEndPositionCapturing(string input, int exclusiveEnd, int i, out // This should never happen, as a final state is already known to exist. Debug.Assert(false); - endRegisters = default(Registers); + resultRegisters = endRegisters; return i_end; } 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 eb64f8cf618273..6e1c6cf566ee65 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 @@ -261,6 +261,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 @@ -437,10 +442,10 @@ internal static SymbolicRegexNode MkAnd(SymbolicRegexBuilder builder, Symb } internal static SymbolicRegexNode MkCaptureStart(SymbolicRegexBuilder builder, int captureNum) => - Create(builder, SymbolicRegexKind.CaptureStart, null, null, captureNum, -1, default, null, SymbolicRegexInfo.Mk()); + 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()); + 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 : @@ -613,6 +618,8 @@ public int GetFixedLength() case SymbolicRegexKind.EndAnchorZRev: case SymbolicRegexKind.WBAnchor: case SymbolicRegexKind.NWBAnchor: + case SymbolicRegexKind.CaptureStart: + case SymbolicRegexKind.CaptureEnd: return 0; case SymbolicRegexKind.Singleton: @@ -805,14 +812,6 @@ internal SymbolicRegexNode MkDerivative(S elem, uint context) #endregion } - case SymbolicRegexKind.CaptureStart: - case SymbolicRegexKind.CaptureEnd: - { - // Capture nodes are no-ops here since there's nothing to record their effect into - deriv = _builder._epsilon; - break; - } - default: deriv = _builder._nothing; break; @@ -867,12 +866,17 @@ internal TransitionRegex MkDerivative() else if (_left.IsNullable) { // If _left is unconditionally nullable - _transitionRegex = mainTransition | _right.MkDerivative(); + TransitionRegex rightTransition = _right.MkDerivative(); + _left.ApplyEffects(effect => { + rightTransition = TransitionRegex.Effect(rightTransition, effect); + }); + _transitionRegex = mainTransition | rightTransition; } else { // The left side contains anchors and can be nullable in some context // Extract the nullability as the lookaround condition + // TODO: effects? SymbolicRegexNode leftNullabilityTest = _left.ExtractNullabilityTest(); _transitionRegex = TransitionRegex.Lookaround(leftNullabilityTest, mainTransition | _right.MkDerivative(), mainTransition); } @@ -920,21 +924,63 @@ internal TransitionRegex MkDerivative() _transitionRegex = ~_left.MkDerivative(); break; - case SymbolicRegexKind.CaptureStart: - _transitionRegex = TransitionRegex.Effect(TransitionRegex.Leaf(_builder._epsilon), - new DerivativeEffect(DerivativeEffect.EffectKind.CaptureStart, _lower)); + default: + _transitionRegex = TransitionRegex.Leaf(_builder._nothing); break; + } + return _transitionRegex; + } - case SymbolicRegexKind.CaptureEnd: - _transitionRegex = TransitionRegex.Effect(TransitionRegex.Leaf(_builder._epsilon), - new DerivativeEffect(DerivativeEffect.EffectKind.CaptureEnd, _lower)); + internal void ApplyEffects(Action apply) + { + if (!StackHelper.TryEnsureSufficientExecutionStack()) + { + StackHelper.CallOnEmptyStack(ApplyEffects, apply); + } + + switch (_kind) + { + case SymbolicRegexKind.Concat: + Debug.Assert(_left is not null && _right is not null); + Debug.Assert(_left.IsNullable && _right.IsNullable); + _left.ApplyEffects(apply); + _right.ApplyEffects(apply); break; - default: - _transitionRegex = TransitionRegex.Leaf(_builder._nothing); + case SymbolicRegexKind.Loop: + Debug.Assert(_left is not null); + if (_lower != 0) + { + Debug.Assert(_left.IsNullable); + _left.ApplyEffects(apply); + } + break; + + case SymbolicRegexKind.Or: + case SymbolicRegexKind.And: + Debug.Assert(_alts is not null); + foreach (SymbolicRegexNode elem in _alts) + { + if (elem.IsNullable) + { + elem.ApplyEffects(apply); + } + } + break; + + case SymbolicRegexKind.Not: + Debug.Assert(_left is not null); + _left.ApplyEffects(apply); + break; + + case SymbolicRegexKind.CaptureStart: + apply(new DerivativeEffect(DerivativeEffect.EffectKind.CaptureStart, _lower)); + break; + + case SymbolicRegexKind.CaptureEnd: + apply(new DerivativeEffect(DerivativeEffect.EffectKind.CaptureEnd, _lower)); break; } - return _transitionRegex; } /// @@ -1026,6 +1072,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: @@ -1232,6 +1280,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); @@ -1278,6 +1334,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: @@ -1413,6 +1471,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 @@ -1468,6 +1532,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: 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 405469085ae4cd..212b1f4f5b5060 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 @@ -102,8 +102,6 @@ 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); - runtextpos = end; if (pos.CaptureStarts != null) { Debug.Assert(pos.CaptureEnds != null); @@ -113,10 +111,15 @@ protected override void Go() if (pos.CaptureStarts[cap] >= 0) { Debug.Assert(pos.CaptureEnds[cap] >= 0); - runmatch!.AddMatch(cap, pos.CaptureStarts[cap], pos.CaptureEnds[cap]); + Capture(cap, pos.CaptureStarts[cap], pos.CaptureEnds[cap]); } } } + 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 f7d56dd2edb0f4..e721b6ffd6fbd3 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 @@ -120,6 +120,9 @@ public TransitionRegex Concat(SymbolicRegexNode node) case TransitionRegexKind.Leaf: Debug.Assert(_node is not null); return Create(_builder, _kind, default(S), null, null, _node._builder.MkConcat(_node, node)); + case TransitionRegexKind.Effect: + Debug.Assert(_first is not null); + return Create(_builder, _kind, default(S), _first.Concat(node), null, null, _effect); default: // All other three cases are disjunctive and obey the same laws of propagation of complement Debug.Assert(_first is not null && _second is not null); @@ -298,6 +301,14 @@ public override string ToString() return $"{_first}|{_second}"; case TransitionRegexKind.Conditional: return $"if({_test},{_first},{_second})"; + case TransitionRegexKind.Effect: + switch (_effect?.Kind) + { + case DerivativeEffect.EffectKind.CaptureStart: + return $"captureStart({_effect?.IntArg0},{_first})"; + default: + return $"captureEnd({_effect?.IntArg0},{_first})"; + } default: return $"if(IsNull({_node}),{_first},{_second})"; } From ba9cffde7a84a4259eeec9b17535a8f2a4cd943a Mon Sep 17 00:00:00 2001 From: Olli Saarikivi Date: Fri, 21 Jan 2022 10:15:10 -0800 Subject: [PATCH 03/29] State/transition priorities for NonBacktracking --- .../Symbolic/RegexNodeToSymbolicConverter.cs | 2 +- .../Symbolic/SymbolicRegexBuilder.cs | 29 ++- .../Symbolic/SymbolicRegexInfo.cs | 2 +- .../Symbolic/SymbolicRegexKind.cs | 1 + .../Symbolic/SymbolicRegexMatcher.cs | 54 +++-- .../Symbolic/SymbolicRegexNode.cs | 223 ++++++++++++++++-- 6 files changed, 263 insertions(+), 48 deletions(-) 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 4f5d4e25b2ba3c..80de448cc39a6c 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 @@ -220,7 +220,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: 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 47d33a0430bb42..9425eb0fae183c 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 @@ -141,6 +141,29 @@ 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 == _nothing) + continue; + if (or == null) + or = elem; + else + or = SymbolicRegexNode.MkOrderedOr(this, or, elem); + if (elem == _anyStar) + break; // .* is the absorbing element + } + if (or == null) + return _nothing; + else + return or; + } + /// /// Make a conjunction of given regexes, simplify by eliminating regexes that accept everything /// @@ -230,7 +253,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) @@ -354,6 +377,10 @@ 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)); 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 54517f1f768f90..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 @@ -25,5 +25,6 @@ internal enum SymbolicRegexKind 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 9b8ff42b7fb09d..9b4755e0c7c2c3 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 @@ -186,7 +186,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); + var unorderedPattern = _pattern.IgnoreOrOrder(); + _dotStarredPattern = _builder.MkConcat(_builder._anyStar, unorderedPattern); var dotstarredInitialStates = new DfaMatchingState[statesCount]; for (uint i = 0; i < dotstarredInitialStates.Length; i++) { @@ -202,7 +203,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++) { @@ -301,8 +302,9 @@ public void ApplyEffect(DerivativeEffect effect, int i) }; } + private HashSet> _seenCapturingStates = new(); // TODO: should this be a member? [MethodImpl(MethodImplOptions.AggressiveInlining)] - private void CapturingDelta(string input, int i, Dictionary, Registers> sourceStates, Dictionary, Registers> targetStates) + private void CapturingDelta(ReadOnlySpan input, int i, List<(DfaMatchingState, Registers)> sourceStates, List<(DfaMatchingState, Registers)> targetStates) { Debug.Assert(targetStates.Count == 0); @@ -311,6 +313,7 @@ private void CapturingDelta(string input, int i, Dictionary(ReadOnlySpan input, ref in return false; } - private int FindEndPositionCapturing(string input, int exclusiveEnd, int i, out Registers resultRegisters) + private int FindEndPositionCapturing(ReadOnlySpan input, int exclusiveEnd, int i, out Registers resultRegisters) { int i_end = exclusiveEnd; Registers endRegisters = default(Registers); @@ -627,8 +626,8 @@ private int FindEndPositionCapturing(string input, int exclusiveEnd, int i, out } } - Dictionary, Registers> current = new(), next = new(); - current.Add(state, initialRegisters); + List<(DfaMatchingState, Registers)> current = new(), next = new(); + current.Add((state, initialRegisters)); while (i < exclusiveEnd) { @@ -638,8 +637,9 @@ private int FindEndPositionCapturing(string input, int exclusiveEnd, int i, out next = tmp; next.Clear(); - foreach (var (q, registers) in current) + for (int m = 0; m < current.Count; ++m) { + var (q, registers) = current[m]; if (q.IsNullable(GetCharKind(input, i + 1))) { // Accepting state has been reached. Record the position. @@ -647,29 +647,35 @@ private int FindEndPositionCapturing(string input, int exclusiveEnd, int i, out endRegisters = registers.Clone(); q.Node.ApplyEffects(effect => endRegisters.ApplyEffect(effect, i + 1)); - // Stop here if q is lazy. + // Remove any lower priority states if (q.IsLazy) { - Debug.Assert(i_end != exclusiveEnd); - resultRegisters = endRegisters; - return i_end; + // Also remove this state if it is lazy + current.RemoveRange(m, current.Count - m); + } + else + { + current.RemoveRange(m + 1, current.Count - m - 1); } + break; } else if (q.IsDeadend) { - // Non-accepting sink state (deadend) has been reached in the original pattern. - // So the match ended when the last i_end was updated. - Debug.Assert(i_end != exclusiveEnd); - resultRegisters = endRegisters; - return i_end; + current.RemoveAt(m); + --m; } } + if (current.Count == 0) + { + Debug.Assert(i_end != exclusiveEnd); + resultRegisters = endRegisters; + return i_end; + } i++; } - // This should never happen, as a final state is already known to exist. - Debug.Assert(false); + Debug.Assert(i_end != exclusiveEnd); resultRegisters = endRegisters; return i_end; } 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 6e1c6cf566ee65..bcd53e69d04579 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 @@ -220,6 +220,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); @@ -426,6 +431,9 @@ internal static SymbolicRegexNode MkLoop(SymbolicRegexBuilder builder, Sym internal static SymbolicRegexNode MkOr(SymbolicRegexBuilder builder, params SymbolicRegexNode[] disjuncts) => MkCollection(builder, SymbolicRegexKind.Or, SymbolicRegexSet.CreateMulti(builder, disjuncts, SymbolicRegexKind.Or), SymbolicRegexInfo.Or(GetInfos(disjuncts))); + internal static SymbolicRegexNode MkOrderedOr(SymbolicRegexBuilder builder, SymbolicRegexNode left, SymbolicRegexNode right) => + Create(builder, SymbolicRegexKind.OrderedOr, left, right, -1, -1, default, null, SymbolicRegexInfo.Or(left._info, right._info)); + internal static SymbolicRegexNode MkOr(SymbolicRegexBuilder builder, SymbolicRegexSet disjuncts) { Debug.Assert(disjuncts._kind == SymbolicRegexKind.Or || disjuncts.IsEverything); @@ -657,6 +665,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; @@ -791,6 +814,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) @@ -822,7 +856,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) @@ -863,22 +900,29 @@ internal TransitionRegex MkDerivative() // If _left is never nullable _transitionRegex = mainTransition; } - else if (_left.IsNullable) + else { - // If _left is unconditionally nullable TransitionRegex rightTransition = _right.MkDerivative(); - _left.ApplyEffects(effect => { + _left.ApplyEffects(effect => + { rightTransition = TransitionRegex.Effect(rightTransition, effect); }); - _transitionRegex = mainTransition | rightTransition; - } - else - { - // The left side contains anchors and can be nullable in some context - // Extract the nullability as the lookaround condition - // TODO: effects? - SymbolicRegexNode leftNullabilityTest = _left.ExtractNullabilityTest(); - _transitionRegex = TransitionRegex.Lookaround(leftNullabilityTest, mainTransition | _right.MkDerivative(), mainTransition); + if (_left.IsLazy) + { + // If _left is lazy then prefer the transition out of it + _transitionRegex = rightTransition | mainTransition; + } + else + { + // If _left is eager then prefer the transition to stay in it + _transitionRegex = mainTransition | rightTransition; + } + if (!_left.IsNullable) + { + // The left side contains anchors and can be nullable in some context + // Extract the nullability as the lookaround condition + _transitionRegex = TransitionRegex.Lookaround(_left.ExtractNullabilityTest(), _transitionRegex, mainTransition); + } } break; @@ -910,6 +954,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); @@ -949,7 +998,8 @@ internal void ApplyEffects(Action apply) case SymbolicRegexKind.Loop: Debug.Assert(_left is not null); - if (_lower != 0) + // Apply effect when backtracking engine would enter loop + if (_lower != 0 || (_upper != 0 && !IsLazy && _left.IsNullable)) { Debug.Assert(_left.IsNullable); _left.ApplyEffects(apply); @@ -968,6 +1018,19 @@ internal void ApplyEffects(Action apply) } break; + case SymbolicRegexKind.OrderedOr: + Debug.Assert(_left is not null && _right is not null); + if (_left.IsNullable) + { + _left.ApplyEffects(apply); + } + else + { + Debug.Assert(_right.IsNullable); + _right.ApplyEffects(apply); + } + break; + case SymbolicRegexKind.Not: Debug.Assert(_left is not null); _left.ApplyEffects(apply); @@ -1032,6 +1095,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; @@ -1083,6 +1149,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: @@ -1205,6 +1272,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); @@ -1357,6 +1431,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; @@ -1436,6 +1516,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()); @@ -1487,6 +1571,79 @@ public SymbolicRegexNode Reverse() } } + /// + /// Transform OrderdOr to Or nodes + /// + public SymbolicRegexNode IgnoreOrOrder() + { + // Guard against stack overflow due to deep recursion + if (!StackHelper.TryEnsureSufficientExecutionStack()) + { + return StackHelper.CallOnEmptyStack(IgnoreOrOrder); + } + + switch (_kind) + { + case SymbolicRegexKind.Loop: + { + Debug.Assert(_left is not null); + SymbolicRegexNode body = _left.IgnoreOrOrder(); + return body == _left ? + this : + MkLoop(_builder, body, _lower, _upper, IsLazy); + } + + case SymbolicRegexKind.Concat: + { + Debug.Assert(_left is not null && _right is not null); + SymbolicRegexNode left1 = _left.IgnoreOrOrder(); + SymbolicRegexNode right1 = _right.IgnoreOrOrder(); + + 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.IgnoreOrOrder(); + 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.IgnoreOrOrder(); + return body == _left ? + this : + MkNot(_builder, body); + } + + case SymbolicRegexKind.OrderedOr: + { + Debug.Assert(_left is not null && _right is not null); + return MkOr(_builder, _left.IgnoreOrOrder(), _right.IgnoreOrOrder()); + } + + default: + return this; + } + } + internal bool StartsWithLoop(int upperBoundLowestValue = 1) { if (!StackHelper.TryEnsureSufficientExecutionStack()) @@ -1507,6 +1664,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; }; @@ -1562,6 +1723,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); @@ -1635,14 +1802,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: { @@ -1657,6 +1826,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; } From 55f6d2778c1c772a146a9803ca207596108e50ae Mon Sep 17 00:00:00 2001 From: Olli Saarikivi Date: Mon, 31 Jan 2022 09:24:36 -0800 Subject: [PATCH 04/29] Various fixes for capturing in NonBacktracking Re-enable replacement patterns. Fix eager derivative. Fix capture numbering to work with sparsely numbered groups. --- .../System/Text/RegularExpressions/Regex.cs | 2 +- .../Text/RegularExpressions/RegexParser.cs | 31 --- .../Symbolic/DfaMatchingState.cs | 5 +- .../Symbolic/RegexNodeToSymbolicConverter.cs | 10 +- .../Symbolic/SymbolicRegexBuilder.cs | 4 +- .../Symbolic/SymbolicRegexMatcher.cs | 18 +- .../Symbolic/SymbolicRegexNode.cs | 177 ++++++++++++++---- .../Symbolic/SymbolicRegexRunnerFactory.cs | 5 +- 8 files changed, 163 insertions(+), 89 deletions(-) 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 6b795e9681bb40..59921ea036317a 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 @@ -77,7 +77,7 @@ internal Regex(string pattern, RegexOptions options, TimeSpan matchTimeout, Cult if ((options & RegexOptions.NonBacktracking) != 0) { // If we're in non-backtracking mode, create the appropriate factory. - factory = new SymbolicRegexRunnerFactory(_code, options, matchTimeout, culture, capsize); + factory = new SymbolicRegexRunnerFactory(_code, options, matchTimeout, culture, capsize, caps); _code = null; } else if (RuntimeFeature.IsDynamicCodeCompiled && UseOptionC()) 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/DfaMatchingState.cs b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Symbolic/DfaMatchingState.cs index bf4efae1eee4ee..7064e575d7c08f 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 @@ -99,7 +99,7 @@ internal DfaMatchingState Next(T minterm) return Node._builder.MkState(derivative, nextCharKind); } - internal IEnumerable<(DfaMatchingState, List)> AntimirovNextWithEffects(T minterm) + internal IEnumerable<(DfaMatchingState, List)> AntimirovEagerNextWithEffects(T minterm) { ICharAlgebra alg = Node._builder._solver; T wordLetterPredicate = Node._builder._wordLetterPredicateForAnchors; @@ -130,7 +130,8 @@ internal DfaMatchingState Next(T minterm) uint context = CharKind.Context(PrevCharKind, nextCharKind); // Compute the derivative of the node for the given context - IEnumerable<(SymbolicRegexNode, List)> derivativesAndEffects = Node.MkDerivative().TransitionsWithEffects(minterm, context); + IEnumerable<(SymbolicRegexNode, List)> derivativesAndEffects = + Node.MkDerivativeWithEffects(context, eager: true).TransitionsWithEffects(minterm, context); foreach (var (derivative, effects) in derivativesAndEffects) { 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 80de448cc39a6c..d80cc61860598a 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 = null) { _categorizer = categorizer; _culture = culture; Solver = categorizer._solver; _builder = new SymbolicRegexBuilder(Solver); + _caps = caps; } /// The character solver associated with the regex converter @@ -231,7 +234,10 @@ public SymbolicRegexNode Convert(RegexNode node, bool topLevel) return _builder._bolAnchor; case RegexNodeKind.Capture when node.N == -1: - return _builder.MkCapture(Convert(node.Child(0), topLevel: false), node.M); + 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: { 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 9425eb0fae183c..bb84eea5b419ab 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 @@ -149,13 +149,13 @@ internal SymbolicRegexNode MkOrderedOr(params SymbolicRegexNode? or = null; foreach (SymbolicRegexNode elem in regexes) { - if (elem == _nothing) + if (elem.IsNothing) continue; if (or == null) or = elem; else or = SymbolicRegexNode.MkOrderedOr(this, or, elem); - if (elem == _anyStar) + if (elem.IsAnyStar) break; // .* is the absorbing element } if (or == null) 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 9b4755e0c7c2c3..64423713941efe 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 @@ -427,7 +427,7 @@ private DfaMatchingState CreateNewTransition(DfaMatchingState, List)>(state.AntimirovNextWithEffects(minterm)); + _builder._capturingDelta[offset] = p = new List<(DfaMatchingState, List)>(state.AntimirovEagerNextWithEffects(minterm)); } return p; @@ -502,7 +502,7 @@ public SymbolicMatch FindMatch(bool isMatch, ReadOnlySpan input, int start } int i_end; - if (_capsize == 0) + if (_capsize == 1) { if (watchdog >= 0) { @@ -616,7 +616,7 @@ private int FindEndPositionCapturing(ReadOnlySpan input, int exclusiveEnd, // Empty match exists because the initial state is accepting. i_end = i - 1; endRegisters = initialRegisters.Clone(); - state.Node.ApplyEffects(effect => endRegisters.ApplyEffect(effect, i + 1)); + state.Node.ApplyEffects(effect => endRegisters.ApplyEffect(effect, i), CharKind.Context(state.PrevCharKind, GetCharKind(input, i))); // Stop here if q is lazy. if (state.IsLazy) @@ -645,18 +645,10 @@ private int FindEndPositionCapturing(ReadOnlySpan input, int exclusiveEnd, // Accepting state has been reached. Record the position. i_end = i; endRegisters = registers.Clone(); - q.Node.ApplyEffects(effect => endRegisters.ApplyEffect(effect, i + 1)); + q.Node.ApplyEffects(effect => endRegisters.ApplyEffect(effect, i + 1), CharKind.Context(q.PrevCharKind, GetCharKind(input, i + 1))); // Remove any lower priority states - if (q.IsLazy) - { - // Also remove this state if it is lazy - current.RemoveRange(m, current.Count - m); - } - else - { - current.RemoveRange(m + 1, current.Count - m - 1); - } + current.RemoveRange(m + 1, current.Count - m - 1); break; } else if (q.IsDeadend) 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 bcd53e69d04579..78c5e249f8e9ba 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 @@ -900,29 +900,17 @@ internal TransitionRegex MkDerivative() // If _left is never nullable _transitionRegex = mainTransition; } + else if (_left.IsNullable) + { + // If _left is unconditionally nullable + _transitionRegex = mainTransition | _right.MkDerivative(); + } else { - TransitionRegex rightTransition = _right.MkDerivative(); - _left.ApplyEffects(effect => - { - rightTransition = TransitionRegex.Effect(rightTransition, effect); - }); - if (_left.IsLazy) - { - // If _left is lazy then prefer the transition out of it - _transitionRegex = rightTransition | mainTransition; - } - else - { - // If _left is eager then prefer the transition to stay in it - _transitionRegex = mainTransition | rightTransition; - } - if (!_left.IsNullable) - { - // The left side contains anchors and can be nullable in some context - // Extract the nullability as the lookaround condition - _transitionRegex = TransitionRegex.Lookaround(_left.ExtractNullabilityTest(), _transitionRegex, mainTransition); - } + // The left side contains anchors and can be nullable in some context + // Extract the nullability as the lookaround condition + SymbolicRegexNode leftNullabilityTest = _left.ExtractNullabilityTest(); + _transitionRegex = TransitionRegex.Lookaround(leftNullabilityTest, mainTransition | _right.MkDerivative(), mainTransition); } break; @@ -980,29 +968,146 @@ internal TransitionRegex MkDerivative() return _transitionRegex; } - internal void ApplyEffects(Action apply) + /// + /// 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 MkDerivativeWithEffects(uint context, bool eager) + { + if (IsNothing || IsEpsilon) + { + return TransitionRegex.Leaf(_builder._nothing); + } + + if (IsAnyStar || IsAnyPlus) + { + return TransitionRegex.Leaf(_builder._anyStar); + } + + if (!StackHelper.TryEnsureSufficientExecutionStack()) + { + return StackHelper.CallOnEmptyStack(MkDerivativeWithEffects, context, eager); + } + + switch (_kind) + { + case SymbolicRegexKind.Singleton: + Debug.Assert(_set is not null); + return TransitionRegex.Conditional(_set, TransitionRegex.Leaf(_builder._epsilon), TransitionRegex.Leaf(_builder._nothing)); + + case SymbolicRegexKind.Concat: + Debug.Assert(_left is not null && _right is not null); + + if (!_left.IsNullableFor(context)) + { + return _left.MkDerivativeWithEffects(context, eager).Concat(_right); + } + else if (_left._kind == SymbolicRegexKind.OrderedOr) + { + Debug.Assert(_left._left is not null && _left._right is not null); + if (eager && _right.IsNullableFor(context) && _left._left.IsNullableFor(context)) + return _builder.MkConcat(_left._left, _right).MkDerivativeWithEffects(context, eager); + else + return _builder.MkConcat(_left._left, _right).MkDerivativeWithEffects(context, eager) | + _builder.MkConcat(_left._right, _right).MkDerivativeWithEffects(context, eager); + } + else + { + bool leftEager = eager && _right.IsNullableFor(context); + TransitionRegex mainTransition = _left.MkDerivativeWithEffects(context, leftEager).Concat(_right); + TransitionRegex nullTransition = _right.MkDerivativeWithEffects(context, eager); + _left.ApplyEffects(effect => + { + nullTransition = TransitionRegex.Effect(nullTransition, effect); + }, context); + if (_left._kind == SymbolicRegexKind.Loop && _left.IsLazy && _left._lower == 0) + return nullTransition | mainTransition; + else + return mainTransition | nullTransition; + } + + 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) + { + return TransitionRegex.Leaf(_builder._nothing); + } + else + { + TransitionRegex step = _left.MkDerivativeWithEffects(context, eager); + if (IsStar || IsPlus) + { + return 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); + return step.Concat(rest); + } + } + + case SymbolicRegexKind.Or: + Debug.Assert(_alts is not null); + TransitionRegex orTr = TransitionRegex.Leaf(_builder._nothing); + foreach (SymbolicRegexNode elem in _alts) + { + orTr = orTr | elem.MkDerivativeWithEffects(context, eager); + } + return orTr; + + case SymbolicRegexKind.OrderedOr: + Debug.Assert(_left is not null && _right is not null); + if (eager && _left.IsNullableFor(context)) + return _left.MkDerivativeWithEffects(context, eager); + else + return _left.MkDerivativeWithEffects(context, eager) | _right.MkDerivativeWithEffects(context, eager); + + case SymbolicRegexKind.And: + Debug.Assert(_alts is not null); + TransitionRegex andTr = TransitionRegex.Leaf(_builder._anyStar); + foreach (SymbolicRegexNode elem in _alts) + { + andTr = andTr & elem.MkDerivativeWithEffects(context, eager); + } + return andTr; + + case SymbolicRegexKind.Not: + Debug.Assert(_left is not null); + return ~_left.MkDerivativeWithEffects(context, eager); + + default: + return TransitionRegex.Leaf(_builder._nothing); + } + } + + internal void ApplyEffects(Action apply, uint context) { if (!StackHelper.TryEnsureSufficientExecutionStack()) { - StackHelper.CallOnEmptyStack(ApplyEffects, apply); + StackHelper.CallOnEmptyStack(ApplyEffects, apply, context); } switch (_kind) { case SymbolicRegexKind.Concat: Debug.Assert(_left is not null && _right is not null); - Debug.Assert(_left.IsNullable && _right.IsNullable); - _left.ApplyEffects(apply); - _right.ApplyEffects(apply); + 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.IsNullable)) + if (_lower != 0 || (_upper != 0 && !IsLazy && _left.IsNullableFor(context))) { - Debug.Assert(_left.IsNullable); - _left.ApplyEffects(apply); + Debug.Assert(_left.IsNullableFor(context)); + _left.ApplyEffects(apply, context); } break; @@ -1011,29 +1116,29 @@ internal void ApplyEffects(Action apply) Debug.Assert(_alts is not null); foreach (SymbolicRegexNode elem in _alts) { - if (elem.IsNullable) + if (elem.IsNullableFor(context)) { - elem.ApplyEffects(apply); + elem.ApplyEffects(apply, context); } } break; case SymbolicRegexKind.OrderedOr: Debug.Assert(_left is not null && _right is not null); - if (_left.IsNullable) + if (_left.IsNullableFor(context)) { - _left.ApplyEffects(apply); + _left.ApplyEffects(apply, context); } else { - Debug.Assert(_right.IsNullable); - _right.ApplyEffects(apply); + Debug.Assert(_right.IsNullableFor(context)); + _right.ApplyEffects(apply, context); } break; case SymbolicRegexKind.Not: Debug.Assert(_left is not null); - _left.ApplyEffects(apply); + _left.ApplyEffects(apply, context); break; case SymbolicRegexKind.CaptureStart: 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 212b1f4f5b5060..f210f14bf85619 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,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.Diagnostics; using System.Globalization; using System.Text.RegularExpressions.Symbolic.Unicode; @@ -17,7 +18,7 @@ internal sealed class SymbolicRegexRunnerFactory : RegexRunnerFactory internal readonly ISymbolicRegexMatcher _matcher; /// Initializes the factory. - public SymbolicRegexRunnerFactory(RegexCode code, RegexOptions options, TimeSpan matchTimeout, CultureInfo culture, int capsize) + public SymbolicRegexRunnerFactory(RegexCode code, RegexOptions options, TimeSpan matchTimeout, CultureInfo culture, int capsize, Hashtable? caps) { // RightToLeft and ECMAScript are currently not supported in conjunction with NonBacktracking. if ((options & (RegexOptions.RightToLeft | RegexOptions.ECMAScript)) != 0) @@ -27,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, caps); var solver = (CharSetSolver)s_unicode._solver; SymbolicRegexNode root = converter.Convert(code.Tree.Root, topLevel: true); From 7d400a49a68bbe299cd5968adcd42a625e65a000 Mon Sep 17 00:00:00 2001 From: Olli Saarikivi Date: Mon, 31 Jan 2022 09:27:08 -0800 Subject: [PATCH 05/29] Enable many subcapture tests for NonBacktracking Also take any subcaptures out of RegexExperiment intersection and negation tests, as capture semantics with these are not correct yet. --- .../tests/AttRegexTests.cs | 37 ++- .../tests/MonoRegexTests.cs | 8 +- .../tests/Regex.GetGroupNames.Tests.cs | 232 +++++++++--------- .../tests/Regex.Groups.Tests.cs | 42 ++-- .../tests/Regex.KnownPattern.Tests.cs | 77 ++---- .../tests/Regex.Match.Tests.cs | 66 ++--- .../tests/Regex.Replace.Tests.cs | 22 +- .../tests/Regex.Split.Tests.cs | 41 +--- .../tests/RegexExperiment.cs | 14 +- 9 files changed, 208 insertions(+), 331 deletions(-) diff --git a/src/libraries/System.Text.RegularExpressions/tests/AttRegexTests.cs b/src/libraries/System.Text.RegularExpressions/tests/AttRegexTests.cs index fb3ea3a7b7a6d2..2f901133391278 100644 --- a/src/libraries/System.Text.RegularExpressions/tests/AttRegexTests.cs +++ b/src/libraries/System.Text.RegularExpressions/tests/AttRegexTests.cs @@ -122,8 +122,8 @@ public static IEnumerable Inputs() yield return new object[] { engine, options, "aba|bab", "baaabbbaba", "(6,9)" }; yield return new object[] { engine, options, "(aa|aaa)*|(a|aaaaa)", "aa", "(0,2)(0,2)" }; yield return new object[] { engine, options, "(a.|.a.)*|(a|.a...)", "aa", "(0,2)(0,2)" }; - yield return new object[] { engine, options, "ab|a", "xabc", "(1,3)", "(1,2)" }; - yield return new object[] { engine, options, "ab|a", "xxabc", "(2,4)", "(2,3)" }; + yield return new object[] { engine, options, "ab|a", "xabc", "(1,3)" }; + yield return new object[] { engine, options, "ab|a", "xxabc", "(2,4)" }; yield return new object[] { engine, options, "(?i)(Ab|cD)*", "aBcD", "(0,4)(2,4)" }; yield return new object[] { engine, options, "[^-]", "--a", "(2,3)" }; yield return new object[] { engine, options, "[a-]*", "--a", "(0,3)" }; @@ -289,18 +289,18 @@ public static IEnumerable Inputs() yield return new object[] { engine, options, "X(.?){6,8}Y", "X1234567Y", "(0,9)(8,8)" }; // was "(0,9)(7,8)" yield return new object[] { engine, options, "X(.?){7,8}Y", "X1234567Y", "(0,9)(8,8)" }; // was "(0,9)(7,8)" yield return new object[] { engine, options, "X(.?){8,8}Y", "X1234567Y", "(0,9)(8,8)" }; - yield return new object[] { engine, options, "(a|ab|c|bcd){0,}(d*)", "ababcd", "(0,1)(1,1)", "(0,6)" }; // was "(0,6)(3,6)(6,6)" - yield return new object[] { engine, options, "(a|ab|c|bcd){1,}(d*)", "ababcd", "(0,1)(1,1)", "(0,6)" }; // was "(0,6)(3,6)(6,6)" + yield return new object[] { engine, options, "(a|ab|c|bcd){0,}(d*)", "ababcd", "(0,1)(1,1)" }; // was "(0,6)(3,6)(6,6)" + yield return new object[] { engine, options, "(a|ab|c|bcd){1,}(d*)", "ababcd", "(0,1)(1,1)" }; // was "(0,6)(3,6)(6,6)" yield return new object[] { engine, options, "(a|ab|c|bcd){2,}(d*)", "ababcd", "(0,6)(3,6)(6,6)" }; yield return new object[] { engine, options, "(a|ab|c|bcd){3,}(d*)", "ababcd", "(0,6)(3,6)(6,6)" }; yield return new object[] { engine, options, "(a|ab|c|bcd){4,}(d*)", "ababcd", "NOMATCH" }; - yield return new object[] { engine, options, "(a|ab|c|bcd){0,10}(d*)", "ababcd", "(0,1)(1,1)", "(0,6)" }; // was "(0,6)(3,6)(6,6)" - yield return new object[] { engine, options, "(a|ab|c|bcd){1,10}(d*)", "ababcd", "(0,1)(1,1)", "(0,6)" }; // was "(0,6)(3,6)(6,6)" + yield return new object[] { engine, options, "(a|ab|c|bcd){0,10}(d*)", "ababcd", "(0,1)(1,1)" }; // was "(0,6)(3,6)(6,6)" + yield return new object[] { engine, options, "(a|ab|c|bcd){1,10}(d*)", "ababcd", "(0,1)(1,1)" }; // was "(0,6)(3,6)(6,6)" yield return new object[] { engine, options, "(a|ab|c|bcd){2,10}(d*)", "ababcd", "(0,6)(3,6)(6,6)" }; yield return new object[] { engine, options, "(a|ab|c|bcd){3,10}(d*)", "ababcd", "(0,6)(3,6)(6,6)" }; yield return new object[] { engine, options, "(a|ab|c|bcd){4,10}(d*)", "ababcd", "NOMATCH" }; - yield return new object[] { engine, options, "(a|ab|c|bcd)*(d*)", "ababcd", "(0,1)(1,1)", "(0,6)" }; // was "(0,6)(3,6)(6,6)" - yield return new object[] { engine, options, "(a|ab|c|bcd)+(d*)", "ababcd", "(0,1)(1,1)", "(0,6)" }; // was "(0,6)(3,6)(6,6)" + yield return new object[] { engine, options, "(a|ab|c|bcd)*(d*)", "ababcd", "(0,1)(1,1)" }; // was "(0,6)(3,6)(6,6)" + yield return new object[] { engine, options, "(a|ab|c|bcd)+(d*)", "ababcd", "(0,1)(1,1)" }; // was "(0,6)(3,6)(6,6)" yield return new object[] { engine, options, "(ab|a|c|bcd){0,}(d*)", "ababcd", "(0,6)(4,5)(5,6)" }; // was "(0,6)(3,6)(6,6)" yield return new object[] { engine, options, "(ab|a|c|bcd){1,}(d*)", "ababcd", "(0,6)(4,5)(5,6)" }; // was "(0,6)(3,6)(6,6)" yield return new object[] { engine, options, "(ab|a|c|bcd){2,}(d*)", "ababcd", "(0,6)(4,5)(5,6)" }; // was "(0,6)(3,6)(6,6)" @@ -358,11 +358,11 @@ public static IEnumerable Inputs() yield return new object[] { engine, options, "(a)*?", "aaa", "(0,0)" }; yield return new object[] { engine, options, "(a*?)*?", "aaa", "(0,0)" }; yield return new object[] { engine, options, "(a*)*(x)", "x", "(0,1)(0,0)(0,1)" }; - yield return new object[] { engine, options, "(a*)*(x)(\\1)", "x", "(0,1)(0,0)(0,1)(1,1)", "NONBACKTRACKINGINCOMPATIBLE" }; - yield return new object[] { engine, options, "(a*)*(x)(\\1)", "ax", "(0,2)(1,1)(1,2)(2,2)", "NONBACKTRACKINGINCOMPATIBLE" }; - yield return new object[] { engine, options, "(a*)*(x)(\\1)", "axa", "(0,2)(1,1)(1,2)(2,2)", "NONBACKTRACKINGINCOMPATIBLE" }; // was "(0,3)(0,1)(1,2)(2,3)" - yield return new object[] { engine, options, "(a*)*(x)(\\1)(x)", "axax", "(0,4)(0,1)(1,2)(2,3)(3,4)", "NONBACKTRACKINGINCOMPATIBLE" }; - yield return new object[] { engine, options, "(a*)*(x)(\\1)(x)", "axxa", "(0,3)(1,1)(1,2)(2,2)(2,3)", "NONBACKTRACKINGINCOMPATIBLE" }; + yield return new object[] { engine, options, "(a*)*(x)(\\1)", "x", "(0,1)(0,0)(0,1)(1,1)", true }; + yield return new object[] { engine, options, "(a*)*(x)(\\1)", "ax", "(0,2)(1,1)(1,2)(2,2)", true }; + yield return new object[] { engine, options, "(a*)*(x)(\\1)", "axa", "(0,2)(1,1)(1,2)(2,2)", true }; // was "(0,3)(0,1)(1,2)(2,3)" + yield return new object[] { engine, options, "(a*)*(x)(\\1)(x)", "axax", "(0,4)(0,1)(1,2)(2,3)(3,4)", true }; + yield return new object[] { engine, options, "(a*)*(x)(\\1)(x)", "axxa", "(0,3)(1,1)(1,2)(2,2)(2,3)", true }; yield return new object[] { engine, options, "(a*)*(x)", "ax", "(0,2)(1,1)(1,2)" }; yield return new object[] { engine, options, "(a*)*(x)", "axa", "(0,2)(1,1)(1,2)" }; // was "(0,2)(0,1)(1,2)" yield return new object[] { engine, options, "(a*)+(x)", "x", "(0,1)(0,0)(0,1)" }; @@ -377,25 +377,20 @@ public static IEnumerable Inputs() [Theory] [MemberData(nameof(Inputs))] - public async Task Test(RegexEngine engine, RegexOptions options, string pattern, string input, string captures, string nonBacktrackingCaptures = null) + public async Task Test(RegexEngine engine, RegexOptions options, string pattern, string input, string expected, bool skipNonBacktracking = false) { if (input == "NULL") { input = ""; } - bool nonBacktracking = engine == RegexEngine.NonBacktracking; - string expected = nonBacktracking && nonBacktrackingCaptures != null ? - nonBacktrackingCaptures : // nonBacktrackingCaptures value overrides the expected result in NonBacktracking mode - captures; - if (expected == "BADBR") { await Assert.ThrowsAnyAsync(async () => await RegexHelpers.GetRegexAsync(engine, pattern, options)); return; } - if (nonBacktracking && nonBacktrackingCaptures == "NONBACKTRACKINGINCOMPATIBLE") + if (engine == RegexEngine.NonBacktracking && skipNonBacktracking) { // In particular: backreferences are not supported in NonBacktracking mode await Assert.ThrowsAnyAsync(() => RegexHelpers.GetRegexAsync(engine, pattern, options)); @@ -426,7 +421,7 @@ public async Task Test(RegexEngine engine, RegexOptions options, string pattern, // NonBacktracking mode only provides the top-level match. // The .NET implementation sometimes has extra captures beyond what the original data specifies, so we assert a subset. - if (nonBacktracking ? !actualSet.IsSubsetOf(expectedSet) : !expectedSet.IsSubsetOf(actualSet)) + if (!expectedSet.IsSubsetOf(actualSet)) { throw new Xunit.Sdk.XunitException($"Actual: {string.Join(", ", actualSet)}{Environment.NewLine}Expected: {string.Join(", ", expected)}"); } diff --git a/src/libraries/System.Text.RegularExpressions/tests/MonoRegexTests.cs b/src/libraries/System.Text.RegularExpressions/tests/MonoRegexTests.cs index 9fa5749f667d05..878bae75c133d7 100644 --- a/src/libraries/System.Text.RegularExpressions/tests/MonoRegexTests.cs +++ b/src/libraries/System.Text.RegularExpressions/tests/MonoRegexTests.cs @@ -60,12 +60,8 @@ public static IEnumerable ValidateRegex_MemberData() string expected = allEngineCases[i].Expected; if (RegexHelpers.IsNonBacktracking(engine)) { - // NonBacktracking doesn't support captures other than top-level. Remove the rest from the expected results. - int j = expected.IndexOf(')'); - if (j >= 0) - { - expected = expected.Substring(0, j + 1); - } + // NonBacktracking doesn't support multiple captures. Remove everything but the last from the expected results. + expected = Regex.Replace(expected, "(\\([0-9]+,[0-9]+\\))+", "$1"); } (string Pattern, RegexOptions Options, string Input, string Expected) testCase = allEngineCases[i]; diff --git a/src/libraries/System.Text.RegularExpressions/tests/Regex.GetGroupNames.Tests.cs b/src/libraries/System.Text.RegularExpressions/tests/Regex.GetGroupNames.Tests.cs index 38d2b72f3e0b6a..b270ea509ec884 100644 --- a/src/libraries/System.Text.RegularExpressions/tests/Regex.GetGroupNames.Tests.cs +++ b/src/libraries/System.Text.RegularExpressions/tests/Regex.GetGroupNames.Tests.cs @@ -12,9 +12,7 @@ public static IEnumerable GetGroupNames_MemberData() { yield return new object[] { "(?\\S+)\\s(?\\S+)", RegexOptions.None, new string[] { "0", "first_name", "last_name" } }; if (PlatformDetection.IsNetCore) - { - yield return new object[] { "(?\\S+)\\s(?\\S+)", RegexHelpers.RegexOptionNonBacktracking, new string[] { "0" } }; - } + yield return new object[] { "(?\\S+)\\s(?\\S+)", RegexHelpers.RegexOptionNonBacktracking, new string[] { "0", "first_name", "last_name" } }; } [Theory] @@ -27,120 +25,116 @@ public void GetGroupNames(string pattern, RegexOptions options, string[] expecte public static IEnumerable GroupNamesAndNumbers_TestData() { - yield return new object[] - { - "(?\\S+)\\s(?\\S+)", "Ryan Byington", - new string[] { "0", "first_name", "last_name"}, - new int[] { 0, 1, 2 }, - new string[] { "Ryan Byington", "Ryan", "Byington" } - }; - - yield return new object[] + foreach (RegexOptions options in new RegexOptions[] { RegexOptions.None, RegexHelpers.RegexOptionNonBacktracking }) { - @"((?abc)\d+)?(?xyz)(.*)", "abc208923xyzanqnakl", - new string[] { "0", "1", "2", "One", "Two" }, - new int[] { 0, 1, 2, 3, 4 }, - new string[] { "abc208923xyzanqnakl", "abc208923", "anqnakl", "abc", "xyz" } - }; - - yield return new object[] - { - @"((?<256>abc)\d+)?(?<16>xyz)(.*)", "0272saasdabc8978xyz][]12_+-", - new string[] { "0", "1", "2", "16", "256" }, - new int[] { 0, 1, 2, 16, 256 }, - new string[] { "abc8978xyz][]12_+-", "abc8978", "][]12_+-", "xyz", "abc" } - }; + if (!PlatformDetection.IsNetCore && (options & RegexHelpers.RegexOptionNonBacktracking) != 0) + continue; + yield return new object[] + { + "(?\\S+)\\s(?\\S+)", "Ryan Byington", + new string[] { "0", "first_name", "last_name"}, + new int[] { 0, 1, 2 }, + new string[] { "Ryan Byington", "Ryan", "Byington" }, + options + }; - yield return new object[] - { - @"((?<4>abc)(?\d+))?(?<2>xyz)(?.*)", "0272saasdabc8978xyz][]12_+-", - new string[] { "0", "1", "2", "digits", "4", "everything_else" }, - new int[] { 0, 1, 2, 3, 4, 5 }, - new string[] { "abc8978xyz][]12_+-", "abc8978", "xyz", "8978", "abc", "][]12_+-" } - }; + yield return new object[] + { + @"((?abc)\d+)?(?xyz)(.*)", "abc208923xyzanqnakl", + new string[] { "0", "1", "2", "One", "Two" }, + new int[] { 0, 1, 2, 3, 4 }, + new string[] { "abc208923xyzanqnakl", "abc208923", "anqnakl", "abc", "xyz" }, + options + }; - yield return new object[] - { - "(?\\S+)\\s(?\\S+)", "Ryan Byington", - new string[] { "0", "first_name" }, - new int[] { 0, 1 }, - new string[] { "Ryan Byington", "Byington" } - }; + yield return new object[] + { + @"((?<256>abc)\d+)?(?<16>xyz)(.*)", "0272saasdabc8978xyz][]12_+-", + new string[] { "0", "1", "2", "16", "256" }, + new int[] { 0, 1, 2, 16, 256 }, + new string[] { "abc8978xyz][]12_+-", "abc8978", "][]12_+-", "xyz", "abc" }, + options + }; - yield return new object[] - { - "(?<15>\\S+)\\s(?<15>\\S+)", "Ryan Byington", - new string[] { "0", "15" }, - new int[] { 0, 15 }, - new string[] { "Ryan Byington", "Byington" } - }; + yield return new object[] + { + @"((?<4>abc)(?\d+))?(?<2>xyz)(?.*)", "0272saasdabc8978xyz][]12_+-", + new string[] { "0", "1", "2", "digits", "4", "everything_else" }, + new int[] { 0, 1, 2, 3, 4, 5 }, + new string[] { "abc8978xyz][]12_+-", "abc8978", "xyz", "8978", "abc", "][]12_+-" }, + options + }; - yield return new object[] - { - "(?'first_name'\\S+)\\s(?'last_name'\\S+)", "Ryan Byington", - new string[] { "0", "first_name", "last_name" }, - new int[] { 0, 1, 2 }, - new string[] { "Ryan Byington", "Ryan", "Byington" } - }; + yield return new object[] + { + "(?\\S+)\\s(?\\S+)", "Ryan Byington", + new string[] { "0", "first_name" }, + new int[] { 0, 1 }, + new string[] { "Ryan Byington", "Byington" }, + options + }; - yield return new object[] - { - @"((?'One'abc)\d+)?(?'Two'xyz)(.*)", "abc208923xyzanqnakl", - new string[] { "0", "1", "2", "One", "Two" }, - new int[] { 0, 1, 2, 3, 4 }, - new string[] { "abc208923xyzanqnakl", "abc208923", "anqnakl", "abc", "xyz" } - }; + yield return new object[] + { + "(?<15>\\S+)\\s(?<15>\\S+)", "Ryan Byington", + new string[] { "0", "15" }, + new int[] { 0, 15 }, + new string[] { "Ryan Byington", "Byington" }, + options + }; - yield return new object[] - { - @"((?'256'abc)\d+)?(?'16'xyz)(.*)", "0272saasdabc8978xyz][]12_+-", - new string[] { "0", "1", "2", "16", "256" }, - new int[] { 0, 1, 2, 16, 256 }, - new string[] { "abc8978xyz][]12_+-", "abc8978", "][]12_+-", "xyz", "abc" } - }; + yield return new object[] + { + "(?'first_name'\\S+)\\s(?'last_name'\\S+)", "Ryan Byington", + new string[] { "0", "first_name", "last_name" }, + new int[] { 0, 1, 2 }, + new string[] { "Ryan Byington", "Ryan", "Byington" }, + options + }; - yield return new object[] - { - @"((?'4'abc)(?'digits'\d+))?(?'2'xyz)(?'everything_else'.*)", "0272saasdabc8978xyz][]12_+-", - new string[] { "0", "1", "2", "digits", "4", "everything_else" }, - new int[] { 0, 1, 2, 3, 4, 5 }, - new string[] { "abc8978xyz][]12_+-", "abc8978", "xyz", "8978", "abc", "][]12_+-" } - }; + yield return new object[] + { + @"((?'One'abc)\d+)?(?'Two'xyz)(.*)", "abc208923xyzanqnakl", + new string[] { "0", "1", "2", "One", "Two" }, + new int[] { 0, 1, 2, 3, 4 }, + new string[] { "abc208923xyzanqnakl", "abc208923", "anqnakl", "abc", "xyz" }, + options + }; - yield return new object[] - { - "(?'first_name'\\S+)\\s(?'first_name'\\S+)", "Ryan Byington", - new string[] { "0", "first_name" }, - new int[] { 0, 1 }, - new string[] { "Ryan Byington", "Byington" } - }; + yield return new object[] + { + @"((?'256'abc)\d+)?(?'16'xyz)(.*)", "0272saasdabc8978xyz][]12_+-", + new string[] { "0", "1", "2", "16", "256" }, + new int[] { 0, 1, 2, 16, 256 }, + new string[] { "abc8978xyz][]12_+-", "abc8978", "][]12_+-", "xyz", "abc" }, + options + }; - yield return new object[] - { - "(?'15'\\S+)\\s(?'15'\\S+)", "Ryan Byington", - new string[] { "0", "15" }, - new int[] { 0, 15 }, - new string[] { "Ryan Byington", "Byington" } - }; + yield return new object[] + { + @"((?'4'abc)(?'digits'\d+))?(?'2'xyz)(?'everything_else'.*)", "0272saasdabc8978xyz][]12_+-", + new string[] { "0", "1", "2", "digits", "4", "everything_else" }, + new int[] { 0, 1, 2, 3, 4, 5 }, + new string[] { "abc8978xyz][]12_+-", "abc8978", "xyz", "8978", "abc", "][]12_+-" }, + options + }; - if (PlatformDetection.IsNetCore) - { yield return new object[] { - "(?'15'\\S+)\\s(?'15'\\S+)", "Ryan Byington", - new string[] { "0" }, - new int[] { 0 }, - new string[] { "Ryan Byington" }, - RegexHelpers.RegexOptionNonBacktracking + "(?'first_name'\\S+)\\s(?'first_name'\\S+)", "Ryan Byington", + new string[] { "0", "first_name" }, + new int[] { 0, 1 }, + new string[] { "Ryan Byington", "Byington" }, + options }; yield return new object[] { - "(?\\S+)\\s(?\\S+)", "Ryan Byington", - new string[] { "0" }, - new int[] { 0 }, - new string[] { "Ryan Byington" }, - RegexHelpers.RegexOptionNonBacktracking + "(?'15'\\S+)\\s(?'15'\\S+)", "Ryan Byington", + new string[] { "0", "15" }, + new int[] { 0, 15 }, + new string[] { "Ryan Byington", "Byington" }, + options }; } } @@ -175,17 +169,15 @@ public void GroupNamesAndNumbers(string pattern, string input, string[] expected public static IEnumerable GroupNameFromNumber_InvalidIndex_ReturnsEmptyString_MemberData() { - yield return new object[] { "foo", 1 }; - yield return new object[] { "foo", -1 }; - yield return new object[] { "(?\\S+)\\s(?\\S+)", -1 }; - yield return new object[] { "(?\\S+)\\s(?\\S+)", 3 }; - yield return new object[] { @"((?<256>abc)\d+)?(?<16>xyz)(.*)", -1 }; - - if (PlatformDetection.IsNetCore) - { - yield return new object[] { "(f)(oo)", 1, RegexHelpers.RegexOptionNonBacktracking }; - yield return new object[] { "(f)(oo)", -1, RegexHelpers.RegexOptionNonBacktracking }; - yield return new object[] { "(f)(oo)", 2, RegexHelpers.RegexOptionNonBacktracking }; + foreach (RegexOptions options in new RegexOptions[] { RegexOptions.None, RegexHelpers.RegexOptionNonBacktracking }) + { + if (!PlatformDetection.IsNetCore && (options & RegexHelpers.RegexOptionNonBacktracking) != 0) + continue; + yield return new object[] { "foo", 1, options }; + yield return new object[] { "foo", -1, options }; + yield return new object[] { "(?\\S+)\\s(?\\S+)", -1, options }; + yield return new object[] { "(?\\S+)\\s(?\\S+)", 3, options }; + yield return new object[] { @"((?<256>abc)\d+)?(?<16>xyz)(.*)", -1, options }; } } @@ -198,16 +190,14 @@ public void GroupNameFromNumber_InvalidIndex_ReturnsEmptyString(string pattern, public static IEnumerable GroupNumberFromName_InvalidName_ReturnsMinusOne_MemberData() { - yield return new object[] { "foo", "no-such-name" }; - yield return new object[] { "foo", "1" }; - yield return new object[] { "(?\\S+)\\s(?\\S+)", "no-such-name" }; - yield return new object[] { "(?\\S+)\\s(?\\S+)", "FIRST_NAME" }; - - if (PlatformDetection.IsNetCore) - { - yield return new object[] { "(f)(oo)", "no-such-name", RegexHelpers.RegexOptionNonBacktracking }; - yield return new object[] { "(f)(oo)", "1", RegexHelpers.RegexOptionNonBacktracking }; - yield return new object[] { "(f)(oo)", "2", RegexHelpers.RegexOptionNonBacktracking }; + foreach (RegexOptions options in new RegexOptions[] { RegexOptions.None, RegexHelpers.RegexOptionNonBacktracking }) + { + if (!PlatformDetection.IsNetCore && (options & RegexHelpers.RegexOptionNonBacktracking) != 0) + continue; + yield return new object[] { "foo", "no-such-name", options }; + yield return new object[] { "foo", "1", options }; + yield return new object[] { "(?\\S+)\\s(?\\S+)", "no-such-name", options }; + yield return new object[] { "(?\\S+)\\s(?\\S+)", "FIRST_NAME", options }; } } diff --git a/src/libraries/System.Text.RegularExpressions/tests/Regex.Groups.Tests.cs b/src/libraries/System.Text.RegularExpressions/tests/Regex.Groups.Tests.cs index d2a07d60dd04e3..15c47692303ba3 100644 --- a/src/libraries/System.Text.RegularExpressions/tests/Regex.Groups.Tests.cs +++ b/src/libraries/System.Text.RegularExpressions/tests/Regex.Groups.Tests.cs @@ -505,13 +505,12 @@ public static IEnumerable Groups_Basic_TestData() yield return new object[] { engine, null, @"^(([d-f]*)|([c-e]*))$", "dddeeeccceee", RegexOptions.None, new string[] { "dddeeeccceee", "dddeeeccceee", "", "dddeeeccceee" } }; yield return new object[] { engine, null, @"^(([c-e]*)|([d-f]*))$", "dddeeeccceee", RegexOptions.None, new string[] { "dddeeeccceee", "dddeeeccceee", "dddeeeccceee", "" } }; - // Different match in NonBackTracking when order of alternations does not matter - yield return new object[] { engine, null, @"(([a-d]*)|([a-z]*))", "aaabbbcccdddeeefff", RegexOptions.None, new string[] { "aaabbbcccddd", "aaabbbcccddd", "aaabbbcccddd", "" }, "aaabbbcccdddeeefff" }; // <-- Nonbacktracking match same as for "(([a-z]*)|([a-d]*))" - yield return new object[] { engine, null, @"(([d-f]*)|([c-e]*))", "dddeeeccceee", RegexOptions.None, new string[] { "dddeee", "dddeee", "dddeee", "" }, "dddeeeccceee" }; // <-- Nonbacktracking match same as for "(([c-e]*)|([d-f]*))" + yield return new object[] { engine, null, @"(([a-d]*)|([a-z]*))", "aaabbbcccdddeeefff", RegexOptions.None, new string[] { "aaabbbcccddd", "aaabbbcccddd", "aaabbbcccddd", "" } }; + yield return new object[] { engine, null, @"(([d-f]*)|([c-e]*))", "dddeeeccceee", RegexOptions.None, new string[] { "dddeee", "dddeee", "dddeee", "" } }; yield return new object[] { engine, null, @"(([c-e]*)|([d-f]*))", "dddeeeccceee", RegexOptions.None, new string[] { "dddeeeccceee", "dddeeeccceee", "dddeeeccceee", "" } }; - yield return new object[] { engine, null, @"(([a-d]*)|(.*))", "aaabbbcccdddeeefff", RegexOptions.None, new string[] { "aaabbbcccddd", "aaabbbcccddd", "aaabbbcccddd", "" }, "aaabbbcccdddeeefff" }; // <-- Nonbacktracking match same as for ".*" - yield return new object[] { engine, null, @"(([d-f]*)|(.*))", "dddeeeccceee", RegexOptions.None, new string[] { "dddeee", "dddeee", "dddeee", "" }, "dddeeeccceee" }; // <-- Nonbacktracking match same as for ".*" + yield return new object[] { engine, null, @"(([a-d]*)|(.*))", "aaabbbcccdddeeefff", RegexOptions.None, new string[] { "aaabbbcccddd", "aaabbbcccddd", "aaabbbcccddd", "" } }; + yield return new object[] { engine, null, @"(([d-f]*)|(.*))", "dddeeeccceee", RegexOptions.None, new string[] { "dddeee", "dddeee", "dddeee", "" } }; yield return new object[] { engine, null, @"(([c-e]*)|(.*))", "dddeeeccceee", RegexOptions.None, new string[] { "dddeeeccceee", "dddeeeccceee", "dddeeeccceee", "" } }; // \p{Pi} (Punctuation Initial quote) \p{Pf} (Punctuation Final quote) @@ -782,7 +781,7 @@ public static IEnumerable Groups_Basic_TestData() yield return new object[] { engine, null, @"(?s).*(?-s)[1a]", "\n\n\n\n1", RegexOptions.None, new string[] { "\n\n\n\n1" } }; yield return new object[] { engine, null, @".*|.*|.*", "", RegexOptions.None, new string[] { "" } }; yield return new object[] { engine, null, @".*123|abc", "abc\n123", RegexOptions.None, new string[] { "abc" } }; - yield return new object[] { engine, null, @".*123|abc", "abc\n123", RegexOptions.Singleline, new string[] { "abc\n123" }, "abc" }; // <-- Nonbacktracking match same as for "abc|.*123" + yield return new object[] { engine, null, @".*123|abc", "abc\n123", RegexOptions.Singleline, new string[] { "abc\n123" } }; yield return new object[] { engine, null, @"abc|.*123", "abc\n123", RegexOptions.Singleline, new string[] { "abc" } }; yield return new object[] { engine, null, @".*", "\n", RegexOptions.None, new string[] { "" } }; yield return new object[] { engine, null, @".*\n", "\n", RegexOptions.None, new string[] { "\n" } }; @@ -791,7 +790,7 @@ public static IEnumerable Groups_Basic_TestData() yield return new object[] { engine, null, @".*", "abc", RegexOptions.None, new string[] { "abc" } }; yield return new object[] { engine, null, @".*abc", "abc", RegexOptions.None, new string[] { "abc" } }; yield return new object[] { engine, null, @".*abc|ghi", "ghi", RegexOptions.None, new string[] { "ghi" } }; - yield return new object[] { engine, null, @".*abc|.*ghi", "abcghi", RegexOptions.None, new string[] { "abc" }, "abcghi" }; // <-- Nonbacktracking match same as for ".*ghi|.*abc" + yield return new object[] { engine, null, @".*abc|.*ghi", "abcghi", RegexOptions.None, new string[] { "abc" } }; yield return new object[] { engine, null, @".*ghi|.*abc", "abcghi", RegexOptions.None, new string[] { "abcghi" } }; yield return new object[] { engine, null, @".*abc|.*ghi", "bcghi", RegexOptions.None, new string[] { "bcghi" } }; yield return new object[] { engine, null, @".*abc|.+c", " \n \n bc", RegexOptions.None, new string[] { " bc" } }; @@ -941,7 +940,7 @@ public static IEnumerable Groups_CustomCulture_TestData_AzeriLatin() [MemberData(nameof(Groups_CustomCulture_TestData_AzeriLatin))] [ActiveIssue("https://github.com/dotnet/runtime/issues/56407", TestPlatforms.Android)] [ActiveIssue("https://github.com/dotnet/runtime/issues/36900", TestPlatforms.iOS | TestPlatforms.tvOS | TestPlatforms.MacCatalyst)] - public async Task Groups(RegexEngine engine, string cultureName, string pattern, string input, RegexOptions options, string[] expectedGroups, string altMatch = null) + public async Task Groups(RegexEngine engine, string cultureName, string pattern, string input, RegexOptions options, string[] expectedGroups) { if (cultureName is null) { @@ -949,12 +948,6 @@ public async Task Groups(RegexEngine engine, string cultureName, string pattern, cultureName = culture.Equals(CultureInfo.InvariantCulture) ? "en-US" : culture.Name; } - // Alternative altMatch when order of alternations matters in backtracking but order does not matter in NonBacktracking mode - // Also in NonBacktracking there is only a single top-level match, which is expectedGroups[0] when altMatch is null - expectedGroups = engine == RegexEngine.NonBacktracking ? - new string[] { altMatch ?? expectedGroups[0] } : - expectedGroups; - if (engine == RegexEngine.NonBacktracking && pattern.Contains("?(cat)")) { // General if-then-else construct is not supported and uses the ?(cat) condition in the tests @@ -980,20 +973,17 @@ public async Task Groups(RegexEngine engine, string cultureName, string pattern, Assert.True(match.Success); Assert.Equal(expectedGroups[0], match.Value); - if (!RegexHelpers.IsNonBacktracking(engine)) - { - Assert.Equal(expectedGroups.Length, match.Groups.Count); + Assert.Equal(expectedGroups.Length, match.Groups.Count); - int[] groupNumbers = regex.GetGroupNumbers(); - string[] groupNames = regex.GetGroupNames(); - for (int i = 0; i < expectedGroups.Length; i++) - { - Assert.Equal(expectedGroups[i], match.Groups[groupNumbers[i]].Value); - Assert.Equal(match.Groups[groupNumbers[i]], match.Groups[groupNames[i]]); + int[] groupNumbers = regex.GetGroupNumbers(); + string[] groupNames = regex.GetGroupNames(); + for (int i = 0; i < expectedGroups.Length; i++) + { + Assert.Equal(expectedGroups[i], match.Groups[groupNumbers[i]].Value); + Assert.Equal(match.Groups[groupNumbers[i]], match.Groups[groupNames[i]]); - Assert.Equal(groupNumbers[i], regex.GroupNumberFromName(groupNames[i])); - Assert.Equal(groupNames[i], regex.GroupNameFromNumber(groupNumbers[i])); - } + Assert.Equal(groupNumbers[i], regex.GroupNumberFromName(groupNames[i])); + Assert.Equal(groupNames[i], regex.GroupNameFromNumber(groupNumbers[i])); } } diff --git a/src/libraries/System.Text.RegularExpressions/tests/Regex.KnownPattern.Tests.cs b/src/libraries/System.Text.RegularExpressions/tests/Regex.KnownPattern.Tests.cs index 3deec76d1528b8..51e55b4013b683 100644 --- a/src/libraries/System.Text.RegularExpressions/tests/Regex.KnownPattern.Tests.cs +++ b/src/libraries/System.Text.RegularExpressions/tests/Regex.KnownPattern.Tests.cs @@ -38,27 +38,18 @@ public async Task Docs_Examples_ScanningHrefs(RegexEngine engine) Match m = r.Match(InputString); Assert.True(m.Success); - if (!RegexHelpers.IsNonBacktracking(engine)) - { - Assert.Equal("http://msdn2.microsoft.com", m.Groups[1].ToString()); - Assert.Equal(43, m.Groups[1].Index); - } + Assert.Equal("http://msdn2.microsoft.com", m.Groups[1].ToString()); + Assert.Equal(43, m.Groups[1].Index); m = m.NextMatch(); Assert.True(m.Success); - if (!RegexHelpers.IsNonBacktracking(engine)) - { - Assert.Equal("http://www.microsoft.com", m.Groups[1].ToString()); - Assert.Equal(102, m.Groups[1].Index); - } + Assert.Equal("http://www.microsoft.com", m.Groups[1].ToString()); + Assert.Equal(102, m.Groups[1].Index); m = m.NextMatch(); Assert.True(m.Success); - if (!RegexHelpers.IsNonBacktracking(engine)) - { - Assert.Equal("http://blogs.msdn.com/bclteam", m.Groups[1].ToString()); - Assert.Equal(176, m.Groups[1].Index); - } + Assert.Equal("http://blogs.msdn.com/bclteam", m.Groups[1].ToString()); + Assert.Equal(176, m.Groups[1].Index); m = m.NextMatch(); Assert.False(m.Success); @@ -69,12 +60,6 @@ public async Task Docs_Examples_ScanningHrefs(RegexEngine engine) [MemberData(nameof(RegexHelpers.AvailableEngines_MemberData), MemberType = typeof(RegexHelpers))] public async Task Docs_Examples_MDYtoDMY(RegexEngine engine) { - if (RegexHelpers.IsNonBacktracking(engine)) - { - // named group replacements not supported - return; - } - Regex r = await RegexHelpers.GetRegexAsync(engine, @"\b(?\d{1,2})/(?\d{1,2})/(?\d{2,4})\b"); string dt = new DateTime(2020, 1, 8, 0, 0, 0, DateTimeKind.Utc).ToString("d", DateTimeFormatInfo.InvariantInfo); @@ -89,10 +74,7 @@ public async Task Docs_Examples_ExtractProtocolPort(RegexEngine engine) Regex r = await RegexHelpers.GetRegexAsync(engine, @"^(?\w+)://[^/]+?(?:\d+)?/"); Match m = r.Match("http://www.contoso.com:8080/letters/readme.html"); Assert.True(m.Success); - if (!RegexHelpers.IsNonBacktracking(engine)) - { - Assert.Equal("http:8080", m.Result("${proto}${port}")); - } + Assert.Equal("http:8080", m.Result("${proto}${port}")); } public static IEnumerable Docs_Examples_ValidateEmail_TestData() @@ -218,7 +200,7 @@ public async Task Docs_GroupingConstructs_NamedMatchedSubexpression1(RegexEngine { if (RegexHelpers.IsNonBacktracking(engine)) { - // subcaptures not supported + // backreferences not supported return; } @@ -250,7 +232,7 @@ public async Task Docs_GroupingConstructs_NamedMatchedSubexpression2(RegexEngine { if (RegexHelpers.IsNonBacktracking(engine)) { - // subcaptures not supported + // multiple captures not supported return; } @@ -536,7 +518,7 @@ public async Task Docs_GroupingConstructs_GroupCaptureRelationship(RegexEngine e { if (RegexHelpers.IsNonBacktracking(engine)) { - // subcaptures not supported + // muultiple captures not supported return; } @@ -585,7 +567,7 @@ public async Task Docs_Capture_Sentences(RegexEngine engine) { if (RegexHelpers.IsNonBacktracking(engine)) { - // subcaptures not supported + // multiple captures not supported return; } @@ -643,7 +625,7 @@ public async Task Docs_Capture_ProductNumber(RegexEngine engine) { if (RegexHelpers.IsNonBacktracking(engine)) { - // subcaptures not supported + // multiple captures not supported return; } @@ -762,10 +744,7 @@ public async Task Docs_Backtracking_WithOptionalQuantifiersOrAlternationConstruc Assert.True(m.Success); Assert.Equal("Essential services are provided by regular expres", m.Value); Assert.Equal(0, m.Index); - if (!RegexHelpers.IsNonBacktracking(engine)) - { - Assert.Equal(47, m.Groups[1].Index); - } + Assert.Equal(47, m.Groups[1].Index); Assert.False(m.NextMatch().Success); } @@ -849,18 +828,12 @@ public async Task Docs_EngineCapabilities_LazyQuantifiers(RegexEngine engine) Regex rGreedy = await RegexHelpers.GetRegexAsync(engine, @".+(\d+)\."); Match match = rGreedy.Match(Input); Assert.True(match.Success); - if (!RegexHelpers.IsNonBacktracking(engine)) - { - Assert.Equal("5", match.Groups[1].Value); - } + Assert.Equal("5", match.Groups[1].Value); Regex rLazy = await RegexHelpers.GetRegexAsync(engine, @".+?(\d+)\."); match = rLazy.Match(Input); Assert.True(match.Success); - if (!RegexHelpers.IsNonBacktracking(engine)) - { - Assert.Equal("107325", match.Groups[1].Value); - } + Assert.Equal("107325", match.Groups[1].Value); } // https://docs.microsoft.com/en-us/dotnet/standard/base-types/details-of-regular-expression-behavior#net-framework-engine-capabilities @@ -991,12 +964,6 @@ public async Task Docs_EngineCapabilities_PositiveNegativeLookbehind(RegexEngine [MemberData(nameof(RegexHelpers.AvailableEngines_MemberData), MemberType = typeof(RegexHelpers))] public async Task Docs_InlineOptions(RegexEngine engine) { - if (RegexHelpers.IsNonBacktracking(engine)) - { - // subcaptures not supported - return; - } - const string Input = "double dare double Double a Drooling dog The Dreaded Deep"; var actual = new StringBuilder(); @@ -1052,20 +1019,14 @@ public async Task Docs_InlineComment(RegexEngine engine) Match match = r.Match(Input); Assert.True(match.Success); Assert.Equal("Drooling dog", match.Value); - if (!RegexHelpers.IsNonBacktracking(engine)) - { - Assert.Equal(2, match.Groups.Count); - Assert.Equal("Drooling", match.Groups[1].Value); - } + Assert.Equal(2, match.Groups.Count); + Assert.Equal("Drooling", match.Groups[1].Value); match = match.NextMatch(); Assert.True(match.Success); Assert.Equal("Dreaded Deep", match.Value); - if (!RegexHelpers.IsNonBacktracking(engine)) - { - Assert.Equal(2, match.Groups.Count); - Assert.Equal("Dreaded", match.Groups[1].Value); - } + Assert.Equal(2, match.Groups.Count); + Assert.Equal("Dreaded", match.Groups[1].Value); Assert.False(match.NextMatch().Success); } diff --git a/src/libraries/System.Text.RegularExpressions/tests/Regex.Match.Tests.cs b/src/libraries/System.Text.RegularExpressions/tests/Regex.Match.Tests.cs index 61b680095effad..1bbd6a0a719029 100644 --- a/src/libraries/System.Text.RegularExpressions/tests/Regex.Match.Tests.cs +++ b/src/libraries/System.Text.RegularExpressions/tests/Regex.Match.Tests.cs @@ -233,9 +233,9 @@ public static IEnumerable Match_MemberData() yield return (@"(?>\w+?)(? Match_MemberData() } // Nested loops - if (!RegexHelpers.IsNonBacktracking(engine)) - { - yield return ("a*(?:a[ab]*)*", "aaaababbbbbbabababababaaabbb", RegexOptions.None, 0, 28, true, "aaaa"); - yield return ("a*(?:a[ab]*?)*?", "aaaababbbbbbabababababaaabbb", RegexOptions.None, 0, 28, true, "aaaa"); - } + yield return ("a*(?:a[ab]*)*", "aaaababbbbbbabababababaaabbb", RegexOptions.None, 0, 28, true, "aaaa"); + yield return ("a*(?:a[ab]*?)*?", "aaaababbbbbbabababababaaabbb", RegexOptions.None, 0, 28, true, "aaaa"); // Using beginning/end of string chars \A, \Z: Actual - "\\Aaaa\\w+zzz\\Z" yield return (@"\Aaaa\w+zzz\Z", "aaaasdfajsdlfjzzz", RegexOptions.IgnoreCase, 0, 17, true, "aaaasdfajsdlfjzzz"); @@ -555,7 +552,6 @@ public static IEnumerable Match_MemberData() yield return (@"(?(\w+)\w+)dog", "catdog", RegexOptions.None, 0, 6, true, "catdog"); yield return (@"(?(abc)\w+|\w{0,2})dog", "catdog", RegexOptions.None, 0, 6, true, "atdog"); yield return (@"(?(abc)cat|\w{0,2})dog", "catdog", RegexOptions.None, 0, 6, true, "atdog"); - yield return (@"(\w+|\d+)a+[ab]+", "123123aa", RegexOptions.None, 0, 8, true, "123123aa"); yield return ("(a|ab|abc|abcd)d", "abcd", RegexOptions.RightToLeft, 0, 4, true, "abcd"); yield return ("(?>(?:a|ab|abc|abcd))d", "abcd", RegexOptions.None, 0, 4, false, string.Empty); yield return ("(?>(?:a|ab|abc|abcd))d", "abcd", RegexOptions.RightToLeft, 0, 4, true, "abcd"); @@ -875,11 +871,8 @@ void VerifyMatch(Match match) // Groups can never be empty Assert.True(match.Groups.Count >= 1); - if (!RegexHelpers.IsNonBacktracking(engine)) - { - Assert.Equal(expectedSuccess, match.Groups[0].Success); - RegexAssert.Equal(expectedValue, match.Groups[0]); - } + Assert.Equal(expectedSuccess, match.Groups[0].Success); + RegexAssert.Equal(expectedValue, match.Groups[0]); } } @@ -1440,11 +1433,6 @@ void VerifyMatch(Match match) Assert.Equal(expected[0].Index, match.Index); Assert.Equal(expected[0].Length, match.Length); - if (RegexHelpers.IsNonBacktracking(engine)) - { - return; - } - Assert.Equal(1, match.Captures.Count); RegexAssert.Equal(expected[0].Value, match.Captures[0]); Assert.Equal(expected[0].Index, match.Captures[0].Index); @@ -1459,12 +1447,24 @@ void VerifyMatch(Match match) Assert.Equal(expected[i].Index, match.Groups[i].Index); Assert.Equal(expected[i].Length, match.Groups[i].Length); - Assert.Equal(expected[i].Captures.Length, match.Groups[i].Captures.Count); - for (int j = 0; j < match.Groups[i].Captures.Count; j++) + if (!RegexHelpers.IsNonBacktracking(engine)) + { + Assert.Equal(expected[i].Captures.Length, match.Groups[i].Captures.Count); + for (int j = 0; j < match.Groups[i].Captures.Count; j++) + { + RegexAssert.Equal(expected[i].Captures[j].Value, match.Groups[i].Captures[j]); + Assert.Equal(expected[i].Captures[j].Index, match.Groups[i].Captures[j].Index); + Assert.Equal(expected[i].Captures[j].Length, match.Groups[i].Captures[j].Length); + } + } + else { - RegexAssert.Equal(expected[i].Captures[j].Value, match.Groups[i].Captures[j]); - Assert.Equal(expected[i].Captures[j].Index, match.Groups[i].Captures[j].Index); - Assert.Equal(expected[i].Captures[j].Length, match.Groups[i].Captures[j].Length); + // NonBacktracking does not support multiple captures + Assert.Equal(1, match.Groups[i].Captures.Count); + int lastExpected = expected[i].Captures.Length - 1; + RegexAssert.Equal(expected[i].Captures[lastExpected].Value, match.Groups[i].Captures[0]); + Assert.Equal(expected[i].Captures[lastExpected].Index, match.Groups[i].Captures[0].Index); + Assert.Equal(expected[i].Captures[lastExpected].Length, match.Groups[i].Captures[0].Length); } } } @@ -2030,25 +2030,12 @@ public async Task Match_DisjunctionOverCounting(RegexEngine engine, string disju public static IEnumerable MatchAmbiguousRegexes_TestData() { - // Different results in NonBacktracking vs backtracking engines - yield return new object[] { RegexEngine.NonBacktracking, "(a|ab|c|bcd){0,}d*", "ababcd", (0, 6) }; - yield return new object[] { RegexEngine.NonBacktracking, "(a|ab|c|bcd){0,10}d*", "ababcd", (0, 6) }; - yield return new object[] { RegexEngine.NonBacktracking, "(a|ab|c|bcd)*d*", "ababcd", (0, 6) }; - yield return new object[] { RegexEngine.NonBacktracking, @"(the)\s*([12][0-9]|3[01]|0?[1-9])", "it is the 10:00 time", (6, 5) }; - foreach (RegexEngine engine in RegexHelpers.AvailableEngines) { - if (engine == RegexEngine.NonBacktracking) continue; - yield return new object[] { engine, "(a|ab|c|bcd){0,}d*", "ababcd", (0, 1) }; yield return new object[] { engine, "(a|ab|c|bcd){0,10}d*", "ababcd", (0, 1) }; yield return new object[] { engine, "(a|ab|c|bcd)*d*", "ababcd", (0, 1) }; yield return new object[] { engine, @"(the)\s*([12][0-9]|3[01]|0?[1-9])", "it is the 10:00 time", (6, 6) }; - } - - // Same results in all engines after reordering of the alternatives above - foreach (RegexEngine engine in RegexHelpers.AvailableEngines) - { yield return new object[] { engine, "(ab|a|bcd|c){0,}d*", "ababcd", (0, 6) }; yield return new object[] { engine, "(ab|a|bcd|c){0,10}d*", "ababcd", (0, 6) }; yield return new object[] { engine, "(ab|a|bcd|c)*d*", "ababcd", (0, 6) }; @@ -2056,11 +2043,6 @@ public static IEnumerable MatchAmbiguousRegexes_TestData() } } - /// - /// NonBacktracking engine ignores the order of alternatives in a union, - /// while a backtracking engine takes the order into account. - /// This may lead to different matches in ambiguous regexes. - /// [Theory] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Doesn't support NonBacktracking")] [MemberData(nameof(MatchAmbiguousRegexes_TestData))] diff --git a/src/libraries/System.Text.RegularExpressions/tests/Regex.Replace.Tests.cs b/src/libraries/System.Text.RegularExpressions/tests/Regex.Replace.Tests.cs index e10591eb00cf20..64acde893a3ab6 100644 --- a/src/libraries/System.Text.RegularExpressions/tests/Regex.Replace.Tests.cs +++ b/src/libraries/System.Text.RegularExpressions/tests/Regex.Replace.Tests.cs @@ -335,12 +335,6 @@ public void Replace_Invalid() AssertExtensions.Throws("startat", () => new Regex("pattern").Replace("input", "replacement", 0, 6)); AssertExtensions.Throws("startat", () => new Regex("pattern").Replace("input", new MatchEvaluator(MatchEvaluator1), 0, 6)); - - if (PlatformDetection.IsNetCore) - { - // Substitutions not supported in NonBacktracking mode - Assert.Throws(() => new Regex("pattern", RegexHelpers.RegexOptionNonBacktracking).Replace("input", "$1", -1)); - } } public static string MatchEvaluator1(Match match) => match.Value.ToLower() == "big" ? "Huge": "Tiny"; @@ -398,18 +392,10 @@ public static IEnumerable TestReplaceWithSubstitution_TestData() [MemberData(nameof(TestReplaceWithSubstitution_TestData))] private void TestReplaceWithSubstitution(string pattern, string input, string replacement, string expectedoutput, RegexOptions opt) { - if (opt == RegexHelpers.RegexOptionNonBacktracking) - { - Assert.Throws(() => Regex.Replace(input, pattern, replacement, opt)); - Assert.Throws(() => new Regex(pattern, opt).Replace(input, replacement, -1)); - } - else - { - var output = new Regex(pattern, opt).Replace(input, replacement, -1); - Assert.Equal(expectedoutput, output); - var output2 = Regex.Replace(input, pattern, replacement, opt); - Assert.Equal(expectedoutput, output2); - } + var output = new Regex(pattern, opt).Replace(input, replacement, -1); + Assert.Equal(expectedoutput, output); + var output2 = Regex.Replace(input, pattern, replacement, opt); + Assert.Equal(expectedoutput, output2); } public static IEnumerable TestReplaceWithToUpperMatchEvaluator_TestData() diff --git a/src/libraries/System.Text.RegularExpressions/tests/Regex.Split.Tests.cs b/src/libraries/System.Text.RegularExpressions/tests/Regex.Split.Tests.cs index 474d4712b9a83e..8e821af1da3c6c 100644 --- a/src/libraries/System.Text.RegularExpressions/tests/Regex.Split.Tests.cs +++ b/src/libraries/System.Text.RegularExpressions/tests/Regex.Split.Tests.cs @@ -33,19 +33,18 @@ public static IEnumerable Split_TestData() yield return new object[] { engine, @"\b", "Hello World!", RegexOptions.None, 0, 0, new string[] { "", "Hello", " ", "World", "!" } }; yield return new object[] { engine, @"^", "Hello \nWorld!", RegexOptions.None | RegexOptions.Multiline, 0, 0, new string[] { "", "Hello \n", "World!" } }; yield return new object[] { engine, @"$", "Hello \nWorld!", RegexOptions.None | RegexOptions.Multiline, 0, 0, new string[] { "Hello ", "\nWorld!", "" } }; + yield return new object[] { engine, @"(\s)?(-)", "once -upon-a time", RegexOptions.None, 17, 0, new string[] { "once", " ", "-", "upon", "-", "a time" } }; + yield return new object[] { engine, @"(\s)?(-)", "once upon a time", RegexOptions.None, 16, 0, new string[] { "once upon a time" } }; + yield return new object[] { engine, @"(\s)?(-)", "once - -upon- a- time", RegexOptions.None, 21, 0, new string[] { "once", " ", "-", "", " ", "-", "upon", "-", " a", "-", " time" } }; - if (!RegexHelpers.IsNonBacktracking(engine)) - { - yield return new object[] { engine, @"(\s)?(-)", "once -upon-a time", RegexOptions.None, 17, 0, new string[] { "once", " ", "-", "upon", "-", "a time" } }; - yield return new object[] { engine, @"(\s)?(-)", "once upon a time", RegexOptions.None, 16, 0, new string[] { "once upon a time" } }; - yield return new object[] { engine, @"(\s)?(-)", "once - -upon- a- time", RegexOptions.None, 21, 0, new string[] { "once", " ", "-", "", " ", "-", "upon", "-", " a", "-", " time" } }; - - yield return new object[] { engine, "a(.)c(.)e", "123abcde456aBCDe789", RegexOptions.None, 19, 0, new string[] { "123", "b", "d", "456aBCDe789" } }; - yield return new object[] { engine, "a(.)c(.)e", "123abcde456aBCDe789", RegexOptions.IgnoreCase, 19, 0, new string[] { "123", "b", "d", "456", "B", "D", "789" } }; + yield return new object[] { engine, "a(.)c(.)e", "123abcde456aBCDe789", RegexOptions.None, 19, 0, new string[] { "123", "b", "d", "456aBCDe789" } }; + yield return new object[] { engine, "a(.)c(.)e", "123abcde456aBCDe789", RegexOptions.IgnoreCase, 19, 0, new string[] { "123", "b", "d", "456", "B", "D", "789" } }; - yield return new object[] { engine, "a(?.)c(.)e", "123abcde456aBCDe789", RegexOptions.None, 19, 0, new string[] { "123", "d", "b", "456aBCDe789" } }; - yield return new object[] { engine, "a(?.)c(.)e", "123abcde456aBCDe789", RegexOptions.IgnoreCase, 19, 0, new string[] { "123", "d", "b", "456", "D", "B", "789" } }; + yield return new object[] { engine, "a(?.)c(.)e", "123abcde456aBCDe789", RegexOptions.None, 19, 0, new string[] { "123", "d", "b", "456aBCDe789" } }; + yield return new object[] { engine, "a(?.)c(.)e", "123abcde456aBCDe789", RegexOptions.IgnoreCase, 19, 0, new string[] { "123", "d", "b", "456", "D", "B", "789" } }; + if (!RegexHelpers.IsNonBacktracking(engine)) + { // RightToLeft yield return new object[] { engine, "", "", RegexOptions.RightToLeft, 0, 0, new string[] { "", "" } }; yield return new object[] { engine, "123", "abc", RegexOptions.RightToLeft, 3, 0, new string[] { "abc" } }; @@ -66,28 +65,6 @@ public static IEnumerable Split_TestData() // Anchors yield return new object[] { engine, @"(?<=\G..)(?=..)", "aabbccdd", RegexOptions.None, 8, 0, new string[] { "aa", "bb", "cc", "dd" } }; } - - if (RegexHelpers.IsNonBacktracking(engine)) - { - // RegexOptions.NonBacktracking also ignores named captures as if they were not given - yield return new object[] { engine, "a(?.)c(.)e", "123abcde456aBCDe789", RegexOptions.None, 19, 0, new string[] { "123", "456aBCDe789" } }; - yield return new object[] { engine, "a(?.)c(.)e", "123abcde456aBCDe789", RegexOptions.IgnoreCase, 19, 0, new string[] { "123", "456", "789" } }; - } - - // RegexOptions.NonBacktracking is similar to RegexOptions.ExplicitCapture when there are no explicit capture names because NonBacktracking does not support captures - // This is the reason for including the RegexOptions.ExplicitCapture options also to check that the results are the same in this case - foreach (RegexOptions options in new[] { RegexOptions.None, RegexOptions.ExplicitCapture }) - { - if (options != RegexOptions.None || RegexHelpers.IsNonBacktracking(engine)) - { - yield return new object[] { engine, @"(\s)?(-)", "once -upon-a time", options, 17, 0, new string[] { "once", "upon", "a time" } }; - yield return new object[] { engine, @"(\s)?(-)", "once upon a time", options, 16, 0, new string[] { "once upon a time" } }; - yield return new object[] { engine, @"(\s)?(-)", "once - -upon- a- time", options, 21, 0, new string[] { "once", "", "upon", " a", " time" } }; - yield return new object[] { engine, "a(.)c(.)e", "123abcde456aBCDe789", options, 19, 0, new string[] { "123", "456aBCDe789" } }; - yield return new object[] { engine, "a.c.e", "123abcde456aBCDe789", options, 19, 0, new string[] { "123", "456aBCDe789" } }; - yield return new object[] { engine, "a.c.e", "123abcde456aBCDe789", options | RegexOptions.IgnoreCase, 19, 0, new string[] { "123", "456", "789" } }; - } - } } } diff --git a/src/libraries/System.Text.RegularExpressions/tests/RegexExperiment.cs b/src/libraries/System.Text.RegularExpressions/tests/RegexExperiment.cs index 3f27aab3d89b86..da9b09ecb74262 100644 --- a/src/libraries/System.Text.RegularExpressions/tests/RegexExperiment.cs +++ b/src/libraries/System.Text.RegularExpressions/tests/RegexExperiment.cs @@ -1,4 +1,4 @@ -// Licensed to the .NET Foundation under one or more agreements.if #DEBUG +// Licensed to the .NET Foundation under one or more agreements.if #DEBUG // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; @@ -110,7 +110,7 @@ private static long MeasureMatchTime(Regex re, string input, out Match match) /// private static string And(params string[] regexes) { - string conj = $"({regexes[regexes.Length - 1]})"; + string conj = $"(?:{regexes[regexes.Length - 1]})"; for (int i = regexes.Length - 2; i >= 0; i--) { conj = $"(?({regexes[i]}){conj}|[0-[0]])"; @@ -230,7 +230,7 @@ public void SRMTest_ComplementFindMatch() { // contains lower, upper, and a digit, and is between 4 and 8 characters long, does not contain 2 consequtive digits var re = new Regex(And(".*[a-z].*", ".*[A-Z].*", ".*[0-9].*", ".{4,8}", - Not(".*(01|12|23|34|45|56|67|78|89).*")), RegexHelpers.RegexOptionNonBacktracking | RegexOptions.Singleline); + Not(".*(?:01|12|23|34|45|56|67|78|89).*")), RegexHelpers.RegexOptionNonBacktracking | RegexOptions.Singleline); var match = re.Match("xxaac12Bxaas3455"); Assert.True(match.Success); Assert.Equal(6, match.Index); @@ -252,8 +252,8 @@ public void PasswordSearch() string twoUpper = ".*[A-Z].*[A-Z].*"; string threeDigits = ".*[0-9].*[0-9].*[0-9].*"; string oneSpecial = @".*[\x21-\x2F\x3A-\x40\x5B-x60\x7B-\x7E].*"; - string Not_countUp = Not(".*(012|123|234|345|456|567|678|789).*"); - string Not_countDown = Not(".*(987|876|765|654|543|432|321|210).*"); + string Not_countUp = Not(".*(?:012|123|234|345|456|567|678|789).*"); + string Not_countDown = Not(".*(?:987|876|765|654|543|432|321|210).*"); // Observe that the space character (immediately before '!' in ASCII) is excluded string length = "[!-~]{8,12}"; @@ -336,8 +336,8 @@ public void PasswordSearchDual() string Not_twoUpper = Not(".*[A-Z].*[A-Z].*"); string Not_threeDigits = Not(".*[0-9].*[0-9].*[0-9].*"); string Not_oneSpecial = Not(@".*[\x21-\x2F\x3A-\x40\x5B-x60\x7B-\x7E].*"); - string countUp = ".*(012|123|234|345|456|567|678|789).*"; - string countDown = ".*(987|876|765|654|543|432|321|210).*"; + string countUp = ".*(?:012|123|234|345|456|567|678|789).*"; + string countDown = ".*(?:987|876|765|654|543|432|321|210).*"; // Observe that the space character (immediately before '!' in ASCII) is excluded string Not_length = Not("[!-~]{8,12}"); From 3436ba0a86b7d792e57526f7207b65de69feb1de Mon Sep 17 00:00:00 2001 From: Olli Saarikivi Date: Fri, 4 Feb 2022 13:42:35 -0800 Subject: [PATCH 06/29] Use new eager derivative even without subcaptures This ensures the correct length matches always. --- .../Symbolic/SymbolicRegexMatcher.cs | 20 ++----------------- 1 file changed, 2 insertions(+), 18 deletions(-) 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 64423713941efe..ac256991fff4a9 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 @@ -501,24 +501,8 @@ public SymbolicMatch FindMatch(bool isMatch, ReadOnlySpan input, int start FindStartPosition(input, i, i_q0_A1); // Walk in reverse to locate the start position of the match } - int i_end; - if (_capsize == 1) - { - if (watchdog >= 0) - { - i_end = i; - } - else - { - i_end = FindEndPosition(input, end, i_start); - } - return new SymbolicMatch(i_start, i_end + 1 - i_start); - } - else - { - i_end = FindEndPositionCapturing(input, end, i_start, out Registers endRegisters); - return new SymbolicMatch(i_start, i_end + 1 - i_start, endRegisters.captureStarts, endRegisters.captureEnds); - } + int i_end = FindEndPositionCapturing(input, end, i_start, out Registers endRegisters); + 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. From 23f929916b67820f79cc28e3dd6247ff35b4e044 Mon Sep 17 00:00:00 2001 From: Olli Saarikivi Date: Fri, 4 Feb 2022 14:15:30 -0800 Subject: [PATCH 07/29] Enable more subcapture tests for NonBacktracking --- .../tests/AttRegexTests.cs | 1 - .../tests/Regex.Groups.Tests.cs | 7 -- .../tests/Regex.KnownPattern.Tests.cs | 28 ++----- .../tests/Regex.Match.Tests.cs | 11 +-- .../tests/Regex.Replace.Tests.cs | 84 +++++++++---------- 5 files changed, 52 insertions(+), 79 deletions(-) diff --git a/src/libraries/System.Text.RegularExpressions/tests/AttRegexTests.cs b/src/libraries/System.Text.RegularExpressions/tests/AttRegexTests.cs index 2f901133391278..850d0ac01264f9 100644 --- a/src/libraries/System.Text.RegularExpressions/tests/AttRegexTests.cs +++ b/src/libraries/System.Text.RegularExpressions/tests/AttRegexTests.cs @@ -419,7 +419,6 @@ public async Task Test(RegexEngine engine, RegexOptions options, string pattern, .Cast() .Select(g => (start: g.Index, end: g.Index + g.Length))); - // NonBacktracking mode only provides the top-level match. // The .NET implementation sometimes has extra captures beyond what the original data specifies, so we assert a subset. if (!expectedSet.IsSubsetOf(actualSet)) { diff --git a/src/libraries/System.Text.RegularExpressions/tests/Regex.Groups.Tests.cs b/src/libraries/System.Text.RegularExpressions/tests/Regex.Groups.Tests.cs index 15c47692303ba3..e326661d5f16b3 100644 --- a/src/libraries/System.Text.RegularExpressions/tests/Regex.Groups.Tests.cs +++ b/src/libraries/System.Text.RegularExpressions/tests/Regex.Groups.Tests.cs @@ -948,13 +948,6 @@ public async Task Groups(RegexEngine engine, string cultureName, string pattern, cultureName = culture.Equals(CultureInfo.InvariantCulture) ? "en-US" : culture.Name; } - if (engine == RegexEngine.NonBacktracking && pattern.Contains("?(cat)")) - { - // General if-then-else construct is not supported and uses the ?(cat) condition in the tests - // TODO-NONBACKTRACKING: The constructor will throw NotSupportedException so this check will become obsolete - return; - } - using var _ = new ThreadCultureChange(cultureName); Regex regex; diff --git a/src/libraries/System.Text.RegularExpressions/tests/Regex.KnownPattern.Tests.cs b/src/libraries/System.Text.RegularExpressions/tests/Regex.KnownPattern.Tests.cs index 51e55b4013b683..5a92535b4b315f 100644 --- a/src/libraries/System.Text.RegularExpressions/tests/Regex.KnownPattern.Tests.cs +++ b/src/libraries/System.Text.RegularExpressions/tests/Regex.KnownPattern.Tests.cs @@ -518,7 +518,7 @@ public async Task Docs_GroupingConstructs_GroupCaptureRelationship(RegexEngine e { if (RegexHelpers.IsNonBacktracking(engine)) { - // muultiple captures not supported + // multiple captures not supported return; } @@ -1189,11 +1189,8 @@ public async Task RealWorld_ExtractResourceUri(RegexEngine engine, string url, s Regex r = await RegexHelpers.GetRegexAsync(engine, @"/providers/(.+?)\?"); Match m = r.Match(url); Assert.True(m.Success); - if (!RegexHelpers.IsNonBacktracking(engine)) - { - Assert.Equal(2, m.Groups.Count); - Assert.Equal(expected, m.Groups[1].Value); - } + Assert.Equal(2, m.Groups.Count); + Assert.Equal(expected, m.Groups[1].Value); } public static IEnumerable RealWorld_IsValidCSharpName_MemberData() @@ -1299,10 +1296,7 @@ public async Task RealWorld_ValueParse(RegexEngine engine, string value, string Regex r = await RegexHelpers.GetRegexAsync(engine, @"(?-?\d+(\.\d+)?)"); Match m = r.Match(value); Assert.True(m.Success); - if (!RegexHelpers.IsNonBacktracking(engine)) // named capture groups unsupported - { - Assert.Equal(expected, m.Groups["value"].Value); - } + Assert.Equal(expected, m.Groups["value"].Value); } public static IEnumerable RealWorld_FirebirdVersionString_MemberData() @@ -1321,10 +1315,7 @@ public async Task RealWorld_FirebirdVersionString(RegexEngine engine, string val Regex r = await RegexHelpers.GetRegexAsync(engine, @"\w{2}-\w(\d+\.\d+\.\d+\.\d+)"); Match m = r.Match(value); Assert.True(m.Success); - if (!RegexHelpers.IsNonBacktracking(engine)) - { - Assert.Equal(expected, m.Groups[1].Value); - } + Assert.Equal(expected, m.Groups[1].Value); } public static IEnumerable RealWorld_ExternalEntryPoint_MemberData() @@ -1345,12 +1336,9 @@ public async Task RealWorld_ExternalEntryPoint(RegexEngine engine, string value, Regex r = await RegexHelpers.GetRegexAsync(engine, @"^(.+)!(.+)\.([^.]+)$"); Match m = r.Match(value); Assert.True(m.Success); - if (!RegexHelpers.IsNonBacktracking(engine)) // subcaptures aren't supported - { - Assert.Equal(a, m.Groups[1].Value); - Assert.Equal(b, m.Groups[2].Value); - Assert.Equal(c, m.Groups[3].Value); - } + Assert.Equal(a, m.Groups[1].Value); + Assert.Equal(b, m.Groups[2].Value); + Assert.Equal(c, m.Groups[3].Value); } /// diff --git a/src/libraries/System.Text.RegularExpressions/tests/Regex.Match.Tests.cs b/src/libraries/System.Text.RegularExpressions/tests/Regex.Match.Tests.cs index 1bbd6a0a719029..bdb556cff5b21e 100644 --- a/src/libraries/System.Text.RegularExpressions/tests/Regex.Match.Tests.cs +++ b/src/libraries/System.Text.RegularExpressions/tests/Regex.Match.Tests.cs @@ -692,13 +692,10 @@ public static IEnumerable Match_MemberData() yield return (@".*?\nFoo", "\nfooThis should match", RegexOptions.IgnoreCase, 0, 21, true, "\nfoo"); yield return (@".*?\dFoo", "This1foo should match", RegexOptions.IgnoreCase, 0, 21, true, "This1foo"); - if (!RegexHelpers.IsNonBacktracking(engine)) // TODO: https://github.com/dotnet/runtime/issues/63395 - { - yield return (@".*?\dFoo", "This1foo should 2FoO match", RegexOptions.IgnoreCase, 0, 26, true, "This1foo"); - yield return (@".*?\dFoo", "This1Foo should 2fOo match", RegexOptions.IgnoreCase, 0, 26, true, "This1Foo"); - yield return (@".*?\dFo{2}", "This1foo should 2FoO match", RegexOptions.IgnoreCase, 0, 26, true, "This1foo"); - yield return (@".*?\dFo{2}", "This1Foo should 2fOo match", RegexOptions.IgnoreCase, 0, 26, true, "This1Foo"); - } + yield return (@".*?\dFoo", "This1foo should 2FoO match", RegexOptions.IgnoreCase, 0, 26, true, "This1foo"); + yield return (@".*?\dFoo", "This1Foo should 2fOo match", RegexOptions.IgnoreCase, 0, 26, true, "This1Foo"); + yield return (@".*?\dFo{2}", "This1foo should 2FoO match", RegexOptions.IgnoreCase, 0, 26, true, "This1foo"); + yield return (@".*?\dFo{2}", "This1Foo should 2fOo match", RegexOptions.IgnoreCase, 0, 26, true, "This1Foo"); yield return (@".*?\dfoo", "1fooThis1FOO should 1foo match", RegexOptions.IgnoreCase, 4, 9, true, "This1FOO"); if (!RegexHelpers.IsNonBacktracking(engine)) diff --git a/src/libraries/System.Text.RegularExpressions/tests/Regex.Replace.Tests.cs b/src/libraries/System.Text.RegularExpressions/tests/Regex.Replace.Tests.cs index 64acde893a3ab6..fcfe41f4d01337 100644 --- a/src/libraries/System.Text.RegularExpressions/tests/Regex.Replace.Tests.cs +++ b/src/libraries/System.Text.RegularExpressions/tests/Regex.Replace.Tests.cs @@ -24,56 +24,55 @@ public static IEnumerable Replace_String_TestData() // Stress yield return new object[] { engine, ".", new string('a', 1000), "b", RegexOptions.None, 1000, 0, new string('b', 1000) }; - if (!RegexHelpers.IsNonBacktracking(engine)) - { - // Undefined groups - yield return new object[] { engine, @"(?<256>cat)\s*(?<512>dog)", "slkfjsdcat dogkljeah", "STARTcat$2048$1024dogEND", RegexOptions.None, 20, 0, "slkfjsdSTARTcat$2048$1024dogENDkljeah" }; - yield return new object[] { engine, @"(?cat)\s*(?dog)", "slkfjsdcat dogkljeah", "START${catTWO}dogcat${dogTWO}END", RegexOptions.None, 20, 0, "slkfjsdSTART${catTWO}dogcat${dogTWO}ENDkljeah" }; - - // Replace with group numbers - yield return new object[] { engine, "([a-z]([a-z]([a-z]([a-z]([a-z]([a-z]([a-z]([a-z]([a-z]([a-z]([a-z]([a-z]([a-z]([a-z]([a-z])))))))))))))))", "abcdefghiklmnop", "$15", RegexOptions.None, 15, 0, "p" }; - yield return new object[] { engine, "([a-z]([a-z]([a-z]([a-z]([a-z]([a-z]([a-z]([a-z]([a-z]([a-z]([a-z]([a-z]([a-z]([a-z]([a-z])))))))))))))))", "abcdefghiklmnop", "$3", RegexOptions.None, 15, 0, "cdefghiklmnop" }; - yield return new object[] { engine, @"D\.(.+)", "D.Bau", "David $1", RegexOptions.None, 5, 0, "David Bau" }; - - // Stress - string pattern = string.Concat(Enumerable.Repeat("([a-z]", 1000).Concat(Enumerable.Repeat(")", 1000))); - string input = string.Concat(Enumerable.Repeat("abcde", 200)); - yield return new object[] { engine, pattern, input, "$1000", RegexOptions.None, input.Length, 0, "e" }; - yield return new object[] { engine, pattern, input, "$1", RegexOptions.None, input.Length, 0, input }; - - // Undefined group - yield return new object[] { engine, "([a_z])(.+)", "abc", "$3", RegexOptions.None, 3, 0, "$3" }; - yield return new object[] { engine, @"(?<256>cat)\s*(?<512>dog)", "slkfjsdcat dogkljeah", "STARTcat$2048$1024dogEND", RegexOptions.None, 20, 0, "slkfjsdSTARTcat$2048$1024dogENDkljeah" }; - - // Valid cases - yield return new object[] { engine, @"[^ ]+\s(?