Commit Graph
930 Commits
Author SHA1 Message Date
Stephen Toub 4c9b71b18e Fix double-negatives with MatchCharacterClass (#62636)
Also add missing set description rendering for \d, \D
2021-12-10 17:13:59 -05:00
Stephen Toub 7c70b5d9e8 Fix describing concatenations in alternations (#62646)
I was previously too aggressive in getting rid of concatenations in the comment rendering.  We would end up flattening concatenations into alternations erroneously.
2021-12-10 16:29:48 -05:00
Stephen Toub 7dcb2892c1 Add \w helper function to RegexCompiler / source generator (#62620) 2021-12-10 14:17:23 -05:00
Stephen Toub ecdad09b6e Relegate PatternsDataSet_ConstructRegexForAll_SourceGenerated test to 64-bit only (#62621) 2021-12-09 22:58:34 -07:00
Stephen Toub 61b5c92c15 A little more regex source generator tweaking (#62605)
* Remove now unecessary "Variable declared but never used" warning suppression

* Avoid declaring inputSpan in FindFirstChar if we don't have to

* Add RegexNode.Ref/Bol/Eol to non-backtracking list

* Move some additionalDeclarations back to where they're used

I was overaggressive in moving these to the beginning.  Some are fine where they're needed.

* Delete dead code

* Emit IsEmpty for more slice.Length checks

* Apply suggestions from code review
2021-12-09 21:16:40 -05:00
Stephen ToubandJose Perez Rodriguez 004a329c03 More regex source generator tweaks (#62539)
* Remove some unnecessary capture position locals

Now that we emit a helper function for the uncapturing loop, we no longer need a local to temporarily store a popped capture position from the stack.

* Consolidate a few declaration lines

* Clean up descriptions further.

* Fix blank lines between nodes

* Build atomic description into some child nodes instead

* Remove stale Debug.Fail being emitted

I'd included it initially for debugging and never removed it.

* Avoid ReserveName for a few iteration variables

* Fix missing ||

* Fix += in char loop to use EmitAdd

Mainly so that `+= 1` is instead rendered as the more idiomatic `++`

* Update warning level in tests to ensure we're observing all warnings

* Clean up loop descriptions a bit

- Use "exactly" for repeaters
- Put a comma before "optionally"
- Special-case a minimum of 2 as "twice"

* Delete defunct base.InitializeReferences call.

This is now a nop.

* Update src/libraries/System.Text.RegularExpressions/gen/RegexGenerator.Emitter.cs

Co-authored-by: Jose Perez Rodriguez <[email protected]>

Co-authored-by: Jose Perez Rodriguez <[email protected]>
2021-12-09 06:58:39 -05:00
Jose Perez Rodriguez b5799616ca Using ReadOnlySpan<char> on SymbolicRegexRunner (#62542) 2021-12-08 19:12:33 -08:00
Stephen Toub d21a020580 More cleanup for source generator (#62461)
* More cleanup for source generator

- Add more comments, both to the implementation and to the generated code
- Avoid an unnecessary goto in the last branch of an alternation
- Invert the backreference logic so that we don't have an extra else branch / level of nesting in the common case
- Add node type asserts to all EmitXx functions
- Move the open-coded uncapture loop into its own shared function
- Remove scoping when outputting a Nothing
- Swap the sides of some if clauses to make them more idiomatic
- Change some "if (i < 1)" to "if (i == 0)"
- Change some "if (0 < span.Length)" to be "if (!span.IsEmpty)"

* Fix renames across RegexCompiler / source generator
2021-12-07 09:32:08 -05:00
Jose Perez Rodriguez 22c75f089f Renaming some local variables to make the generated code more readable (#62460)
* Renaming some local variables to make the generated code more readable

* Renaming crawlpos as well.
2021-12-06 21:32:04 -05:00
Stephen Toub 9e8e4fc3cf Some more Regex cleanup and optimization (mostly source generator) (#62426)
* Reduce (?!) to nothing

The expression "(?!)" (an empty negative lookahead) is sometimes used in expressions at a point where we want to match nothing and thus fail a match, often in combination with a conditional operation.  This negative lookahead wrapped around an empty can be reduced to simply a Nothing, which is cheaper to process.

* Special-case an empty pattern in the source generator

* Output more idiomatic C# for some backreference conditionals

We currently output goto-based code, avoiding an actual if/else construct in case the child branches need to backtrack (and with the forced scoping for the if/else blocks, backtracking would result in compilation failures due to trying to jump to labels defined inside those scopes).  But if we know in advance that no such backtracking will happen, we can output the nicer if/else code.

* Improve code generated for backreferences

We were iterating through each individual character in our own open-coded loop, but for case-sensitive, we can just delegate to SequenceEqual.

* Avoid mutating RegexNode tree for expression conditionals

Rather than wrapping a node in a new positive lookahead assertion node, just call the logic to emit the node as if it were a positive lookahead.

* Change a few -1 comparisons to be 0 comparisons

Ever so slightly cheaper

* Factor stack pushing/popping into helper methods
2021-12-06 15:41:56 -05:00
Stephen Toub e968da215f Revise the Regex description output in source (#62369)
* Improve comments in generated Regex code

To help make the generated code easier to understand and debug.

* Format RegexOptions textually when possible
2021-12-06 13:58:53 -05:00
Stephen Toub 11e2315519 Add regex test for parsing runtime-assets expressions (#62344)
* Add regex test for parsing runtime-assets expressions

* Address PR feedback
2021-12-04 16:11:00 -05:00
Stephen Toub 2df4e53d1d Disable TestIgnoreCaseRelation test 2021-12-04 16:10:37 -05:00
Jose Perez Rodriguez 9f4809e8b9 Use Spans on Go() methods for Code Gen engines (#62324)
* Use Spans on Emitter Go() methods

* Use Spans on Compiler Go() methods

* Rename localSpan to slice in order to avoid confusion with runtextSpan
2021-12-03 18:45:02 -08:00
Stephen Toub 80ba698a41 Delete old code generation approach from RegexCompiler / source generator (#62318)
* Delete old code generation approach from RegexCompiler / source generator

In .NET Framework and up through .NET Core 3.1, the code generated for RegexOptions.Compiler was effectively an unrolled version of what RegexInterpreter would process.  The RegexNode tree would be turned into a series of opcodes via RegexWriter; the interpreter would then sit in a loop processing those opcodes, and the RegexCompiler iterates through the opcodes generating code for each equivalent to what the interpreter would do but with some decisions made at compile-time rather than at run-time.  This approach, however, leads to complicated code that's not pay-for-play (e.g. a big backtracking jump table that all compilations go through even if there's no backtracking), that doesn't factor in the shape of the tree (e.g. it's difficult to add optimizations based on interactions between nodes in the graph), and that doesn't read well when emitted as C# instead of IL as part of the source generator.  In .NET 5, we started adding an alternative implementation that processed the RegexNode tree directly, addressing all of those cited issues; however, it only worked for a subset of expressions, namely those with little-to-no backtracking (e.g. non-atomic loops and alternations weren't supported).  Since then, we've improved it to the point where everything other than RegexOptions.RightToLeft (which implicitly means lookbehinds as well) is supported, and we've agreed it's ok to drop compilation for those constructs; if they ever become an issue, we can add support for them via the new compilation scheme.

As such, this PR:
- Deletes all of the code associated with the older code generation scheme
- Updates the Regex ctor to fall back to selecting the interpreter if the expression can't be compiled
- Updates the source generator to fall back to just emitting a cached use of Regex if the expression can't be compiled (and issuing a diagnostic in that case)
- Adds several tests that now pass with the new scheme that didn't with the old (and that still don't with the interpreter)

* Make the addition of more declarations a bit more robust

* Reduce backtracking code gen when nodes are atomic

Also added some comments and renamed a few methods for consistency between RegexCompiler and RegexGenerator.Emitter

* Fix tests on mono interpreter
2021-12-03 17:09:51 -05:00
Dan Moseley c9f9697fe7 Add parser tests from nim-regex (#62093)
* new parser tests

* baseline

* Nim tests

* typos

* positive cases

* new parser tests

* change to \u
2021-12-03 12:52:18 -07:00
Stephen Toub 00246f9cd7 Disable TestIgnoreCaseRelationBorderCasesInNonBacktracking test (#62319) 2021-12-03 06:28:35 -05:00
Stephen Toub 53ed08bc0f Simplify code emitted for single char repeater (#62322)
Rather than outputting an if block per unrolled iteration, just output a clause for each iteration as part of a single if block.  We already do this for concatenations, but we don't yet for standalone repeaters.
2021-12-03 06:26:51 -05:00
Stephen Toub fd1a62cf51 Finish new code gen approach for RegexCompiler / source generator (#62268)
* Add an ifdef to compile one source generated test at a time

* Change the ATT test theory to factor out the engine

* Add a few tests and delete some unnecessary ones

* Finish the new code gen strategy (all but RightToLeft)

* Fix mono failures (hopefully)
2021-12-02 19:13:34 -05:00
Jose Perez Rodriguez 252b7c2227 Use ReadOnlySpan<char> on RegexCompiled engine. (#62245)
* Use ReadOnlySpan<char> on RegexCompiled engine.

* Fixing unit tests by correcting some bad IL.
2021-12-02 09:55:18 -05:00
Jose Perez RodriguezandStephen Toub da3a933a18 Use ReadOnlySpan<char> instead of strings on SourceGenerator engine (#62222)
Co-authored-by: Stephen Toub <[email protected]>
2021-12-01 16:38:28 -08:00
Jose Perez Rodriguez 6af8b243c9 Have RegexInterpreter work over ReadOnlySpan<char> instead of strings. (#62165) 2021-11-30 20:55:59 -08:00
dotnet bot 141dae43d9 Localized file check-in by OneLocBuild Task: Build definition ID 679: Build ID 1482158 (#61858) 2021-11-22 20:19:02 -08:00
Stephen Toub fc488523a9 Add backtracking loops, backreferences, and if-then-else constructs to Regex "simplified" code gen (#61906)
* Add a few tests for captures inside various constructs

* Slightly optimize creation of multis that don't participate in case conversion

* Add simple codegen support for backtracking Loops

* Add simple codegen support for backreferences

* Add simple codegen support for if-then-else backreference conditionals

* Add simple codegen support for if-then-else expression conditionals

* Flip default on MarkLabel emitting semicolon

Labels need to be followed by something other than a closing brace.  Previously I was trying to opt labels in to emitting a semi-colon, but it's too error prone.  Instead, we now by default emit a semicolon, and only skip it from call sites that opt-out because it's obvious they'll always be followed by code.

* Add simple codegen support for balancing groups

* Address PR feedback
2021-11-22 22:51:55 -05:00
Stephen Toub 259b561c38 Delete Regex timeout tests with RegexOptions.Debug (#61888)
We don't need these tests (the Debug flag is only compiled into Debug builds and is there for diagnostic purposes), and it seems these have been taking too long sporadically. 
Closes https://github.com/dotnet/runtime/issues/61794
2021-11-22 13:33:27 -05:00
Stephen Toub 28dd6aa784 Expand One/Notone/Setlazy support to Lazy (#61784)
The logic added in a recent PR to support simplified code generation for a Regex with {One/Notone/Set}lazy nodes is almost sufficient to support Lazy as well.  This fills the gap.  It also deletes an erroneous optimization added in .NET 5 that removed top-level Atomic nodes; the idea behind it was that such nodes are meaningless as, at the top-level, nothing can backtrack in anyway, but it then means that any node which is paying attention to whether its parent is Atomic may no longer find it (and that's needed by Lazy).
2021-11-19 07:06:58 -05:00
Stephen Toub 9e986b5704 Add single char lazy loop support to simplified Regex code gen (#61698)
* Reduce atomic single char lazy loops

* Add single char lazy loop support to simplified code gen
2021-11-18 09:30:24 -05:00
Steve Pfister 95e31446a2 Create runtime clone to manually kick off full test runs (#61641)
This change allows devs to manually kick off full test runs on the configurations that only execute smoke tests per PR. 

To kick things off, you can run /azp run runtime-manual
2021-11-17 21:51:40 -05:00
Stephen Toub 25237fab42 Factor out and improve the vectorization of RegexInterpreter.FindFirstChar (#61490)
* Factor out and improve the vectorization of RegexInterpreter.FindFirstChar

This change started with the "simple" goal of factoring out the FindFirstChar logic from RegexInterpreter and consuming it in SymbolicRegexMatcher.  The existing engines use FindFirstChar to quickly skip ahead to the next location that might possibly match, at which point they fall back to analyzing the whole pattern at that location.  SymbolicRegexMatcher (used by RegexOptions.NonBacktracking) had its own implementation for this, which it used any time it entered a start state.  This required non-trivial additional code to maintain, and there's no good reason it should be separate from the other engines.

However, what started out as a simple change grew due to regressions that resulted from differences in the implementations.  In particular, SymbolicRegexMatcher already works off of precomputed equivalence tables for casing, which gives it very different characteristics in this regard from the existing engines.  For example, SymbolicRegexMatcher's existing "skip ahead to the next possible match start location" logic already evaluated all the characters that could possibly start a match, which included variations of the same character when using IgnoreCase, but the existing RegexInterpreter logic didn't.  That discrepancy then results in a significant IgnoreCase regression for NonBacktracking due to losing the ability to use a vectorized search for the next starting location.  We already plan to shift the existing engines over to a plan where all of these equivalences are computed at construction time rather than using ToLower at both construction time and match time, so this PR takes some steps in that direction, doing so for most of ASCII.  This has added some temporary cruft, which we'll be able to delete once we fully shift the implementations over (which we should do in the near future).

Another difference was SymbolicRegexMatcher was enabling use of IndexOfAny for up to 5 characters, whereas RegexOptions.Compiled was only doing up to 3 characters, and RegexInterpreter wasn't doing for any number.  The PR now uses 5 everywhere.

However, the more characters involved, the more overhead there is to IndexOfAny, and for some inputs, the higher the chances are that IndexOfAny will find a match sooner, which means its overhead compounds more.  To help with that, we now not only compute the possible characters that might match at the beginning of the pattern, but also characters that might match at a fixed offset from the beginning of the pattern (e.g. in \d{3}-\d{2}-\d{4}, it will find the '-' at offset 3 and be able to vectorize a search for that and then back off by the relevant distance.  That then also means we might end up with multiple sets to choose to search for, and this PR borrows an idea from Rust, which is to use some rough frequency analysis to determine which set should be targeted.  It's not perfect, and we can update the texts use to seed the analysis (right now I based it primarily on *.cs files in dotnet/runtime and some Project Gutenberg texts), but it's good enough for these purposes for now.

We'd previously switched to using IndexOf for a case-sensitive prefix string, but still were using Boyer-Moore for case-insensitive.  Now that we're able to also vectorize a search for case-insensitive values (right now just ASCII letter, but that'll be fixed soon), we can just get rid of Boyer-Moore entirely.  This saves all the costs to do with constructing the Boyer-Moore tables and also avoids having to generate the Boyer-Moore implementations in RegexOptions.Compiled and the source generator.

The casing change also defeated some other optimizations already present.  For example, in .NET 5 we added an optimization whereby an alternation like `abcef|abcgh` would be transformed into `abc(?:ef|gh)`, and that would apply whether case-sensitive or case-insensitive.  But by transforming the expression at construction now for case-insensitive into `[Aa][Bb][Cc][Ee][Ff]|[Aa][Bb][Cc][Gg][Hh]`, that optimization was defeated.  I've added a new optimization pass for alternations that will detect common prefixes even if they're sets.

The casing change also revealed some cosmetic issues.  As part of the change, when we encounter a "multi" (a multi-character string in the pattern), we convert that single case-insensitive RegexNode to instead be one case-sensitive RegexNode per character, with a set for all the equivalent characters that can match.  This then defeats some of the nice formatting we had for multis in the source generator, so as part of this change, the source generator has been augmented to output nicer code for concatenations.  And because sets like [Ee] are now way more common (since e.g. a case-insensitive 'e' will be transformed into such a set), we also special-case that in both the source generator and RegexOptions.Compiled, to spit out the equivalent of `(c | 0x20) == 'e'` rather than `(c == 'E'| c == 'e')`.

Along the way, I cleaned up a few things as well, such as passing around a CultureInfo more rather than repeatedly calling CultureInfo.CurrentCulture, using CollectionsMarshal.GetValueRefOrAddDefault on a hot path to do with interning strings in a lookup table, tweaking SymbolicRegexRunnerFactory's Runner to itself be generic to avoid an extra layer of virtual dispatch per operation, and cleaning up code / comments in SymbolicRegexMatcher along the way.

For the most part the purpose of the change wasn't to improve perf, and in fact I was willing to accept some regressions in the name of consolidation.  There are a few regressions here, mostly small, and mostly for cases where we're simply paying an overhead for vectorization, e.g. where the current location is fine to match, or where the target character being searched for is very frequent.  Overall, though, there are some substantial improvements.

* Fix missing condition in RegexCompiler

* Try to fix mono failures and address comment feedback

* Delete more now dead code

* Fix dead code emitting after refactoring

Previously return statements while emitting anchors were short-circuiting the rest of the emitting code, but when I moved that code into a helper, the returns stopped having that impact, such that we'd end up emitting a return statement and then emit dead code after it.  Fix it.

* Remove some now dead code
2021-11-17 11:41:12 -05:00
Stephen Toub 83661ff53d Remove some unnecessary slicing from generated Regex code (#61701)
* Remove some unnecessary slicing from generated Regex code

When we're outputting code to match a "multi" (a sequence of multiple characters), we're currently issuing a Slice for the known tracked offset even if that offset is 0.  We can skip that nop.

* Address PR feedback
2021-11-17 08:22:14 -05:00
Stephen Toub 44d28bf5b6 Extend RegexCharClass.Canonicalize range inversion optimization (#61562)
* Extend RegexCharClass.Canonicalize range inversion optimization

There's a simple optimization in RegexCharClass.Canonicalize that was added in .NET 5, with the goal of taking a set that's made up of exactly two ranges and seeing whether those ranges were leaving out exactly one character.  If they were, the set can instead be rewritten as that character negated, which is a normalized form used downstream and optimized.  We can extend this normalization ever so slightly to be for two ranges separated not just be a single character but by more than that as well.

* Update TODO comment

* Add some more reduction tests
2021-11-17 07:52:37 -05:00
dotnet bot 9e110065e2 Localized file check-in by OneLocBuild Task: Build definition ID 679: Build ID 1472678 (#61680)
* Localized file check-in by OneLocBuild Task: Build definition ID 679: Build ID 1472242

* Localized file check-in by OneLocBuild Task: Build definition ID 679: Build ID 1472678
2021-11-16 13:42:46 -08:00
Stephen Toub 3b71d3b0aa Enable SymbolicRegexNode.IsNullableFor fast path to inline (#61605) 2021-11-15 17:54:53 -05:00
Stephen Toub e85de5316c Fix CharInClass reference in regex emitter (#61559)
We've tried to consistently use global:: whenever referring to core library types in the regex generator emitted code.  I'd missed these two.

(That said, these make the code a lot harder to read, especially in places where we're unable to use extension methods as extensions, so we'll want to revisit this policy.)
2021-11-15 14:21:34 -05:00
Santiago Fernandez Madero b39603446b Lock non localizable strings on regex resources (#61489) 2021-11-12 10:06:15 -08:00
Jose Perez Rodriguez dfb8c90b86 Adding Regex source generator to Microsoft.netcore.app.ref pack (#61329) 2021-11-08 23:26:40 -05:00
Olli Saarikivi 215ff0b77a Simplify minterm generation in Regex NonBacktracking engine (#61232)
PartitionTree had a holdover from when it was tracking the predicates
that made up each minterm, which caused it to use order n too much
memory for some patterns.
Nodes with the same predicate as the parent are no longer created.
This also significantly simplified the algorithm.
Remove the deduplication, since its now optional and the only call
site already passes in a unique set of predicates.
Make MintermGenerator take an IEnumerable.
2021-11-05 16:05:03 -07:00
b67f97839d improved BDD Unicode table representation in NonBacktracking engine (#61142)
* improved BDD Unicode table representation in NonBacktracking engine

* remove line

Co-authored-by: Dan Moseley <[email protected]>

* improved bounds-check elimination

Co-authored-by: Stephen Toub <[email protected]>

* clearer notation of numbers

Co-authored-by: Dan Moseley <[email protected]>

* fixed typo

Co-authored-by: Dan Moseley <[email protected]>
Co-authored-by: Stephen Toub <[email protected]>
2021-11-04 13:02:32 -10:00
Margus VeanesandStephen Toub 1e48eca957 lock protect nullability cache of symbolic regex node (#60942)
* fixed nullability checking to be threadsafe

* use volatile write for nullability cache

Co-authored-by: Stephen Toub <[email protected]>

* made read of nullability cache volatile and fixed other PR comments

* made non-lock-protected reads from SymbolicRegexBuilder._delta volatile

* Apply suggestions from code review

Co-authored-by: Stephen Toub <[email protected]>
2021-11-03 19:55:39 -04:00
Ankit JainandLarry Ewing 5a078b513f [wasm] Re-enable source generator tests failing due to OOM (#60701)
This adds support for setting per-project optimization flags, and sets them for these projects so they don't OOM.

Microsoft.Extensions.Logging.Generators.Roslyn3.11.Tests
Microsoft.Extensions.Logging.Generators.Roslyn4.0.Tests
System.Text.Json.SourceGeneration.Roslyn3.11.Unit.Tests
System.Text.Json.SourceGeneration.Roslyn4.0.Unit.Tests
System.Text.RegularExpressions.Generators.Tests
Some individual ones are disabled due to
#58226, and #60899 .

Additionally, if a AOT build fails, then on linux it dumps the last few lines from dmesg, to help identify it was an oom-kill.

Fixes #51961 .

Co-authored-by: Larry Ewing <[email protected]>
2021-11-02 16:16:25 -04:00
Dan Moseley 594f32e430 Avoid bogus cred scanning hits (#61070)
* Remove quasi passwords

* oops
2021-11-02 10:39:28 -04:00
Steve Pfister 8c6aeea1d8 Bring up full library test CI runs on iOS / tvOS devices (#59503)
This change enables device runs on CI by building each test app on the helix instance it was deployed to. In past attempts, we looked at enhancing what takes place on the build machine via build tricks, compressing / cleaning up files early, etc and we could not overcome the need for excessively long timeouts and far more disk space.

The change also adopts the patterns established in the wasm test build, giving us the opportunity to support different scenario runs as well as workloads testing in the future.
2021-11-02 07:43:15 -04:00
Stephen Toub 034d5e224d Use IndexOf(..., span) in Regex FindFirstChar (#60888)
* Use IndexOf(..., span) in Regex FindFirstChar

We currently use Boyer-Moore to find a multi-character prefix in FindFirstChar.  That's good, and when it was originally added it was very likely better than IndexOf(..., string), but since then the latter has been vectorized and its throughput has improved significantly (we also plan to improve it further).  While there are situations where Boyer-Moore does better, for general text searching and typical cases, IndexOf wins.  So, this commit adds the ability for FindFirstChar to use IndexOf to search for a span, and prefers that over Boyer-Moore when it's applicable, namely when we're case-sensitive and left-to-right processing.

* Centralize check for whether IndexOf is supported
2021-10-27 12:44:08 -04:00
Viktor Hofer 0964be0ae9 Update slngen and solution files (#60871)
Update slngen tooling to latest stable version and solution files since
a lot changed since the last time they were updated:
- NET7 (removal of older TFMs)
- Source Generators
2021-10-26 21:23:54 +02:00
Stephen Toub d2c19e1ce6 Fix DGML debug tests for Regex NonBacktracking (#60853) 2021-10-26 07:11:44 -04:00
Stephen Toub 1cc64c50c3 Refactor Regex FindFirstChar (#60822)
* Refactor Regexcompiler/Emitter.FindFirstChar

These have become unwieldy, with multiple large code blocks for finding the first character at which to perform a full match, and we'll be adding more soon.  This simply splits each of those out into their own method.  No functional changes.

* Use switch in RegexInterpreter.FindFirstChar

We don't need to re-evaluate which mechanism to use on every FindFirstChar call... we can do so once in the ctor and then just switch on that in the actual FindFirstChar call.
2021-10-25 20:49:58 -04:00
Olli SaarikiviandStephen Toub 9ba1b85c48 More stack overflow avoidance in regex NonBacktracking (#60786)
* Add stackoverflow avoidance to SymbolicRegexNode

Remove unused Restrict methods instead of adding avoidance.

Co-authored-by: Stephen Toub <[email protected]>

* Add more stack overflow avoidance in regex

This follows a full audit of the NonBacktracking code.

* Apply suggestions from code review

Co-authored-by: Stephen Toub <[email protected]>
2021-10-24 12:04:01 -04:00
Stephen Toub 8c8157f694 Add limited support for backtracking Regex single char loops to simplified code gen (#60385)
* Add limited support for backtracking Regex single char loops to simplified code gen

In .NET 5, we added simpler compiled code gen for regexes that didn't entail backtracking (or that had only very constrained backtracking, such as a top-level alternation).  In our corpus of ~90K regular expressions, that code generator is employed for ~40% of them.  The primary purpose of adding that code generator initially was performance, as it was able to avoid lots of the expense that original code generator had, especially for simple regexes.  However, with the source generator, it's much more valuable to use this code gen as the generated code is human-readable and really helps to understand how the regex is operating, is much more easily debugged, etc.

This change allows the simplified code gen to be used even if there are backtracking single-character loops in the regex, as long as those loops are in a top-level concatenation (or a simple grouping structure like a capture).  This increases the percentage of expressions in our corpus that will use the simplified code gen to ~65%.

Once we have the simplified loop code gen, it's also a lot easier to add in vectorization of searching for the next location to back off to based on a literal that comes immediately after the loop (e.g. "abc.*def").  This adds support into both RegexOptions.Compiled and the source generator to use LastIndexOf in that case.

The change also entailed adding/updating a few recursive functions.  The plan has been to adopt the same model as in System.Linq.Expressions, Roslyn, and elsewhere, where we fork processing to continue on a secondary thread, rather than trying to enforce some max depth or rewrite as iterative, so I've done that as part of this change as well.

* Address PR feedback

* Clean up partial classes in SourceGenRegexAsync test helper
2021-10-22 00:34:18 -04:00
Stephen Toub 835e4939f2 Reduce time for Regex tests (#60660)
The introduction of the source generator tests significantly increased the time to execute the regex test suite.  A large chunk of this time is spent for each individual pattern creating an assembly load context, spinning up Roslyn to generate and then compile the code, and then tearing everything down.  We can significantly speed things up if, for the theories that generate a lot of individual tests, we instead batch the compilation to generate and compile the code for many expressions at the same time.

This PR does so and more than halves the execution time for the regex test suite on my machine.  I only added batching for the two largest theories that were contributing the most overhead; we can do so for others should it prove warranted, but it looks like there's diminishing returns here.

I also moved a couple of tests to outerloop.
2021-10-21 17:02:06 -04:00
Stephen Toub ed9ab1bd94 Several tweaks to RegexGenerator (the tool, not the emitted code) (#60667)
- Fixed a bunch of nullable reference types warnings (they're suppressed as a netstandard2.0 project, but I temporarily and locally compiled it for netcoreapp current to get clean)
- Fixed the comparer used to aid in avoiding recomputing regexes when typing
- Added a hook to start exploring code gen for NonBacktracking
2021-10-21 13:04:21 -04:00