Generator-Client.swift 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688
  1. /*
  2. * Copyright 2018, gRPC Authors All rights reserved.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. import Foundation
  17. import SwiftProtobuf
  18. import SwiftProtobufPluginLibrary
  19. extension Generator {
  20. internal func printClient() {
  21. if self.options.generateClient {
  22. self.println()
  23. self.printServiceClientProtocol()
  24. self.println()
  25. self.printClientProtocolExtension()
  26. self.println()
  27. self.printClassBackedServiceClientImplementation()
  28. self.println()
  29. self.printStructBackedServiceClientImplementation()
  30. self.println()
  31. self.printAsyncServiceClientProtocol()
  32. self.println()
  33. self.printAsyncClientProtocolExtension()
  34. self.println()
  35. self.printAsyncClientProtocolSafeWrappersExtension()
  36. self.println()
  37. self.printAsyncServiceClientImplementation()
  38. self.println()
  39. // Both implementations share definitions for interceptors and metadata.
  40. self.printServiceClientInterceptorFactoryProtocol()
  41. self.println()
  42. self.printClientMetadata()
  43. }
  44. if self.options.generateTestClient {
  45. self.println()
  46. self.printTestClient()
  47. }
  48. }
  49. internal func printFunction(
  50. name: String,
  51. arguments: [String],
  52. returnType: String?,
  53. access: String? = nil,
  54. sendable: Bool = false,
  55. async: Bool = false,
  56. throws: Bool = false,
  57. genericWhereClause: String? = nil,
  58. bodyBuilder: (() -> Void)?
  59. ) {
  60. // Add a space after access, if it exists.
  61. let functionHead = (access.map { $0 + " " } ?? "") + (sendable ? "@Sendable " : "")
  62. let `return` = returnType.map { " -> " + $0 } ?? ""
  63. let genericWhere = genericWhereClause.map { " " + $0 } ?? ""
  64. let asyncThrows: String
  65. switch (async, `throws`) {
  66. case (true, true):
  67. asyncThrows = " async throws"
  68. case (true, false):
  69. asyncThrows = " async"
  70. case (false, true):
  71. asyncThrows = " throws"
  72. case (false, false):
  73. asyncThrows = ""
  74. }
  75. let hasBody = bodyBuilder != nil
  76. if arguments.isEmpty {
  77. // Don't bother splitting across multiple lines if there are no arguments.
  78. self.println(
  79. "\(functionHead)func \(name)()\(asyncThrows)\(`return`)\(genericWhere)",
  80. newline: !hasBody
  81. )
  82. } else {
  83. self.println("\(functionHead)func \(name)(")
  84. self.withIndentation {
  85. // Add a comma after each argument except the last.
  86. arguments.forEach(
  87. beforeLast: {
  88. self.println($0 + ",")
  89. },
  90. onLast: {
  91. self.println($0)
  92. }
  93. )
  94. }
  95. self.println(")\(asyncThrows)\(`return`)\(genericWhere)", newline: !hasBody)
  96. }
  97. if let bodyBuilder = bodyBuilder {
  98. self.println(" {")
  99. self.withIndentation {
  100. bodyBuilder()
  101. }
  102. self.println("}")
  103. }
  104. }
  105. private func printServiceClientProtocol() {
  106. let comments = self.service.protoSourceComments()
  107. if !comments.isEmpty {
  108. // Source comments already have the leading '///'
  109. self.println(comments, newline: false)
  110. self.println("///")
  111. }
  112. self.println(
  113. "/// Usage: instantiate `\(self.clientClassName)`, then call methods of this protocol to make API calls."
  114. )
  115. self.println("\(self.access) protocol \(self.clientProtocolName): GRPCClient {")
  116. self.withIndentation {
  117. self.println("var serviceName: String { get }")
  118. self.println("var interceptors: \(self.clientInterceptorProtocolName)? { get }")
  119. for method in service.methods {
  120. self.println()
  121. self.method = method
  122. self.printFunction(
  123. name: self.methodFunctionName,
  124. arguments: self.methodArgumentsWithoutDefaults,
  125. returnType: self.methodReturnType,
  126. bodyBuilder: nil
  127. )
  128. }
  129. }
  130. println("}")
  131. }
  132. private func printClientProtocolExtension() {
  133. self.println("extension \(self.clientProtocolName) {")
  134. self.withIndentation {
  135. // Service name.
  136. self.println("\(self.access) var serviceName: String {")
  137. self.withIndentation {
  138. self.println("return \"\(self.servicePath)\"")
  139. }
  140. self.println("}")
  141. // Default method implementations.
  142. self.printMethods()
  143. }
  144. self.println("}")
  145. }
  146. private func printServiceClientInterceptorFactoryProtocol() {
  147. self.println("\(self.access) protocol \(self.clientInterceptorProtocolName): Sendable {")
  148. self.withIndentation {
  149. // Method specific interceptors.
  150. for method in service.methods {
  151. self.println()
  152. self.method = method
  153. self.println(
  154. "/// - Returns: Interceptors to use when invoking '\(self.methodFunctionName)'."
  155. )
  156. // Skip the access, we're defining a protocol.
  157. self.printMethodInterceptorFactory(access: nil)
  158. }
  159. }
  160. self.println("}")
  161. }
  162. private func printMethodInterceptorFactory(
  163. access: String?,
  164. bodyBuilder: (() -> Void)? = nil
  165. ) {
  166. self.printFunction(
  167. name: self.methodInterceptorFactoryName,
  168. arguments: [],
  169. returnType: "[ClientInterceptor<\(self.methodInputName), \(self.methodOutputName)>]",
  170. access: access,
  171. bodyBuilder: bodyBuilder
  172. )
  173. }
  174. private func printClassBackedServiceClientImplementation() {
  175. self.println("@available(*, deprecated)")
  176. self.println("extension \(clientClassName): @unchecked Sendable {}")
  177. self.println()
  178. self.println("@available(*, deprecated, renamed: \"\(clientStructName)\")")
  179. println("\(access) final class \(clientClassName): \(clientProtocolName) {")
  180. self.withIndentation {
  181. println("private let lock = Lock()")
  182. println("private var _defaultCallOptions: CallOptions")
  183. println("private var _interceptors: \(clientInterceptorProtocolName)?")
  184. println("\(access) let channel: GRPCChannel")
  185. println("\(access) var defaultCallOptions: CallOptions {")
  186. self.withIndentation {
  187. println("get { self.lock.withLock { return self._defaultCallOptions } }")
  188. println("set { self.lock.withLockVoid { self._defaultCallOptions = newValue } }")
  189. }
  190. self.println("}")
  191. println("\(access) var interceptors: \(clientInterceptorProtocolName)? {")
  192. self.withIndentation {
  193. println("get { self.lock.withLock { return self._interceptors } }")
  194. println("set { self.lock.withLockVoid { self._interceptors = newValue } }")
  195. }
  196. println("}")
  197. println()
  198. println("/// Creates a client for the \(servicePath) service.")
  199. println("///")
  200. self.printParameters()
  201. println("/// - channel: `GRPCChannel` to the service host.")
  202. println(
  203. "/// - defaultCallOptions: Options to use for each service call if the user doesn't provide them."
  204. )
  205. println("/// - interceptors: A factory providing interceptors for each RPC.")
  206. println("\(access) init(")
  207. self.withIndentation {
  208. println("channel: GRPCChannel,")
  209. println("defaultCallOptions: CallOptions = CallOptions(),")
  210. println("interceptors: \(clientInterceptorProtocolName)? = nil")
  211. }
  212. self.println(") {")
  213. self.withIndentation {
  214. println("self.channel = channel")
  215. println("self._defaultCallOptions = defaultCallOptions")
  216. println("self._interceptors = interceptors")
  217. }
  218. self.println("}")
  219. }
  220. println("}")
  221. }
  222. private func printStructBackedServiceClientImplementation() {
  223. println("\(access) struct \(clientStructName): \(clientProtocolName) {")
  224. self.withIndentation {
  225. println("\(access) var channel: GRPCChannel")
  226. println("\(access) var defaultCallOptions: CallOptions")
  227. println("\(access) var interceptors: \(clientInterceptorProtocolName)?")
  228. println()
  229. println("/// Creates a client for the \(servicePath) service.")
  230. println("///")
  231. self.printParameters()
  232. println("/// - channel: `GRPCChannel` to the service host.")
  233. println(
  234. "/// - defaultCallOptions: Options to use for each service call if the user doesn't provide them."
  235. )
  236. println("/// - interceptors: A factory providing interceptors for each RPC.")
  237. println("\(access) init(")
  238. self.withIndentation {
  239. println("channel: GRPCChannel,")
  240. println("defaultCallOptions: CallOptions = CallOptions(),")
  241. println("interceptors: \(clientInterceptorProtocolName)? = nil")
  242. }
  243. self.println(") {")
  244. self.withIndentation {
  245. println("self.channel = channel")
  246. println("self.defaultCallOptions = defaultCallOptions")
  247. println("self.interceptors = interceptors")
  248. }
  249. self.println("}")
  250. }
  251. println("}")
  252. }
  253. private func printMethods() {
  254. for method in self.service.methods {
  255. self.println()
  256. self.method = method
  257. switch self.streamType {
  258. case .unary:
  259. self.printUnaryCall()
  260. case .serverStreaming:
  261. self.printServerStreamingCall()
  262. case .clientStreaming:
  263. self.printClientStreamingCall()
  264. case .bidirectionalStreaming:
  265. self.printBidirectionalStreamingCall()
  266. }
  267. }
  268. }
  269. private func printUnaryCall() {
  270. self.println(self.method.documentation(streamingType: self.streamType), newline: false)
  271. self.println("///")
  272. self.printParameters()
  273. self.printRequestParameter()
  274. self.printCallOptionsParameter()
  275. self.println("/// - Returns: A `UnaryCall` with futures for the metadata, status and response.")
  276. self.printFunction(
  277. name: self.methodFunctionName,
  278. arguments: self.methodArguments,
  279. returnType: self.methodReturnType,
  280. access: self.access
  281. ) {
  282. self.println("return self.makeUnaryCall(")
  283. self.withIndentation {
  284. self.println("path: \(self.methodPathUsingClientMetadata),")
  285. self.println("request: request,")
  286. self.println("callOptions: callOptions ?? self.defaultCallOptions,")
  287. self.println(
  288. "interceptors: self.interceptors?.\(self.methodInterceptorFactoryName)() ?? []"
  289. )
  290. }
  291. self.println(")")
  292. }
  293. }
  294. private func printServerStreamingCall() {
  295. self.println(self.method.documentation(streamingType: self.streamType), newline: false)
  296. self.println("///")
  297. self.printParameters()
  298. self.printRequestParameter()
  299. self.printCallOptionsParameter()
  300. self.printHandlerParameter()
  301. self.println("/// - Returns: A `ServerStreamingCall` with futures for the metadata and status.")
  302. self.printFunction(
  303. name: self.methodFunctionName,
  304. arguments: self.methodArguments,
  305. returnType: self.methodReturnType,
  306. access: self.access
  307. ) {
  308. self.println("return self.makeServerStreamingCall(")
  309. self.withIndentation {
  310. self.println("path: \(self.methodPathUsingClientMetadata),")
  311. self.println("request: request,")
  312. self.println("callOptions: callOptions ?? self.defaultCallOptions,")
  313. self.println(
  314. "interceptors: self.interceptors?.\(self.methodInterceptorFactoryName)() ?? [],"
  315. )
  316. self.println("handler: handler")
  317. }
  318. self.println(")")
  319. }
  320. }
  321. private func printClientStreamingCall() {
  322. self.println(self.method.documentation(streamingType: self.streamType), newline: false)
  323. self.println("///")
  324. self.printClientStreamingDetails()
  325. self.println("///")
  326. self.printParameters()
  327. self.printCallOptionsParameter()
  328. self
  329. .println(
  330. "/// - Returns: A `ClientStreamingCall` with futures for the metadata, status and response."
  331. )
  332. self.printFunction(
  333. name: self.methodFunctionName,
  334. arguments: self.methodArguments,
  335. returnType: self.methodReturnType,
  336. access: self.access
  337. ) {
  338. self.println("return self.makeClientStreamingCall(")
  339. self.withIndentation {
  340. self.println("path: \(self.methodPathUsingClientMetadata),")
  341. self.println("callOptions: callOptions ?? self.defaultCallOptions,")
  342. self.println(
  343. "interceptors: self.interceptors?.\(self.methodInterceptorFactoryName)() ?? []"
  344. )
  345. }
  346. self.println(")")
  347. }
  348. }
  349. private func printBidirectionalStreamingCall() {
  350. self.println(self.method.documentation(streamingType: self.streamType), newline: false)
  351. self.println("///")
  352. self.printClientStreamingDetails()
  353. self.println("///")
  354. self.printParameters()
  355. self.printCallOptionsParameter()
  356. self.printHandlerParameter()
  357. self.println("/// - Returns: A `ClientStreamingCall` with futures for the metadata and status.")
  358. self.printFunction(
  359. name: self.methodFunctionName,
  360. arguments: self.methodArguments,
  361. returnType: self.methodReturnType,
  362. access: self.access
  363. ) {
  364. self.println("return self.makeBidirectionalStreamingCall(")
  365. self.withIndentation {
  366. self.println("path: \(self.methodPathUsingClientMetadata),")
  367. self.println("callOptions: callOptions ?? self.defaultCallOptions,")
  368. self.println(
  369. "interceptors: self.interceptors?.\(self.methodInterceptorFactoryName)() ?? [],"
  370. )
  371. self.println("handler: handler")
  372. }
  373. self.println(")")
  374. }
  375. }
  376. private func printClientStreamingDetails() {
  377. println("/// Callers should use the `send` method on the returned object to send messages")
  378. println(
  379. "/// to the server. The caller should send an `.end` after the final message has been sent."
  380. )
  381. }
  382. private func printParameters() {
  383. println("/// - Parameters:")
  384. }
  385. private func printRequestParameter() {
  386. println("/// - request: Request to send to \(method.name).")
  387. }
  388. private func printCallOptionsParameter() {
  389. println("/// - callOptions: Call options.")
  390. }
  391. private func printHandlerParameter() {
  392. println("/// - handler: A closure called when each response is received from the server.")
  393. }
  394. }
  395. extension Generator {
  396. private func printFakeResponseStreams() {
  397. for method in self.service.methods {
  398. self.println()
  399. self.method = method
  400. switch self.streamType {
  401. case .unary, .clientStreaming:
  402. self.printUnaryResponse()
  403. case .serverStreaming, .bidirectionalStreaming:
  404. self.printStreamingResponse()
  405. }
  406. }
  407. }
  408. private func printUnaryResponse() {
  409. self.printResponseStream(isUnary: true)
  410. self.println()
  411. self.printEnqueueUnaryResponse(isUnary: true)
  412. self.println()
  413. self.printHasResponseStreamEnqueued()
  414. }
  415. private func printStreamingResponse() {
  416. self.printResponseStream(isUnary: false)
  417. self.println()
  418. self.printEnqueueUnaryResponse(isUnary: false)
  419. self.println()
  420. self.printHasResponseStreamEnqueued()
  421. }
  422. private func printEnqueueUnaryResponse(isUnary: Bool) {
  423. let name: String
  424. let responseArg: String
  425. let responseArgAndType: String
  426. if isUnary {
  427. name = "enqueue\(self.method.name)Response"
  428. responseArg = "response"
  429. responseArgAndType = "_ \(responseArg): \(self.methodOutputName)"
  430. } else {
  431. name = "enqueue\(self.method.name)Responses"
  432. responseArg = "responses"
  433. responseArgAndType = "_ \(responseArg): [\(self.methodOutputName)]"
  434. }
  435. self.printFunction(
  436. name: name,
  437. arguments: [
  438. responseArgAndType,
  439. "_ requestHandler: @escaping (FakeRequestPart<\(self.methodInputName)>) -> () = { _ in }",
  440. ],
  441. returnType: nil,
  442. access: self.access
  443. ) {
  444. self.println("let stream = self.make\(self.method.name)ResponseStream(requestHandler)")
  445. if isUnary {
  446. self.println("// This is the only operation on the stream; try! is fine.")
  447. self.println("try! stream.sendMessage(\(responseArg))")
  448. } else {
  449. self.println("// These are the only operation on the stream; try! is fine.")
  450. self.println("\(responseArg).forEach { try! stream.sendMessage($0) }")
  451. self.println("try! stream.sendEnd()")
  452. }
  453. }
  454. }
  455. private func printResponseStream(isUnary: Bool) {
  456. let type = isUnary ? "FakeUnaryResponse" : "FakeStreamingResponse"
  457. let factory = isUnary ? "makeFakeUnaryResponse" : "makeFakeStreamingResponse"
  458. self
  459. .println(
  460. "/// Make a \(isUnary ? "unary" : "streaming") response for the \(self.method.name) RPC. This must be called"
  461. )
  462. self.println("/// before calling '\(self.methodFunctionName)'. See also '\(type)'.")
  463. self.println("///")
  464. self.println("/// - Parameter requestHandler: a handler for request parts sent by the RPC.")
  465. self.printFunction(
  466. name: "make\(self.method.name)ResponseStream",
  467. arguments: [
  468. "_ requestHandler: @escaping (FakeRequestPart<\(self.methodInputName)>) -> () = { _ in }"
  469. ],
  470. returnType: "\(type)<\(self.methodInputName), \(self.methodOutputName)>",
  471. access: self.access
  472. ) {
  473. self
  474. .println(
  475. "return self.fakeChannel.\(factory)(path: \(self.methodPathUsingClientMetadata), requestHandler: requestHandler)"
  476. )
  477. }
  478. }
  479. private func printHasResponseStreamEnqueued() {
  480. self
  481. .println("/// Returns true if there are response streams enqueued for '\(self.method.name)'")
  482. self.println("\(self.access) var has\(self.method.name)ResponsesRemaining: Bool {")
  483. self.withIndentation {
  484. self.println(
  485. "return self.fakeChannel.hasFakeResponseEnqueued(forPath: \(self.methodPathUsingClientMetadata))"
  486. )
  487. }
  488. self.println("}")
  489. }
  490. private func printTestClient() {
  491. self.println("@available(swift, deprecated: 5.6)")
  492. self.println("extension \(self.testClientClassName): @unchecked Sendable {}")
  493. self.println()
  494. self.println(
  495. "@available(swift, deprecated: 5.6, message: \"Test clients are not Sendable "
  496. + "but the 'GRPCClient' API requires clients to be Sendable. Using a localhost client and "
  497. + "server is the recommended alternative.\")"
  498. )
  499. self.println(
  500. "\(self.access) final class \(self.testClientClassName): \(self.clientProtocolName) {"
  501. )
  502. self.withIndentation {
  503. self.println("private let fakeChannel: FakeChannel")
  504. self.println("\(access) var defaultCallOptions: CallOptions")
  505. self.println("\(access) var interceptors: \(clientInterceptorProtocolName)?")
  506. self.println()
  507. self.println("\(self.access) var channel: GRPCChannel {")
  508. self.withIndentation {
  509. self.println("return self.fakeChannel")
  510. }
  511. self.println("}")
  512. self.println()
  513. self.println("\(self.access) init(")
  514. self.withIndentation {
  515. self.println("fakeChannel: FakeChannel = FakeChannel(),")
  516. self.println("defaultCallOptions callOptions: CallOptions = CallOptions(),")
  517. self.println("interceptors: \(clientInterceptorProtocolName)? = nil")
  518. }
  519. self.println(") {")
  520. self.withIndentation {
  521. self.println("self.fakeChannel = fakeChannel")
  522. self.println("self.defaultCallOptions = callOptions")
  523. self.println("self.interceptors = interceptors")
  524. }
  525. self.println("}")
  526. self.printFakeResponseStreams()
  527. }
  528. self.println("}") // end class
  529. }
  530. }
  531. extension Generator {
  532. private var streamType: StreamingType {
  533. return streamingType(self.method)
  534. }
  535. }
  536. extension Generator {
  537. private var methodArguments: [String] {
  538. switch self.streamType {
  539. case .unary:
  540. return [
  541. "_ request: \(self.methodInputName)",
  542. "callOptions: CallOptions? = nil",
  543. ]
  544. case .serverStreaming:
  545. return [
  546. "_ request: \(self.methodInputName)",
  547. "callOptions: CallOptions? = nil",
  548. "handler: @escaping (\(methodOutputName)) -> Void",
  549. ]
  550. case .clientStreaming:
  551. return ["callOptions: CallOptions? = nil"]
  552. case .bidirectionalStreaming:
  553. return [
  554. "callOptions: CallOptions? = nil",
  555. "handler: @escaping (\(methodOutputName)) -> Void",
  556. ]
  557. }
  558. }
  559. private var methodArgumentsWithoutDefaults: [String] {
  560. return self.methodArguments.map { arg in
  561. // Remove default arg from call options.
  562. if arg == "callOptions: CallOptions? = nil" {
  563. return "callOptions: CallOptions?"
  564. } else {
  565. return arg
  566. }
  567. }
  568. }
  569. private var methodArgumentsWithoutCallOptions: [String] {
  570. return self.methodArguments.filter {
  571. !$0.hasPrefix("callOptions: ")
  572. }
  573. }
  574. private var methodReturnType: String {
  575. switch self.streamType {
  576. case .unary:
  577. return "UnaryCall<\(self.methodInputName), \(self.methodOutputName)>"
  578. case .serverStreaming:
  579. return "ServerStreamingCall<\(self.methodInputName), \(self.methodOutputName)>"
  580. case .clientStreaming:
  581. return "ClientStreamingCall<\(self.methodInputName), \(self.methodOutputName)>"
  582. case .bidirectionalStreaming:
  583. return "BidirectionalStreamingCall<\(self.methodInputName), \(self.methodOutputName)>"
  584. }
  585. }
  586. }
  587. extension StreamingType {
  588. fileprivate var name: String {
  589. switch self {
  590. case .unary:
  591. return "Unary"
  592. case .clientStreaming:
  593. return "Client streaming"
  594. case .serverStreaming:
  595. return "Server streaming"
  596. case .bidirectionalStreaming:
  597. return "Bidirectional streaming"
  598. }
  599. }
  600. }
  601. extension MethodDescriptor {
  602. var documentation: String? {
  603. let comments = self.protoSourceComments(commentPrefix: "")
  604. return comments.isEmpty ? nil : comments
  605. }
  606. fileprivate func documentation(streamingType: StreamingType) -> String {
  607. let sourceComments = self.protoSourceComments()
  608. if sourceComments.isEmpty {
  609. return "/// \(streamingType.name) call to \(self.name)\n" // comments end with "\n" already.
  610. } else {
  611. return sourceComments // already prefixed with "///"
  612. }
  613. }
  614. }
  615. extension Array {
  616. /// Like `forEach` except that the `body` closure operates on all elements except for the last,
  617. /// and the `last` closure only operates on the last element.
  618. fileprivate func forEach(beforeLast body: (Element) -> Void, onLast last: (Element) -> Void) {
  619. for element in self.dropLast() {
  620. body(element)
  621. }
  622. if let lastElement = self.last {
  623. last(lastElement)
  624. }
  625. }
  626. }