|
11 | 11 | //===----------------------------------------------------------------------===//
|
12 | 12 |
|
13 | 13 | import SwiftSyntax
|
| 14 | +import Foundation |
| 15 | + |
| 16 | +/// A regular expression matching sequences of `#`s with an adjacent quote or |
| 17 | +/// interpolation. Used to determine the number of `#`s for a raw string literal. |
| 18 | +private let rawStringPotentialEscapesPattern = try! NSRegularExpression( |
| 19 | + pattern: [ |
| 20 | + #""(#+)"#, // Match potential opening delimiters |
| 21 | + #"(#+)""#, // Match potential closing delimiters |
| 22 | + #"\\(#+)\("#, // Match potential interpolations |
| 23 | + ].joined(separator: "|") |
| 24 | +) |
14 | 25 |
|
15 | 26 | extension StringLiteralExpr {
|
16 |
| - public init(_ value: String, openQuote: TokenSyntax = .stringQuote, closeQuote: TokenSyntax = .stringQuote) { |
| 27 | + /// Creates a string literal, optionally specifying quotes and delimiters. |
| 28 | + public init( |
| 29 | + openDelimiter: TokenSyntax? = nil, |
| 30 | + openQuote: TokenSyntax = .stringQuote, |
| 31 | + _ value: String, |
| 32 | + closeQuote: TokenSyntax = .stringQuote, |
| 33 | + closeDelimiter: TokenSyntax? = nil |
| 34 | + ) { |
17 | 35 | let content = TokenSyntax.stringSegment(value)
|
18 | 36 | let segment = StringSegment(content: content)
|
19 | 37 | let segments = StringLiteralSegments([segment])
|
20 | 38 |
|
21 |
| - self.init(openQuote: openQuote, |
22 |
| - segments: segments, |
23 |
| - closeQuote: closeQuote) |
| 39 | + self.init( |
| 40 | + openDelimiter: openDelimiter, |
| 41 | + openQuote: openQuote, |
| 42 | + segments: segments, |
| 43 | + closeQuote: closeQuote, |
| 44 | + closeDelimiter: closeDelimiter |
| 45 | + ) |
| 46 | + } |
| 47 | + |
| 48 | + /// Creates a raw string literal. Automatically determines |
| 49 | + /// the number of `#`s needed to express the string as-is without any escapes. |
| 50 | + public init(raw value: String) { |
| 51 | + // Match potential escapes in the string |
| 52 | + let matches = rawStringPotentialEscapesPattern.matches(in: value, range: NSRange(value.startIndex..., in: value)) |
| 53 | + |
| 54 | + // Find longest sequence of `#`s by taking the maximum length over all captures |
| 55 | + let maxPoundCount = matches |
| 56 | + .compactMap { match in (1..<match.numberOfRanges).map { match.range(at: $0).length }.max() } |
| 57 | + .max() ?? 0 |
| 58 | + |
| 59 | + // Use a delimiter that is exactly one longer |
| 60 | + let delimiter = TokenSyntax.rawStringDelimiter(String(repeating: "#", count: 1 + maxPoundCount)) |
| 61 | + |
| 62 | + self.init( |
| 63 | + openDelimiter: delimiter, |
| 64 | + value, |
| 65 | + closeDelimiter: delimiter |
| 66 | + ) |
24 | 67 | }
|
25 | 68 | }
|
0 commit comments