I was previously too aggressive in getting rid of concatenations in the comment rendering. We would end up flattening concatenations into alternations erroneously.
* 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
* 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]>
* 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
* 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
* Improve comments in generated Regex code
To help make the generated code easier to understand and debug.
* Format RegexOptions textually when possible
* 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
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.
* 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)
* 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
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
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).
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
* 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
* 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
* 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
* 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
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.)
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.
* 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]>
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]>
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.
* 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
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
* 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.
* 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]>
* 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
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.
- 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