forked from swiftlang/swift-experimental-string-processing
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCompileTests.swift
593 lines (550 loc) · 20.1 KB
/
CompileTests.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2021-2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
@testable import _RegexParser
@testable import _StringProcessing
import TestSupport
import XCTest
enum DecodedInstr {
case invalid
case moveImmediate
case moveCurrentPosition
case restorePosition
case branch
case condBranchZeroElseDecrement
case condBranchSamePosition
case save
case saveAddress
case splitSaving
case clear
case clearThrough
case accept
case fail
case advance
case match
case matchCaseInsensitive
case matchScalar
case matchScalarCaseInsensitiveUnchecked
case matchScalarCaseInsensitive
case matchScalarUnchecked
case matchBitsetScalar
case matchAnyNonNewline
case matchBitset
case matchBuiltin
case matchUTF8
case consumeBy
case assertBy
case matchBy
case backreference
case beginCapture
case endCapture
case transformCapture
case captureValue
case quantify
}
extension DecodedInstr {
/// Decode the given instruction by looking at the opcode and payload, expanding out certain instructions
/// like matchScalar and match into their variants
///
/// Must stay in sync with Processor.cycle
static func decode(_ instruction: Instruction) -> DecodedInstr {
let (opcode, payload) = instruction.destructure
switch opcode {
case .invalid:
fatalError("Invalid program")
case .moveImmediate:
return .moveImmediate
case .moveCurrentPosition:
return .moveCurrentPosition
case .restorePosition:
return .restorePosition
case .branch:
return .branch
case .condBranchZeroElseDecrement:
return .condBranchZeroElseDecrement
case .condBranchSamePosition:
return .condBranchSamePosition
case .save:
return .save
case .saveAddress:
return .saveAddress
case .splitSaving:
return .splitSaving
case .clear:
return .clear
case .clearThrough:
return .clearThrough
case .accept:
return .accept
case .fail:
return .fail
case .advance:
return .advance
case .match:
let (isCaseInsensitive, _) = payload.elementPayload
if isCaseInsensitive {
return .matchCaseInsensitive
} else {
return .match
}
case .matchScalar:
let (_, caseInsensitive, boundaryCheck) = payload.scalarPayload
if caseInsensitive {
if boundaryCheck {
return .matchScalarCaseInsensitive
} else {
return .matchScalarCaseInsensitiveUnchecked
}
} else {
if boundaryCheck {
return .matchScalar
} else {
return .matchScalarUnchecked
}
}
case .matchBitset:
let (isScalar, _) = payload.bitsetPayload
if isScalar {
return .matchBitsetScalar
} else {
return .matchBitset
}
case .consumeBy:
return .consumeBy
case .matchAnyNonNewline:
return .matchAnyNonNewline
case .assertBy:
return .assertBy
case .matchBy:
return .matchBy
case .quantify:
return .quantify
case .backreference:
return .backreference
case .beginCapture:
return .beginCapture
case .endCapture:
return .endCapture
case .transformCapture:
return .transformCapture
case .captureValue:
return .captureValue
case .matchBuiltin:
return .matchBuiltin
case .matchUTF8:
return .matchUTF8
}
}
}
extension RegexTests {
private func testCompilationEquivalence(
_ equivs: [String],
file: StaticString = #file,
line: UInt = #line
) throws {
assert(!equivs.isEmpty)
let progs = try equivs.map {
try _compileRegex($0)
}
let ref = progs.first!
for (prog, equiv) in zip(progs, equivs).dropFirst() {
guard ref.instructions.elementsEqual(
prog.instructions) else {
XCTFail("""
Reference:
\(ref)
Current:
\(prog)
Compiled from:
\(equiv)
""",
file: file, line: line)
continue
}
}
}
private func testCompileError(
_ regex: String, _ error: RegexCompilationError,
file: StaticString = #file, line: UInt = #line
) {
do {
_ = try _compileRegex(regex)
XCTFail("Expected compile error", file: file, line: line)
} catch let err as RegexCompilationError {
XCTAssertEqual(err, error, file: file, line: line)
} catch {
XCTFail("Unknown compile error", file: file, line: line)
}
}
func testInvalidScalarCoalescing() throws {
guard ensureNewStdlib() else { return }
// Non-single-scalar bounds.
testCompileError(
#"[a\u{302}-✅]"#, .invalidCharacterClassRangeOperand("a\u{302}"))
testCompileError(
#"[e\u{301}-\u{302}]"#, .invalidCharacterClassRangeOperand("e\u{301}"))
testCompileError(
#"[\u{73}\u{323}\u{307}-\u{1E00}]"#,
.invalidCharacterClassRangeOperand("\u{73}\u{323}\u{307}"))
testCompileError(
#"[a\u{315}\u{301}-\u{302}]"#,
.invalidCharacterClassRangeOperand("a\u{315}\u{301}")
)
testCompileError(
#"[a-z1e\u{301}-\u{302}\u{E1}3-59]"#,
.invalidCharacterClassRangeOperand("e\u{301}")
)
testCompileError(
#"[[e\u{301}-\u{302}]&&e\u{303}]"#,
.invalidCharacterClassRangeOperand("e\u{301}")
)
}
func testCompileQuantification() throws {
// NOTE: While we might change how we compile
// quantifications, they should be compiled equivalently
// for different syntactic expressions.
let equivalents: Array<[String]> = [
["a*", "a{0,}"],
["a+", "a{1,}"],
["a?", "a{0,1}", "a{,1}"],
["a*?", "a{0,}?"],
["a+?", "a{1,}?"],
["a??", "a{0,1}?", "a{,1}?"],
["a*+", "a{0,}+"],
["a++", "a{1,}+"],
["a?+", "a{0,1}+", "a{,1}+"],
]
for row in equivalents {
try testCompilationEquivalence(row)
}
}
func testCompileGroups() throws {
let equivalents: Array<[String]> = [
["(?= assert)",
"(*pla: assert)",
"(*positive_lookahead: assert)"],
["(?! assert)",
"(*nla: assert)",
"(*negative_lookahead: assert)"],
["a+?",
"(?U)a+",
"(?U:a+)"],
["a+",
"(?U)(?-U)a+",
"(?U)(?^s)a+"],
]
for row in equivalents {
try testCompilationEquivalence(row)
}
}
func testCompileInitialOptions() throws {
func expectInitialOptions<T>(
_ regex: Regex<T>,
_ optionSequence: AST.MatchingOptionSequence,
file: StaticString = #file,
line: UInt = #line
) throws {
var options = MatchingOptions()
options.apply(optionSequence)
XCTAssertTrue(
regex.program.loweredProgram.initialOptions._equal(to: options),
file: file, line: line)
}
func expectInitialOptions(
_ pattern: String,
_ optionSequence: AST.MatchingOptionSequence,
file: StaticString = #file,
line: UInt = #line
) throws {
let regex = try Regex(pattern)
try expectInitialOptions(regex, optionSequence, file: file, line: line)
}
try expectInitialOptions(".", matchingOptions())
try expectInitialOptions("(?i)(?-i).", matchingOptions())
try expectInitialOptions("(?i).", matchingOptions(adding: [.caseInsensitive]))
try expectInitialOptions("(?i).(?-i)", matchingOptions(adding: [.caseInsensitive]))
try expectInitialOptions(
"(?im)(?s).",
matchingOptions(adding: [.caseInsensitive, .multiline, .singleLine]))
try expectInitialOptions(".", matchingOptions())
// FIXME: Figure out (?X) and (?u) semantics
try XCTExpectFailure("Figure out (?X) and (?u) semantics") {
try expectInitialOptions(
"(?im)(?s).(?u)",
matchingOptions(adding: [.caseInsensitive, .multiline, .singleLine]))
}
try expectInitialOptions(
"(?i:.)",
matchingOptions(adding: [.caseInsensitive]))
try expectInitialOptions(
"(?i:.)(?m:.)",
matchingOptions(adding: [.caseInsensitive]))
try expectInitialOptions(
"((?i:.))",
matchingOptions(adding: [.caseInsensitive]))
}
func expectProgram(
for regex: String,
syntax: SyntaxOptions = .traditional,
semanticLevel: RegexSemanticLevel? = nil,
contains targets: Set<DecodedInstr> = [],
doesNotContain invalid: Set<DecodedInstr> = [],
file: StaticString = #file,
line: UInt = #line
) {
do {
let prog = try _compileRegex(regex, syntax, semanticLevel)
var found: Set<DecodedInstr> = []
for inst in prog.instructions {
let decoded = DecodedInstr.decode(inst)
found.insert(decoded)
if invalid.contains(decoded) {
XCTFail(
"Compiled regex '\(regex)' contains incorrect opcode \(decoded)",
file: file,
line: line)
return
}
}
if !found.isSuperset(of: targets) {
XCTFail(
"Compiled regex '\(regex)' did not contain desired opcodes. Wanted: \(targets), found: \(found)",
file: file,
line: line)
}
} catch {
XCTFail(
"Failed to compile regex '\(regex)': \(error)",
file: file,
line: line)
}
}
func testBitsetCompile() {
expectProgram(
for: "[abc]",
contains: [.matchBitset],
doesNotContain: [.consumeBy, .matchBitsetScalar])
expectProgram(
for: "[abc]",
semanticLevel: .unicodeScalar,
contains: [.matchBitsetScalar],
doesNotContain: [.matchBitset, .consumeBy])
expectProgram(
for: #"[\Qab\Ec]"#,
contains: [.matchBitset],
doesNotContain: [.consumeBy, .matchBitsetScalar])
expectProgram(
for: #"[\Qab\Ec]"#,
semanticLevel: .unicodeScalar,
contains: [.matchBitsetScalar],
doesNotContain: [.matchBitset, .consumeBy])
expectProgram(
for: "[a-c]",
contains: [.matchBitset],
doesNotContain: [.consumeBy, .matchBitsetScalar])
expectProgram(
for: "[a-c0123]",
contains: [.matchBitset],
doesNotContain: [.matchBitsetScalar, .consumeBy])
expectProgram(
for: #"\w"#,
contains: [.matchBuiltin],
doesNotContain: [.consumeBy, .matchBitset, .matchBitsetScalar])
expectProgram(
for: #"[\w]"#,
contains: [.matchBuiltin],
doesNotContain: [.consumeBy, .matchBitset, .matchBitsetScalar])
expectProgram(
for: #"\w"#,
semanticLevel: .unicodeScalar,
contains: [.matchBuiltin],
doesNotContain: [.consumeBy, .matchBitset, .matchBitsetScalar])
expectProgram(
for: #"[\w]"#,
semanticLevel: .unicodeScalar,
contains: [.matchBuiltin],
doesNotContain: [.consumeBy, .matchBitset, .matchBitsetScalar])
expectProgram(
for: #"\p{Greek}"#,
contains: [.consumeBy],
doesNotContain: [.matchBuiltin, .matchBitset, .matchBitsetScalar])
// Must have new stdlib for character class ranges.
guard ensureNewStdlib() else { return }
expectProgram(
for: "[a-á]",
contains: [.consumeBy],
doesNotContain: [.matchBitset, .matchBitsetScalar])
expectProgram(
for: "[a-fá-ém-zk]",
contains: [.matchBitset, .consumeBy],
doesNotContain: [.matchBitsetScalar])
}
func testScalarOptimizeCompilation() {
// all ascii quoted literal -> elide boundary checks
expectProgram(
for: "abcd",
contains: [.matchScalar, .matchScalarUnchecked],
doesNotContain: [.match, .consumeBy])
// ascii character -> matchScalar with boundary check
expectProgram(
for: "a",
contains: [.matchScalar],
doesNotContain: [.match, .consumeBy, .matchScalarUnchecked])
// quoted literal is not all ascii -> match scalar when possible, always do boundary checks
expectProgram(
for: "aaa\u{301}",
contains: [.match, .matchScalar],
doesNotContain: [.consumeBy, .matchScalarUnchecked])
// scalar mode -> always emit match scalar without boundary checks
expectProgram(
for: "abcd",
semanticLevel: .unicodeScalar,
contains: [.matchScalarUnchecked],
doesNotContain: [.match, .consumeBy, .matchScalar])
expectProgram(
for: "a",
semanticLevel: .unicodeScalar,
contains: [.matchScalarUnchecked],
doesNotContain: [.match, .consumeBy, .matchScalar])
expectProgram(
for: "a\u{301}",
semanticLevel: .unicodeScalar,
contains: [.matchScalarUnchecked],
doesNotContain: [.match, .consumeBy, .matchScalar])
expectProgram(
for: "abcdefg",
semanticLevel: .unicodeScalar,
contains: [.matchUTF8],
doesNotContain: [.match, .consumeBy, .matchScalar])
expectProgram(
for: "abcdefg",
semanticLevel: .graphemeCluster,
contains: [.matchUTF8],
doesNotContain: [.match, .consumeBy, .matchScalar])
expectProgram(
for: "aaa\u{301}",
semanticLevel: .unicodeScalar,
contains: [.matchUTF8],
doesNotContain: [.match, .consumeBy, .matchScalar])
expectProgram(
for: "aaa\u{301}",
semanticLevel: .graphemeCluster,
contains: [.match],
doesNotContain: [.matchUTF8, .consumeBy])
}
func testCaseInsensitivityCompilation() {
// quoted literal is all ascii -> match scalar case insensitive and skip
// boundary checks
expectProgram(
for: "(?i)abcd",
contains: [.matchScalarCaseInsensitiveUnchecked, .matchScalarCaseInsensitive],
doesNotContain: [.match, .matchCaseInsensitive, .matchScalar, .matchScalarUnchecked])
// quoted literal is all non-cased ascii -> emit match scalar instructions
expectProgram(
for: "(?i)&&&&",
contains: [.matchScalar, .matchScalarUnchecked],
doesNotContain: [.match, .matchCaseInsensitive,
.matchScalarCaseInsensitive, .matchScalarCaseInsensitiveUnchecked])
// quoted literal is not all ascii -> match scalar case insensitive when
// possible, match character case insensitive when needed, always perform
// boundary check
expectProgram(
for: "(?i)abcd\u{301}",
contains: [.matchCaseInsensitive, .matchScalarCaseInsensitive],
doesNotContain: [.matchScalarCaseInsensitiveUnchecked, .match, .matchScalar])
// same as before but contains ascii non cased characters -> emit matchScalar for them
expectProgram(
for: "(?i)abcd\u{301};.'!",
contains: [.matchCaseInsensitive, .matchScalarCaseInsensitive, .matchScalar],
doesNotContain: [.matchScalarCaseInsensitiveUnchecked, .match])
// contains non-ascii non-cased characters -> emit match
expectProgram(
for: "(?i)abcd\u{301};.'!💖",
contains: [.matchCaseInsensitive, .matchScalarCaseInsensitive, .matchScalar, .match],
doesNotContain: [.matchScalarCaseInsensitiveUnchecked])
// scalar mode -> emit unchecked scalar match only, emit case insensitive
// only if the scalar is cased
expectProgram(
for: "(?i);.'!💖",
semanticLevel: .unicodeScalar,
contains: [.matchScalarUnchecked],
doesNotContain: [.matchScalarCaseInsensitiveUnchecked])
expectProgram(
for: "(?i)abcdé",
semanticLevel: .unicodeScalar,
contains: [.matchScalarCaseInsensitiveUnchecked],
doesNotContain: [.matchScalarUnchecked])
}
func testQuantificationForwardProgressCompile() {
// Unbounded quantification + non forward progressing inner nodes
// Expect to emit the position checking instructions
expectProgram(for: #"(?:(?=a)){1,}"#, contains: [.moveCurrentPosition, .condBranchSamePosition])
expectProgram(for: #"(?:\b)*"#, contains: [.moveCurrentPosition, .condBranchSamePosition])
expectProgram(for: #"(?:(?#comment))+"#, contains: [.moveCurrentPosition, .condBranchSamePosition])
expectProgram(for: #"(?:|)+"#, contains: [.moveCurrentPosition, .condBranchSamePosition])
expectProgram(for: #"(?:\w|)+"#, contains: [.moveCurrentPosition, .condBranchSamePosition])
expectProgram(for: #"(?:\w|(?i-i:))+"#, contains: [.moveCurrentPosition, .condBranchSamePosition])
expectProgram(for: #"(?:\w|(?#comment))+"#, contains: [.moveCurrentPosition, .condBranchSamePosition])
expectProgram(for: #"(?:\w|(?#comment)(?i-i:))+"#, contains: [.moveCurrentPosition, .condBranchSamePosition])
expectProgram(for: #"(?:\w|(?i))+"#, contains: [.moveCurrentPosition, .condBranchSamePosition])
// Bounded quantification, don't emit position checking
expectProgram(for: #"(?:(?=a)){1,4}"#, doesNotContain: [.moveCurrentPosition, .condBranchSamePosition])
expectProgram(for: #"(?:\b)?"#, doesNotContain: [.moveCurrentPosition, .condBranchSamePosition])
expectProgram(for: #"(?:(?#comment)){,4}"#, doesNotContain: [.moveCurrentPosition, .condBranchSamePosition])
expectProgram(for: #"(?:|){,4}"#, doesNotContain: [.moveCurrentPosition, .condBranchSamePosition])
expectProgram(for: #"(?:\w|){,4}"#, doesNotContain: [.moveCurrentPosition, .condBranchSamePosition])
expectProgram(for: #"(?:\w|(?i-i:)){,4}"#, doesNotContain: [.moveCurrentPosition, .condBranchSamePosition])
expectProgram(for: #"(?:\w|(?#comment)){,4}"#, doesNotContain: [.moveCurrentPosition, .condBranchSamePosition])
expectProgram(for: #"(?:\w|(?#comment)(?i-i:)){,4}"#, doesNotContain: [.moveCurrentPosition, .condBranchSamePosition])
expectProgram(for: #"(?:\w|(?i)){,4}"#, doesNotContain: [.moveCurrentPosition, .condBranchSamePosition])
// Inner node is a quantification that does not guarantee forward progress
expectProgram(for: #"(a*)*"#, contains: [.moveCurrentPosition, .condBranchSamePosition])
expectProgram(for: #"(a?)*"#, contains: [.moveCurrentPosition, .condBranchSamePosition])
expectProgram(for: #"(a{,5})*"#, contains: [.moveCurrentPosition, .condBranchSamePosition])
expectProgram(for: #"((\b){,4})*"#, contains: [.moveCurrentPosition, .condBranchSamePosition])
expectProgram(for: #"((\b){1,4})*"#, contains: [.moveCurrentPosition, .condBranchSamePosition])
expectProgram(for: #"((|){1,4})*"#, contains: [.moveCurrentPosition, .condBranchSamePosition])
// Inner node is a quantification that guarantees forward progress
expectProgram(for: #"(a+)*"#, doesNotContain: [.moveCurrentPosition, .condBranchSamePosition])
expectProgram(for: #"(a{1,})*"#, doesNotContain: [.moveCurrentPosition, .condBranchSamePosition])
}
func testCanOnlyMatchAtStart() throws {
func expectCanOnlyMatchAtStart(
_ regexStr: String,
_ expectTrue: Bool,
file: StaticString = #file,
line: UInt = #line
) throws {
let regex = try Regex(regexStr)
XCTAssertEqual(
regex.program.loweredProgram.canOnlyMatchAtStart, expectTrue,
file: file, line: line)
}
try expectCanOnlyMatchAtStart("^foo", true) // anchor
try expectCanOnlyMatchAtStart("\\Afoo", true) // more specific anchor
try expectCanOnlyMatchAtStart("foo", false) // no anchor
try expectCanOnlyMatchAtStart("(?i)^foo", true) // unrelated option
try expectCanOnlyMatchAtStart("(?m)^foo", false) // anchors match newlines
try expectCanOnlyMatchAtStart("(?i:^foo)", true) // unrelated option
try expectCanOnlyMatchAtStart("(?m:^foo)", false) // anchors match newlines
try expectCanOnlyMatchAtStart("(^foo|bar)", false) // one side of alternation
try expectCanOnlyMatchAtStart("(foo|^bar)", false) // other side of alternation
try expectCanOnlyMatchAtStart("(^foo|^bar)", true) // both sides of alternation
// Test quantifiers that include the anchor
try expectCanOnlyMatchAtStart("(^foo)?bar", false)
try expectCanOnlyMatchAtStart("(^foo)*bar", false)
try expectCanOnlyMatchAtStart("(^foo)+bar", true)
try expectCanOnlyMatchAtStart("(?:^foo)+bar", true)
// Test quantifiers before the anchor
try expectCanOnlyMatchAtStart("(foo)?^bar", true) // The initial group must match ""
try expectCanOnlyMatchAtStart("(?:foo)?^bar", true)
try expectCanOnlyMatchAtStart("(foo)+^bar", false) // This can't actually match anywhere
}
}