1
0

ArgumentDecoder.swift 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  1. //===----------------------------------------------------------------------===//
  2. //
  3. // This source file is part of the Swift Argument Parser open source project
  4. //
  5. // Copyright (c) 2020 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. //
  10. //===----------------------------------------------------------------------===//
  11. /// A previously decoded parsable arguments type.
  12. ///
  13. /// Because arguments are consumed and decoded the first time they're
  14. /// encountered, we save the decoded instances for using later in the
  15. /// command/subcommand hierarchy.
  16. struct DecodedArguments {
  17. var type: ParsableArguments.Type
  18. var value: ParsableArguments
  19. var commandType: ParsableCommand.Type? {
  20. type as? ParsableCommand.Type
  21. }
  22. var command: ParsableCommand? {
  23. value as? ParsableCommand
  24. }
  25. }
  26. /// A decoder that decodes from parsed command-line arguments.
  27. final class ArgumentDecoder: Decoder {
  28. init(values: ParsedValues, previouslyDecoded: [DecodedArguments] = []) {
  29. self.values = values
  30. self.previouslyDecoded = previouslyDecoded
  31. self.usedOrigins = InputOrigin()
  32. }
  33. let values: ParsedValues
  34. var usedOrigins: InputOrigin
  35. var nextCommandIndex = 0
  36. var previouslyDecoded: [DecodedArguments] = []
  37. var codingPath: [CodingKey] = []
  38. var userInfo: [CodingUserInfoKey: Any] = [:]
  39. func container<K>(keyedBy type: K.Type) throws -> KeyedDecodingContainer<K>
  40. where K: CodingKey {
  41. let container = ParsedArgumentsContainer(
  42. for: self, keyType: K.self, codingPath: codingPath)
  43. return KeyedDecodingContainer(container)
  44. }
  45. func unkeyedContainer() throws -> UnkeyedDecodingContainer {
  46. throw Error.topLevelHasNoUnkeyedContainer
  47. }
  48. func singleValueContainer() throws -> SingleValueDecodingContainer {
  49. throw Error.topLevelHasNoSingleValueContainer
  50. }
  51. }
  52. extension ArgumentDecoder {
  53. fileprivate func element(forKey key: InputKey) -> ParsedValues.Element? {
  54. guard let element = values.element(forKey: key) else { return nil }
  55. usedOrigins.formUnion(element.inputOrigin)
  56. return element
  57. }
  58. }
  59. extension ArgumentDecoder {
  60. enum Error: Swift.Error {
  61. case topLevelHasNoUnkeyedContainer
  62. case topLevelHasNoSingleValueContainer
  63. case singleValueDecoderHasNoContainer
  64. case wrongKeyType(CodingKey.Type, CodingKey.Type)
  65. }
  66. }
  67. final class ParsedArgumentsContainer<K>: KeyedDecodingContainerProtocol
  68. where K: CodingKey {
  69. var codingPath: [CodingKey]
  70. let decoder: ArgumentDecoder
  71. init(for decoder: ArgumentDecoder, keyType: K.Type, codingPath: [CodingKey]) {
  72. self.codingPath = codingPath
  73. self.decoder = decoder
  74. }
  75. var allKeys: [K] {
  76. fatalError()
  77. }
  78. fileprivate func element(forKey key: K) -> ParsedValues.Element? {
  79. let k = InputKey(codingKey: key, path: codingPath)
  80. return decoder.element(forKey: k)
  81. }
  82. func contains(_ key: K) -> Bool {
  83. element(forKey: key) != nil
  84. }
  85. func decodeNil(forKey key: K) throws -> Bool {
  86. element(forKey: key)?.value == nil
  87. }
  88. func decode<T>(_ type: T.Type, forKey key: K) throws -> T where T: Decodable {
  89. let parsedElement = element(forKey: key)
  90. if let parsedElement = parsedElement,
  91. parsedElement.inputOrigin.isDefaultValue,
  92. let rawValue = parsedElement.value
  93. {
  94. guard let value = rawValue as? T else {
  95. throw InternalParseError.wrongType(
  96. valueRepresentation: "\(rawValue)", forKey: parsedElement.key)
  97. }
  98. return value
  99. }
  100. let subDecoder = SingleValueDecoder(
  101. userInfo: decoder.userInfo, underlying: decoder,
  102. codingPath: codingPath + [key],
  103. key: InputKey(codingKey: key, path: codingPath),
  104. parsedElement: parsedElement)
  105. return try type.init(from: subDecoder)
  106. }
  107. func decodeIfPresent<T>(
  108. _ type: T.Type, forKey key: KeyedDecodingContainer<K>.Key
  109. ) throws -> T? where T: Decodable {
  110. let parsedElement = element(forKey: key)
  111. if let parsedElement = parsedElement,
  112. parsedElement.inputOrigin.isDefaultValue
  113. {
  114. return parsedElement.value as? T
  115. }
  116. let subDecoder = SingleValueDecoder(
  117. userInfo: decoder.userInfo, underlying: decoder,
  118. codingPath: codingPath + [key],
  119. key: InputKey(codingKey: key, path: codingPath),
  120. parsedElement: parsedElement)
  121. do {
  122. return try type.init(from: subDecoder)
  123. } catch let error as ParserError {
  124. if case .noValue = error {
  125. return nil
  126. } else {
  127. throw error
  128. }
  129. }
  130. }
  131. func nestedContainer<NestedKey>(keyedBy type: NestedKey.Type, forKey key: K)
  132. throws -> KeyedDecodingContainer<NestedKey> where NestedKey: CodingKey
  133. {
  134. fatalError()
  135. }
  136. func nestedUnkeyedContainer(forKey key: K) throws -> UnkeyedDecodingContainer
  137. {
  138. fatalError()
  139. }
  140. func superDecoder() throws -> Decoder {
  141. fatalError()
  142. }
  143. func superDecoder(forKey key: K) throws -> Decoder {
  144. fatalError()
  145. }
  146. }
  147. struct SingleValueDecoder: Decoder {
  148. var userInfo: [CodingUserInfoKey: Any]
  149. var underlying: ArgumentDecoder
  150. var codingPath: [CodingKey]
  151. var key: InputKey
  152. var parsedElement: ParsedValues.Element?
  153. func container<K>(keyedBy type: K.Type) throws -> KeyedDecodingContainer<K>
  154. where K: CodingKey {
  155. KeyedDecodingContainer(
  156. ParsedArgumentsContainer(
  157. for: underlying, keyType: type, codingPath: codingPath))
  158. }
  159. func unkeyedContainer() throws -> UnkeyedDecodingContainer {
  160. guard let e = parsedElement else {
  161. var errorPath = codingPath
  162. guard let last = errorPath.popLast() else {
  163. preconditionFailure("Expected non-empty coding path")
  164. }
  165. throw ParserError.noValue(
  166. forKey: InputKey(codingKey: last, path: errorPath))
  167. }
  168. guard let a = e.value as? [Any] else {
  169. throw ParserError.invalidState
  170. }
  171. return UnkeyedContainer(
  172. codingPath: codingPath, parsedElement: e, array: ArrayWrapper(a))
  173. }
  174. func singleValueContainer() throws -> SingleValueDecodingContainer {
  175. SingleValueContainer(
  176. underlying: self, codingPath: codingPath, parsedElement: parsedElement)
  177. }
  178. func previousValue<T>(_ type: T.Type) throws -> T {
  179. guard
  180. let previous = underlying.previouslyDecoded.first(where: {
  181. type == $0.type
  182. })
  183. else { throw ParserError.invalidState }
  184. // swift-format-ignore: NeverForceUnwrap
  185. // We know the type is correct because we check it above.
  186. return previous.value as! T
  187. }
  188. func saveValue<T: ParsableArguments>(_ value: T, type: T.Type = T.self) {
  189. underlying.previouslyDecoded.append(
  190. DecodedArguments(type: type, value: value))
  191. }
  192. struct SingleValueContainer: SingleValueDecodingContainer {
  193. var underlying: SingleValueDecoder
  194. var codingPath: [CodingKey]
  195. var parsedElement: ParsedValues.Element?
  196. func decodeNil() -> Bool {
  197. parsedElement == nil
  198. }
  199. func decode<T>(_ type: T.Type) throws -> T where T: Decodable {
  200. guard let e = parsedElement else {
  201. var errorPath = codingPath
  202. guard let last = errorPath.popLast() else {
  203. preconditionFailure("Expected non-empty coding path")
  204. }
  205. throw ParserError.noValue(
  206. forKey: InputKey(codingKey: last, path: errorPath))
  207. }
  208. guard let s = e.value as? T else {
  209. throw InternalParseError.wrongType(
  210. valueRepresentation: "nil", forKey: e.key)
  211. }
  212. return s
  213. }
  214. }
  215. struct UnkeyedContainer: UnkeyedDecodingContainer {
  216. var codingPath: [CodingKey]
  217. var parsedElement: ParsedValues.Element
  218. var array: ArrayWrapperProtocol
  219. var count: Int? {
  220. array.count
  221. }
  222. var isAtEnd: Bool {
  223. array.isAtEnd
  224. }
  225. var currentIndex: Int {
  226. array.currentIndex
  227. }
  228. mutating func decodeNil() throws -> Bool {
  229. false
  230. }
  231. mutating func decode<T>(_ type: T.Type) throws -> T where T: Decodable {
  232. guard let next = array.getNext() else { fatalError() }
  233. guard let t = next as? T else {
  234. throw InternalParseError.wrongType(
  235. valueRepresentation: "\(next)", forKey: parsedElement.key)
  236. }
  237. return t
  238. }
  239. mutating func nestedContainer<NestedKey>(keyedBy type: NestedKey.Type)
  240. throws -> KeyedDecodingContainer<NestedKey> where NestedKey: CodingKey
  241. {
  242. fatalError()
  243. }
  244. mutating func nestedUnkeyedContainer() throws -> UnkeyedDecodingContainer {
  245. fatalError()
  246. }
  247. mutating func superDecoder() throws -> Decoder {
  248. fatalError()
  249. }
  250. }
  251. }
  252. /// A type-erasing wrapper for consuming elements of an array.
  253. protocol ArrayWrapperProtocol {
  254. var count: Int? { get }
  255. var isAtEnd: Bool { get }
  256. var currentIndex: Int { get }
  257. mutating func getNext() -> Any?
  258. }
  259. struct ArrayWrapper<A>: ArrayWrapperProtocol {
  260. var base: [A]
  261. var currentIndex: Int
  262. init(_ a: [A]) {
  263. self.base = a
  264. self.currentIndex = a.startIndex
  265. }
  266. var count: Int? {
  267. base.count
  268. }
  269. var isAtEnd: Bool {
  270. base.endIndex <= currentIndex
  271. }
  272. mutating func getNext() -> Any? {
  273. guard currentIndex < base.endIndex else { return nil }
  274. let next = base[currentIndex]
  275. currentIndex += 1
  276. return next
  277. }
  278. }