File: StringLiterals.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 (786 lines) | stat: -rw-r--r-- 30,727 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
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 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
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//

#if swift(>=6)
@_spi(RawSyntax) internal import SwiftSyntax
#else
@_spi(RawSyntax) import SwiftSyntax
#endif

// MARK: - Check multiline string literal indentation

fileprivate class StringLiteralExpressionIndentationChecker {
  // MARK: Entry

  init(expectedIndentation: SyntaxText, arena: SyntaxArena) {
    self.expectedIndentation = expectedIndentation
    self.arena = arena
  }

  func checkIndentation(of expressionSegment: RawExpressionSegmentSyntax) -> RawExpressionSegmentSyntax? {
    if let rewrittenSegment = self.visit(node: RawSyntax(expressionSegment)) {
      return rewrittenSegment.as(RawExpressionSegmentSyntax.self)
    } else {
      return nil
    }
  }

  // MARK: Implementation

  private let expectedIndentation: SyntaxText
  private let arena: SyntaxArena

  private func visit(node: RawSyntax) -> RawSyntax? {
    if node.isToken {
      return visitTokenNode(token: node.as(RawTokenSyntax.self)!)
    } else {
      return visitLayoutNode(node: node)
    }
  }

  private func visitTokenNode(token: RawTokenSyntax) -> RawSyntax? {
    if !token.leadingTriviaPieces.contains(where: { $0.isNewline }) {
      // Only checking tokens on a newline
      return nil
    }
    let hasSufficientIndentation = token.tokenView.leadingTrivia { leadingTrivia -> Bool in
      let indentationStartIndex =
        leadingTrivia
        .lastIndex(where: { $0 == UInt8(ascii: "\n") || $0 == UInt8(ascii: "\r") })?
        .advanced(by: 1)
        ?? leadingTrivia.startIndex
      return SyntaxText(rebasing: leadingTrivia[indentationStartIndex...]).hasPrefix(expectedIndentation)
    }
    if hasSufficientIndentation {
      return nil
    }
    if let tokenDiagnostic = token.tokenView.tokenDiagnostic, tokenDiagnostic.severity == .error {
      // Token already has a lexer error, ignore the indentation error until that
      // error is fixed
      return nil
    }
    let tokenWithDiagnostic = token.tokenView.withTokenDiagnostic(
      tokenDiagnostic: TokenDiagnostic(.insufficientIndentationInMultilineStringLiteral, byteOffset: 0),
      arena: arena
    )
    return RawSyntax(tokenWithDiagnostic)
  }

  private func visitLayoutNode(node: RawSyntax) -> RawSyntax? {
    let layoutView = node.layoutView!

    var hasRewrittenChild = false
    var rewrittenChildren: [RawSyntax?] = []
    for child in layoutView.children {
      if let child, let rewrittenChild = visit(node: child) {
        hasRewrittenChild = true
        rewrittenChildren.append(rewrittenChild)
      } else {
        rewrittenChildren.append(child)
      }
    }
    precondition(rewrittenChildren.count == layoutView.children.count)
    if hasRewrittenChild {
      return layoutView.replacingLayout(with: rewrittenChildren, arena: arena)
    } else {
      return nil
    }
  }
}

// MARK: - Post-process multi-line string literals

fileprivate extension SyntaxText {
  /// If the text ends with any newline character, return that character,
  /// otherwise `nil`.
  var newlineSuffix: SyntaxText? {
    if hasSuffix("\r\n") {
      return "\r\n"
    } else if hasSuffix("\n") {
      return "\n"
    } else if hasSuffix("\r") {
      return "\r"
    } else {
      return nil
    }
  }

  /// If the text is a single newline character, return the trivia piece that
  /// represents it, otherwise `nil`.
  var triviaPieceIfNewline: RawTriviaPiece? {
    if self == "\r\n" {
      return .carriageReturnLineFeeds(1)
    } else if self == "\n" {
      return .newlines(1)
    } else if self == "\r" {
      return .carriageReturns(1)
    } else {
      return nil
    }
  }
}

extension Parser {
  /// If `text` only consists of indentation whitespace (space and tab), return
  /// the trivia pieces that represent `text`, otherwise return `nil`.
  private func parseIndentationTrivia(text: SyntaxText) -> [RawTriviaPiece]? {
    let trivia = TriviaParser.parseTrivia(text, position: .leading)
    if trivia.allSatisfy({ $0.isIndentationWhitespace }) {
      return trivia
    } else {
      return nil
    }
  }

  private func reclassifyTrivia(
    in token: RawTokenSyntax,
    leading reclassifyLeading: SyntaxText = "",
    trailing reclassifyTrailing: SyntaxText = "",
    tokenDiagnostic: TokenDiagnostic? = nil
  ) -> RawTokenSyntax {
    precondition(SyntaxText(rebasing: token.tokenText.prefix(reclassifyLeading.count)) == reclassifyLeading)
    precondition(SyntaxText(rebasing: token.tokenText.suffix(reclassifyTrailing.count)) == reclassifyTrailing)
    return RawTokenSyntax(
      kind: token.tokenKind,
      text: SyntaxText(rebasing: token.tokenText.dropFirst(reclassifyLeading.count).dropLast(reclassifyTrailing.count)),
      leadingTriviaPieces: token.leadingTriviaPieces + TriviaParser.parseTrivia(reclassifyLeading, position: .leading),
      trailingTriviaPieces: TriviaParser.parseTrivia(reclassifyTrailing, position: .trailing)
        + token.trailingTriviaPieces,
      presence: token.presence,
      tokenDiagnostic: token.tokenView.tokenDiagnostic ?? tokenDiagnostic,
      arena: self.arena
    )
  }

  /// Re-classify the newline of the last line as trivia since the newline is
  /// not part of the represented string. If the last line has its newline
  /// escaped by a trailing `\`, mark that string segment as unexpected and
  /// generate a missing segment that doesn't have a trailing `\`.
  ///
  /// Returns `true` if the closing quote is on its own line and `false` otherwise.
  private func reclassifyNewlineOfLastSegmentAsTrivia(
    rawStringDelimitersToken: RawTokenSyntax?,
    openQuoteHasTrailingNewline: Bool,
    middleSegments: inout [RawStringLiteralSegmentListSyntax.Element]
  ) -> Bool {
    guard let segment = middleSegments.last else {
      return openQuoteHasTrailingNewline
    }
    switch segment {
    case .stringSegment(let lastMiddleSegment):
      if !lastMiddleSegment.content.trailingTriviaPieces.isEmpty {
        precondition(
          lastMiddleSegment.content.trailingTriviaPieces.contains(where: { $0.isBackslash }),
          "The lexer should only add trailing trivia to a string segment if the newline is escaped by a backslash"
        )

        if rawStringDelimitersToken != nil {
          // ... except in raw string literals where the C++ parser accepts the
          // last line to be escaped. To match the C++ parser's behavior, we also
          // need to allow escaped newline in raw string literals.
          return true
        }

        let unexpectedBeforeContent = lastMiddleSegment.content
        let content = RawTokenSyntax(
          missing: .stringSegment,
          text: lastMiddleSegment.content.tokenText,
          leadingTriviaPieces: lastMiddleSegment.content.leadingTriviaPieces,
          trailingTriviaPieces: lastMiddleSegment.content.trailingTriviaPieces.filter({ $0.isNewline }),
          arena: self.arena
        )
        middleSegments[middleSegments.count - 1] = .stringSegment(
          RawStringSegmentSyntax(
            RawUnexpectedNodesSyntax(
              combining: lastMiddleSegment.unexpectedBeforeContent,
              unexpectedBeforeContent,
              arena: self.arena
            ),
            content: content,
            lastMiddleSegment.unexpectedAfterContent,
            arena: self.arena
          )
        )
        return true
      } else if let newlineSuffix = lastMiddleSegment.content.tokenText.newlineSuffix {
        // The newline at the end of the last line in the string literal is not part of the represented string.
        // Mark it as trivia.
        let content = self.reclassifyTrivia(in: lastMiddleSegment.content, trailing: newlineSuffix)

        middleSegments[middleSegments.count - 1] = .stringSegment(
          RawStringSegmentSyntax(
            lastMiddleSegment.unexpectedBeforeContent,
            content: content,
            lastMiddleSegment.unexpectedAfterContent,
            arena: self.arena
          )
        )
        return true
      } else {
        return false
      }
    case .expressionSegment:
      return false
    #if RESILIENT_LIBRARIES
    @unknown default:
      fatalError()
    #endif
    }
  }

  /// Re-classifying the indentation of the middle lines as trivia, such that
  /// the string segment token only contains whitespace that is part of the
  /// actual string. If a line is under-indented a
  /// `.insufficientIndentationInMultilineStringLiteral` lexer error will be
  /// attached to the string segment token.
  private func postProcessIndentationAndEscapedNewlineOfMiddleSegments(
    rawStringDelimitersToken: RawTokenSyntax?,
    middleSegments: inout [RawStringLiteralSegmentListSyntax.Element],
    isFirstSegmentOnNewLine: Bool,
    indentation: SyntaxText
  ) {
    let expressionIndentationChecker = StringLiteralExpressionIndentationChecker(
      expectedIndentation: indentation,
      arena: self.arena
    )

    var isSegmentOnNewLine = isFirstSegmentOnNewLine
    for (index, segment) in middleSegments.enumerated() {
      switch segment {
      case .stringSegment(var segment):
        // We are not considering leading trivia for indentation computation.
        // If these assertions are violated, we can probably lift them but we
        // would need to check that they produce the expected results.
        precondition(segment.content.leadingTriviaByteLength == 0)

        // Re-classify indentation as leading trivia
        if isSegmentOnNewLine {
          if segment.content.tokenText.hasPrefix(indentation) {
            segment = RawStringSegmentSyntax(
              segment.unexpectedBeforeContent,
              content: self.reclassifyTrivia(in: segment.content, leading: indentation),
              segment.unexpectedAfterContent,
              arena: self.arena
            )
          } else if (segment.content.tokenText == "" || segment.content.tokenText.triviaPieceIfNewline != nil)
            && segment.content.trailingTriviaPieces.allSatisfy({ $0.isNewline })
          {
            // Empty lines don't need to be indented and there's no indentation we need to strip away.
          } else {
            let actualIndentation = SyntaxText(
              rebasing: segment.content.tokenText.prefix(while: { $0 == UInt8(ascii: " ") || $0 == UInt8(ascii: "\t") })
            )
            let tokenDiagnostic = TokenDiagnostic(.insufficientIndentationInMultilineStringLiteral, byteOffset: 0)
            let content = self.reclassifyTrivia(
              in: segment.content,
              leading: actualIndentation,
              tokenDiagnostic: tokenDiagnostic
            )
            segment = RawStringSegmentSyntax(
              segment.unexpectedBeforeContent,
              content: content,
              segment.unexpectedAfterContent,
              arena: self.arena
            )
          }
        }

        isSegmentOnNewLine =
          segment.content.tokenText.newlineSuffix != nil
          || (segment.content.trailingTriviaPieces.last?.isNewline ?? false)

        middleSegments[index] = .stringSegment(segment)
      case .expressionSegment(let segment):
        isSegmentOnNewLine = segment.rightParen.trailingTriviaPieces.contains(where: { $0.isNewline })

        if let rewrittenSegment = expressionIndentationChecker.checkIndentation(of: segment) {
          middleSegments[index] = .expressionSegment(rewrittenSegment)
        }
      #if RESILIENT_LIBRARIES
      @unknown default:
        fatalError()
      #endif
      }
    }
  }

  /// After parsing a multi-line string literal from tokens produced by the lexer,
  /// post-process the string literal by performing the following steps
  ///  - Ensuring that the open quote is followed by a newline (i.e. the opening
  ///    quote shouldn't have any any text on the same line). If this is not the
  ///    case, mark the existing opening quote as unexpected and synthesize
  ///    a missing quote that is followed by a newline
  ///  - Re-classifying the indentation of the middle lines as trivia, such that
  ///    the string segment token only contains whitespace that is part of the
  ///    actual string. If a line is under-indented a
  ///    `.insufficientIndentationInMultilineStringLiteral` lexer error will be
  ///    attached to the string segment token.
  ///  - Re-classify the newline of the last line as trivia since the newline is
  ///    not part of the represented string. If the last line has its newline
  ///    escaped by a trailing `\`, mark that string segment as unexpected and
  ///    generate a missing segment that doesn't have a trailing `\`.
  private func postProcessMultilineStringLiteral(
    rawStringDelimitersToken: RawTokenSyntax?,
    openQuote: RawTokenSyntax,
    segments allSegments: [RawStringLiteralSegmentListSyntax.Element],
    closeQuote: RawTokenSyntax
  ) -> (
    unexpectedBeforeOpeningQuote: [RawTokenSyntax],
    openingQuote: RawTokenSyntax,
    segments: [RawStringLiteralSegmentListSyntax.Element],
    unexpectedBeforeClosingQuote: [RawTokenSyntax],
    closingQuote: RawTokenSyntax
  ) {
    // -------------------------------------------------------------------------
    // Precondition

    precondition(
      allSegments.allSatisfy {
        if case .stringSegment(let segment) = $0 {
          return segment.unexpectedBeforeContent == nil
            && segment.unexpectedAfterContent == nil
            && segment.content.leadingTriviaByteLength == 0
        } else {
          return true
        }
      },
      "String segment produced by the lexer should not have unexpected text or trivia because we would drop it during post-processing"
    )

    // -------------------------------------------------------------------------
    // Variables

    var middleSegments = allSegments
    // In a well-formed string literal, the last segment only consists of whitespace and contains the closing quote's indentation
    let lastSegment = middleSegments.popLast()?.as(RawStringSegmentSyntax.self)

    let indentation: SyntaxText
    let indentationTrivia: [RawTriviaPiece]

    var unexpectedBeforeOpenQuote: [RawTokenSyntax] = []
    var openQuote = openQuote
    var unexpectedBeforeCloseQuote: [RawTokenSyntax] = []
    var closeQuote = closeQuote

    // -------------------------------------------------------------------------
    // Check that the close quote is on new line

    let openQuoteHasTrailingNewline = openQuote.trailingTriviaPieces.last?.isNewline ?? false

    let closeDelimiterOnNewLine = reclassifyNewlineOfLastSegmentAsTrivia(
      rawStringDelimitersToken: rawStringDelimitersToken,
      openQuoteHasTrailingNewline: openQuoteHasTrailingNewline,
      middleSegments: &middleSegments
    )

    if !closeDelimiterOnNewLine || closeQuote.leadingTriviaByteLength != 0 {
      unexpectedBeforeCloseQuote = [closeQuote]
      closeQuote = RawTokenSyntax(missing: closeQuote.tokenKind, leadingTriviaPieces: [.newlines(1)], arena: self.arena)

      // The closing delimiter doesn't start on a new line and thus it doesn't
      // make sense to try and extract indentation from it.
      return (unexpectedBeforeOpenQuote, openQuote, allSegments, unexpectedBeforeCloseQuote, closeQuote)
    }

    // -------------------------------------------------------------------------
    // Parse indentation of the closing quote

    if let lastSegment,
      let parsedTrivia = parseIndentationTrivia(text: lastSegment.content.tokenText)
    {
      indentationTrivia = parsedTrivia
      indentation = lastSegment.content.tokenText
      closeQuote = RawTokenSyntax(
        kind: closeQuote.tokenKind,
        text: closeQuote.tokenText,
        leadingTriviaPieces: parsedTrivia + closeQuote.leadingTriviaPieces,
        trailingTriviaPieces: closeQuote.trailingTriviaPieces,
        presence: closeQuote.presence,
        tokenDiagnostic: closeQuote.tokenView.tokenDiagnostic,
        arena: self.arena
      )
    } else {
      if let lastSegment = lastSegment {
        indentationTrivia = TriviaParser.parseTrivia(lastSegment.content.tokenText, position: .leading).prefix(while: {
          $0.isIndentationWhitespace
        })
        let indentationByteLength = indentationTrivia.reduce(0, { $0 + $1.byteLength })
        indentation = SyntaxText(rebasing: lastSegment.content.tokenText[0..<indentationByteLength])
        middleSegments.append(.stringSegment(lastSegment))
      } else {
        indentationTrivia = []
        indentation = ""
      }

      unexpectedBeforeCloseQuote = [closeQuote]
      closeQuote = RawTokenSyntax(
        missing: closeQuote.tokenKind,
        leadingTriviaPieces: [.newlines(1)] + indentationTrivia,
        arena: self.arena
      )
    }

    // -------------------------------------------------------------------------
    // Check that the open quote is followed by newline

    // Condition for the loop below that indicates whether the segment we are
    // iterating over is on a new line.

    if !openQuoteHasTrailingNewline {
      unexpectedBeforeOpenQuote = [openQuote]
      openQuote = RawTokenSyntax(
        missing: openQuote.tokenKind,
        trailingTriviaPieces: [.newlines(1)] + indentationTrivia,
        arena: self.arena
      )
    }

    // -------------------------------------------------------------------------
    // Check indentation of segments and escaped newlines at end of segment

    postProcessIndentationAndEscapedNewlineOfMiddleSegments(
      rawStringDelimitersToken: rawStringDelimitersToken,
      middleSegments: &middleSegments,
      isFirstSegmentOnNewLine: openQuoteHasTrailingNewline,
      indentation: indentation
    )

    // -------------------------------------------------------------------------
    // Done

    return (
      unexpectedBeforeOpenQuote,
      openQuote,
      middleSegments,
      unexpectedBeforeCloseQuote,
      closeQuote
    )
  }
}

// MARK: - Parse string literals

extension Parser {
  /// Consumes a raw string or extended regex delimiter that has the same
  /// number of `#` as `openDelimiter`.
  mutating func parsePoundDelimiter(
    _ kind: RawTokenKind,
    matching openDelimiter: RawTokenSyntax?
  ) -> (unexpectedBeforeCheckedDelimiter: RawUnexpectedNodesSyntax?, checkedDelimiter: RawTokenSyntax?) {
    // Check for leadingTriviaText == "" so we don't consume the leading raw
    // string delimiter of an upcoming string literal, e.g. in
    // ```
    // "normal literal"
    // #"raw literal"#
    // ```
    let delimiter: RawTokenSyntax?
    if self.at(TokenSpec(kind)) && self.currentToken.leadingTriviaText == "" {
      delimiter = self.consumeAnyToken()
    } else {
      delimiter = nil
    }

    switch (openDelimiter, delimiter) {
    case (nil, nil):
      return (nil, nil)
    case (let open?, nil):
      return (nil, missingToken(kind, text: open.tokenText))
    case (nil, .some):
      return (RawUnexpectedNodesSyntax([delimiter], arena: self.arena), nil)
    case (let open?, let close?):
      if open.tokenText == close.tokenText {
        return (nil, close)
      } else {
        return (RawUnexpectedNodesSyntax([delimiter], arena: self.arena), missingToken(kind, text: open.tokenText))
      }
    }
  }

  /// Parse a string literal expression.
  mutating func parseStringLiteral() -> RawStringLiteralExprSyntax {
    /// Parse opening raw string delimiter if exist.
    let openingPounds = self.consume(if: .rawStringPoundDelimiter)

    /// Try to parse @ in order to recover from Objective-C style literals
    let unexpectedAtSign = self.consume(if: .atSign)

    /// Parse open quote.
    var (unexpectedBeforeOpeningQuote, openQuote) = self.expect(
      .stringQuote,
      .multilineStringQuote,
      default: .stringQuote
    )
    unexpectedBeforeOpeningQuote = RawUnexpectedNodesSyntax(
      combining: unexpectedAtSign,
      unexpectedBeforeOpeningQuote,
      arena: self.arena
    )
    var openQuoteKind: RawTokenKind = openQuote.tokenKind
    if openQuote.isMissing, let singleQuote = self.consume(if: .singleQuote) {
      unexpectedBeforeOpeningQuote = RawUnexpectedNodesSyntax(
        combining: unexpectedBeforeOpeningQuote,
        singleQuote,
        arena: self.arena
      )
      openQuoteKind = .singleQuote
    }

    /// Parse segments.
    var segments: [RawStringLiteralSegmentListSyntax.Element] = []
    var loopProgress = LoopProgressCondition()
    while self.hasProgressed(&loopProgress) {
      // If we encounter a token with leading trivia, we're no longer in the
      // string literal.
      guard currentToken.leadingTriviaText.isEmpty else { break }

      if let stringSegment = self.consume(if: .stringSegment, TokenSpec(.identifier, remapping: .stringSegment)) {
        segments.append(.stringSegment(RawStringSegmentSyntax(content: stringSegment, arena: self.arena)))
      } else if let backslash = self.consume(if: .backslash) {
        let (unexpectedBeforeDelimiter, delimiter) = self.parsePoundDelimiter(
          .rawStringPoundDelimiter,
          matching: openingPounds
        )
        let leftParen = self.expectWithoutRecoveryOrLeadingTrivia(.leftParen)
        let expressions = RawLabeledExprListSyntax(
          elements: self.parseArgumentListElements(pattern: .none),
          arena: self.arena
        )

        // For recovery, eat anything up to the next token that either starts a new string segment or terminates the string.
        // This allows us to skip over extraneous identifiers etc. in an unterminated string interpolation.
        var unexpectedBeforeRightParen: [RawTokenSyntax] = []
        var unexpectedProgress = LoopProgressCondition()
        while !self.at(.rightParen, .stringSegment, .backslash) && !self.at(TokenSpec(openQuoteKind), .endOfFile)
          && self.hasProgressed(&unexpectedProgress)
        {
          unexpectedBeforeRightParen.append(self.consumeAnyToken())
        }
        // Consume the right paren if present, ensuring that it's on the same
        // line if this is a single-line literal. Leading trivia is fine as
        // we allow e.g "\(foo )".
        let rightParen: Token
        if self.at(.rightParen) && self.atStartOfLine && openQuote.tokenKind != .multilineStringQuote {
          rightParen = missingToken(.rightParen)
        } else {
          rightParen = self.expectWithoutRecovery(.rightParen)
        }
        if case .inStringInterpolation = self.currentToken.cursor.currentState {
          // The parser has more knowledge that we have reached the end of the
          // string interpolation now, even if we haven't seen the closing ')'.
          // For example, consider the following code
          //   "\(abc "
          // Since the lexer doesn't know anything about the expression structure,
          // it assumes that the `"` starts a new string literal. But since we
          // know in the parser that an identifier cannot be followed by a string
          // literal without a connecting binary operator and can thus consider
          // it as the surrounding string literal end, which thus also terminates
          // the string interpolation.
          self.lexemes.perform(stateTransition: .pop, currentToken: &self.currentToken)
        }
        segments.append(
          .expressionSegment(
            RawExpressionSegmentSyntax(
              backslash: backslash,
              unexpectedBeforeDelimiter,
              pounds: delimiter,
              leftParen: leftParen,
              expressions: expressions,
              RawUnexpectedNodesSyntax(unexpectedBeforeRightParen, arena: self.arena),
              rightParen: rightParen,
              arena: self.arena
            )
          )
        )
      } else {
        break
      }
    }

    /// Parse close quote.
    let unexpectedBeforeClosingQuote: RawUnexpectedNodesSyntax?
    let closingQuote: RawTokenSyntax
    if openQuoteKind == .singleQuote {
      let singleQuote = self.expectWithoutRecoveryOrLeadingTrivia(.singleQuote)
      unexpectedBeforeClosingQuote = RawUnexpectedNodesSyntax([singleQuote], arena: self.arena)
      closingQuote = missingToken(.stringQuote)
    } else {
      unexpectedBeforeClosingQuote = nil
      closingQuote = self.expectWithoutRecoveryOrLeadingTrivia(TokenSpec(openQuote.tokenKind))
    }

    let (unexpectedBeforeClosingPounds, closingPounds) = self.parsePoundDelimiter(
      .rawStringPoundDelimiter,
      matching: openingPounds
    )

    if openQuote.tokenKind == .multilineStringQuote, !openQuote.isMissing, !closingQuote.isMissing {
      let postProcessed = postProcessMultilineStringLiteral(
        rawStringDelimitersToken: openingPounds,
        openQuote: openQuote,
        segments: segments,
        closeQuote: closingQuote
      )
      return RawStringLiteralExprSyntax(
        openingPounds: openingPounds,
        RawUnexpectedNodesSyntax(
          combining: unexpectedBeforeOpeningQuote,
          postProcessed.unexpectedBeforeOpeningQuote,
          arena: self.arena
        ),
        openingQuote: postProcessed.openingQuote,
        segments: RawStringLiteralSegmentListSyntax(elements: postProcessed.segments, arena: self.arena),
        RawUnexpectedNodesSyntax(
          combining: postProcessed.unexpectedBeforeClosingQuote,
          unexpectedBeforeClosingQuote,
          arena: self.arena
        ),
        closingQuote: postProcessed.closingQuote,
        unexpectedBeforeClosingPounds,
        closingPounds: closingPounds,
        arena: self.arena
      )
    } else {
      return RawStringLiteralExprSyntax(
        openingPounds: openingPounds,
        unexpectedBeforeOpeningQuote,
        openingQuote: openQuote,
        segments: RawStringLiteralSegmentListSyntax(elements: segments, arena: self.arena),
        unexpectedBeforeClosingQuote,
        closingQuote: closingQuote,
        unexpectedBeforeClosingPounds,
        closingPounds: closingPounds,
        arena: self.arena
      )
    }
  }

  mutating func parseSimpleString() -> RawSimpleStringLiteralExprSyntax {
    let openDelimiter = self.consume(if: .rawStringPoundDelimiter)
    let (unexpectedBeforeOpenQuote, openQuote) = self.expect(
      anyIn: SimpleStringLiteralExprSyntax.OpeningQuoteOptions.self,
      default: .stringQuote
    )

    /// Parse segments.
    var segments: [RawStringSegmentSyntax] = []
    var loopProgress = LoopProgressCondition()
    while hasProgressed(&loopProgress) {
      // If we encounter a token with leading trivia, we're no longer in the
      // string literal.
      guard currentToken.leadingTriviaText.isEmpty else { break }

      if let stringSegment = self.consume(if: .stringSegment, TokenSpec(.identifier, remapping: .stringSegment)) {
        var unexpectedAfterContent: RawUnexpectedNodesSyntax?

        if let (backslash, leftParen) = self.consume(if: .backslash, followedBy: .leftParen) {
          var unexpectedTokens: [RawSyntax] = [RawSyntax(backslash), RawSyntax(leftParen)]

          let (unexpectedBeforeRightParen, rightParen) = self.expect(TokenSpec(.rightParen, allowAtStartOfLine: false))
          unexpectedTokens += unexpectedBeforeRightParen?.elements ?? []
          unexpectedTokens.append(RawSyntax(rightParen))

          unexpectedAfterContent = RawUnexpectedNodesSyntax(
            unexpectedTokens,
            arena: self.arena
          )
        }

        segments.append(RawStringSegmentSyntax(content: stringSegment, unexpectedAfterContent, arena: self.arena))
      } else {
        break
      }
    }

    let (unexpectedBetweenSegmentAndCloseQuote, closeQuote) = self.expect(
      anyIn: SimpleStringLiteralExprSyntax.ClosingQuoteOptions.self,
      default: openQuote.closeTokenKind
    )
    let closeDelimiter = self.consume(if: .rawStringPoundDelimiter)

    if openQuote.tokenKind == .multilineStringQuote, !openQuote.isMissing, !closeQuote.isMissing {
      let postProcessed = postProcessMultilineStringLiteral(
        rawStringDelimitersToken: openDelimiter,
        openQuote: openQuote,
        segments: segments.compactMap { RawStringLiteralSegmentListSyntax.Element.stringSegment($0) },
        closeQuote: closeQuote
      )

      return RawSimpleStringLiteralExprSyntax(
        RawUnexpectedNodesSyntax(
          combining: openDelimiter,
          unexpectedBeforeOpenQuote,
          postProcessed.unexpectedBeforeOpeningQuote,
          arena: self.arena
        ),
        openingQuote: postProcessed.openingQuote,
        segments: RawSimpleStringLiteralSegmentListSyntax(
          // `RawSimpleStringLiteralSegmentListSyntax` only accepts `RawStringSegmentSyntax`.
          // So we can safely cast.
          elements: postProcessed.segments.map { $0.cast(RawStringSegmentSyntax.self) },
          arena: self.arena
        ),
        RawUnexpectedNodesSyntax(
          combining: unexpectedBetweenSegmentAndCloseQuote,
          postProcessed.unexpectedBeforeClosingQuote,
          arena: self.arena
        ),
        closingQuote: postProcessed.closingQuote,
        RawUnexpectedNodesSyntax(
          [closeDelimiter],
          arena: self.arena
        ),
        arena: self.arena
      )
    } else {
      return RawSimpleStringLiteralExprSyntax(
        RawUnexpectedNodesSyntax(combining: unexpectedBeforeOpenQuote, openDelimiter, arena: self.arena),
        openingQuote: openQuote,
        segments: RawSimpleStringLiteralSegmentListSyntax(elements: segments, arena: self.arena),
        unexpectedBetweenSegmentAndCloseQuote,
        closingQuote: closeQuote,
        RawUnexpectedNodesSyntax([closeDelimiter], arena: self.arena),
        arena: self.arena
      )
    }
  }
}

// MARK: - Utilities

fileprivate extension RawTokenSyntax {
  var closeTokenKind: SimpleStringLiteralExprSyntax.ClosingQuoteOptions {
    switch self {
    case .multilineStringQuote:
      return .multilineStringQuote
    case .stringQuote:
      return .stringQuote
    default:
      return .stringQuote
    }
  }
}

fileprivate extension SyntaxText {
  private func hasSuffix(_ other: String) -> Bool {
    var other = other
    return other.withSyntaxText { self.hasSuffix($0) }
  }
}

fileprivate extension RawTriviaPiece {
  var isBackslash: Bool {
    switch self {
    case .backslashes: return true
    default: return false
    }
  }
}