Skip to content

Fast-path ASCII character class matching #690

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Dec 11, 2023

Conversation

milseman
Copy link
Member

@milseman milseman commented Aug 2, 2023

Based on top of #689.

  • Needs the same bounds checking story fixed as Overhaul quantification fast-path #689
  • Need to refactor AsciiBitset
    • Inverting a bitset and inverting the semantics are two separate things
    • E.g. 😀 never matches an ASCII bitset no matter what bits are set or inverted, but it will match an inverted ASCII character class because that inversion affects the semantics of a match
    • String processing logic doesn't really belong on the type, this is the only usage place
  • Need to refactor some of the quickASCIICharacter for more refined semantics
    • Take isScalarSemantics, take allow-CR-LF, etc.

Performance relative to #689 (which in turn is a significant improvement over main):

=== Regressions ======================================================================
- symDiffCCC_All                          48.5ms	48.2ms	342µs		0.7%
- SubtractionCCC_All                      21.2ms	20.9ms	243µs		1.2%
- Words_All_Scalar                        12.4ms	12.3ms	117µs		0.9%
- LiteralSearchNotFound_All               6.6ms	6.51ms	90.9µs		1.4%
- LiteralSearchNotFound_All_Scalar        5.88ms	5.83ms	48.5µs		0.8%
- EagarQuantWithTerminal_Whole_Scalar     845µs	812µs	33.5µs		4.1%
=== Improvements =====================================================================
- EmailLookahead_All                      19.9ms	39.1ms	-19.2ms		-49.2%
- EmailLookaheadNoMatches_All             24.9ms	39.1ms	-14.2ms		-36.2%
- EmailLookaheadList                      4ms	9.35ms	-5.35ms		-57.2%
- EmailRFC_All                            59.4ms	63.4ms	-4.04ms		-6.4%
- EmailLookahead_All_Scalar               17.8ms	21.7ms	-3.85ms		-17.8%
- CaseInsensitiveCCC_All_Scalar           6.32ms	10.1ms	-3.73ms		-37.1%
- CaseInsensitiveCCC_All                  6.36ms	9.95ms	-3.59ms		-36.1%
- EmailLookaheadNoMatches_All_Scalar      22.7ms	26.1ms	-3.4ms		-13.0%
- InvertedCCC_All                         16.8ms	20.1ms	-3.24ms		-16.1%
- InvertedCCC_All_Scalar                  16.8ms	20ms	-3.15ms		-15.8%
- BasicRangeCCC_All                       6.36ms	9.14ms	-2.77ms		-30.3%
- BasicCCC_All                            5.93ms	8.68ms	-2.75ms		-31.6%
- BasicCCC_All_Scalar                     5.94ms	8.65ms	-2.71ms		-31.3%
- BasicRangeCCC_All_Scalar                6.43ms	9.13ms	-2.7ms		-29.5%
- EmailRFCNoMatches_All_Scalar            124ms	126ms	-2.66ms		-2.1%
- EmailRFC_All_Scalar                     45.7ms	47.1ms	-1.4ms		-3.0%
- IPv6Address                             2.58ms	3.77ms	-1.19ms		-31.5%
- EmojiRegex_All                          71.6ms	72.7ms	-1.09ms		-1.5%
- EmailLookaheadList_Scalar               3.9ms	4.92ms	-1.02ms		-20.8%
- MACAddress                              2.37ms	2.8ms	-429µs		-15.3%
- Css_All                                 3.31ms	3.7ms	-392µs		-10.6%
- GraphemeBreakNoCap_All                  3.39ms	3.76ms	-370µs		-9.8%
- LiteralSearch_All                       6.77ms	7.13ms	-363µs		-5.1%
- BasicBuiltinCharacterClass_All          8.26ms	8.49ms	-225µs		-2.7%
- HangulSyllable_All                      6.91ms	7.14ms	-224µs		-3.1%
- GraphemeBreakNoCap_All_Scalar           3.16ms	3.38ms	-221µs		-6.5%
- IPv4Address                             2.34ms	2.55ms	-203µs		-8.0%
- IPv6Address_Scalar                      2.41ms	2.61ms	-202µs		-7.7%
- ReluctantQuantWithTerminal_Whole_Scalar 6.42ms	6.59ms	-169µs		-2.6%
- MACAddress_Scalar                       2.29ms	2.42ms	-135µs		-5.6%
- HangulSyllable_All_Scalar               6.24ms	6.37ms	-133µs		-2.1%
- LiteralSearch_All_Scalar                5.99ms	6.1ms	-103µs		-1.7%
- Css_All_Scalar                          3.05ms	3.15ms	-97µs		-3.1%
- ReluctantQuantWithTerminal_Whole        6.46ms	6.56ms	-95.5µs		-1.5%
- AnchoredNotFound_Whole_Scalar           5.44ms	5.5ms	-56µs		-1.0%
- IPv4Address_Scalar                      2.2ms	2.25ms	-51µs		-2.3%
- Lines_All_Scalar                        1.71ms	1.74ms	-35.2µs		-2.0%
- Lines_All                               1.73ms	1.76ms	-25.7µs		-1.5%
- EagarQuantWithTerminal_Whole            815µs	834µs	-18.7µs		-2.2%

@milseman milseman requested a review from natecook1000 August 2, 2023 12:10
@milseman
Copy link
Member Author

It makes sense to pull out isInverted into the instruction encoding, which also motivates some more refactoring of instruction payload encoding. I'll be working on some cleanups and refactorings to help motivate and enable this first.

Uses quickASCIICharacter to speed up ASCII character class matching.

2x speedup for EmailLookahead_All and many, many others. 10% regression in AnchoredNotFound_First and related.
@milseman milseman force-pushed the ascii_character_class_overhaul branch from 8c35c9d to eee2721 Compare December 10, 2023 18:28
@milseman
Copy link
Member Author

Reviving this to focus on just the ASCII-character fast path. These are the perf numbers now:

=== Regressions ======================================================================
- AnchoredNotFound_First                  9.86ms	8.92ms	941µs		10.5%
- AnchoredNotFound_All                    14.6ms	13.7ms	901µs		6.6%
- AnchoredNotFound_First_Scalar           5.99ms	5.38ms	616µs		11.5%
- BasicBuiltinCharacterClass_All_Scalar   7.7ms	7.11ms	589µs		8.3%
- AnchoredNotFound_All_Scalar             9.67ms	9.1ms	570µs		6.3%
- DiceRollsInText_All                     41.9ms	41.4ms	563µs		1.4%
- DiceRollsInText_All_Scalar              39.3ms	38.9ms	356µs		0.9%
- Numbers_All                             6.01ms	5.83ms	184µs		3.2%
- Numbers_All_Scalar                      5.26ms	5.09ms	178µs		3.5%
- IntersectionCCC_All                     22.1ms	21.9ms	178µs		0.8%
- IntersectionCCC_All_Scalar              22.2ms	22ms	168µs		0.8%
- LiteralSearchNotFound_All_Scalar        5.69ms	5.54ms	157µs		2.8%
- SubtractionCCC_All_Scalar               21.3ms	21.1ms	148µs		0.7%
- Words_All_Scalar                        12.2ms	12ms	147µs		1.2%
- SubtractionCCC_All                      21.3ms	21.1ms	146µs		0.7%
- LiteralSearch_All                       6.81ms	6.67ms	140µs		2.1%
- LiteralSearch_All_Scalar                5.87ms	5.74ms	133µs		2.3%
- NotFound_All                            7.31ms	7.19ms	118µs		1.6%
- LiteralSearchNotFound_All               6.61ms	6.5ms	110µs		1.7%
- NotFound_All_Scalar                     6.33ms	6.23ms	100µs		1.6%
- HangulSyllable_First_Scalar             2.92ms	2.85ms	72.8µs		2.6%
- HangulSyllable_First                    3.37ms	3.3ms	70.2µs		2.1%
=== Improvements =====================================================================
- EmailLookahead_All                      19.5ms	40.6ms	-21.1ms		-52.1%
- EmailLookaheadNoMatches_All             23ms	39.1ms	-16.1ms		-41.2%
- EmailLookaheadList                      3.94ms	9.7ms	-5.77ms		-59.4%
- EmailRFC_All                            64ms	68.8ms	-4.81ms		-7.0%
- CaseInsensitiveCCC_All_Scalar           6.46ms	11ms	-4.54ms		-41.3%
- EmailLookahead_All_Scalar               17.3ms	21.6ms	-4.32ms		-20.0%
- CaseInsensitiveCCC_All                  6.47ms	10.7ms	-4.25ms		-39.6%
- BasicCCC_All                            6.03ms	9.56ms	-3.53ms		-36.9%
- BasicCCC_All_Scalar                     6.03ms	9.56ms	-3.52ms		-36.9%
- BasicRangeCCC_All                       6.5ms	10ms	-3.52ms		-35.1%
- BasicRangeCCC_All_Scalar                6.51ms	10ms	-3.5ms		-34.9%
- EmailLookaheadNoMatches_All_Scalar      20.7ms	23.9ms	-3.26ms		-13.6%
- InvertedCCC_All_Scalar                  16.8ms	19.8ms	-2.99ms		-15.1%
- EmailRFCNoMatches_All                   161ms	164ms	-2.96ms		-1.8%
- InvertedCCC_All                         17ms	19.9ms	-2.93ms		-14.7%
- IPv6Address                             2.58ms	3.86ms	-1.28ms		-33.2%
- EmailLookaheadList_Scalar               3.7ms	4.82ms	-1.12ms		-23.2%
- EmailRFC_All_Scalar                     45.3ms	46.3ms	-1.05ms		-2.3%
- EmailRFCNoMatches_All_Scalar            122ms	123ms	-801µs		-0.7%
- MACAddress                              2.4ms	2.82ms	-417µs		-14.8%
- Css_All                                 3.27ms	3.67ms	-401µs		-10.9%
- CompilerMessages_All_Scalar             75.1ms	75.5ms	-371µs		-0.5%
- BasicBuiltinCharacterClass_All          8.27ms	8.62ms	-343µs		-4.0%
- ReluctantQuantWithTerminal_Whole_Scalar 5.22ms	5.49ms	-270µs		-4.9%
- GraphemeBreakNoCap_All                  3.53ms	3.77ms	-241µs		-6.4%
- IPv6Address_Scalar                      2.42ms	2.6ms	-181µs		-7.0%
- ReluctantQuantWithTerminal_Whole        5.29ms	5.46ms	-170µs		-3.1%
- IPv4Address                             2.24ms	2.4ms	-159µs		-6.6%
- HangulSyllable_All                      6.82ms	6.94ms	-111µs		-1.6%
- MACAddress_Scalar                       2.28ms	2.39ms	-106µs		-4.4%
- ReluctantQuant_Whole_Scalar             9.2ms	9.3ms	-102µs		-1.1%
- HangulSyllable_All_Scalar               6.03ms	6.13ms	-98.9µs		-1.6%
- GraphemeBreakNoCap_All_Scalar           3.12ms	3.17ms	-56.5µs		-1.8%
- Css_All_Scalar                          2.91ms	2.96ms	-47µs		-1.6%
- IPv4Address_Scalar                      2.07ms	2.1ms	-23µs		-1.1%
- EagarQuantWithTerminal_Whole_Scalar     781µs	790µs	-8.83µs		-1.1%

@milseman milseman changed the title [Prototype] Overhaul ASCII character class matching Fast-path ASCII character class matching Dec 10, 2023
@milseman milseman marked this pull request as ready for review December 10, 2023 18:28
@milseman
Copy link
Member Author

@swift-ci please test

@milseman milseman merged commit 4e742b4 into swiftlang:main Dec 11, 2023
@milseman milseman deleted the ascii_character_class_overhaul branch December 11, 2023 01:19
milseman added a commit that referenced this pull request Dec 15, 2023
* Atomically load the lowered program (#610)

Since we're atomically initializing the compiled program in
`Regex.Program`, we need to pair that with an atomic load.

Resolves #609.

* Add tests for line start/end word boundary diffs (#616)

The `default` and `simple` word boundaries have different behaviors
at the start and end of strings/lines. These tests validate that we
have the correct behavior implemented. Related to issue #613.

* Add tweaks for Android

* Fix documentation typo (#615)

* Fix abstract for Regex.dotMatchesNewlines(_:). (#614)

The old version looks like it was accidentally duplicated from
anchorsMatchLineEndings(_:) just below it.

* Remove `RegexConsumer` and fix its dependencies (#617)

* Remove `RegexConsumer` and fix its dependencies

This eliminates the RegexConsumer type and rewrites its users to call
through to other, existing functionality on Regex or in the Algorithms
implementations. RegexConsumer doesn't take account of the dual
subranges required for matching, so it can produce results that are
inconsistent with matches(of:) and ranges(of:), which were rewritten
earlier.

rdar://102841216

* Remove remaining from-end algorithm methods

This removes methods that are left over from when we were considering
from-end algorithms. These aren't tested and may not have the correct
semantics, so it's safer to remove them entirely.

* Improve StringProcessing and RegexBuilder documentation (#611)

This includes documentation improvements for core types/methods,
RegexBuilder types along with their generated variadic initializers,
and adds some curation. It also includes tests of the documentation
code samples.

* Set availability for inverted character class test (#621)

This feature depends on running with a Swift 5.7 stdlib, and fails
when that isn't available.

* Add type annotations in RegexBuilder tests

These changes work around a change to the way result builders are
compiled that removes the ability for result builder closure outputs
to affect the overload resolution elsewhere in an expression.

Workarounds for rdar://104881395 and rdar://104645543

* Workaround for fileprivate array issue

A recent compiler change results in fileprivate arrays sometimes
not keeping their buffers around long enough. This change avoids that
issue by removing the fileprivate annotations from the affected type.

* Fix an issue where named character classes weren't getting converted in the result builder. <rdar://104480703>

* Stop at end of search string in TwoWaySearcher (#631)

When searching for a substring that doesn't exist, it was possible
for TwoWaySearcher to advance beyond the end of the search string,
causing a crash. This change adds a `limitedBy:` parameter to that
index movement, avoiding the invalid movement.

Fixes rdar://105154010

* Correct misspelling in DSL renderer (#627)

vertial -> vertical

rdar://104602317

* Fix output type mismatch with RegexBuilder (#626)

Some regex literals (and presumably other `Regex` instances) lose
their output type information when used in a RegexBuilder closure due
to the way the concatenating builder calls are overloaded. In
particular, any output type with labeled tuples or where the sum of
tuple components in the accumulated and new output types is greater
than 10 will be ignored.

Regex internals don't make this distinction, however, so there ends up
being a mismatch between what a `Regex.Match` instance tries to
produce and the output type of the outermost regex. For example, this
code results in a crash, because `regex` is a `Regex<Substring>`
but the match tries to produce a `(Substring, number: Substring)`:

    let regex = Regex {
        ZeroOrMore(.whitespace)
        /:(?<number>\d+):/
        ZeroOrMore(.whitespace)
    }
    let match = try regex.wholeMatch(in: " :21: ")
    print(match!.output)

To fix this, we add a new `ignoreCapturesInTypedOutput` DSLTree node
to mark situations where the output type is discarded. This status
is propagated through the capture list into the match's storage,
which lets us produce the correct output type. Note that we can't just
drop the capture groups when building the compiled program because
(1) different parts of the regex might reference the capture group
and (2) all capture groups are available if a developer converts the
output to `AnyRegexOutput`.

    let anyOutput = AnyRegexOutput(match)
    // anyOutput[1] == "21"
    // anyOutput["number"] == Optional("21")

Fixes #625. rdar://104823356

Note: Linux seems to crash on different tests when the two customTest
overloads have `internal` visibility or are called. Switching one of the
functions to be generic over a RegexComponent works around the issue.

* Revert "Merge pull request #628 from apple/result_builder_changes_workaround"

This reverts commit 7e059b7, reversing
changes made to 3ca8b13.

* Use `some` syntax in variadics

This supports a type checker fix after the change in how result
builder closure parameters are type-checked.

* Type checker workaround: adjust test

* Further refactor to work around type checker regression

* Align availability macro with OS versions (#641)

* Speed up general character class matching (#642)

Short-circuit Character.isASCII checks inside built in character class matching.

Also, make benchmark try a few more times before giving up.

* Test for \s matching CRLF when scalar matching (#648)

* General ascii fast paths for character classes (#644)

General ASCII fast-paths for builtin character classes

* Remove the unsupported `anyScalar` case (#650)

We decided not to support the `anyScalar` character class, which would
match a single Unicode scalar regardless of matching mode. However,
its representation was still included in the various character class
types in the regex engine, leading to unreachable code and unclear
requirements when changing or adding new code. This change removes
that representation where possible.

The `DSLTree.Atom.CharacterClass` enum is left unchanged, since it
is marked `@_spi(RegexBuilder) public`. Any use of that enum case
is handled with a `fatalError("Unsupported")`, and it isn't produced
on any code path.

* Fix range-based quantification fast path (#653)

The fast path for quantification incorrectly discards the last save
position when the quantification used up all possible trips, which is
only possible with range-based quantifications (e.g. `{0,3}`). This
bug shows up when a range-based quantifier matches the maximum - 1
repetitions of the preceding pattern.

For example, the regex `/a{0,2}a/` should succeed as a full match any
of the strings "aa", "aaa", or "aaaa". However, the pattern fails
to match "aaa", since the save point allowing a single "a" to match
the first `a{0,2}` part of the regex is discarded.

This change only discards the last save position when advancing the
quantifier fails due to a failure to match, not maxing out the number
of trips.

* Add in ASCII fast-path for anyNonNewline (#654)

* Avoid long expression type checks (#657)

These changes remove several seconds of type-checking time from the
RegexBuilder test cases, bringing all expressions under 150ms (on
the tested computer).

* Processor cleanup (#655)

Clean up and refactor the processor

* Simplify instruction fetching

* Refactor metrics out, and void their storage in release builds

*Put operations onto String

* Fix `firstRange(of:)` search (#656)

Calls to `ranges(of:)` and `firstRange(of:)` with a string parameter
actually use two different string searching algorithms. `ranges(of:)`
uses the "z-searcher" algorithm, while `firstRange(of:)` uses a
two-way search. Since it's better to align on a single path for these
searches, the z-searcher has lower requirements, and the two-way
search implementation has a correctness bug, this change removes
the two-way search algorithm and uses z-search for `firstRange(of:)`.

The correctness bug in `firstRange(of:)` appears only when searching
for the second (or later) occurrence of a substring, which you have
to be fairly deliberate about. In the example below, the substring
at offsets `7..<12` is missed:

    let text = "ADACBADADACBADACB"
    //          =====  -----=====
    let pattern = "ADACB"
    let firstRange = text.firstRange(of: pattern)!
    // firstRange ~= 0..<5
    let secondRange = text[firstRange.upperBound...].firstRange(of: pattern)!
    // secondRange ~= 12..<17

This change also removes some unrelated, unused code in Split.swift,
in addition to removing an (unused) usage of `TwoWaySearcher`.

rdar://92794248

* Bug fix and hot path for quantified `.` (#658)

Bug fix in newline hot path, and apply hot path to quantified dot

* Run scalar-semantic benchmark variants (#659)

Run scalar semantic benchmarks

* Refactor operations to be on String (#664)

Finish refactoring logic onto String

* Provide unique generic method parameter names (#669)

This is getting warned on in the 5.9 compiler, will be an error
starting in Swift 6.

* Enable quantification optimizations for scalar semantics (#671)

*  Quantified scalar semantic matching

* Fix doc comment for trimPrefix and trimmingPrefix funcs (#673)

* Update availability for the 5.8 release (#680)

* Optimize search for start-anchored regexes (#682)

When a regex is anchored to the start of a subject, there's no need
to search throughout a string for the pattern when searching for the
first match: a prefix match is sufficient.

This adds a regex compilation-time check about whether a match can
only be found at the start of a subject, and then uses that to
choose whether to defer to `prefixMatch` from within `firstMatch`.

* Fix misuse of `XCTSkip()` (#685)

* Handle boundaries when matching in substrings (#675)

* Handle boundaries when matching in substrings

Some of our existing matching routines use the start/endIndex
of the input, which is basically never the right thing to do.

This change revises those checks to use the search bounds, by
either moving the boundary check out of the matching method, or
if the boundary is a part of what needs to be matched (e.g.
word boundaries have different behavior at the start/end than
in the middle of a string) the search bounds are passed into
the matching method.

Testing is currently handled by piggy-backing on the existing
match tests; we should add more tests to handle substring-
specific edge cases.

* Handle sub-character substring boundaries

This change passes the end boundary down into matching methods, and
uses it to find the actual character that is part of the input
substring, even if the substring's end boundary is in the middle of
a grapheme cluster.

Substrings cannot have sub-Unicode scalar boundaries as of Swift
5.7; we can remove a check for this when matching an individual
scalar.

* Overhaul quantification fast-path (#689)

Overhaul quantification save points and fast path logic, for significant wins in simplicity and performance.

* adopt the stdlib’s pattern for atomic lazy references

- avoids reliance on a pointer conversion

* pass a pointer instead of inout conversion

- this function is imported in a way that causes the compiler to not detect it as a C function

* Update Sources/_StringProcessing/Regex/Core.swift

comment spelling fix

* Adds SPI for a NSRE compatibility mode option (#698)

NSRegularExpression matches at the Unicode scalar level, but also
matches `\r\n` sequences with a single `.` when single-line mode is
enabled. This adds a `_nsreCompatibility` property that enables both
of those behaviors, and implements support for the special case
handling of `.`.

* Add ASCII fast-path ASCII character class matching (#690)

Uses quickASCIICharacter to speed up ASCII character class matching.

2x speedup for EmailLookahead_All and many, many others. 10% regression in AnchoredNotFound_First and related.

---------

Co-authored-by: Nate Cook <natecook@apple.com>
Co-authored-by: Butta <repo@butta.fastem.com>
Co-authored-by: Ole Begemann <ole@oleb.net>
Co-authored-by: Alex Martini <amartini@apple.com>
Co-authored-by: Alejandro Alonso <alejandro_alonso@apple.com>
Co-authored-by: David Ewing <dewing@apple.com>
Co-authored-by: Dave Ewing <96321608+DaveEwing@users.noreply.github.com>
Co-authored-by: Valeriy Van <github@w7software.com>
Co-authored-by: Jonathan Grynspan <grynspan@me.com>
Co-authored-by: Guillaume Lessard <guillaume.lessard@apple.com>
Co-authored-by: Guillaume Lessard <glessard@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants