Repository navigation
Expand file tree
/
Copy pathJSONCParser.swift
More file actions
218 lines (196 loc) · 7.87 KB
/
Copy pathJSONCParser.swift
File metadata and controls
218 lines (196 loc) · 7.87 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
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
import Foundation
enum JSONCParser {
static func preprocess(data: Data) throws -> Data {
let source = try sourceString(from: data)
let withoutBOM = source.hasPrefix("\u{feff}") ? String(source.dropFirst()) : source
let stripped = try stripComments(from: withoutBOM)
let normalized = try stripTrailingCommas(from: stripped)
return Data(normalized.utf8)
}
private static func sourceString(from data: Data) throws -> String {
if let encoding = detectedJSONEncoding(for: data),
let source = String(data: data, encoding: encoding) {
return source
}
if let source = String(data: data, encoding: .utf8) {
return source
}
var convertedString: NSString?
var usedLossyConversion = ObjCBool(false)
let encoding = NSString.stringEncoding(
for: data,
encodingOptions: [
.suggestedEncodingsKey: [
String.Encoding.utf8.rawValue,
String.Encoding.utf16BigEndian.rawValue,
String.Encoding.utf16LittleEndian.rawValue,
String.Encoding.utf32BigEndian.rawValue,
String.Encoding.utf32LittleEndian.rawValue,
],
.useOnlySuggestedEncodingsKey: true,
.allowLossyKey: false,
],
convertedString: &convertedString,
usedLossyConversion: &usedLossyConversion
)
if let convertedString, !usedLossyConversion.boolValue {
return convertedString as String
}
if encoding != 0, !usedLossyConversion.boolValue {
let stringEncoding = String.Encoding(rawValue: encoding)
if let source = String(data: data, encoding: stringEncoding) {
return source
}
}
throw JSONCError.invalidTextEncoding
}
private static func detectedJSONEncoding(for data: Data) -> String.Encoding? {
let bytes = Array(data.prefix(4))
if bytes.starts(with: [0x00, 0x00, 0xFE, 0xFF]) { return .utf32BigEndian }
if bytes.starts(with: [0xFF, 0xFE, 0x00, 0x00]) { return .utf32LittleEndian }
if bytes.starts(with: [0xFE, 0xFF]) { return .utf16BigEndian }
if bytes.starts(with: [0xFF, 0xFE]) { return .utf16LittleEndian }
if bytes.starts(with: [0xEF, 0xBB, 0xBF]) { return .utf8 }
guard bytes.count >= 4 else { return nil }
switch (bytes[0] == 0, bytes[1] == 0, bytes[2] == 0, bytes[3] == 0) {
case (true, true, true, false):
return .utf32BigEndian
case (false, true, true, true):
return .utf32LittleEndian
case (true, false, true, false):
return .utf16BigEndian
case (false, true, false, true):
return .utf16LittleEndian
default:
return nil
}
}
private static func stripComments(from source: String) throws -> String {
var result = ""
var index = source.startIndex
var inString = false
var isEscaped = false
while index < source.endIndex {
let character = source[index]
if inString {
result.append(character)
if isEscaped {
isEscaped = false
} else if character == "\\" {
isEscaped = true
} else if character == "\"" {
inString = false
}
index = source.index(after: index)
continue
}
if character == "\"" {
inString = true
result.append(character)
index = source.index(after: index)
continue
}
if character == "/" {
let nextIndex = source.index(after: index)
if nextIndex < source.endIndex {
let next = source[nextIndex]
if next == "/" {
index = source.index(after: nextIndex)
while index < source.endIndex && source[index] != "\n" {
index = source.index(after: index)
}
continue
}
if next == "*" {
index = source.index(after: nextIndex)
var didClose = false
while index < source.endIndex {
let current = source[index]
let followingIndex = source.index(after: index)
if current == "*" && followingIndex < source.endIndex && source[followingIndex] == "/" {
index = source.index(after: followingIndex)
didClose = true
break
}
index = followingIndex
}
guard didClose else {
throw JSONCError.unterminatedBlockComment
}
continue
}
}
}
result.append(character)
index = source.index(after: index)
}
return result
}
private static func stripTrailingCommas(from source: String) throws -> String {
var result = ""
var index = source.startIndex
var inString = false
var isEscaped = false
var lastSignificantCharacter: Character?
while index < source.endIndex {
let character = source[index]
if inString {
result.append(character)
if isEscaped {
isEscaped = false
} else if character == "\\" {
isEscaped = true
} else if character == "\"" {
inString = false
lastSignificantCharacter = character
}
index = source.index(after: index)
continue
}
if character == "\"" {
inString = true
result.append(character)
index = source.index(after: index)
continue
}
if character == "," {
var lookahead = source.index(after: index)
while lookahead < source.endIndex && source[lookahead].isWhitespace {
lookahead = source.index(after: lookahead)
}
if lookahead < source.endIndex && (source[lookahead] == "}" || source[lookahead] == "]") {
if lastSignificantCharacter == nil ||
lastSignificantCharacter == "," ||
lastSignificantCharacter == "{" ||
lastSignificantCharacter == "[" ||
lastSignificantCharacter == ":" {
throw JSONCError.invalidTrailingComma
}
index = source.index(after: index)
continue
}
}
result.append(character)
if !character.isWhitespace {
lastSignificantCharacter = character
}
index = source.index(after: index)
}
return result
}
private enum JSONCError: LocalizedError {
case invalidTextEncoding
case invalidTrailingComma
case unterminatedBlockComment
var errorDescription: String? {
switch self {
case .invalidTextEncoding:
return "config file text encoding is not supported"
case .invalidTrailingComma:
return "invalid trailing comma"
case .unterminatedBlockComment:
return "unterminated block comment"
}
}
}
}