File: ConsumerInterface.swift

package info (click to toggle)
swiftlang 6.0.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,519,992 kB
  • sloc: cpp: 9,107,863; ansic: 2,040,022; asm: 1,135,751; python: 296,500; objc: 82,456; f90: 60,502; lisp: 34,951; pascal: 19,946; sh: 18,133; perl: 7,482; ml: 4,937; javascript: 4,117; makefile: 3,840; awk: 3,535; xml: 914; fortran: 619; cs: 573; ruby: 573
file content (796 lines) | stat: -rw-r--r-- 25,924 bytes parent folder | download
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
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//

@_implementationOnly import _RegexParser

extension Character {
  var _singleScalarAsciiValue: UInt8? {
    guard self != "\r\n" else { return nil }
    return asciiValue
  }
}

extension DSLTree._AST.Atom {
  var singleScalarASCIIValue: UInt8? {
    return ast.singleScalarASCIIValue
  }
}

extension DSLTree.Atom {
  var singleScalarASCIIValue: UInt8? {
    switch self {
    case let .char(c):
      return c._singleScalarAsciiValue
    case let .scalar(s) where s.isASCII:
      return UInt8(ascii: s)
    case let .unconverted(atom):
      return atom.singleScalarASCIIValue
    default:
      return nil
    }
  }
}

extension String {
  /// Compares this string to `other` using the loose matching rule UAX44-LM2,
  /// which ignores case, whitespace, underscores, and nearly all medial
  /// hyphens.
  ///
  /// FIXME: Only ignore medial hyphens
  /// FIXME: Special case for U+1180 HANGUL JUNGSEONG O-E
  /// See https://www.unicode.org/reports/tr44/#Matching_Rules
  fileprivate func isEqualByUAX44LM2(to other: String) -> Bool {
    var index = startIndex
    var otherIndex = other.startIndex
    
    while index < endIndex && otherIndex < other.endIndex {
      if self[index].isWhitespace || self[index] == "-" || self[index] == "_" {
        formIndex(after: &index)
        continue
      }
      if other[otherIndex].isWhitespace || other[otherIndex] == "-" || other[otherIndex] == "_" {
        other.formIndex(after: &otherIndex)
        continue
      }
      
      if self[index] != other[otherIndex] && self[index].lowercased() != other[otherIndex].lowercased() {
        return false
      }

      formIndex(after: &index)
      other.formIndex(after: &otherIndex)
    }
    return index == endIndex && otherIndex == other.endIndex
  }
}

func consumeName(_ name: String, opts: MatchingOptions) -> MEProgram.ConsumeFunction {
  let consume = consumeFunction(for: opts)
  return consume(propertyScalarPredicate {
    // FIXME: name aliases not covered by $0.nameAlias are missed
    // e.g. U+FEFF has both 'BYTE ORDER MARK' and 'BOM' as aliases
    $0.name?.isEqualByUAX44LM2(to: name) == true
      || $0.nameAlias?.isEqualByUAX44LM2(to: name) == true
  })
}

// TODO: This is basically an AST interpreter, which would
// be good or interesting to build regardless, and serves
// as a compiler fall-back path

extension AST.Atom {
  // TODO: clarify difference between this and
  // literal character value...
  //
  // For now this just extracts `.char` case
  //
  // TODO: Shouldn't this be parameterized over matching
  // level?
  var singleCharacter: Character? {
    switch kind {
    case .char(let c): return c
    default: return nil
    }
  }

  var singleScalar: UnicodeScalar? {
    switch kind {
    case .scalar(let s): return s.value
    case .escaped(let e):
      guard let s = e.scalarValue else { return nil }
      return s
    default: return nil
    }
  }
  
  var singleScalarASCIIValue: UInt8? {
    if let s = singleScalar, s.isASCII {
       return UInt8(ascii: s)
     }
    switch kind {
    case let .char(c):
      return c._singleScalarAsciiValue
    default:
      return nil
    }
  }
  
  func generateConsumer(
    _ opts: MatchingOptions
  ) throws -> MEProgram.ConsumeFunction? {
    switch kind {
    case let .property(p):
      return try p.generateConsumer(opts)

    case let .namedCharacter(name):
      return consumeName(name, opts: opts)
      
    case .scalarSequence, .keyboardControl, .keyboardMeta,
        .keyboardMetaControl, .backreference, .subpattern, .callout,
        .backtrackingDirective, .changeMatchingOptions, .invalid:
      // FIXME: implement
      return nil
      
    case .char, .scalar, .escaped, .dot, .caretAnchor, .dollarAnchor:
      fatalError("Handled in ByteCodeGen or earlier.")

    #if RESILIENT_LIBRARIES
    @unknown default:
      fatalError()
    #endif
    }
  }
}

extension DSLTree.CustomCharacterClass.Member {
  func asAsciiBitset(
    _ opts: MatchingOptions,
    _ isInverted: Bool
  ) -> DSLTree.CustomCharacterClass.AsciiBitset? {
    typealias Bitset = DSLTree.CustomCharacterClass.AsciiBitset
    switch self {
    case let .atom(a):
      if let val = a.singleScalarASCIIValue {
        return Bitset(val, isInverted, opts.isCaseInsensitive)
      }
    case let .range(low, high):
      if let lowVal = low.singleScalarASCIIValue,
         let highVal = high.singleScalarASCIIValue {
        return Bitset(low: lowVal, high: highVal, isInverted: isInverted,
                      isCaseInsensitive: opts.isCaseInsensitive)
      }
    case .quotedLiteral(let str):
      var bitset = Bitset(isInverted: isInverted)
      for c in str {
        guard let ascii = c._singleScalarAsciiValue else { return nil }
        bitset = bitset.union(Bitset(ascii, isInverted, opts.isCaseInsensitive))
      }
      return bitset
    default:
      return nil
    }
    return nil
  }
  
  func generateConsumer(
    _ opts: MatchingOptions
  ) throws -> MEProgram.ConsumeFunction {
    switch self {
    case let .range(low, high):
      guard let lhsChar = low.literalCharacterValue else {
        throw Unsupported("\(low) in range")
      }
      guard let rhsChar = high.literalCharacterValue else {
        throw Unsupported("\(high) in range")
      }

      // We must have NFC single scalar bounds.
      guard let lhs = lhsChar.singleScalar, lhs.isNFC else {
        throw RegexCompilationError.invalidCharacterClassRangeOperand(lhsChar)
      }
      guard let rhs = rhsChar.singleScalar, rhs.isNFC else {
        throw RegexCompilationError.invalidCharacterClassRangeOperand(rhsChar)
      }
      guard lhs <= rhs else {
        throw Unsupported("Invalid range \(low)-\(high)")
      }

      let isCaseInsensitive = opts.isCaseInsensitive
      let isCharacterSemantic = opts.semanticLevel == .graphemeCluster
      
      return { input, bounds in
        let curIdx = bounds.lowerBound
        let nextIndex = input.index(
          after: curIdx, isScalarSemantics: !isCharacterSemantic)

        // Under grapheme semantics, we compare based on single NFC scalars. If
        // such a character is not single scalar under NFC, the match fails. In
        // scalar semantics, we compare the exact scalar value to the NFC
        // bounds.
        let scalar = isCharacterSemantic ? input[curIdx].singleNFCScalar
                                         : input.unicodeScalars[curIdx]
        guard let scalar = scalar else { return nil }
        let scalarRange = lhs ... rhs
        if scalarRange.contains(scalar) {
          return nextIndex
        }

        // Check for case insensitive matches.
        func matchesCased(
          _ cased: (UnicodeScalar.Properties) -> String
        ) -> Bool {
          let casedStr = cased(scalar.properties)
          // In character semantic mode, we need to map to NFC. In scalar
          // semantics, we should have an exact scalar.
          let mapped = isCharacterSemantic ? casedStr.singleNFCScalar
                                           : casedStr.singleScalar
          guard let mapped = mapped else { return false }
          return scalarRange.contains(mapped)
        }
        if isCaseInsensitive {
          if scalar.properties.changesWhenLowercased,
              matchesCased(\.lowercaseMapping) {
            return nextIndex
          }
          if scalar.properties.changesWhenUppercased,
             matchesCased(\.uppercaseMapping) {
            return nextIndex
          }
        }
        return nil
      }

    case .atom, .custom, .intersection, .subtraction, .symmetricDifference:
      fatalError("Handled in 'emitCustomCharacterClass'")

    case .quotedLiteral:
      fatalError("Removed in 'flatteningCustomCharacterClassMembers'")

    case .trivia:
      // TODO: Should probably strip this earlier...
      return { _, _ in nil }
    }
  }
}

extension DSLTree.CustomCharacterClass {
  func asAsciiBitset(_ opts: MatchingOptions) -> AsciiBitset? {
    return members.reduce(
      .init(isInverted: isInverted),
      {result, member in
        if let next = member.asAsciiBitset(opts, isInverted) {
          return result?.union(next)
        } else {
          return nil
        }
      }
    )
  }
}

// NOTE: Conveniences, though not most performant
typealias ScalarPredicate = (UnicodeScalar) -> Bool

private func scriptScalarPredicate(_ s: Unicode.Script) -> ScalarPredicate {
  { Unicode.Script($0) == s }
}
private func scriptExtensionScalarPredicate(_ s: Unicode.Script) -> ScalarPredicate {
  { Unicode.Script.extensions(for: $0).contains(s) }
}
private func categoryScalarPredicate(_ gc: Unicode.GeneralCategory) -> ScalarPredicate {
  { gc == $0.properties.generalCategory }
}
private func categoriesScalarPredicate(_ gcs: [Unicode.GeneralCategory]) -> ScalarPredicate {
  { gcs.contains($0.properties.generalCategory) }
}
private func propertyScalarPredicate(_ p: @escaping (Unicode.Scalar.Properties) -> Bool) -> ScalarPredicate {
  { p($0.properties) }
}

func consumeScalar(
  _ p: @escaping ScalarPredicate
) -> MEProgram.ConsumeFunction {
  { input, bounds in
    // TODO: bounds check?
    let curIdx = bounds.lowerBound
    if p(input.unicodeScalars[curIdx]) {
      // TODO: semantic level?
      return input.unicodeScalars.index(after: curIdx)
    }
    return nil
  }
}
func consumeCharacterWithLeadingScalar(
  _ p: @escaping ScalarPredicate
) -> MEProgram.ConsumeFunction {
  { input, bounds in
    let curIdx = bounds.lowerBound
    if p(input[curIdx].unicodeScalars.first!) {
      return input.index(after: curIdx)
    }
    return nil
  }
}
func consumeCharacterWithSingleScalar(
  _ p: @escaping ScalarPredicate
) -> MEProgram.ConsumeFunction {
  { input, bounds in
    let curIdx = bounds.lowerBound
    
    if input[curIdx].hasExactlyOneScalar && p(input[curIdx].unicodeScalars.first!) {
      return input.index(after: curIdx)
    }
    return nil
  }
}

func consumeFunction(
  for opts: MatchingOptions
) -> (@escaping ScalarPredicate) -> MEProgram.ConsumeFunction {
  opts.semanticLevel == .graphemeCluster
    ? consumeCharacterWithLeadingScalar
    : consumeScalar
}

extension AST.Atom.CharacterProperty {
  func generateConsumer(
    _ opts: MatchingOptions
  ) throws -> MEProgram.ConsumeFunction {
    // Handle inversion for us, albeit not efficiently
    func invert(
      _ p: @escaping MEProgram.ConsumeFunction
    ) -> MEProgram.ConsumeFunction {
      return { input, bounds in
        if p(input, bounds) != nil { return nil }

        // TODO: bounds check
        return input.index(
          after: bounds.lowerBound, 
          isScalarSemantics: opts.semanticLevel == .unicodeScalar)
      }
    }

    let consume = consumeFunction(for: opts)
    let preInversion: MEProgram.ConsumeFunction =
    try {
      switch kind {
        // TODO: is this modeled differently?
      case .any:
        return { input, bounds in
          // TODO: bounds check?
          return input.index(after: bounds.lowerBound)
        }
      case .assigned:
        return consume {
          $0.properties.generalCategory != .unassigned
        }
      case .ascii:
        // Note: ASCII must look at the whole character, not just the first
        // scalar. That is, "e\u{301}" is not an ASCII character, even though
        // the first scalar is.
        return opts.semanticLevel == .graphemeCluster
          ? consumeCharacterWithSingleScalar(\.isASCII)
          : consumeScalar(\.isASCII)

      case .generalCategory(let p):
        return try p.generateConsumer(opts)

      case .binary(let prop, value: let value):
        let cons = try prop.generateConsumer(opts)
        return value ? cons : invert(cons)

      case .script(let s):
        return consume(scriptScalarPredicate(s))

      case .scriptExtension(let s):
        return consume(scriptExtensionScalarPredicate(s))
        
      case .named(let n):
        return consumeName(n, opts: opts)

      case .age(let major, let minor):
        return consume {
          guard let age = $0.properties.age else { return false }
          return age <= (major, minor)
        }
        
      case .numericValue(let value):
        return consume { $0.properties.numericValue == value }
        
      case .numericType(let type):
        return consume { $0.properties.numericType == type }
        
      case .ccc(let ccc):
        return consume { $0.properties.canonicalCombiningClass == ccc }
        
      case .mapping(.lowercase, let value):
        return consume { $0.properties.lowercaseMapping == value }

      case .mapping(.uppercase, let value):
        return consume { $0.properties.uppercaseMapping == value }

      case .mapping(.titlecase, let value):
        return consume { $0.properties.titlecaseMapping == value }

      case .block(let b):
        throw Unsupported("TODO: map block: \(b)")

      case .posix(let p):
        return p.generateConsumer(opts)

      case .pcreSpecial(let s):
        throw Unsupported("TODO: map PCRE special: \(s)")

      case .javaSpecial(let s):
        throw Unsupported("TODO: map Java special: \(s)")

      case .invalid:
        throw Unreachable("Expected valid property")

      #if RESILIENT_LIBRARIES
      @unknown default:
        throw Unreachable("Unknown kind \(kind)")
      #endif
      }

    }()

    if !isInverted { return preInversion }
    return invert(preInversion)
  }
}

extension Unicode.BinaryProperty {
  // FIXME: Semantic level, vet for precise defs
  func generateConsumer(
    _ opts: MatchingOptions
  ) throws -> MEProgram.ConsumeFunction {
    let consume = consumeFunction(for: opts)

    // Note if you implement support for any of the below, you need to adjust
    // the switch in Sema.swift to not have it be diagnosed as unsupported
    // (potentially guarded on deployment version).
    switch self {
    case .asciiHexDigit:
      return consume(propertyScalarPredicate {
        $0.isHexDigit && $0.isASCIIHexDigit
      })
    case .alphabetic:
      return consume(propertyScalarPredicate(\.isAlphabetic))
    case .bidiControl:
      return consume(propertyScalarPredicate(\.isBidiControl))
    case .bidiMirrored:
      return consume(propertyScalarPredicate(\.isBidiMirrored))
    case .cased:
      return consume(propertyScalarPredicate(\.isCased))
    case .compositionExclusion:
      break
    case .caseIgnorable:
      return consume(propertyScalarPredicate(\.isCaseIgnorable))
    case .changesWhenCasefolded:
      return consume(propertyScalarPredicate(\.changesWhenCaseFolded))
    case .changesWhenCasemapped:
      return consume(propertyScalarPredicate(\.changesWhenCaseMapped))
    case .changesWhenNFKCCasefolded:
      return consume(propertyScalarPredicate(\.changesWhenNFKCCaseFolded))
    case .changesWhenLowercased:
      return consume(propertyScalarPredicate(\.changesWhenLowercased))
    case .changesWhenTitlecased:
      return consume(propertyScalarPredicate(\.changesWhenTitlecased))
    case .changesWhenUppercased:
      return consume(propertyScalarPredicate(\.changesWhenUppercased))
    case .dash:
      return consume(propertyScalarPredicate(\.isDash))
    case .deprecated:
      return consume(propertyScalarPredicate(\.isDeprecated))
    case .defaultIgnorableCodePoint:
      return consume(propertyScalarPredicate(\.isDefaultIgnorableCodePoint))
    case .diacratic: // spelling?
      return consume(propertyScalarPredicate(\.isDiacritic))
    case .emojiModifierBase:
      if #available(macOS 10.12.2, iOS 10.2, tvOS 10.1, watchOS 3.1.1, *) {
        return consume(propertyScalarPredicate(\.isEmojiModifierBase))
      } else {
        throw Unsupported(
          "isEmojiModifierBase on old OSes")
      }
    case .emojiComponent:
      break
    case .emojiModifier:
      if #available(macOS 10.12.2, iOS 10.2, tvOS 10.1, watchOS 3.1.1, *) {
        return consume(propertyScalarPredicate(\.isEmojiModifier))
      } else {
        throw Unsupported("isEmojiModifier on old OSes")
      }
    case .emoji:
      if #available(macOS 10.12.2, iOS 10.2, tvOS 10.1, watchOS 3.1.1, *) {
        return consume(propertyScalarPredicate(\.isEmoji))
      } else {
        throw Unsupported("isEmoji on old OSes")
      }
    case .emojiPresentation:
      if #available(macOS 10.12.2, iOS 10.2, tvOS 10.1, watchOS 3.1.1, *) {
        return consume(propertyScalarPredicate(\.isEmojiPresentation))
      } else {
        throw Unsupported(
          "isEmojiPresentation on old OSes")
      }
    case .extender:
      return consume(propertyScalarPredicate(\.isExtender))
    case .extendedPictographic:
      break // NOTE: Stdlib has this data internally
    case .fullCompositionExclusion:
      return consume(propertyScalarPredicate(\.isFullCompositionExclusion))
    case .graphemeBase:
      return consume(propertyScalarPredicate(\.isGraphemeBase))
    case .graphemeExtended:
      return consume(propertyScalarPredicate(\.isGraphemeExtend))
    case .graphemeLink:
      break
    case .hexDigit:
      return consume(propertyScalarPredicate(\.isHexDigit))
    case .hyphen:
      break
    case .idContinue:
      return consume(propertyScalarPredicate(\.isIDContinue))
    case .ideographic:
      return consume(propertyScalarPredicate(\.isIdeographic))
    case .idStart:
      return consume(propertyScalarPredicate(\.isIDStart))
    case .idsBinaryOperator:
      return consume(propertyScalarPredicate(\.isIDSBinaryOperator))
    case .idsTrinaryOperator:
      return consume(propertyScalarPredicate(\.isIDSTrinaryOperator))
    case .joinControl:
      return consume(propertyScalarPredicate(\.isJoinControl))
    case .logicalOrderException:
      return consume(propertyScalarPredicate(\.isLogicalOrderException))
    case .lowercase:
      return consume(propertyScalarPredicate(\.isLowercase))
    case .math:
      return consume(propertyScalarPredicate(\.isMath))
    case .noncharacterCodePoint:
      return consume(propertyScalarPredicate(\.isNoncharacterCodePoint))
    case .otherAlphabetic:
      break
    case .otherDefaultIgnorableCodePoint:
      break
    case .otherGraphemeExtended:
      break
    case .otherIDContinue:
      break
    case .otherIDStart:
      break
    case .otherLowercase:
      break
    case .otherMath:
      break
    case .otherUppercase:
      break
    case .patternSyntax:
      return consume(propertyScalarPredicate(\.isPatternSyntax))
    case .patternWhitespace:
      return consume(propertyScalarPredicate(\.isPatternWhitespace))
    case .prependedConcatenationMark:
      break
    case .quotationMark:
      return consume(propertyScalarPredicate(\.isQuotationMark))
    case .radical:
      return consume(propertyScalarPredicate(\.isRadical))
    case .regionalIndicator:
      return consume { s in
        (0x1F1E6...0x1F1FF).contains(s.value)
      }
    case .softDotted:
      return consume(propertyScalarPredicate(\.isSoftDotted))
    case .sentenceTerminal:
      return consume(propertyScalarPredicate(\.isSentenceTerminal))
    case .terminalPunctuation:
      return consume(propertyScalarPredicate(\.isTerminalPunctuation))
    case .unifiedIdiograph: // spelling?
      return consume(propertyScalarPredicate(\.isUnifiedIdeograph))
    case .uppercase:
      return consume(propertyScalarPredicate(\.isUppercase))
    case .variationSelector:
      return consume(propertyScalarPredicate(\.isVariationSelector))
    case .whitespace:
      return consume(propertyScalarPredicate(\.isWhitespace))
    case .xidContinue:
      return consume(propertyScalarPredicate(\.isXIDContinue))
    case .xidStart:
      return consume(propertyScalarPredicate(\.isXIDStart))
    case .expandsOnNFC, .expandsOnNFD, .expandsOnNFKD,
        .expandsOnNFKC:
      throw Unsupported("Unicode-deprecated: \(self)")
    #if RESILIENT_LIBRARIES
    @unknown default:
      break
    #endif
    }

    throw Unsupported("TODO: map prop \(self)")
  }
}

extension Unicode.POSIXProperty {
  // FIXME: Semantic level, vet for precise defs
  func generateConsumer(
    _ opts: MatchingOptions
  ) -> MEProgram.ConsumeFunction {
    let consume = consumeFunction(for: opts)

    // FIXME: modes, etc
    switch self {
    case .alnum:
      return consume(propertyScalarPredicate {
        $0.isAlphabetic || $0.numericType != nil
      })
    case .blank:
      return consume { s in
        s.properties.generalCategory == .spaceSeparator ||
        s == "\t"
      }

    case .graph:
      return consume(propertyScalarPredicate { p in
        !(
          p.isWhitespace ||
          p.generalCategory == .control ||
          p.generalCategory == .surrogate ||
          p.generalCategory == .unassigned
        )
      })
    case .print:
      return consume(propertyScalarPredicate { p in
        // FIXME: better def
        p.generalCategory != .control
      })
    case .word:
      return consume(propertyScalarPredicate { p in
        // FIXME: better def
        p.isAlphabetic || p.numericType != nil
        || p.isJoinControl
        || p.isDash// marks and connectors...
      })

    case .xdigit:
      return consume(propertyScalarPredicate(\.isHexDigit)) // or number

    #if RESILIENT_LIBRARIES
    @unknown default:
      fatalError()
    #endif
    }
  }
}

extension Unicode.ExtendedGeneralCategory {
  // FIXME: Semantic level
  func generateConsumer(
    _ opts: MatchingOptions
  ) throws -> MEProgram.ConsumeFunction {
    let consume = consumeFunction(for: opts)

    switch self {
    case .letter:
      return consume(categoriesScalarPredicate([
        .uppercaseLetter, .lowercaseLetter,
        .titlecaseLetter, .modifierLetter,
        .otherLetter
      ]))

    case .mark:
      return consume(categoriesScalarPredicate([
        .nonspacingMark, .spacingMark, .enclosingMark
      ]))

    case .number:
      return consume(categoriesScalarPredicate([
        .decimalNumber, .letterNumber, .otherNumber
      ]))

    case .symbol:
      return consume(categoriesScalarPredicate([
        .mathSymbol, .currencySymbol, .modifierSymbol,
        .otherSymbol
      ]))

    case .punctuation:
      return consume(categoriesScalarPredicate([
        .connectorPunctuation, .dashPunctuation,
        .openPunctuation, .closePunctuation,
        .initialPunctuation, .finalPunctuation,
        .otherPunctuation
      ]))

    case .separator:
      return consume(categoriesScalarPredicate([
        .spaceSeparator, .lineSeparator, .paragraphSeparator
      ]))

    case .other:
      return consume(categoriesScalarPredicate([
        .control, .format, .surrogate, .privateUse, .unassigned
      ]))

    case .casedLetter:
      return consume(categoriesScalarPredicate([
        .uppercaseLetter, .lowercaseLetter, .titlecaseLetter
      ]))

    case .control:
      return consume(categoryScalarPredicate(.control))
    case .format:
      return consume(categoryScalarPredicate(.format))
    case .unassigned:
      return consume(categoryScalarPredicate(.unassigned))
    case .privateUse:
      return consume(categoryScalarPredicate(.privateUse))
    case .surrogate:
      return consume(categoryScalarPredicate(.surrogate))
    case .lowercaseLetter:
      return consume(categoryScalarPredicate(.lowercaseLetter))
    case .modifierLetter:
      return consume(categoryScalarPredicate(.modifierLetter))
    case .otherLetter:
      return consume(categoryScalarPredicate(.otherLetter))
    case .titlecaseLetter:
      return consume(categoryScalarPredicate(.titlecaseLetter))
    case .uppercaseLetter:
      return consume(categoryScalarPredicate(.uppercaseLetter))
    case .spacingMark:
      return consume(categoryScalarPredicate(.spacingMark))
    case .enclosingMark:
      return consume(categoryScalarPredicate(.enclosingMark))
    case .nonspacingMark:
      return consume(categoryScalarPredicate(.nonspacingMark))
    case .decimalNumber:
      return consume(categoryScalarPredicate(.decimalNumber))
    case .letterNumber:
      return consume(categoryScalarPredicate(.letterNumber))
    case .otherNumber:
      return consume(categoryScalarPredicate(.otherNumber))
    case .connectorPunctuation:
      return consume(categoryScalarPredicate(.connectorPunctuation))
    case .dashPunctuation:
      return consume(categoryScalarPredicate(.dashPunctuation))
    case .closePunctuation:
      return consume(categoryScalarPredicate(.closePunctuation))
    case .finalPunctuation:
      return consume(categoryScalarPredicate(.finalPunctuation))
    case .initialPunctuation:
      return consume(categoryScalarPredicate(.initialPunctuation))
    case .otherPunctuation:
      return consume(categoryScalarPredicate(.otherPunctuation))
    case .openPunctuation:
      return consume(categoryScalarPredicate(.openPunctuation))
    case .currencySymbol:
      return consume(categoryScalarPredicate(.currencySymbol))
    case .modifierSymbol:
      return consume(categoryScalarPredicate(.modifierSymbol))
    case .mathSymbol:
      return consume(categoryScalarPredicate(.mathSymbol))
    case .otherSymbol:
      return consume(categoryScalarPredicate(.otherSymbol))
    case .lineSeparator:
      return consume(categoryScalarPredicate(.lineSeparator))
    case .paragraphSeparator:
      return consume(categoryScalarPredicate(.paragraphSeparator))
    case .spaceSeparator:
      return consume(categoryScalarPredicate(.spaceSeparator))

    #if RESILIENT_LIBRARIES
    @unknown default:
      fatalError()
    #endif
    }
  }
}