forked from swiftlang/swift-syntax
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFormatRawStringLiteral.swift
More file actions
119 lines (109 loc) · 3.71 KB
/
FormatRawStringLiteral.swift
File metadata and controls
119 lines (109 loc) · 3.71 KB
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
//===----------------------------------------------------------------------===//
//
// 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
}
}
var shouldRemoveHashes = maximumHashes == 0
let quote = lit.openingQuote.text
if shouldRemoveHashes {
if quote == "\"" {
// Check for the #"""..."""# case which parses as quote=""" and content wrapped in quotes.
// If we remove hashes, we get """...""", which is invalid single-line multiline syntax.
for segment in lit.segments {
if case .stringSegment(let s) = segment {
if s.content.text.hasPrefix("\"") && s.content.text.hasSuffix("\"") {
shouldRemoveHashes = false
break
}
}
}
} else if quote == "\"\"\"" {
// Check for single-line multiline strings.
let containsNewline =
lit.openingQuote.trailingTrivia.description.contains("\n")
|| lit.segments.contains(where: { $0.description.contains("\n") })
|| lit.closingQuote.leadingTrivia.description.contains("\n")
if !containsNewline {
shouldRemoveHashes = false
}
}
}
if shouldRemoveHashes {
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
}
}