Skip to content
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

[Optimization] Specialized quantification instruction #577

Merged
merged 45 commits into from
Aug 3, 2022
Merged
Show file tree
Hide file tree
Changes from 43 commits
Commits
Show all changes
45 commits
Select commit Hold shift + click to select a range
3b6b676
Copy over new ascii bitset
rctcwyvrn Jul 5, 2022
33caa79
Add matchBuiltin
rctcwyvrn Jul 5, 2022
139daa5
Remove debug prints
rctcwyvrn Jul 5, 2022
9abf4af
Remove bitset fast path
rctcwyvrn Jul 5, 2022
286f5d8
Fully remove remnants of the bitset fast path
rctcwyvrn Jul 6, 2022
9e915cd
Merge branch 'main' into speedy-builtins
rctcwyvrn Jul 7, 2022
e593ddb
Completely replace AssertionFunction with regexAssert(by:)
rctcwyvrn Jul 11, 2022
25dc277
Merge branch 'main' into speedy-builtins
rctcwyvrn Jul 12, 2022
3e38ac6
Cleanup
rctcwyvrn Jul 12, 2022
e5d8b4a
Move match builtin and assert + Add AssertionPayload
rctcwyvrn Jul 12, 2022
0466c25
Cleanup assertions
rctcwyvrn Jul 12, 2022
87078ad
Merge branch 'main' into speedy-builtins
rctcwyvrn Jul 12, 2022
1ef91f3
First version
rctcwyvrn Jul 13, 2022
f401e84
Fix tests
rctcwyvrn Jul 13, 2022
b09f45f
Update opcode description for assertBy
rctcwyvrn Jul 13, 2022
00ae70b
Bugfixes
rctcwyvrn Jul 13, 2022
d33b57c
Merge branch 'speedy-builtins' into quicker-quant-qualifies-quality
rctcwyvrn Jul 13, 2022
62bec3f
Finish bugfixes
rctcwyvrn Jul 13, 2022
8cf6b21
Fixed array copy issue with savepoints
rctcwyvrn Jul 13, 2022
8d61e7d
Add assertions + cleanup
rctcwyvrn Jul 13, 2022
c0bc139
Clean up loop structure in runQuantify
rctcwyvrn Jul 13, 2022
42e5a58
Use range based save points
rctcwyvrn Jul 14, 2022
b2dedac
Undo the change where I made it recompute index after for some reason
rctcwyvrn Jul 14, 2022
7b4eaff
More cleanup
rctcwyvrn Jul 14, 2022
c581ea2
Merge branch 'main' into speedy-builtins
rctcwyvrn Jul 14, 2022
627c982
Merge branch 'speedy-builtins' into quicker-quant-qualifies-quality
rctcwyvrn Jul 15, 2022
2a82231
Merge branch 'main' into speedy-builtins
rctcwyvrn Jul 15, 2022
fb1576a
Update branch to match main
rctcwyvrn Jul 15, 2022
3b9485e
Use the newly cleaned up _CharacterClassModel
rctcwyvrn Jul 16, 2022
64d1ed9
Add characterClass DSLTree node
rctcwyvrn Jul 16, 2022
2a6fe3c
Bugfixes
rctcwyvrn Jul 19, 2022
2c2406e
Merge branch 'main' into quicker-quant-qualifies-quality
rctcwyvrn Jul 19, 2022
9352821
Merge branch 'speedy-builtins' into quicker-quant-qualifies-quality
rctcwyvrn Jul 19, 2022
9ed9f57
Allow strict and inverted character classes
rctcwyvrn Jul 19, 2022
bee167f
Cleanup magic constants
rctcwyvrn Jul 19, 2022
cf01751
Add specialized quantify paths
rctcwyvrn Jul 19, 2022
e2f60d3
Fix dot quantify
rctcwyvrn Jul 19, 2022
d7015ec
Remove unneeded save point
rctcwyvrn Jul 19, 2022
b417434
experimental signal failure restoring
rctcwyvrn Jul 19, 2022
512bef5
Reduce ARCs in signalFailure()
rctcwyvrn Jul 19, 2022
ff9c375
Just do things inline in signalFailure()
rctcwyvrn Jul 20, 2022
b026402
Cleanup some comments
rctcwyvrn Jul 20, 2022
d02c5cd
Cleanup
rctcwyvrn Jul 29, 2022
ce90ba9
Merge branch 'main' into quicker-quant-qualifies-quality
rctcwyvrn Aug 3, 2022
f90f01c
Slight cleanup
rctcwyvrn Aug 3, 2022
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 23 additions & 11 deletions Sources/RegexBuilder/CharacterClass.swift
Original file line number Diff line number Diff line change
Expand Up @@ -15,27 +15,39 @@
@available(SwiftStdlib 5.7, *)
public struct CharacterClass {
internal var ccc: DSLTree.CustomCharacterClass
/// The builtin character class, if this CharacterClass is representable by one
internal var builtin: DSLTree.Atom.CharacterClass?

init(_ ccc: DSLTree.CustomCharacterClass) {
self.ccc = ccc
self.builtin = nil
}

init(unconverted atom: DSLTree._AST.Atom) {
self.ccc = .init(members: [.atom(.unconverted(atom))])
init(builtin: DSLTree.Atom.CharacterClass) {
self.ccc = .init(members: [.atom(.characterClass(builtin))])
self.builtin = builtin
}
}

@available(SwiftStdlib 5.7, *)
extension CharacterClass: RegexComponent {
public var regex: Regex<Substring> {
_RegexFactory().customCharacterClass(ccc)
if let cc = builtin {
return _RegexFactory().characterClass(cc)
} else {
return _RegexFactory().customCharacterClass(ccc)
}
}
}

@available(SwiftStdlib 5.7, *)
extension CharacterClass {
public var inverted: CharacterClass {
CharacterClass(ccc.inverted)
if let inv = builtin?.inverted {
return CharacterClass(builtin: inv)
} else {
return CharacterClass(ccc.inverted)
}
}
}

Expand All @@ -50,15 +62,15 @@ extension RegexComponent where Self == CharacterClass {
}

public static var anyGraphemeCluster: CharacterClass {
.init(unconverted: ._anyGrapheme)
.init(builtin: .anyGrapheme)
}

public static var whitespace: CharacterClass {
.init(unconverted: ._whitespace)
.init(builtin: .whitespace)
}

public static var digit: CharacterClass {
.init(unconverted: ._digit)
.init(builtin: .digit)
}

public static var hexDigit: CharacterClass {
Expand All @@ -70,19 +82,19 @@ extension RegexComponent where Self == CharacterClass {
}

public static var horizontalWhitespace: CharacterClass {
.init(unconverted: ._horizontalWhitespace)
.init(builtin: .horizontalWhitespace)
}

public static var newlineSequence: CharacterClass {
.init(unconverted: ._newlineSequence)
.init(builtin: .newlineSequence)
}

public static var verticalWhitespace: CharacterClass {
.init(unconverted: ._verticalWhitespace)
.init(builtin: .verticalWhitespace)
}

public static var word: CharacterClass {
.init(unconverted: ._word)
.init(builtin: .word)
}
}

Expand Down
240 changes: 102 additions & 138 deletions Sources/_StringProcessing/ByteCodeGen.swift
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,9 @@ fileprivate extension Compiler.ByteCodeGen {
emitMatchScalar(s)
}

case let .characterClass(cc):
emitCharacterClass(cc)

case let .assertion(kind):
try emitAssertion(kind)

Expand Down Expand Up @@ -148,147 +151,27 @@ fileprivate extension Compiler.ByteCodeGen {
}
}

mutating func emitStartOfLine() {
builder.buildAssert { [semanticLevel = options.semanticLevel]
(_, _, input, pos, subjectBounds) in
if pos == subjectBounds.lowerBound { return true }
switch semanticLevel {
case .graphemeCluster:
return input[input.index(before: pos)].isNewline
case .unicodeScalar:
return input.unicodeScalars[input.unicodeScalars.index(before: pos)].isNewline
}
}
}

mutating func emitEndOfLine() {
builder.buildAssert { [semanticLevel = options.semanticLevel]
(_, _, input, pos, subjectBounds) in
if pos == subjectBounds.upperBound { return true }
switch semanticLevel {
case .graphemeCluster:
return input[pos].isNewline
case .unicodeScalar:
return input.unicodeScalars[pos].isNewline
}
}
}

mutating func emitAssertion(
_ kind: DSLTree.Atom.Assertion
) throws {
// FIXME: Depends on API model we have... We may want to
// think through some of these with API interactions in mind
//
// This might break how we use `bounds` for both slicing
// and things like `firstIndex`, that is `firstIndex` may
// need to supply both a slice bounds and a per-search bounds.
switch kind {
case .startOfSubject:
builder.buildAssert { (_, _, input, pos, subjectBounds) in
pos == subjectBounds.lowerBound
}

case .endOfSubjectBeforeNewline:
builder.buildAssert { [semanticLevel = options.semanticLevel]
(_, _, input, pos, subjectBounds) in
if pos == subjectBounds.upperBound { return true }
switch semanticLevel {
case .graphemeCluster:
return input.index(after: pos) == subjectBounds.upperBound
&& input[pos].isNewline
case .unicodeScalar:
return input.unicodeScalars.index(after: pos) == subjectBounds.upperBound
&& input.unicodeScalars[pos].isNewline
}
}

case .endOfSubject:
builder.buildAssert { (_, _, input, pos, subjectBounds) in
pos == subjectBounds.upperBound
}

case .resetStartOfMatch:
// FIXME: Figure out how to communicate this out
if kind == .resetStartOfMatch {
throw Unsupported(#"\K (reset/keep assertion)"#)

case .firstMatchingPositionInSubject:
// TODO: We can probably build a nice model with API here

// FIXME: This needs to be based on `searchBounds`,
// not the `subjectBounds` given as an argument here
builder.buildAssert { (_, _, input, pos, subjectBounds) in false }

case .textSegment:
builder.buildAssert { (_, _, input, pos, _) in
// FIXME: Grapheme or word based on options
input.isOnGraphemeClusterBoundary(pos)
}

case .notTextSegment:
builder.buildAssert { (_, _, input, pos, _) in
// FIXME: Grapheme or word based on options
!input.isOnGraphemeClusterBoundary(pos)
}

case .startOfLine:
emitStartOfLine()

case .endOfLine:
emitEndOfLine()

case .caretAnchor:
if options.anchorsMatchNewlines {
emitStartOfLine()
} else {
builder.buildAssert { (_, _, input, pos, subjectBounds) in
pos == subjectBounds.lowerBound
}
}

case .dollarAnchor:
if options.anchorsMatchNewlines {
emitEndOfLine()
} else {
builder.buildAssert { (_, _, input, pos, subjectBounds) in
pos == subjectBounds.upperBound
}
}

case .wordBoundary:
builder.buildAssert { [options]
(cache, maxIndex, input, pos, subjectBounds) in
if options.usesSimpleUnicodeBoundaries {
// TODO: How should we handle bounds?
return _CharacterClassModel.word.isBoundary(
input,
at: pos,
bounds: subjectBounds,
with: options
)
} else {
return input.isOnWordBoundary(at: pos, using: &cache, &maxIndex)
}
}

case .notWordBoundary:
builder.buildAssert { [options]
(cache, maxIndex, input, pos, subjectBounds) in
if options.usesSimpleUnicodeBoundaries {
// TODO: How should we handle bounds?
return !_CharacterClassModel.word.isBoundary(
input,
at: pos,
bounds: subjectBounds,
with: options
)
} else {
return !input.isOnWordBoundary(at: pos, using: &cache, &maxIndex)
}
}
}
builder.buildAssert(
by: kind,
options.anchorsMatchNewlines,
options.usesSimpleUnicodeBoundaries,
options.usesASCIIWord,
options.semanticLevel)
}


mutating func emitCharacterClass(_ cc: DSLTree.Atom.CharacterClass) {
builder.buildMatchBuiltin(
cc.model,
cc.model.isStrictAscii(options: options),
isScalar: options.semanticLevel == .unicodeScalar)
}

mutating func emitMatchScalar(_ s: UnicodeScalar) {
assert(options.semanticLevel == .unicodeScalar)
if options.isCaseInsensitive && s.properties.isCased {
Expand Down Expand Up @@ -591,6 +474,10 @@ fileprivate extension Compiler.ByteCodeGen {
let minTrips = low
assert((extraTrips ?? 1) >= 0)

if tryEmitFastQuant(child, updatedKind, minTrips, extraTrips) {
return
}

// The below is a general algorithm for bounded and unbounded
// quantification. It can be specialized when the min
// is 0 or 1, or when extra trips is 1 or unbounded.
Expand Down Expand Up @@ -775,6 +662,83 @@ fileprivate extension Compiler.ByteCodeGen {
builder.label(exit)
}

/// Specialized quantification instruction for repetition of certain nodes in grapheme semantic mode
/// Allowed nodes are:
/// - single ascii scalar .char
/// - ascii .customCharacterClass
/// - single grapheme consumgin built in character classes
/// - .any, .anyNonNewline, .dot
mutating func tryEmitFastQuant(
_ child: DSLTree.Node,
_ kind: AST.Quantification.Kind,
_ minTrips: Int,
_ extraTrips: Int?
) -> Bool {
guard optimizationsEnabled
&& minTrips <= QuantifyPayload.maxStorableTrips
&& extraTrips ?? 0 <= QuantifyPayload.maxStorableTrips
&& options.matchLevel == .graphemeCluster
&& kind != .reluctant else {
return false
}

switch child {
case .customCharacterClass(let ccc):
// ascii only custom character class
guard let bitset = ccc.asAsciiBitset(options) else {
return false
}
builder.buildQuantify(bitset: bitset, kind, minTrips, extraTrips)

case .atom(let atom):
switch atom {
case .char(let c):
// Single scalar ascii value character
guard let val = c._singleScalarAsciiValue else {
return false
}
builder.buildQuantify(asciiChar: val, kind, minTrips, extraTrips)

case .any:
builder.buildQuantifyAny(
matchesNewlines: true, kind, minTrips, extraTrips)
case .anyNonNewline:
builder.buildQuantifyAny(
matchesNewlines: false, kind, minTrips, extraTrips)
case .dot:
builder.buildQuantifyAny(
matchesNewlines: options.dotMatchesNewline, kind, minTrips, extraTrips)

case .characterClass(let cc):
// Custom character class that consumes a single grapheme
let model = cc.model
guard model.consumesSingleGrapheme else {
return false
}
builder.buildQuantify(
builtin: model.cc,
isStrict: model.isStrictAscii(options: options),
isInverted: model.isInverted,
kind,
minTrips,
extraTrips)
default:
return false
}
case .convertedRegexLiteral(let node, _):
return tryEmitFastQuant(node, kind, minTrips, extraTrips)
case .nonCapturingGroup(let groupKind, let node):
// .nonCapture nonCapturingGroups are ignored during compilation
guard groupKind.ast == .nonCapture else {
return false
}
return tryEmitFastQuant(node, kind, minTrips, extraTrips)
default:
return false
}
return true
}

mutating func emitCustomCharacterClass(
_ ccc: DSLTree.CustomCharacterClass
) throws {
Expand All @@ -785,10 +749,10 @@ fileprivate extension Compiler.ByteCodeGen {
} else {
builder.buildMatchAsciiBitset(asciiBitset)
}
} else {
let consumer = try ccc.generateConsumer(options)
builder.buildConsume(by: consumer)
return
}
let consumer = try ccc.generateConsumer(options)
builder.buildConsume(by: consumer)
}

@discardableResult
Expand Down
Loading