@@ -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//===----------------------------------------------------------------------===//
0 commit comments