-
Notifications
You must be signed in to change notification settings - Fork 441
/
Copy pathFormatRawStringLiteral.swift
91 lines (84 loc) · 2.71 KB
/
FormatRawStringLiteral.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
//===----------------------------------------------------------------------===//
//
// 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 compiler(>=6)
public import SwiftSyntax
#else
import SwiftSyntax
#endif
/// Format a string literal by inserting or removing the appropriate number of
/// raw string `#` delimiters.
///
/// ## Before
///
/// ```swift
/// "The # of values is \(count)"
/// "Hello \#(world)"
/// ###"Hello World"###
/// ```
///
/// ## After
///
/// ```swift
/// ##"The # of values is \(count)"##
/// ##"Hello \#(world)"##
/// "Hello World"
/// ```
public struct FormatRawStringLiteral: SyntaxRefactoringProvider {
public static func refactor(syntax lit: StringLiteralExprSyntax, in context: Void) -> StringLiteralExprSyntax? {
var maximumHashes = 0
for segment in lit.segments {
switch segment {
case .expressionSegment(let expr):
if let rawStringDelimiter = expr.pounds {
// Pick up any delimiters in interpolation segments \#...#(...)
maximumHashes = max(maximumHashes, rawStringDelimiter.text.longestRun(of: "#"))
}
case .stringSegment(let string):
// Find the longest run of # characters in the content of the literal.
maximumHashes = max(maximumHashes, string.content.text.longestRun(of: "#"))
#if RESILIENT_LIBRARIES
@unknown default:
fatalError()
#endif
}
}
guard maximumHashes > 0 else {
return
lit
.with(\.openingPounds, lit.openingPounds?.with(\.tokenKind, .rawStringPoundDelimiter("")))
.with(\.closingPounds, lit.closingPounds?.with(\.tokenKind, .rawStringPoundDelimiter("")))
}
let delimiters = String(repeating: "#", count: maximumHashes + 1)
return
lit
.with(\.openingPounds, lit.openingPounds?.with(\.tokenKind, .rawStringPoundDelimiter(delimiters)))
.with(\.closingPounds, lit.closingPounds?.with(\.tokenKind, .rawStringPoundDelimiter(delimiters)))
}
}
extension String {
fileprivate func longestRun(of needle: Character) -> Int {
var longest = 0
var it = self.makeIterator()
while let c = it.next() {
guard c == needle else {
continue
}
var localLongest = 1
while let c = it.next(), c == needle {
localLongest += 1
continue
}
longest = max(localLongest, longest)
}
return longest
}
}