Repository: dotnet/runtime
File: src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexCompiler.cs (C#)

Code before:
                Ldc(range);
                Label boundsCheckPassed = DefineLabel();
                BltUnFar(boundsCheckPassed);
                Pop(); // Pop the duplicated value before jumping to noMatch
                BrFar(noMatchLabel);
                MarkLabel(boundsCheckPassed);

                // Emit the switch
                Switch(switchTable);

                // Fall-through after switch should never happen because the bounds check above
                // ensures the value is within [0, range) and the switch table has entries for all values.
                // This branch is just a safety net.
                BrFar(noMatchLabel);

                // Emit the code for each branch
                for (int i = 0; i < childCount; i++)
                {
                    MarkLabel(branchLabels[i]);
                    sliceStaticPos = startingTextSpanPos;

                    // This is used for atomic alternations and non-atomic alternations where no
                    // branch can backtrack. Failures should jump to the original done label.
                    // Set it before emitting the child so that any failing matches inside will
                    // jump to the right place.
                    doneLabel = originalDoneLabel;

                    RegexNode child = node.Child(i);
                    RegexNode? startingLiteralNode = child.FindStartingLiteralNode(allowZeroWidth: false);
                    Debug.Assert(startingLiteralNode is not null, "Unexpectedly couldn't find the branch starting node.");

                    // Emit the code for the branch, without the first character that was already matched in the switch.
                    switch (child.Kind)
                    {
                        case RegexNodeKind.One:
                        case RegexNodeKind.Set:
                            // The character was handled entirely by the switch. No additional matching is needed.
                            sliceStaticPos++;
                            break;

                        case RegexNodeKind.Multi:
                            // First character was handled by the switch. Emit matching code for the remainder of the multi string.
                            sliceStaticPos++;
                            EmitNode(CreateSlicedMulti(child));
                            break;

                        case RegexNodeKind.Concatenate when child.Child(0) == startingLiteralNode && (startingLiteralNode.Kind is RegexNodeKind.One or RegexNodeKind.Set or RegexNodeKind.Multi):
                            // This is a concatenation where its first node is the starting literal we found and that starting literal
                            // is one of the nodes above that we know how to handle completely. This is a common
                            // enough case that we want to special-case it to avoid duplicating the processing for that character
                            // unnecessarily. First slice off the first character that was already handled. If that child is a multi, temporarily

Review comment (suggestion):
@copilot, can this be moved down to the corresponding location where this is done in the source generator? I'm unclear why you moved it up here.

Code after:
                    // all branches see the original).
                    doneLabel = originalDoneLabel;

                    // If we get here in the generated code, the branch completed successfully.
                    // Before jumping to the end, we need to zero out sliceStaticPos, so that no
                    // matter what the value is after the branch, whatever follows the alternate
                    // will see the same sliceStaticPos.
                    TransferSliceStaticPosToPos();
                    BrFar(matchLabel);
                }

                // Successfully completed the alternate.
                MarkLabel(matchLabel);
                Debug.Assert(sliceStaticPos == 0);

                // Creates a new Multi node with the first character sliced off
                static RegexNode CreateSlicedMulti(RegexNode multi)
                {
                    Debug.Assert(multi.Kind is RegexNodeKind.Multi, $"Expected a Multi node, got {multi.Kind}");
                    return multi.Str!.Length == 2 ?
                        new(RegexNodeKind.One, multi.Options, multi.Str[1]) :
                        new(RegexNodeKind.Multi, multi.Options, multi.Str.Substring(1));
                }
            }

            // Emits the code to handle a backreference.
            void EmitBackreference(RegexNode node)
            {
                Debug.Assert(node.Kind is RegexNodeKind.Backreference, $"Unexpected type: {node.Kind}");

                int capnum = RegexParser.MapCaptureNumber(node.M, _regexTree!.CaptureNumberSparseMapping);
                bool rtl = (node.Options & RegexOptions.RightToLeft) != 0;

                TransferSliceStaticPosToPos();

                Label backreferenceEnd = DefineLabel();

                // if (!base.IsMatched(capnum)) goto (ecmascript ? end : doneLabel);
                Ldthis();
                Ldc(capnum);
                Call(IsMatchedMethod);
                BrfalseFar((node.Options & RegexOptions.ECMAScript) == 0 ? doneLabel : backreferenceEnd);

                using RentedLocalBuilder matchLength = RentInt32Local();
                using RentedLocalBuilder matchIndex = RentInt32Local();
                using RentedLocalBuilder i = RentInt32Local();

                // int matchLength = base.MatchLength(capnum);
                Ldthis();
                Ldc(capnum);
                Call(MatchLengthMethod);