Skip to content

Implement named backreferences #433

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 2 commits into from
May 25, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
15 changes: 15 additions & 0 deletions Sources/_RegexParser/Regex/Parse/CaptureList.swift
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,21 @@ extension CaptureList {
}
}

extension CaptureList {
/// Retrieve the capture index of a given named capture, or `nil` if there is
/// no such capture.
public func indexOfCapture(named name: String) -> Int? {
// Named references are guaranteed to be unique for literal ASTs by Sema.
// The DSL tree does not use named references.
captures.indices.first(where: { captures[$0].name == name })
}

/// Whether the capture list has a given named capture.
public func hasCapture(named name: String) -> Bool {
indexOfCapture(named: name) != nil
}
}

// MARK: Generating from AST

extension AST.Node {
Expand Down
3 changes: 3 additions & 0 deletions Sources/_RegexParser/Regex/Parse/Diagnostics.swift
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@ enum ParseError: Error, Hashable {
case unsupported(String)
case deprecatedUnicode(String)
case invalidReference(Int)
case invalidNamedReference(String)
case duplicateNamedCapture(String)
case invalidCharacterClassRangeOperand
case invalidQuantifierRange(Int, Int)
Expand Down Expand Up @@ -211,6 +212,8 @@ extension ParseError: CustomStringConvertible {
return "\(kind) is a deprecated Unicode property, and is not supported"
case let .invalidReference(i):
return "no capture numbered \(i)"
case let .invalidNamedReference(name):
return "no capture named '\(name)'"
case let .duplicateNamedCapture(str):
return "group named '\(str)' already exists"
case let .invalidQuantifierRange(lhs, rhs):
Expand Down
14 changes: 7 additions & 7 deletions Sources/_RegexParser/Regex/Parse/Sema.swift
Original file line number Diff line number Diff line change
Expand Up @@ -72,20 +72,20 @@ extension RegexValidator {
}

func validateReference(_ ref: AST.Reference) throws {
if let recLevel = ref.recursionLevel {
throw error(.unsupported("recursion level"), at: recLevel.location)
}
switch ref.kind {
case .absolute(let i):
guard i <= captures.captures.count else {
throw error(.invalidReference(i), at: ref.innerLoc)
}
case .named(let name):
guard captures.hasCapture(named: name) else {
throw error(.invalidNamedReference(name), at: ref.innerLoc)
}
case .relative:
throw error(.unsupported("relative capture reference"), at: ref.innerLoc)
case .named:
// TODO: This could be implemented by querying the capture list for an
// index.
throw error(.unsupported("named capture reference"), at: ref.innerLoc)
}
if let recLevel = ref.recursionLevel {
throw error(.unsupported("recursion level"), at: recLevel.location)
}
}

Expand Down
9 changes: 8 additions & 1 deletion Sources/_StringProcessing/ByteCodeGen.swift
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,11 @@ extension Compiler {
var options: MatchingOptions
var builder = Program.Builder()

init(options: MatchingOptions, captureList: CaptureList) {
self.options = options
self.builder.captureList = captureList
}

mutating func finish(
) throws -> Program {
builder.buildAccept()
Expand Down Expand Up @@ -62,7 +67,9 @@ extension Compiler.ByteCodeGen {
case .absolute(let i):
// Backreferences number starting at 1
builder.buildBackreference(.init(i-1))
case .relative, .named:
case .named(let name):
try builder.buildNamedReference(name)
case .relative:
throw Unsupported("Backreference kind: \(ref)")
}
}
Expand Down
5 changes: 3 additions & 2 deletions Sources/_StringProcessing/Compiler.swift
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,9 @@ class Compiler {

__consuming func emit() throws -> Program {
// TODO: Handle global options
var codegen = ByteCodeGen(options: options)
codegen.builder.captureList = tree.root._captureList
var codegen = ByteCodeGen(
options: options, captureList: tree.root._captureList
)
try codegen.emitNode(tree.root)
let program = try codegen.finish()
return program
Expand Down
15 changes: 11 additions & 4 deletions Sources/_StringProcessing/Engine/MEBuilder.swift
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ extension MEProgram where Input.Element: Hashable {
// Symbolic reference resolution
var unresolvedReferences: [ReferenceID: [InstructionAddress]] = [:]
var referencedCaptureOffsets: [ReferenceID: Int] = [:]
var namedCaptureOffsets: [String: Int] = [:]

var captureCount: Int {
// We currently deduce the capture count from the capture register number.
nextCaptureRegister.rawValue
Expand Down Expand Up @@ -284,6 +284,13 @@ extension MEProgram.Builder {
unresolvedReferences[id, default: []].append(lastInstructionAddress)
}

mutating func buildNamedReference(_ name: String) throws {
guard let index = captureList.indexOfCapture(named: name) else {
throw RegexCompilationError.uncapturedReference
}
buildBackreference(.init(index))
}

// TODO: Mutating because of fail address fixup, drop when
// that's removed
mutating func assemble() throws -> MEProgram {
Expand Down Expand Up @@ -359,7 +366,6 @@ extension MEProgram.Builder {
registerInfo: regInfo,
captureList: captureList,
referencedCaptureOffsets: referencedCaptureOffsets,
namedCaptureOffsets: namedCaptureOffsets,
initialOptions: initialOptions)
}

Expand Down Expand Up @@ -456,9 +462,10 @@ extension MEProgram.Builder {
assert(preexistingValue == nil)
}
if let name = name {
// TODO: Reject duplicate capture names unless `(?J)`?
namedCaptureOffsets.updateValue(captureCount, forKey: name)
let index = captureList.indexOfCapture(named: name)
assert(index == nextCaptureRegister.rawValue)
}
assert(nextCaptureRegister.rawValue < captureList.captures.count)
return nextCaptureRegister
}

Expand Down
1 change: 0 additions & 1 deletion Sources/_StringProcessing/Engine/MECapture.swift
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,6 @@ extension Processor._StoredCapture: CustomStringConvertible {
struct MECaptureList {
var values: Array<Processor<String>._StoredCapture>
var referencedCaptureOffsets: [ReferenceID: Int]
var namedCaptureOffsets: [String: Int]

// func extract(from s: String) -> Array<Array<Substring>> {
// caps.map { $0.map { s[$0] } }
Expand Down
1 change: 0 additions & 1 deletion Sources/_StringProcessing/Engine/MEProgram.swift
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,6 @@ struct MEProgram<Input: Collection> where Input.Element: Equatable {

let captureList: CaptureList
let referencedCaptureOffsets: [ReferenceID: Int]
let namedCaptureOffsets: [String: Int]

var initialOptions: MatchingOptions
}
Expand Down
3 changes: 1 addition & 2 deletions Sources/_StringProcessing/Executor.swift
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,7 @@ struct Executor {

let capList = MECaptureList(
values: cpu.storedCaptures,
referencedCaptureOffsets: engine.program.referencedCaptureOffsets,
namedCaptureOffsets: engine.program.namedCaptureOffsets)
referencedCaptureOffsets: engine.program.referencedCaptureOffsets)

let range = inputRange.lowerBound..<endIdx
let caps = engine.program.captureList.createElements(capList, input)
Expand Down
17 changes: 13 additions & 4 deletions Tests/RegexTests/MatchTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -1142,23 +1142,32 @@ extension RegexTests {
}

func testMatchReferences() {
// TODO: Implement backreference/subpattern matching.
firstMatchTest(
#"(.)\1"#,
input: "112", match: "11")
firstMatchTest(
#"(.)(.)(.)(.)(.)(.)(.)(.)(.)(.)\10"#,
input: "aaaaaaaaabbc", match: "aaaaaaaaabb")

firstMatchTest(
#"(.)(.)(.)(.)(.)(.)(.)(.)(.)(?<a1>.)(?P=a1)"#,
input: "aaaaaaaaabbc", match: "aaaaaaaaabb")

firstMatchTest(
#"(.)\g001"#,
input: "112", match: "11")

firstMatchTest(#"(.)(.)\g-02"#, input: "abac", match: "aba", xfail: true)
firstMatchTest(#"(?<a>.)(.)\k<a>"#, input: "abac", match: "aba", xfail: true)
firstMatchTest(#"\g'+2'(.)(.)"#, input: "abac", match: "aba", xfail: true)
firstMatchTest(#"(?<a>.)(.)\k<a>"#, input: "abac", match: "aba")

firstMatchTest(#"(?<a>.)(?<b>.)(?<c>.)\k<c>\k<a>\k<b>"#,
input: "xyzzxy", match: "xyzzxy")

firstMatchTest(#"\1(.)"#, input: "112", match: nil)
firstMatchTest(#"\k<a>(?<a>.)"#, input: "112", match: nil)

// TODO: Implement subpattern matching.
firstMatchTest(#"(.)(.)\g-02"#, input: "abac", match: "aba", xfail: true)
firstMatchTest(#"\g'+2'(.)(.)"#, input: "abac", match: "aba", xfail: true)
}

func testMatchExamples() {
Expand Down
41 changes: 34 additions & 7 deletions Tests/RegexTests/ParseTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -1242,16 +1242,37 @@ extension RegexTests {
parseTest(#"\k'-3'"#, backreference(.relative(-3)), throwsError: .unsupported)
parseTest(#"\k'1'"#, backreference(.absolute(1)), throwsError: .invalid)

parseTest(#"\k{a0}"#, backreference(.named("a0")), throwsError: .unsupported)
parseTest(#"\k<bc>"#, backreference(.named("bc")), throwsError: .unsupported)
parseTest(#"\g{abc}"#, backreference(.named("abc")), throwsError: .unsupported)
parseTest(#"(?P=abc)"#, backreference(.named("abc")), throwsError: .unsupported)
parseTest(
#"(?<a>)\k<a>"#, concat(
namedCapture("a", empty()), backreference(.named("a"))
), captures: [.named("a")]
)
parseTest(
#"(?<a>)\k{a}"#, concat(
namedCapture("a", empty()), backreference(.named("a"))
), captures: [.named("a")]
)
parseTest(
#"(?<a>)\g{a}"#, concat(
namedCapture("a", empty()), backreference(.named("a"))
), captures: [.named("a")]
)
parseTest(
#"(?<a>)(?P=a)"#, concat(
namedCapture("a", empty()), backreference(.named("a"))
), captures: [.named("a")]
)

parseTest(#"\k{a0}"#, backreference(.named("a0")), throwsError: .invalid)
parseTest(#"\k<bc>"#, backreference(.named("bc")), throwsError: .invalid)
parseTest(#"\g{abc}"#, backreference(.named("abc")), throwsError: .invalid)
parseTest(#"(?P=abc)"#, backreference(.named("abc")), throwsError: .invalid)

// Oniguruma recursion levels.
parseTest(#"\k<bc-0>"#, backreference(.named("bc"), recursionLevel: 0), throwsError: .unsupported)
parseTest(#"\k<a+0>"#, backreference(.named("a"), recursionLevel: 0), throwsError: .unsupported)
parseTest(#"\k<1+1>"#, backreference(.absolute(1), recursionLevel: 1), throwsError: .invalid)
parseTest(#"\k<3-8>"#, backreference(.absolute(3), recursionLevel: -8), throwsError: .invalid)
parseTest(#"\k<1+1>"#, backreference(.absolute(1), recursionLevel: 1), throwsError: .unsupported)
parseTest(#"\k<3-8>"#, backreference(.absolute(3), recursionLevel: -8), throwsError: .unsupported)
parseTest(#"\k'-3-8'"#, backreference(.relative(-3), recursionLevel: -8), throwsError: .unsupported)
parseTest(#"\k'bc-8'"#, backreference(.named("bc"), recursionLevel: -8), throwsError: .unsupported)
parseTest(#"\k'+3-8'"#, backreference(.relative(3), recursionLevel: -8), throwsError: .unsupported)
Expand Down Expand Up @@ -2167,7 +2188,7 @@ extension RegexTests {
throwsError: .unsupported
)
parseWithDelimitersTest(
#"re'a\k'b0A''"#, concat("a", backreference(.named("b0A"))), throwsError: .unsupported)
#"re'a\k'b0A''"#, concat("a", backreference(.named("b0A"))), throwsError: .invalid)
parseWithDelimitersTest(
#"re'\k'+2-1''"#, backreference(.relative(2), recursionLevel: -1),
throwsError: .unsupported
Expand Down Expand Up @@ -2811,6 +2832,12 @@ extension RegexTests {
diagnosticTest(#"(?:)()\2"#, .invalidReference(2))
diagnosticTest(#"(?:)(?:)\2"#, .invalidReference(2))

diagnosticTest(#"\k<a>"#, .invalidNamedReference("a"))
diagnosticTest(#"(?:)\k<a>"#, .invalidNamedReference("a"))
diagnosticTest(#"()\k<a>"#, .invalidNamedReference("a"))
diagnosticTest(#"()\k<a>()"#, .invalidNamedReference("a"))
diagnosticTest(#"(?<b>)\k<a>()"#, .invalidNamedReference("a"))

// MARK: Conditionals

diagnosticTest(#"(?(1)a|b|c)"#, .tooManyBranchesInConditional(3))
Expand Down