|
| 1 | +//===--- StringParser.swift -----------------------------------------------===// |
| 2 | +// |
| 3 | +// This source file is part of the Swift.org open source project |
| 4 | +// |
| 5 | +// Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors |
| 6 | +// Licensed under Apache License v2.0 with Runtime Library Exception |
| 7 | +// |
| 8 | +// See https://swift.org/LICENSE.txt for license information |
| 9 | +// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors |
| 10 | +// |
| 11 | +//===----------------------------------------------------------------------===// |
| 12 | + |
| 13 | +/// A simple utility to parse a string. |
| 14 | +public struct StringParser { |
| 15 | + private var s: Substring |
| 16 | + private let originalLength: Int |
| 17 | + |
| 18 | + private mutating func consumeWhitespace() { |
| 19 | + s = s.drop { $0.isWhitespace } |
| 20 | + } |
| 21 | + |
| 22 | + public init(_ string: String) { |
| 23 | + s = Substring(string) |
| 24 | + originalLength = string.count |
| 25 | + } |
| 26 | + |
| 27 | + public mutating func isEmpty() -> Bool { |
| 28 | + consumeWhitespace() |
| 29 | + return s.isEmpty |
| 30 | + } |
| 31 | + |
| 32 | + public mutating func consume(_ str: String) -> Bool { |
| 33 | + consumeWhitespace() |
| 34 | + if !s.starts(with: str) { return false } |
| 35 | + s = s.dropFirst(str.count) |
| 36 | + return true |
| 37 | + } |
| 38 | + |
| 39 | + public mutating func consumeInt(withWhiteSpace: Bool = true) -> Int? { |
| 40 | + if withWhiteSpace { |
| 41 | + consumeWhitespace() |
| 42 | + } |
| 43 | + var intStr = "" |
| 44 | + s = s.drop { |
| 45 | + if $0.isNumber { |
| 46 | + intStr.append($0) |
| 47 | + return true |
| 48 | + } |
| 49 | + return false |
| 50 | + } |
| 51 | + return Int(intStr) |
| 52 | + } |
| 53 | + |
| 54 | + public mutating func consumeIdentifier() -> String? { |
| 55 | + consumeWhitespace() |
| 56 | + var name = "" |
| 57 | + s = s.drop { |
| 58 | + if $0.isLetter { |
| 59 | + name.append($0) |
| 60 | + return true |
| 61 | + } |
| 62 | + return false |
| 63 | + } |
| 64 | + return name.isEmpty ? nil : name |
| 65 | + } |
| 66 | + |
| 67 | + public func throwError(_ message: StaticString) throws -> Never { |
| 68 | + throw ParsingError(message: message, position: originalLength - s.count) |
| 69 | + } |
| 70 | +} |
| 71 | + |
| 72 | +public struct ParsingError : Error { |
| 73 | + public let message: StaticString |
| 74 | + public let position: Int |
| 75 | +} |
0 commit comments