Skip to content

Commit 75da7d9

Browse files
committed
Swift SIL: add a StringParser utility for simple parsing tasks
1 parent beb2bd2 commit 75da7d9

File tree

2 files changed

+72
-0
lines changed

2 files changed

+72
-0
lines changed

SwiftCompilerSources/Sources/SIL/Utils.swift

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -163,6 +163,73 @@ extension LazyFilterSequence : CollectionLikeSequence,
163163
FormattedLikeArray, CustomStringConvertible, CustomReflectable
164164
where Base: CollectionLikeSequence {}
165165

166+
//===----------------------------------------------------------------------===//
167+
// String parsing
168+
//===----------------------------------------------------------------------===//
169+
170+
public struct StringParser {
171+
private var s: Substring
172+
private let originalLength: Int
173+
174+
private mutating func consumeWhitespace() {
175+
s = s.drop { $0.isWhitespace }
176+
}
177+
178+
public init(_ string: String) {
179+
s = Substring(string)
180+
originalLength = string.count
181+
}
182+
183+
mutating func isEmpty() -> Bool {
184+
consumeWhitespace()
185+
return s.isEmpty
186+
}
187+
188+
public mutating func consume(_ str: String) -> Bool {
189+
consumeWhitespace()
190+
if !s.starts(with: str) { return false }
191+
s = s.dropFirst(str.count)
192+
return true
193+
}
194+
195+
public mutating func consumeInt(withWhiteSpace: Bool = true) -> Int? {
196+
if withWhiteSpace {
197+
consumeWhitespace()
198+
}
199+
var intStr = ""
200+
s = s.drop {
201+
if $0.isNumber {
202+
intStr.append($0)
203+
return true
204+
}
205+
return false
206+
}
207+
return Int(intStr)
208+
}
209+
210+
public mutating func consumeIdentifier() -> String? {
211+
consumeWhitespace()
212+
var name = ""
213+
s = s.drop {
214+
if $0.isLetter {
215+
name.append($0)
216+
return true
217+
}
218+
return false
219+
}
220+
return name.isEmpty ? nil : name
221+
}
222+
223+
public func throwError(_ message: StaticString) throws -> Never {
224+
throw ParsingError(message: message, position: originalLength - s.count)
225+
}
226+
}
227+
228+
public struct ParsingError : Error {
229+
public let message: StaticString
230+
public let position: Int
231+
}
232+
166233
//===----------------------------------------------------------------------===//
167234
// Bridging Utilities
168235
//===----------------------------------------------------------------------===//

include/swift/SIL/SILBridging.h

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -136,6 +136,11 @@ typedef struct {
136136
SwiftObject obj;
137137
} BridgedMultiValueResult;
138138

139+
typedef struct {
140+
const unsigned char * _Nullable message;
141+
SwiftInt position;
142+
} BridgedParsingError;
143+
139144
// Must be in sync with SILInstruction::MemoryBehavior
140145
// TODO: do this less hacky.
141146
typedef enum {

0 commit comments

Comments
 (0)