forked from swiftlang/swift-experimental-string-processing
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathVariadicsGenerator.swift
998 lines (908 loc) · 33.6 KB
/
VariadicsGenerator.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
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
// swift run VariadicsGenerator --max-arity 10 > Sources/RegexBuilder/Variadics.swift
import ArgumentParser
#if os(macOS)
import Darwin
#elseif canImport(Glibc)
import Glibc
#elseif os(Windows)
import CRT
#elseif canImport(Bionic)
import Bionic
#endif
// (T), (T)
// (T), (T, T)
// …
// (T), (T, T, T, T, T, T, T)
// (T, T), (T)
// (T, T), (T, T)
// …
// (T, T), (T, T, T, T, T, T)
// …
struct Permutations: Sequence {
let totalArity: Int
struct Iterator: IteratorProtocol {
let totalArity: Int
var leftArity: Int = 0
var rightArity: Int = 0
mutating func next() -> (combinedArity: Int, nextArity: Int)? {
guard leftArity < totalArity else {
return nil
}
defer {
if leftArity + rightArity >= totalArity {
leftArity += 1
rightArity = 0
} else {
rightArity += 1
}
}
return (leftArity, rightArity)
}
}
public func makeIterator() -> Iterator {
Iterator(totalArity: totalArity)
}
}
func captureTypeList(
_ arity: Int,
lowerBound: Int = 0,
optional: Bool = false
) -> String {
let opt = optional ? "?" : ""
return (lowerBound..<arity).map {
"C\($0+1)\(opt)"
}.joined(separator: ", ")
}
func output(_ content: String) {
print(content, terminator: "")
}
func outputMark(_ content: String) {
print("// MARK: - \(content)\n")
}
func outputForEach<C: Collection>(
_ elements: C,
separator: String? = nil,
lineTerminator: String? = nil,
_ content: (C.Element) -> String
) {
for i in elements.indices {
output(content(elements[i]))
let needsSep = elements.index(after: i) != elements.endIndex
if needsSep, let sep = separator {
output(sep)
}
if let lt = lineTerminator {
let indent = needsSep ? " " : " "
output("\(lt)\n\(indent)")
}
}
}
struct StandardErrorStream: TextOutputStream {
func write(_ string: String) {
fputs(string, stderr)
}
}
var standardError = StandardErrorStream()
typealias Counter = Int64
let regexComponentProtocolName = "RegexComponent"
let outputAssociatedTypeName = "RegexOutput"
let patternProtocolRequirementName = "regex"
let regexTypeName = "Regex"
let baseMatchTypeName = "Substring"
let concatBuilderName = "RegexComponentBuilder"
let altBuilderName = "AlternationBuilder"
let defaultAvailableAttr = "@available(SwiftStdlib 5.7, *)"
@main
struct VariadicsGenerator: ParsableCommand {
@Option(help: "The maximum arity of declarations to generate.")
var maxArity: Int = 10
@Flag(help: "Suppress status messages while generating.")
var silent: Bool = false
func log(_ message: String, terminator: String = "\n") {
if !silent {
print(message, terminator: terminator, to: &standardError)
}
}
func run() throws {
precondition(maxArity > 1)
precondition(maxArity < Counter.bitWidth)
output("""
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2021-2023 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
//
//===----------------------------------------------------------------------===//
// BEGIN AUTO-GENERATED CONTENT
@_spi(RegexBuilder) import _StringProcessing
""")
log("Generating concatenation overloads...")
for (leftArity, rightArity) in Permutations(totalArity: maxArity) {
if rightArity == 0 {
outputMark("Partial block (left arity \(leftArity))")
continue
}
log(" Left arity: \(leftArity) Right arity: \(rightArity)")
emitConcatenation(leftArity: leftArity, rightArity: rightArity)
}
outputMark("Partial block (empty)")
for arity in 0...maxArity {
emitConcatenationWithEmpty(leftArity: arity)
}
output("\n\n")
log("Generating quantifiers...")
for arity in 0...maxArity {
outputMark("Quantifiers (arity \(arity))")
log(" Arity \(arity): ", terminator: "")
for kind in QuantifierKind.allCases {
log("\(kind.rawValue) ", terminator: "")
emitQuantifier(kind: kind, arity: arity)
}
log("repeating ", terminator: "")
emitRepeating(arity: arity)
log("")
}
log("Generating atomic groups...")
outputMark("Atomic groups")
for arity in 0...maxArity {
log(" Arity \(arity): ", terminator: "")
emitAtomicGroup(arity: arity)
log("")
}
log("Generating alternation overloads...")
for (leftArity, rightArity) in Permutations(totalArity: maxArity) {
if rightArity == 0 {
outputMark("Alternation builder (arity \(leftArity))")
}
log(" Left arity: \(leftArity) Right arity: \(rightArity)")
emitAlternation(leftArity: leftArity, rightArity: rightArity)
}
log("Generating 'AlternationBuilder.buildBlock(_:)' overloads...")
outputMark("Alternation builder buildBlock")
for arity in 1...maxArity {
log(" Capture arity: \(arity)")
emitUnaryAlternationBuildBlock(arity: arity)
}
log("Generating 'capture' and 'tryCapture' overloads...")
for arity in 0...maxArity {
log(" Capture arity: \(arity)")
emitCapture(arity: arity)
}
output("\n\n")
output("// END AUTO-GENERATED CONTENT\n")
log("Done!")
}
func tupleType(arity: Int, genericParameters: () -> String) -> String {
assert(arity >= 0)
if arity == 0 {
return genericParameters()
}
return "(\(genericParameters()))"
}
func emitConcatenation(leftArity: Int, rightArity: Int) {
let genericParams: String = {
var result = "W0, W1, "
result += captureTypeList(leftArity+rightArity)
return result
}()
// Emit concatenation type declaration.
let leftOutputType = leftArity == 0
? "W0"
: "(W0, \(captureTypeList(leftArity)))"
let rightOutputType = rightArity == 0
? "W1"
: "(W1, \(captureTypeList(leftArity+rightArity, lowerBound: leftArity)))"
let matchType: String = {
if leftArity+rightArity == 0 {
return baseMatchTypeName
} else {
return "(\(baseMatchTypeName), "
+ captureTypeList(leftArity+rightArity)
+ ")"
}
}()
// Emit concatenation builder.
output("""
\(defaultAvailableAttr)
extension \(concatBuilderName) {
@_alwaysEmitIntoClient
public static func buildPartialBlock<\(genericParams)>(
accumulated: some RegexComponent<\(leftOutputType)>,
next: some RegexComponent<\(rightOutputType)>
) -> \(regexTypeName)<\(matchType)> {
let factory = makeFactory()
""")
if leftArity == 0 {
output("""
return factory.accumulate(ignoringOutputTypeOf: accumulated, next)
""")
} else {
output("""
return factory.accumulate(accumulated, next)
""")
}
output("""
}
}
""")
}
func emitConcatenationWithEmpty(leftArity: Int) {
// T + () = T
output("""
\(defaultAvailableAttr)
extension \(concatBuilderName) {
@_alwaysEmitIntoClient
public static func buildPartialBlock<W0
""")
outputForEach(0..<leftArity) {
", C\($0)"
}
output("""
>(
accumulated: some \(regexComponentProtocolName)<
""")
if leftArity == 0 {
output("W0")
} else {
output("(W0")
outputForEach(0..<leftArity) {
", C\($0)"
}
output(")")
}
output("""
>,
next: some \(regexComponentProtocolName)
) -> \(regexTypeName)<
""")
if leftArity == 0 {
output(baseMatchTypeName)
} else {
output("(\(baseMatchTypeName)")
outputForEach(0..<leftArity) {
", C\($0)"
}
output(")")
}
output("""
> {
let factory = makeFactory()
""")
if leftArity == 0 {
output("""
return factory.accumulate(ignoringOutputTypeOf: accumulated, andAlso: next)
""")
} else {
output("""
return factory.accumulate(accumulated, ignoringOutputTypeOf: next)
""")
}
output("""
}
}
""")
}
enum QuantifierKind: String, CaseIterable {
case zeroOrOne = "Optionally"
case zeroOrMore = "ZeroOrMore"
case oneOrMore = "OneOrMore"
var operatorName: String {
switch self {
case .zeroOrOne: return ".?"
case .zeroOrMore: return ".*"
case .oneOrMore: return ".+"
}
}
var astQuantifierAmount: String {
switch self {
case .zeroOrOne: return "zeroOrOne"
case .zeroOrMore: return "zeroOrMore"
case .oneOrMore: return "oneOrMore"
}
}
var commentAbstract: String {
switch self {
case .zeroOrOne: return """
/// Creates a regex component that matches the given component
/// zero or one times.
"""
case .zeroOrMore: return """
/// Creates a regex component that matches the given component
/// zero or more times.
"""
case .oneOrMore: return """
/// Creates a regex component that matches the given component
/// one or more times.
"""
}
}
}
struct QuantifierParameters {
var arity: Int
var disfavored: String
var genericParams: String
var whereClauseForInit: String
var quantifiedCaptures: String
var matchType: String
init(kind: QuantifierKind, arity: Int) {
self.arity = arity
self.disfavored = arity == 0 ? " @_disfavoredOverload\n" : ""
self.genericParams = {
var result = ""
if arity > 0 {
result += "W, "
result += captureTypeList(arity)
}
return result.isEmpty
? ""
: "<\(result)>"
}()
let capturesJoined = captureTypeList(arity)
self.quantifiedCaptures = {
switch kind {
case .zeroOrOne, .zeroOrMore:
return captureTypeList(arity, optional: true)
case .oneOrMore:
return capturesJoined
}
}()
self.matchType = arity == 0
? baseMatchTypeName
: "(\(baseMatchTypeName), \(quantifiedCaptures))"
self.whereClauseForInit = "where \(outputAssociatedTypeName) == \(matchType)"
}
var primaryAssociatedType: String {
arity == 0 ? "" : "<(W, \(captureTypeList(arity)))>"
}
}
func emitQuantifier(kind: QuantifierKind, arity: Int) {
assert(arity >= 0)
let params = QuantifierParameters(kind: kind, arity: arity)
output("""
\(defaultAvailableAttr)
extension \(kind.rawValue) {
\(kind.commentAbstract)
///
/// - Parameters:
/// - component: The regex component.
/// - behavior: The repetition behavior to use when repeating
/// `component` in the match. If `behavior` is `nil`, the default
/// repetition behavior is used, which can be changed from
/// `eager` by calling `repetitionBehavior(_:)` on the resulting
/// `Regex`.
\(params.disfavored)\
@_alwaysEmitIntoClient
public init\(params.genericParams)(
_ component: some RegexComponent\(params.primaryAssociatedType),
_ behavior: RegexRepetitionBehavior? = nil
) \(params.whereClauseForInit) {
let factory = makeFactory()
self.init(factory.\(kind.astQuantifierAmount)(component, behavior))
}
}
\(defaultAvailableAttr)
extension \(kind.rawValue) {
\(kind.commentAbstract)
///
/// - Parameters:
/// - behavior: The repetition behavior to use when repeating
/// `component` in the match. If `behavior` is `nil`, the default
/// repetition behavior is used, which can be changed from
/// `eager` by calling `repetitionBehavior(_:)` on the resulting
/// `Regex`.
/// - componentBuilder: A builder closure that generates a regex
/// component.
\(params.disfavored)\
@_alwaysEmitIntoClient
public init\(params.genericParams)(
_ behavior: RegexRepetitionBehavior? = nil,
@\(concatBuilderName) _ componentBuilder: () -> some RegexComponent\(params.primaryAssociatedType)
) \(params.whereClauseForInit) {
let factory = makeFactory()
self.init(factory.\(kind.astQuantifierAmount)(componentBuilder(), behavior))
}
}
\(kind == .zeroOrOne ?
"""
\(defaultAvailableAttr)
extension \(concatBuilderName) {
@_alwaysEmitIntoClient
public static func buildLimitedAvailability\(params.genericParams)(
_ component: some RegexComponent\(params.primaryAssociatedType)
) -> \(regexTypeName)<\(params.matchType)> {
let factory = makeFactory()
return factory.\(kind.astQuantifierAmount)(component, nil)
}
}
""" : "")
""")
}
func emitAtomicGroup(arity: Int) {
assert(arity >= 0)
let groupName = "Local"
func node(builder: Bool) -> String {
"""
component\(builder ? "Builder()" : "")
"""
}
let disfavored = arity == 0 ? " @_disfavoredOverload\n" : ""
let genericParams: String = {
var result = ""
if arity > 0 {
result += "<W, "
result += captureTypeList(arity)
result += ">"
}
return result
}()
let capturesJoined = captureTypeList(arity)
let matchType = arity == 0
? baseMatchTypeName
: "(\(baseMatchTypeName), \(capturesJoined))"
let whereClauseForInit = "where \(outputAssociatedTypeName) == \(matchType)"
output("""
\(defaultAvailableAttr)
extension \(groupName) {
/// Creates an atomic group with the given regex component.
///
/// - Parameter component: The regex component to wrap in an atomic
/// group.
\(defaultAvailableAttr)
\(disfavored)\
@_alwaysEmitIntoClient
public init\(genericParams)(
_ component: some RegexComponent\(arity == 0 ? "" : "<(W, \(capturesJoined))>")
) \(whereClauseForInit) {
let factory = makeFactory()
self.init(factory.atomicNonCapturing(\(node(builder: false))))
}
}
\(defaultAvailableAttr)
extension \(groupName) {
/// Creates an atomic group with the given regex component.
///
/// - Parameter componentBuilder: A builder closure that generates a
/// regex component to wrap in an atomic group.
\(defaultAvailableAttr)
\(disfavored)\
@_alwaysEmitIntoClient
public init\(genericParams)(
@\(concatBuilderName) _ componentBuilder: () -> some RegexComponent\(arity == 0 ? "" : "<(W, \(capturesJoined))>")
) \(whereClauseForInit) {
let factory = makeFactory()
self.init(factory.atomicNonCapturing(\(node(builder: true))))
}
}
""")
}
func emitRepeating(arity: Int) {
assert(arity >= 0)
// `repeat(..<5)` has the same generic semantics as zeroOrMore
let params = QuantifierParameters(kind: .zeroOrMore, arity: arity)
// TODO: Could `repeat(count:)` have the same generic semantics as oneOrMore?
// We would need to prohibit `repeat(count: 0)`; can only happen at runtime
output("""
\(defaultAvailableAttr)
extension Repeat {
/// Creates a regex component that matches the given component repeated
/// the specified number of times.
///
/// - Parameters:
/// - component: The regex component to repeat.
/// - count: The number of times to repeat `component`. `count` must
/// be greater than or equal to zero.
\(params.disfavored)\
@_alwaysEmitIntoClient
public init\(params.genericParams)(
_ component: some RegexComponent\(params.primaryAssociatedType),
count: Int
) \(params.whereClauseForInit) {
precondition(count >= 0, "Must specify a positive count")
let factory = makeFactory()
self.init(factory.exactly(count, component))
}
/// Creates a regex component that matches the given component repeated
/// the specified number of times.
///
/// - Parameters:
/// - count: The number of times to repeat `component`. `count` must
/// be greater than or equal to zero.
/// - componentBuilder: A builder closure that creates the regex
/// component to repeat.
\(params.disfavored)\
@_alwaysEmitIntoClient
public init\(params.genericParams)(
count: Int,
@\(concatBuilderName) _ componentBuilder: () -> some RegexComponent\(params.primaryAssociatedType)
) \(params.whereClauseForInit) {
precondition(count >= 0, "Must specify a positive count")
let factory = makeFactory()
self.init(factory.exactly(count, componentBuilder()))
}
/// Creates a regex component that matches the given component repeated
/// a number of times specified by the given range expression.
///
/// - Parameters:
/// - component: The regex component to repeat.
/// - expression: A range expression specifying the number of times
/// that `component` can repeat.
/// - behavior: The repetition behavior to use when repeating
/// `component` in the match. If `behavior` is `nil`, the default
/// repetition behavior is used, which can be changed from
/// `eager` by calling `repetitionBehavior(_:)` on the resulting
/// `Regex`.
\(params.disfavored)\
@_alwaysEmitIntoClient
public init\(params.genericParams)(
_ component: some RegexComponent\(params.primaryAssociatedType),
_ expression: some RangeExpression<Int>,
_ behavior: RegexRepetitionBehavior? = nil
) \(params.whereClauseForInit) {
let factory = makeFactory()
self.init(factory.repeating(expression.relative(to: 0..<Int.max), behavior, component))
}
/// Creates a regex component that matches the given component repeated
/// a number of times specified by the given range expression.
///
/// - Parameters:
/// - expression: A range expression specifying the number of times
/// that `component` can repeat.
/// - behavior: The repetition behavior to use when repeating
/// `component` in the match. If `behavior` is `nil`, the default
/// repetition behavior is used, which can be changed from
/// `eager` by calling `repetitionBehavior(_:)` on the resulting
/// `Regex`.
/// - componentBuilder: A builder closure that creates the regex
/// component to repeat.
\(params.disfavored)\
@_alwaysEmitIntoClient
public init\(params.genericParams)(
_ expression: some RangeExpression<Int>,
_ behavior: RegexRepetitionBehavior? = nil,
@\(concatBuilderName) _ componentBuilder: () -> some RegexComponent\(params.primaryAssociatedType)
) \(params.whereClauseForInit) {
let factory = makeFactory()
self.init(factory.repeating(expression.relative(to: 0..<Int.max), behavior, componentBuilder()))
}
}
""")
}
func emitAlternation(leftArity: Int, rightArity: Int) {
let leftCaptureTypes = captureTypeList(leftArity)
let rightCaptureTypes = captureTypeList(leftArity + rightArity, lowerBound: leftArity)
let leftGenParams = leftArity == 0
? ""
: "W0, " + leftCaptureTypes
let rightGenParams = rightArity == 0
? ""
: "W1, " + rightCaptureTypes
let _bothParams = [leftGenParams, rightGenParams]
.filter { !$0.isEmpty }
.joined(separator: ", ")
let genericParams = _bothParams.isEmpty
? ""
: "<\(_bothParams)>"
let resultCaptures: String = {
var result = leftCaptureTypes
if leftArity > 0, rightArity > 0 {
result += ", "
}
result += captureTypeList(leftArity + rightArity, lowerBound: leftArity, optional: true)
return result
}()
let matchType: String = {
if leftArity == 0, rightArity == 0 {
return baseMatchTypeName
}
return "(\(baseMatchTypeName), \(resultCaptures))"
}()
output("""
\(defaultAvailableAttr)
extension \(altBuilderName) {
@_alwaysEmitIntoClient
public static func buildPartialBlock\(genericParams)(
accumulated: some RegexComponent\(leftGenParams.isEmpty ? "" : "<(\(leftGenParams))>"),
next: some RegexComponent\(rightGenParams.isEmpty ? "" : "<(\(rightGenParams))>")
) -> ChoiceOf<\(matchType)> {
let factory = makeFactory()
return .init(factory.accumulateAlternation(accumulated, next))
}
}
""")
}
func emitUnaryAlternationBuildBlock(arity: Int) {
assert(arity > 0)
let captures = captureTypeList(arity)
let genericParams: String = {
if arity == 0 {
return "R"
}
return "R, W, " + captures
}()
let whereClause: String = """
where R: \(regexComponentProtocolName), \
R.\(outputAssociatedTypeName) == (W, \(captures))
"""
let resultCaptures = captureTypeList(arity, optional: true)
output("""
\(defaultAvailableAttr)
extension \(altBuilderName) {
@_alwaysEmitIntoClient
public static func buildPartialBlock<\(genericParams)>(first regex: R) -> ChoiceOf<(W, \(resultCaptures))> \(whereClause) {
let factory = makeFactory()
return .init(factory.orderedChoice(regex))
}
}
""")
}
func emitCapture(arity: Int) {
let disfavored = arity == 0 ? " @_disfavoredOverload\n" : ""
let genericParams = arity == 0
? "W"
: "W, " + captureTypeList(arity)
let matchType = arity == 0
? "W"
: "(W, " + captureTypeList(arity) + ")"
func newMatchType(newCaptureType: String) -> String {
return arity == 0
? "(\(baseMatchTypeName), \(newCaptureType))"
: "(\(baseMatchTypeName), \(newCaptureType), " + captureTypeList(arity) + ")"
}
let rawNewMatchType = newMatchType(newCaptureType: "W")
let transformedNewMatchType = newMatchType(newCaptureType: "NewCapture")
let whereClauseRaw = "where \(outputAssociatedTypeName) == \(rawNewMatchType)"
let whereClauseTransformed = "where \(outputAssociatedTypeName) == \(transformedNewMatchType)"
outputMark("Non-builder capture (arity \(arity))")
output("""
\(defaultAvailableAttr)
extension Capture {
/// Creates a capture for the given component.
///
/// - Parameter component: The regex component to capture.
\(disfavored)\
@_alwaysEmitIntoClient
public init<\(genericParams)>(
_ component: some RegexComponent<\(matchType)>
) \(whereClauseRaw) {
let factory = makeFactory()
self.init(factory.capture(component))
}
/// Creates a capture for the given component using the specified
/// reference.
///
/// - Parameters:
/// - component: The regex component to capture.
/// - reference: The reference to use for anything captured by
/// `component`.
\(disfavored)\
@_alwaysEmitIntoClient
public init<\(genericParams)>(
_ component: some RegexComponent<\(matchType)>,
as reference: Reference<W>
) \(whereClauseRaw) {
let factory = makeFactory()
self.init(factory.capture(component, reference._raw))
}
/// Creates a capture for the given component, transforming with the
/// given closure.
///
/// - Parameters:
/// - component: The regex component to capture.
/// - transform: A closure that takes the substring matched by
/// `component` and returns a new value to capture. If `transform`
/// throws an error, matching is abandoned and the error is returned
/// to the caller.
\(disfavored)\
@_alwaysEmitIntoClient
public init<\(genericParams), NewCapture>(
_ component: some RegexComponent<\(matchType)>,
transform: @escaping (W) throws -> NewCapture
) \(whereClauseTransformed) {
let factory = makeFactory()
self.init(factory.capture(component, nil, transform))
}
/// Creates a capture for the given component using the specified
/// reference, transforming with the given closure.
///
/// - Parameters:
/// - component: The regex component to capture.
/// - reference: The reference to use for anything captured by
/// `component`.
/// - transform: A closure that takes the substring matched by
/// `component` and returns a new value to capture. If `transform`
/// throws an error, matching is abandoned and the error is returned
/// to the caller.
\(disfavored)\
@_alwaysEmitIntoClient
public init<\(genericParams), NewCapture>(
_ component: some RegexComponent<\(matchType)>,
as reference: Reference<NewCapture>,
transform: @escaping (W) throws -> NewCapture
) \(whereClauseTransformed) {
let factory = makeFactory()
self.init(factory.capture(component, reference._raw, transform))
}
}
\(defaultAvailableAttr)
extension TryCapture {
/// Creates a capture for the given component, attempting to transform
/// with the given closure.
///
/// - Parameters:
/// - component: The regex component to capture.
/// - transform: A closure that takes the substring matched by
/// `component` and returns a new value to capture, or `nil` if
/// matching should proceed, backtracking if allowed. If `transform`
/// throws an error, matching is abandoned and the error is returned
/// to the caller.
\(disfavored)\
@_alwaysEmitIntoClient
public init<\(genericParams), NewCapture>(
_ component: some RegexComponent<\(matchType)>,
transform: @escaping (W) throws -> NewCapture?
) \(whereClauseTransformed) {
let factory = makeFactory()
self.init(factory.captureOptional(component, nil, transform))
}
/// Creates a capture for the given component using the specified
/// reference, attempting to transform with the given closure.
///
/// - Parameters:
/// - component: The regex component to capture.
/// - reference: The reference to use for anything captured by
/// `component`.
/// - transform: A closure that takes the substring matched by
/// `component` and returns a new value to capture, or `nil` if
/// matching should proceed, backtracking if allowed. If `transform`
/// throws an error, matching is abandoned and the error is returned
/// to the caller.
\(disfavored)\
@_alwaysEmitIntoClient
public init<\(genericParams), NewCapture>(
_ component: some RegexComponent<\(matchType)>,
as reference: Reference<NewCapture>,
transform: @escaping (W) throws -> NewCapture?
) \(whereClauseTransformed) {
let factory = makeFactory()
self.init(factory.captureOptional(component, reference._raw, transform))
}
}
""")
outputMark("Builder capture (arity \(arity))")
output("""
\(defaultAvailableAttr)
extension Capture {
/// Creates a capture for the given component.
///
/// - Parameter componentBuilder: A builder closure that generates a
/// regex component to capture.
\(disfavored)\
@_alwaysEmitIntoClient
public init<\(genericParams)>(
@\(concatBuilderName) _ componentBuilder: () -> some RegexComponent<\(matchType)>
) \(whereClauseRaw) {
let factory = makeFactory()
self.init(factory.capture(componentBuilder()))
}
/// Creates a capture for the given component using the specified
/// reference.
///
/// - Parameters:
/// - reference: The reference to use for anything captured by
/// `component`.
/// - componentBuilder: A builder closure that generates a regex
/// component to capture.
\(disfavored)\
@_alwaysEmitIntoClient
public init<\(genericParams)>(
as reference: Reference<W>,
@\(concatBuilderName) _ componentBuilder: () -> some RegexComponent<\(matchType)>
) \(whereClauseRaw) {
let factory = makeFactory()
self.init(factory.capture(componentBuilder(), reference._raw))
}
/// Creates a capture for the given component, transforming with the
/// given closure.
///
/// - Parameters:
/// - componentBuilder: A builder closure that generates a regex
/// component to capture.
/// - transform: A closure that takes the substring matched by
/// `component` and returns a new value to capture. If `transform`
/// throws an error, matching is abandoned and the error is returned
/// to the caller.
\(disfavored)\
@_alwaysEmitIntoClient
public init<\(genericParams), NewCapture>(
@\(concatBuilderName) _ componentBuilder: () -> some RegexComponent<\(matchType)>,
transform: @escaping (W) throws -> NewCapture
) \(whereClauseTransformed) {
let factory = makeFactory()
self.init(factory.capture(componentBuilder(), nil, transform))
}
/// Creates a capture for the given component using the specified
/// reference, transforming with the given closure.
///
/// - Parameters:
/// - reference: The reference to use for anything captured by
/// `component`.
/// - componentBuilder: A builder closure that generates a regex
/// component to capture.
/// - transform: A closure that takes the substring matched by
/// `component` and returns a new value to capture. If `transform`
/// throws an error, matching is abandoned and the error is returned
/// to the caller.
\(disfavored)\
@_alwaysEmitIntoClient
public init<\(genericParams), NewCapture>(
as reference: Reference<NewCapture>,
@\(concatBuilderName) _ componentBuilder: () -> some RegexComponent<\(matchType)>,
transform: @escaping (W) throws -> NewCapture
) \(whereClauseTransformed) {
let factory = makeFactory()
self.init(factory.capture(componentBuilder(), reference._raw, transform))
}
}
\(defaultAvailableAttr)
extension TryCapture {
/// Creates a capture for the given component, attempting to transform
/// with the given closure.
///
/// - Parameters:
/// - componentBuilder: A builder closure that generates a regex
/// component to capture.
/// - transform: A closure that takes the substring matched by
/// `component` and returns a new value to capture, or `nil` if
/// matching should proceed, backtracking if allowed. If `transform`
/// throws an error, matching is abandoned and the error is returned
/// to the caller.
\(disfavored)\
@_alwaysEmitIntoClient
public init<\(genericParams), NewCapture>(
@\(concatBuilderName) _ componentBuilder: () -> some RegexComponent<\(matchType)>,
transform: @escaping (W) throws -> NewCapture?
) \(whereClauseTransformed) {
let factory = makeFactory()
self.init(factory.captureOptional(componentBuilder(), nil, transform))
}
/// Creates a capture for the given component using the specified
/// reference, attempting to transform with the given closure.
///
/// - Parameters:
/// - reference: The reference to use for anything captured by
/// `component`.
/// - componentBuilder: A builder closure that generates a regex
/// component to capture.
/// - transform: A closure that takes the substring matched by
/// `component` and returns a new value to capture, or `nil` if
/// matching should proceed, backtracking if allowed. If `transform`
/// throws an error, matching is abandoned and the error is returned
/// to the caller.
\(disfavored)\
@_alwaysEmitIntoClient
public init<\(genericParams), NewCapture>(
as reference: Reference<NewCapture>,
@\(concatBuilderName) _ componentBuilder: () -> some RegexComponent<\(matchType)>,
transform: @escaping (W) throws -> NewCapture?
) \(whereClauseTransformed) {
let factory = makeFactory()
self.init(factory.captureOptional(componentBuilder(), reference._raw, transform))
}
}
""")
}
}