File: LiteralPrinter.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 (628 lines) | stat: -rw-r--r-- 17,024 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
//===----------------------------------------------------------------------===//
//
// 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

@available(SwiftStdlib 5.7, *)
extension Regex {
  /// The literal pattern for this regex.
  ///
  /// This is non-`nil` when used on a regex that can be represented as a
  /// string. The literal pattern may be different from the literal or string
  /// that was used to create the regex, though parsing the `_literalPattern`
  /// always generates the same internal representation as the original regex.
  ///
  ///     // The literal pattern for some regexes is identical to the original:
  ///     let regex1 = /(\d+):(\d+)/
  ///     // regex1._literalPattern == #"(\d+):(\d+)"#
  ///
  ///     // The literal pattern for others is different, but equivalent:
  ///     let regex2 = /\p{isName=BEE}/
  ///     // regex2._literalPattern == #"\N{BEE}"#
  ///
  /// If this regex includes components that cannot be represented in a regex
  /// literal, such as a capture transform or a custom parser that conforms to
  /// the `CustomConsumingRegexComponent` protocol, this property is `nil`.
  ///
  /// The value of this property may change between different releases of Swift.
  @available(SwiftStdlib 6.0, *)
  public var _literalPattern: String? {
    var gen = LiteralPrinter(options: MatchingOptions())
    gen.outputNode(self.program.tree.root)
    return gen.canonicalLiteralString
  }
}

enum PatternSegment {
  case converted(String)
  case inconvertible(DSLTree.Node)
  
  var string: String? {
    switch self {
    case let .converted(str):
      return str
    case .inconvertible:
      return nil
    }
  }
}

fileprivate struct LiteralPrinter {
  var options: MatchingOptions
  private var segments: [PatternSegment] = []
  
  init(options: MatchingOptions) {
    self.options = options
  }
  
  var canonicalLiteralString: String? {
    var result = ""
    result.reserveCapacity(segments.count)
    
    for segment in segments {
      guard let str = segment.string else {
        return nil
      }
      result.append(str)
    }
    return result
  }
  
  mutating func output(_ str: String) {
    segments.append(.converted(str))
  }
  
  mutating func saveInconvertible(_ node: DSLTree.Node) {
    segments.append(.inconvertible(node))
  }
}

extension LiteralPrinter {
  mutating func outputNode(_ node: DSLTree.Node) {
    switch node {
    case let .orderedChoice(children):
      outputAlternation(children)
    case let .concatenation(children):
      outputConcatenation(children)
      
    case let .capture(name, nil, child, nil):
      options.beginScope()
      defer { options.endScope() }
      outputCapture(name, child)
    case .capture:
      // Captures that use a reference or a transform are unsupported
      saveInconvertible(node)
      
    case let .nonCapturingGroup(kind, child):
      guard let kindPattern = kind._patternString else {
        saveInconvertible(node)
        return
      }
      options.beginScope()
      defer { options.endScope() }

      output(kindPattern)
      if case .changeMatchingOptions(let optionSequence) = kind.ast {
        options.apply(optionSequence)
      }
      outputNode(child)
      output(")")
      
    case let .ignoreCapturesInTypedOutput(child):
      outputNode(child)
    case .convertedRegexLiteral(let node, _):
      outputNode(node)

    case let .quantification(amount, kind, node):
      outputQuantification(amount, kind, node)
    case let .customCharacterClass(charClass):
      outputCustomCharacterClass(charClass)
    case let .atom(atom):
      outputAtom(atom)
    case let .quotedLiteral(literal):
      output(prepareQuotedLiteral(literal))

    case .trivia(_):
      // TODO: Include trivia?
      return
    case .empty:
      return

    case .conditional, .absentFunction, .consumer, .matcher, .characterPredicate:
      saveInconvertible(node)
    }
  }
  
  mutating func outputAlternation(_ children: [DSLTree.Node]) {
    guard let first = children.first else { return }
    
    outputNode(first)
    for child in children.dropFirst() {
      output("|")
      outputNode(child)
    }
  }
  
  mutating func outputConcatenation(_ children: [DSLTree.Node]) {
    for child in children {
      outputNode(child)
    }
  }
  
  mutating func outputCapture(_ name: String?, _ child: DSLTree.Node) {
    if let name {
      output("(?<\(name)>")
    } else {
      output("(")
    }
    outputNode(child)
    output(")")
  }
  
  func requiresGrouping(_ node: DSLTree.Node) -> Bool {
    switch node {
    case .concatenation(let children):
      switch children.count {
      case 0:
        return false
      case 1:
        return requiresGrouping(children.first!)
      default:
        return true
      }
      
    case .quotedLiteral(let literal):
      return prepareQuotedLiteral(literal).count > 1
      
    default:
      return false
    }
  }

  mutating func outputQuantification(
    _ amount: DSLTree._AST.QuantificationAmount,
    _ kind: DSLTree.QuantificationKind,
    _ child: DSLTree.Node
  ) {
    // RegexBuilder regexes can have children that need 
    if requiresGrouping(child) {
      output("(?:")
      outputNode(child)
      output(")")
    } else {
      outputNode(child)
    }

    switch amount.ast {
    case .zeroOrMore:
      output("*")
    case .oneOrMore:
      output("+")
    case .zeroOrOne:
      output("?")
    case let .exactly(n):
      output("{\(n.value!)}")
    case let .nOrMore(n):
      output("{\(n.value!),}")
    case let .upToN(n):
      output("{,\(n.value!)}")
    case let .range(low, high):
      output("{\(low.value!),\(high.value!)}")
    #if RESILIENT_LIBRARIES
    @unknown default:
      fatalError()
    #endif
    }
    
    outputQuantificationKind(kind)
  }
  
  mutating func outputQuantificationKind(_ kind: DSLTree.QuantificationKind) {
    switch kind {
    case .`default`:
      // We can treat this as if the current default had been given explicity.
      outputQuantificationKind(
        .explicit(.init(ast: options.defaultQuantificationKind)))
    case let .explicit(kind):
      switch kind.ast {
      case .eager:
        output(options.isReluctantByDefault ? "?" : "")
      case .reluctant:
        output(options.isReluctantByDefault ? "" : "?")
      case .possessive:
        output("+")
      #if RESILIENT_LIBRARIES
      @unknown default:
        fatalError()
      #endif
      }
    case let .syntax(kind):
      // Syntactically-specified quantification modifiers can stay as-is.
      switch kind.ast {
      case .eager:
        output("")
      case .reluctant:
        output("?")
      case .possessive:
        output("+")
      #if RESILIENT_LIBRARIES
      @unknown default:
        fatalError()
      #endif
      }
    }
  }

  mutating func outputAssertion(_ assertion: DSLTree.Atom.Assertion) {
    switch assertion {
    case .startOfSubject:
      output(#"\A"#)
    case .endOfSubjectBeforeNewline:
      output(#"\Z"#)
    case .endOfSubject:
      output(#"\z"#)
    case .resetStartOfMatch:
      output(#"\K"#)
    case .firstMatchingPositionInSubject:
      output(#"\G"#)
    case .textSegment:
      output(#"\y"#)
    case .notTextSegment:
      output(#"\Y"#)
    case .startOfLine:
      if options.anchorsMatchNewlines {
        output(#"^"#)
      } else {
        output(#"(?m:^)"#)
      }
    case .endOfLine:
      if options.anchorsMatchNewlines {
        output(#"$"#)
      } else {
        output(#"(?m:$)"#)
      }
    case .caretAnchor:
      output("^")
    case .dollarAnchor:
      output("$")
    case .wordBoundary:
      output(#"\b"#)
    case .notWordBoundary:
      output(#"\B"#)
    }
  }
  
  mutating func outputAtom(_ atom: DSLTree.Atom) {
    switch atom {
    case .char(let char):
      output(char.escapingForLiteral)
    case .scalar(let scalar):
      output(scalar.escapedString)
    case .any:
      if options.dotMatchesNewline {
        output(".")
      } else {
        output("(?s:.)")
      }
    case .anyNonNewline:
      if options.dotMatchesNewline {
        output("(?-s:.)")
      } else {
        output(".")
      }
    case .dot:
      output(".")
    case .characterClass(let charClass):
      if let patt = charClass._patternString {
        output(patt)
      } else {
        saveInconvertible(.atom(atom))
      }
    case .assertion(let assertion):
      outputAssertion(assertion)
    case .backreference(let backref):
      outputReference(backref)
    case .symbolicReference(_):
      // RegexBuilder only
      saveInconvertible(.atom(atom))
    case .changeMatchingOptions(let optionSequence):
      output(optionSequence.ast._patternString)
      output(")")
      options.apply(optionSequence.ast)
    case .unconverted(let atom):
      outputUnconvertedAST(atom.ast)
    }
  }
  
  mutating func outputReference(_ ref: DSLTree._AST.Reference) {
    switch ref.ast.kind {
    case .absolute(let number):
      guard let value = number.value else {
        saveInconvertible(.atom(.backreference(ref)))
        return
      }
      if value < 10 {
        output("\\\(value)")
      } else {
        output("\\g{\(value)}")
      }
    case .relative(let number):
      guard let value = number.value else {
        saveInconvertible(.atom(.backreference(ref)))
        return
      }
      let prefix = value < 0 ? "-" : "+"
      output("\\g{\(prefix)\(abs(value))}")
    case .named(let name):
      output("\\g{\(name)}")
    #if RESILIENT_LIBRARIES
    @unknown default:
      fatalError()
    #endif
    }
  }
  
  func prepareQuotedLiteral(_ literal: String) -> String {
    if options.usesExtendedWhitespace || literal.containsRegexMetaCharacters {
      return #"\Q\#(literal)\E"#
    } else {
      return literal.escapingConfusableCharacters()
    }
  }
  
  mutating func outputCustomCharacterClass(_ charClass: DSLTree.CustomCharacterClass) {
    // Sometimes we end up with a singly-wrapped CCC — flatten it out
    if !charClass.isInverted {
      let trivialessMembers = charClass.members.filter {
        if case .trivia = $0 { return false } else { return true }
      }
      if trivialessMembers.count == 1,
         case let .custom(inner) = trivialessMembers[0] {
        outputCustomCharacterClass(inner)
        return
      }
    }
    
    output(charClass.isInverted ? "[^" : "[")
    for member in charClass.members {
      switch member {
      case let .atom(atom):
        outputAtom(atom)
      case let .range(low, high):
        outputAtom(low)
        output("-")
        outputAtom(high)
      case let .custom(charClass):
        outputCustomCharacterClass(charClass)
      case let .quotedLiteral(literal):
        if options.usesExtendedWhitespace || literal.containsRegexMetaCharacters {
          output(#"\Q\#(literal)\E"#)
        } else {
          output(literal)
        }
      case .trivia(_):
        // TODO: ignore trivia?
        break
      case let .intersection(left, right):
        outputCustomCharacterClass(left)
        output("&&")
        outputCustomCharacterClass(right)
      case let .subtraction(left, right):
        outputCustomCharacterClass(left)
        output("--")
        outputCustomCharacterClass(right)
      case let .symmetricDifference(left, right):
        outputCustomCharacterClass(left)
        output("~~")
        outputCustomCharacterClass(right)
      }
    }
    output("]")
  }
  
  mutating func outputUnconvertedAST(_ ast: AST.Atom) {
    switch ast.kind {
    case let .property(property):
      if let base = property._regexBase {
        output(base)
      } else {
        saveInconvertible(.atom(.unconverted(.init(ast: ast))))
      }
    case let .namedCharacter(name):
      output("\\N{\(name)}")
    default:
      saveInconvertible(.atom(.unconverted(.init(ast: ast))))
    }
  }
}

// MARK: - Supporting extensions

fileprivate let metachars = Set(#"\[](){}|+*?^$.-"#)

extension String {
  var containsRegexMetaCharacters: Bool {
    contains(where: \.isRegexMetaCharacter)
  }
  
  func escapingConfusableCharacters() -> String {
    lazy.map(\.escapingConfusable).joined()
  }
}

extension UnicodeScalar {
  var escapedString: String {
    switch self {
    case "\n": return #"\n"#
    case "\r": return #"\r"#
    case "\t": return #"\t"#
    default:
      let code = String(value, radix: 16, uppercase: true)
      let prefix = code.count <= 4
        ? #"\u"# + String(repeating: "0", count: 4 - code.count)
        : #"\U"# + String(repeating: "0", count: 8 - code.count)
      return prefix + code
    }
  }
}

extension Character {
  var isRegexMetaCharacter: Bool {
    metachars.contains(self)
  }
  
  var escapingConfusable: String {
    if isConfusable {
      return String(unicodeScalars.first!) +
        unicodeScalars.dropFirst().lazy.map(\.escapedString).joined()
    } else {
      return String(self)
    }
  }
  
  var escapingForLiteral: String {
    if isRegexMetaCharacter {
      return "\\\(self)"
    } else {
      return escapingConfusable
    }
  }
}

// MARK: Pattern Strings

// Pattern representation for the types below is unaffected by the regex's
// options state, so they can be pure conversions.

extension DSLTree.Atom.CharacterClass {
  fileprivate var _patternString: String? {
    switch self {
    case .digit:
      return #"\d"#
    case .notDigit:
      return #"\D"#
    case .horizontalWhitespace:
      return #"\h"#
    case .notHorizontalWhitespace:
      return #"\H"#
    case .newlineSequence:
      return #"\R"#
    case .notNewline:
      return #"\N"#
    case .whitespace:
      return #"\s"#
    case .notWhitespace:
      return #"\S"#
    case .verticalWhitespace:
      return #"\v"#
    case .notVerticalWhitespace:
      return #"\V"#
    case .word:
      return #"\w"#
    case .notWord:
      return #"\W"#
    case .anyGrapheme:
      return #"\X"#
    case .anyUnicodeScalar:
      return nil
    }
  }
}

extension AST.MatchingOption.Kind {
  fileprivate var _patternString: String? {
    switch self {
    // PCRE options
    case .caseInsensitive: return "i"
    case .allowDuplicateGroupNames: return "J"
    case .multiline: return "m"
    case .namedCapturesOnly: return "n"
    case .singleLine: return "s"
    case .reluctantByDefault: return "U"
    case .extended: return "x"
    case .extraExtended: return "xx"
      
    // ICU options
    case .unicodeWordBoundaries: return "w"
      
    // Oniguruma options
    case .asciiOnlyDigit: return "D"
    case .asciiOnlyPOSIXProps: return "P"
    case .asciiOnlySpace: return "S"
    case .asciiOnlyWord: return "W"
      
    // Oniguruma text segment options (these are mutually exclusive and cannot
    // be unset, only flipped between)
    case .textSegmentGraphemeMode: return "y{g}"
    case .textSegmentWordMode: return "y{w}"
      
    // Swift semantic matching level
    case .graphemeClusterSemantics: return "X"
    case .unicodeScalarSemantics: return "u"
    case .byteSemantics: return "b"
      
    // Swift-only default possessive quantifier
    case .possessiveByDefault: return nil
      
    // NSRE Compatibility option; no literal representation
    case .nsreCompatibleDot: return nil

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

extension AST.MatchingOptionSequence {
  fileprivate var _patternString: String {
    let adding = adding.compactMap(\.kind._patternString).joined()
    let removing = removing.compactMap(\.kind._patternString).joined()
    
    if resetsCurrentOptions {
      assert(removing.isEmpty)
      return "(?^\(adding)"
    } else {
      return "(?\(adding)"
      + (removing.isEmpty ? "" : "-\(removing)")
    }
  }
}

extension DSLTree._AST.GroupKind {
  fileprivate var _patternString: String? {
    switch self.ast {
    case .capture:                return "("
    case .namedCapture(let n):    return "(?<\(n.value)>"
    case .balancedCapture(_):     return nil
    case .nonCapture:             return "(?:"
    case .nonCaptureReset:        return "(?|"
    case .atomicNonCapturing:     return "(?>"
    case .lookahead:              return "(?="
    case .negativeLookahead:      return "(?!"
    case .nonAtomicLookahead:     return "(?*"
    case .lookbehind:             return "(?<="
    case .negativeLookbehind:     return "(?<!"
    case .nonAtomicLookbehind:    return "(?<*"
    case .scriptRun:              return "(*sr:"
    case .atomicScriptRun:        return "(*asr:"
      
    case let .changeMatchingOptions(sequence):
      return sequence._patternString + ":"

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