TextBasedRenderer.swift 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163
  1. /*
  2. * Copyright 2023, 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. //===----------------------------------------------------------------------===//
  17. //
  18. // This source file is part of the SwiftOpenAPIGenerator open source project
  19. //
  20. // Copyright (c) 2023 Apple Inc. and the SwiftOpenAPIGenerator project authors
  21. // Licensed under Apache License v2.0
  22. //
  23. // See LICENSE.txt for license information
  24. // See CONTRIBUTORS.txt for the list of SwiftOpenAPIGenerator project authors
  25. //
  26. // SPDX-License-Identifier: Apache-2.0
  27. //
  28. //===----------------------------------------------------------------------===//
  29. import Foundation
  30. /// An object for building up a generated file line-by-line.
  31. ///
  32. /// After creation, make calls such as `writeLine` to build up the file,
  33. /// and call `rendered` at the end to get the full file contents.
  34. final class StringCodeWriter {
  35. /// The stored lines of code.
  36. private var lines: [String]
  37. /// The current nesting level.
  38. private var level: Int
  39. /// The indentation for each level as the number of spaces.
  40. internal let indentation: Int
  41. /// Whether the next call to `writeLine` will continue writing to the last
  42. /// stored line. Otherwise a new line is appended.
  43. private var nextWriteAppendsToLastLine: Bool = false
  44. /// Creates a new empty writer.
  45. init(indentation: Int) {
  46. self.level = 0
  47. self.lines = []
  48. self.indentation = indentation
  49. }
  50. /// Concatenates the stored lines of code into a single string.
  51. /// - Returns: The contents of the full file in a single string.
  52. func rendered() -> String { lines.joined(separator: "\n") }
  53. /// Writes a line of code.
  54. ///
  55. /// By default, a new line is appended to the file.
  56. ///
  57. /// To continue the last line, make a call to `nextLineAppendsToLastLine`
  58. /// before calling `writeLine`.
  59. /// - Parameter line: The contents of the line to write.
  60. func writeLine(_ line: String) {
  61. let newLine: String
  62. if nextWriteAppendsToLastLine && !lines.isEmpty {
  63. let existingLine = lines.removeLast()
  64. newLine = existingLine + line
  65. } else {
  66. let indentation = Array(repeating: " ", count: self.indentation * level).joined()
  67. newLine = indentation + line
  68. }
  69. lines.append(newLine)
  70. nextWriteAppendsToLastLine = false
  71. }
  72. /// Increases the indentation level by 1.
  73. func push() { level += 1 }
  74. /// Decreases the indentation level by 1.
  75. /// - Precondition: Current level must be greater than 0.
  76. func pop() {
  77. precondition(level > 0, "Cannot pop below 0")
  78. level -= 1
  79. }
  80. /// Executes the provided closure with one level deeper indentation.
  81. /// - Parameter work: The closure to execute.
  82. /// - Returns: The result of the closure execution.
  83. func withNestedLevel<R>(_ work: () -> R) -> R {
  84. push()
  85. defer { pop() }
  86. return work()
  87. }
  88. /// Sets a flag on the writer so that the next call to `writeLine` continues
  89. /// the last stored line instead of starting a new line.
  90. ///
  91. /// Safe to call repeatedly, it gets reset by `writeLine`.
  92. func nextLineAppendsToLastLine() { nextWriteAppendsToLastLine = true }
  93. }
  94. @available(*, unavailable)
  95. extension TextBasedRenderer: Sendable {}
  96. /// A renderer that uses string interpolation and concatenation
  97. /// to convert the provided structure code into raw string form.
  98. struct TextBasedRenderer: RendererProtocol {
  99. func render(
  100. structured: StructuredSwiftRepresentation
  101. ) throws
  102. -> SourceFile
  103. {
  104. let namedFile = structured.file
  105. renderFile(namedFile.contents)
  106. let string = writer.rendered()
  107. return SourceFile(name: namedFile.name, contents: string)
  108. }
  109. /// The underlying writer.
  110. private let writer: StringCodeWriter
  111. /// Creates a new empty renderer.
  112. static var `default`: TextBasedRenderer { .init(indentation: 4) }
  113. init(indentation: Int) {
  114. self.writer = StringCodeWriter(indentation: indentation)
  115. }
  116. // MARK: - Internals
  117. /// Returns the current contents of the writer as a string.
  118. func renderedContents() -> String { writer.rendered() }
  119. /// Renders the specified Swift file.
  120. func renderFile(_ description: FileDescription) {
  121. if let topComment = description.topComment {
  122. renderComment(topComment)
  123. writer.writeLine("")
  124. }
  125. if let imports = description.imports {
  126. renderImports(imports)
  127. writer.writeLine("")
  128. }
  129. for (codeBlock, isLast) in description.codeBlocks.enumeratedWithLastMarker() {
  130. renderCodeBlock(codeBlock)
  131. if !isLast {
  132. writer.writeLine("")
  133. }
  134. }
  135. }
  136. /// Renders the specified comment.
  137. func renderComment(_ comment: Comment) {
  138. let prefix: String
  139. let commentString: String
  140. switch comment {
  141. case .inline(let string):
  142. prefix = "//"
  143. commentString = string
  144. case .doc(let string):
  145. prefix = "///"
  146. commentString = string
  147. case .mark(let string, sectionBreak: true):
  148. prefix = "// MARK: -"
  149. commentString = string
  150. case .mark(let string, sectionBreak: false):
  151. prefix = "// MARK:"
  152. commentString = string
  153. case .preFormatted(let string):
  154. prefix = ""
  155. commentString = string
  156. }
  157. let lines = commentString.transformingLines { line, isLast in
  158. // The last line of a comment that is blank should be dropped.
  159. // Pre formatted documentation might contain such lines.
  160. if line.isEmpty && prefix.isEmpty && isLast {
  161. return nil
  162. } else {
  163. let formattedPrefix = !prefix.isEmpty && !line.isEmpty ? "\(prefix) " : prefix
  164. return "\(formattedPrefix)\(line)"
  165. }
  166. }
  167. lines.forEach(writer.writeLine)
  168. }
  169. /// Renders the specified import statements.
  170. func renderImports(_ imports: [ImportDescription]?) { (imports ?? []).forEach(renderImport) }
  171. /// Renders a single import statement.
  172. func renderImport(_ description: ImportDescription) {
  173. func render(preconcurrency: Bool) {
  174. let spiPrefix = description.spi.map { "@_spi(\($0)) " } ?? ""
  175. let preconcurrencyPrefix = preconcurrency ? "@preconcurrency " : ""
  176. if let item = description.item {
  177. writer.writeLine(
  178. "\(preconcurrencyPrefix)\(spiPrefix)import \(item.kind) \(description.moduleName).\(item.name)"
  179. )
  180. } else if let moduleTypes = description.moduleTypes {
  181. for type in moduleTypes {
  182. writer.writeLine("\(preconcurrencyPrefix)\(spiPrefix)import \(type)")
  183. }
  184. } else {
  185. writer.writeLine("\(preconcurrencyPrefix)\(spiPrefix)import \(description.moduleName)")
  186. }
  187. }
  188. switch description.preconcurrency {
  189. case .always: render(preconcurrency: true)
  190. case .never: render(preconcurrency: false)
  191. case .onOS(let operatingSystems):
  192. writer.writeLine("#if \(operatingSystems.map { "os(\($0))" }.joined(separator: " || "))")
  193. render(preconcurrency: true)
  194. writer.writeLine("#else")
  195. render(preconcurrency: false)
  196. writer.writeLine("#endif")
  197. }
  198. }
  199. /// Renders the specified access modifier.
  200. func renderedAccessModifier(_ accessModifier: AccessModifier) -> String {
  201. switch accessModifier {
  202. case .public: return "public"
  203. case .package: return "package"
  204. case .internal: return "internal"
  205. case .fileprivate: return "fileprivate"
  206. case .private: return "private"
  207. }
  208. }
  209. /// Renders the specified identifier.
  210. func renderIdentifier(_ identifier: IdentifierDescription) {
  211. switch identifier {
  212. case .pattern(let string): writer.writeLine(string)
  213. case .type(let existingTypeDescription):
  214. renderExistingTypeDescription(existingTypeDescription)
  215. }
  216. }
  217. /// Renders the specified member access expression.
  218. func renderMemberAccess(_ memberAccess: MemberAccessDescription) {
  219. if let left = memberAccess.left {
  220. renderExpression(left)
  221. writer.nextLineAppendsToLastLine()
  222. }
  223. writer.writeLine(".\(memberAccess.right)")
  224. }
  225. /// Renders the specified function call argument.
  226. func renderFunctionCallArgument(_ arg: FunctionArgumentDescription) {
  227. if let left = arg.label {
  228. writer.writeLine("\(left): ")
  229. writer.nextLineAppendsToLastLine()
  230. }
  231. renderExpression(arg.expression)
  232. }
  233. /// Renders the specified function call.
  234. func renderFunctionCall(_ functionCall: FunctionCallDescription) {
  235. renderExpression(functionCall.calledExpression)
  236. writer.nextLineAppendsToLastLine()
  237. writer.writeLine("(")
  238. let arguments = functionCall.arguments
  239. if arguments.count > 1 {
  240. writer.withNestedLevel {
  241. for (argument, isLast) in arguments.enumeratedWithLastMarker() {
  242. renderFunctionCallArgument(argument)
  243. if !isLast {
  244. writer.nextLineAppendsToLastLine()
  245. writer.writeLine(",")
  246. }
  247. }
  248. }
  249. } else {
  250. writer.nextLineAppendsToLastLine()
  251. if let argument = arguments.first { renderFunctionCallArgument(argument) }
  252. writer.nextLineAppendsToLastLine()
  253. }
  254. writer.writeLine(")")
  255. if let trailingClosure = functionCall.trailingClosure {
  256. writer.nextLineAppendsToLastLine()
  257. writer.writeLine(" ")
  258. renderClosureInvocation(trailingClosure)
  259. }
  260. }
  261. /// Renders the specified assignment expression.
  262. func renderAssignment(_ assignment: AssignmentDescription) {
  263. renderExpression(assignment.left)
  264. writer.nextLineAppendsToLastLine()
  265. writer.writeLine(" = ")
  266. writer.nextLineAppendsToLastLine()
  267. renderExpression(assignment.right)
  268. }
  269. /// Renders the specified switch case kind.
  270. func renderSwitchCaseKind(_ kind: SwitchCaseKind) {
  271. switch kind {
  272. case let .`case`(expression, associatedValueNames):
  273. let associatedValues: String
  274. let maybeLet: String
  275. if !associatedValueNames.isEmpty {
  276. associatedValues = "(" + associatedValueNames.joined(separator: ", ") + ")"
  277. maybeLet = "let "
  278. } else {
  279. associatedValues = ""
  280. maybeLet = ""
  281. }
  282. writer.writeLine("case \(maybeLet)")
  283. writer.nextLineAppendsToLastLine()
  284. renderExpression(expression)
  285. writer.nextLineAppendsToLastLine()
  286. writer.writeLine(associatedValues)
  287. case .multiCase(let expressions):
  288. writer.writeLine("case ")
  289. writer.nextLineAppendsToLastLine()
  290. for (expression, isLast) in expressions.enumeratedWithLastMarker() {
  291. renderExpression(expression)
  292. writer.nextLineAppendsToLastLine()
  293. if !isLast { writer.writeLine(", ") }
  294. writer.nextLineAppendsToLastLine()
  295. }
  296. case .`default`: writer.writeLine("default")
  297. }
  298. }
  299. /// Renders the specified switch case.
  300. func renderSwitchCase(_ switchCase: SwitchCaseDescription) {
  301. renderSwitchCaseKind(switchCase.kind)
  302. writer.nextLineAppendsToLastLine()
  303. writer.writeLine(":")
  304. writer.withNestedLevel { renderCodeBlocks(switchCase.body) }
  305. }
  306. /// Renders the specified switch expression.
  307. func renderSwitch(_ switchDesc: SwitchDescription) {
  308. writer.writeLine("switch ")
  309. writer.nextLineAppendsToLastLine()
  310. renderExpression(switchDesc.switchedExpression)
  311. writer.nextLineAppendsToLastLine()
  312. writer.writeLine(" {")
  313. for caseDesc in switchDesc.cases { renderSwitchCase(caseDesc) }
  314. writer.writeLine("}")
  315. }
  316. /// Renders the specified if statement.
  317. func renderIf(_ ifDesc: IfStatementDescription) {
  318. let ifBranch = ifDesc.ifBranch
  319. writer.writeLine("if ")
  320. writer.nextLineAppendsToLastLine()
  321. renderExpression(ifBranch.condition)
  322. writer.nextLineAppendsToLastLine()
  323. writer.writeLine(" {")
  324. writer.withNestedLevel { renderCodeBlocks(ifBranch.body) }
  325. writer.writeLine("}")
  326. for branch in ifDesc.elseIfBranches {
  327. writer.nextLineAppendsToLastLine()
  328. writer.writeLine(" else if ")
  329. writer.nextLineAppendsToLastLine()
  330. renderExpression(branch.condition)
  331. writer.nextLineAppendsToLastLine()
  332. writer.writeLine(" {")
  333. writer.withNestedLevel { renderCodeBlocks(branch.body) }
  334. writer.writeLine("}")
  335. }
  336. if let elseBody = ifDesc.elseBody {
  337. writer.nextLineAppendsToLastLine()
  338. writer.writeLine(" else {")
  339. writer.withNestedLevel { renderCodeBlocks(elseBody) }
  340. writer.writeLine("}")
  341. }
  342. }
  343. /// Renders the specified switch expression.
  344. func renderDoStatement(_ description: DoStatementDescription) {
  345. writer.writeLine("do {")
  346. writer.withNestedLevel { renderCodeBlocks(description.doStatement) }
  347. if let catchBody = description.catchBody {
  348. writer.writeLine("} catch {")
  349. if !catchBody.isEmpty {
  350. writer.withNestedLevel { renderCodeBlocks(catchBody) }
  351. } else {
  352. writer.nextLineAppendsToLastLine()
  353. }
  354. }
  355. writer.writeLine("}")
  356. }
  357. /// Renders the specified value binding expression.
  358. func renderValueBinding(_ valueBinding: ValueBindingDescription) {
  359. writer.writeLine("\(renderedBindingKind(valueBinding.kind)) ")
  360. writer.nextLineAppendsToLastLine()
  361. renderFunctionCall(valueBinding.value)
  362. }
  363. /// Renders the specified keyword.
  364. func renderedKeywordKind(_ kind: KeywordKind) -> String {
  365. switch kind {
  366. case .return: return "return"
  367. case .try(hasPostfixQuestionMark: let hasPostfixQuestionMark):
  368. return "try\(hasPostfixQuestionMark ? "?" : "")"
  369. case .await: return "await"
  370. case .throw: return "throw"
  371. case .yield: return "yield"
  372. }
  373. }
  374. /// Renders the specified unary keyword expression.
  375. func renderUnaryKeywordExpression(_ expression: UnaryKeywordDescription) {
  376. writer.writeLine(renderedKeywordKind(expression.kind))
  377. guard let expr = expression.expression else { return }
  378. writer.nextLineAppendsToLastLine()
  379. writer.writeLine(" ")
  380. writer.nextLineAppendsToLastLine()
  381. renderExpression(expr)
  382. }
  383. /// Renders the specified closure invocation.
  384. func renderClosureInvocation(_ invocation: ClosureInvocationDescription) {
  385. writer.writeLine("{")
  386. if !invocation.argumentNames.isEmpty {
  387. writer.nextLineAppendsToLastLine()
  388. writer.writeLine(" \(invocation.argumentNames.joined(separator: ", ")) in")
  389. }
  390. if let body = invocation.body { writer.withNestedLevel { renderCodeBlocks(body) } }
  391. writer.writeLine("}")
  392. }
  393. /// Renders the specified binary operator.
  394. func renderedBinaryOperator(_ op: BinaryOperator) -> String { op.rawValue }
  395. /// Renders the specified binary operation.
  396. func renderBinaryOperation(_ operation: BinaryOperationDescription) {
  397. renderExpression(operation.left)
  398. writer.nextLineAppendsToLastLine()
  399. writer.writeLine(" \(renderedBinaryOperator(operation.operation)) ")
  400. writer.nextLineAppendsToLastLine()
  401. renderExpression(operation.right)
  402. }
  403. /// Renders the specified inout expression.
  404. func renderInOutDescription(_ description: InOutDescription) {
  405. writer.writeLine("&")
  406. writer.nextLineAppendsToLastLine()
  407. renderExpression(description.referencedExpr)
  408. }
  409. /// Renders the specified optional chaining expression.
  410. func renderOptionalChainingDescription(_ description: OptionalChainingDescription) {
  411. renderExpression(description.referencedExpr)
  412. writer.nextLineAppendsToLastLine()
  413. writer.writeLine("?")
  414. }
  415. /// Renders the specified tuple expression.
  416. func renderTupleDescription(_ description: TupleDescription) {
  417. writer.writeLine("(")
  418. writer.nextLineAppendsToLastLine()
  419. let members = description.members
  420. for (member, isLast) in members.enumeratedWithLastMarker() {
  421. renderExpression(member)
  422. if !isLast {
  423. writer.nextLineAppendsToLastLine()
  424. writer.writeLine(", ")
  425. }
  426. writer.nextLineAppendsToLastLine()
  427. }
  428. writer.writeLine(")")
  429. }
  430. /// Renders the specified expression.
  431. func renderExpression(_ expression: Expression) {
  432. switch expression {
  433. case .literal(let literalDescription): renderLiteral(literalDescription)
  434. case .identifier(let identifierDescription):
  435. renderIdentifier(identifierDescription)
  436. case .memberAccess(let memberAccessDescription): renderMemberAccess(memberAccessDescription)
  437. case .functionCall(let functionCallDescription): renderFunctionCall(functionCallDescription)
  438. case .assignment(let assignment): renderAssignment(assignment)
  439. case .switch(let switchDesc): renderSwitch(switchDesc)
  440. case .ifStatement(let ifDesc): renderIf(ifDesc)
  441. case .doStatement(let doStmt): renderDoStatement(doStmt)
  442. case .valueBinding(let valueBinding): renderValueBinding(valueBinding)
  443. case .unaryKeyword(let unaryKeyword): renderUnaryKeywordExpression(unaryKeyword)
  444. case .closureInvocation(let closureInvocation): renderClosureInvocation(closureInvocation)
  445. case .binaryOperation(let binaryOperation): renderBinaryOperation(binaryOperation)
  446. case .inOut(let inOut): renderInOutDescription(inOut)
  447. case .optionalChaining(let optionalChaining):
  448. renderOptionalChainingDescription(optionalChaining)
  449. case .tuple(let tuple): renderTupleDescription(tuple)
  450. }
  451. }
  452. /// Renders the specified literal expression.
  453. func renderLiteral(_ literal: LiteralDescription) {
  454. func write(_ string: String) { writer.writeLine(string) }
  455. switch literal {
  456. case let .string(string):
  457. // Use a raw literal if the string contains a quote/backslash.
  458. if string.contains("\"") || string.contains("\\") {
  459. write("#\"\(string)\"#")
  460. } else {
  461. write("\"\(string)\"")
  462. }
  463. case let .int(int): write("\(int)")
  464. case let .bool(bool): write(bool ? "true" : "false")
  465. case .nil: write("nil")
  466. case .array(let items):
  467. writer.writeLine("[")
  468. if !items.isEmpty {
  469. writer.withNestedLevel {
  470. for (item, isLast) in items.enumeratedWithLastMarker() {
  471. renderExpression(item)
  472. if !isLast {
  473. writer.nextLineAppendsToLastLine()
  474. writer.writeLine(",")
  475. }
  476. }
  477. }
  478. } else {
  479. writer.nextLineAppendsToLastLine()
  480. }
  481. writer.writeLine("]")
  482. }
  483. }
  484. /// Renders the specified where clause requirement.
  485. func renderedWhereClauseRequirement(_ requirement: WhereClauseRequirement) -> String {
  486. switch requirement {
  487. case .conformance(let left, let right): return "\(left): \(right)"
  488. }
  489. }
  490. /// Renders the specified where clause.
  491. func renderedWhereClause(_ clause: WhereClause) -> String {
  492. let renderedRequirements = clause.requirements.map(renderedWhereClauseRequirement)
  493. return "where \(renderedRequirements.joined(separator: ", "))"
  494. }
  495. /// Renders the specified extension declaration.
  496. func renderExtension(_ extensionDescription: ExtensionDescription) {
  497. if let accessModifier = extensionDescription.accessModifier {
  498. writer.writeLine(renderedAccessModifier(accessModifier) + " ")
  499. writer.nextLineAppendsToLastLine()
  500. }
  501. writer.writeLine("extension \(extensionDescription.onType)")
  502. writer.nextLineAppendsToLastLine()
  503. if !extensionDescription.conformances.isEmpty {
  504. writer.writeLine(": \(extensionDescription.conformances.joined(separator: ", "))")
  505. writer.nextLineAppendsToLastLine()
  506. }
  507. if let whereClause = extensionDescription.whereClause {
  508. writer.writeLine(" " + renderedWhereClause(whereClause))
  509. writer.nextLineAppendsToLastLine()
  510. }
  511. writer.writeLine(" {")
  512. for (declaration, isLast) in extensionDescription.declarations.enumeratedWithLastMarker() {
  513. writer.withNestedLevel {
  514. renderDeclaration(declaration)
  515. if !isLast {
  516. writer.writeLine("")
  517. }
  518. }
  519. }
  520. writer.writeLine("}")
  521. }
  522. /// Renders the specified type reference to an existing type.
  523. func renderExistingTypeDescription(_ type: ExistingTypeDescription) {
  524. switch type {
  525. case .any(let existingTypeDescription):
  526. writer.writeLine("any ")
  527. writer.nextLineAppendsToLastLine()
  528. renderExistingTypeDescription(existingTypeDescription)
  529. case .generic(let wrapper, let wrapped):
  530. renderExistingTypeDescription(wrapper)
  531. writer.nextLineAppendsToLastLine()
  532. writer.writeLine("<")
  533. writer.nextLineAppendsToLastLine()
  534. renderExistingTypeDescription(wrapped)
  535. writer.nextLineAppendsToLastLine()
  536. writer.writeLine(">")
  537. case .optional(let existingTypeDescription):
  538. renderExistingTypeDescription(existingTypeDescription)
  539. writer.nextLineAppendsToLastLine()
  540. writer.writeLine("?")
  541. case .member(let components):
  542. writer.writeLine(components.joined(separator: "."))
  543. case .array(let existingTypeDescription):
  544. writer.writeLine("[")
  545. writer.nextLineAppendsToLastLine()
  546. renderExistingTypeDescription(existingTypeDescription)
  547. writer.nextLineAppendsToLastLine()
  548. writer.writeLine("]")
  549. case .dictionaryValue(let existingTypeDescription):
  550. writer.writeLine("[String: ")
  551. writer.nextLineAppendsToLastLine()
  552. renderExistingTypeDescription(existingTypeDescription)
  553. writer.nextLineAppendsToLastLine()
  554. writer.writeLine("]")
  555. case .some(let existingTypeDescription):
  556. writer.writeLine("some ")
  557. writer.nextLineAppendsToLastLine()
  558. renderExistingTypeDescription(existingTypeDescription)
  559. case .closure(let closureSignatureDescription):
  560. renderClosureSignature(closureSignatureDescription)
  561. }
  562. }
  563. /// Renders the specified typealias declaration.
  564. func renderTypealias(_ alias: TypealiasDescription) {
  565. var words: [String] = []
  566. if let accessModifier = alias.accessModifier {
  567. words.append(renderedAccessModifier(accessModifier))
  568. }
  569. words.append(contentsOf: [
  570. "typealias", alias.name, "=",
  571. ])
  572. writer.writeLine(words.joinedWords() + " ")
  573. writer.nextLineAppendsToLastLine()
  574. renderExistingTypeDescription(alias.existingType)
  575. }
  576. /// Renders the specified binding kind.
  577. func renderedBindingKind(_ kind: BindingKind) -> String {
  578. switch kind {
  579. case .var: return "var"
  580. case .let: return "let"
  581. }
  582. }
  583. /// Renders the specified variable declaration.
  584. func renderVariable(_ variable: VariableDescription) {
  585. do {
  586. if let accessModifier = variable.accessModifier {
  587. writer.writeLine(renderedAccessModifier(accessModifier) + " ")
  588. writer.nextLineAppendsToLastLine()
  589. }
  590. if variable.isStatic {
  591. writer.writeLine("static ")
  592. writer.nextLineAppendsToLastLine()
  593. }
  594. writer.writeLine(renderedBindingKind(variable.kind) + " ")
  595. writer.nextLineAppendsToLastLine()
  596. renderExpression(variable.left)
  597. if let type = variable.type {
  598. writer.nextLineAppendsToLastLine()
  599. writer.writeLine(": ")
  600. writer.nextLineAppendsToLastLine()
  601. renderExistingTypeDescription(type)
  602. }
  603. }
  604. if let right = variable.right {
  605. writer.nextLineAppendsToLastLine()
  606. writer.writeLine(" = ")
  607. writer.nextLineAppendsToLastLine()
  608. renderExpression(right)
  609. }
  610. if let body = variable.getter {
  611. writer.nextLineAppendsToLastLine()
  612. writer.writeLine(" {")
  613. writer.withNestedLevel {
  614. let hasExplicitGetter =
  615. !variable.getterEffects.isEmpty || variable.setter != nil || variable.modify != nil
  616. if hasExplicitGetter {
  617. let keywords = variable.getterEffects.map(renderedFunctionKeyword).joined(separator: " ")
  618. let line = "get \(keywords) {"
  619. writer.writeLine(line)
  620. writer.push()
  621. }
  622. renderCodeBlocks(body)
  623. if hasExplicitGetter {
  624. writer.pop()
  625. writer.writeLine("}")
  626. }
  627. if let modify = variable.modify {
  628. writer.writeLine("_modify {")
  629. writer.withNestedLevel { renderCodeBlocks(modify) }
  630. writer.writeLine("}")
  631. }
  632. if let setter = variable.setter {
  633. writer.writeLine("set {")
  634. writer.withNestedLevel { renderCodeBlocks(setter) }
  635. writer.writeLine("}")
  636. }
  637. }
  638. writer.writeLine("}")
  639. }
  640. }
  641. /// Renders the specified struct declaration.
  642. func renderStruct(_ structDesc: StructDescription) {
  643. if let accessModifier = structDesc.accessModifier {
  644. writer.writeLine(renderedAccessModifier(accessModifier) + " ")
  645. writer.nextLineAppendsToLastLine()
  646. }
  647. writer.writeLine("struct \(structDesc.name)")
  648. writer.nextLineAppendsToLastLine()
  649. if !structDesc.conformances.isEmpty {
  650. writer.writeLine(": \(structDesc.conformances.joined(separator: ", "))")
  651. writer.nextLineAppendsToLastLine()
  652. }
  653. writer.writeLine(" {")
  654. if !structDesc.members.isEmpty {
  655. writer.withNestedLevel {
  656. for (member, isLast) in structDesc.members.enumeratedWithLastMarker() {
  657. renderDeclaration(member)
  658. if !isLast {
  659. writer.writeLine("")
  660. }
  661. }
  662. }
  663. } else {
  664. writer.nextLineAppendsToLastLine()
  665. }
  666. writer.writeLine("}")
  667. }
  668. /// Renders the specified protocol declaration.
  669. func renderProtocol(_ protocolDesc: ProtocolDescription) {
  670. if let accessModifier = protocolDesc.accessModifier {
  671. writer.writeLine("\(renderedAccessModifier(accessModifier)) ")
  672. writer.nextLineAppendsToLastLine()
  673. }
  674. writer.writeLine("protocol \(protocolDesc.name)")
  675. writer.nextLineAppendsToLastLine()
  676. if !protocolDesc.conformances.isEmpty {
  677. let conformances = protocolDesc.conformances.joined(separator: ", ")
  678. writer.writeLine(": \(conformances)")
  679. writer.nextLineAppendsToLastLine()
  680. }
  681. writer.writeLine(" {")
  682. if !protocolDesc.members.isEmpty {
  683. writer.withNestedLevel {
  684. for (member, isLast) in protocolDesc.members.enumeratedWithLastMarker() {
  685. renderDeclaration(member)
  686. if !isLast {
  687. writer.writeLine("")
  688. }
  689. }
  690. }
  691. } else {
  692. writer.nextLineAppendsToLastLine()
  693. }
  694. writer.writeLine("}")
  695. }
  696. /// Renders the specified enum declaration.
  697. func renderEnum(_ enumDesc: EnumDescription) {
  698. if enumDesc.isFrozen {
  699. writer.writeLine("@frozen ")
  700. writer.nextLineAppendsToLastLine()
  701. }
  702. if let accessModifier = enumDesc.accessModifier {
  703. writer.writeLine("\(renderedAccessModifier(accessModifier)) ")
  704. writer.nextLineAppendsToLastLine()
  705. }
  706. if enumDesc.isIndirect {
  707. writer.writeLine("indirect ")
  708. writer.nextLineAppendsToLastLine()
  709. }
  710. writer.writeLine("enum \(enumDesc.name)")
  711. writer.nextLineAppendsToLastLine()
  712. if !enumDesc.conformances.isEmpty {
  713. writer.writeLine(": \(enumDesc.conformances.joined(separator: ", "))")
  714. writer.nextLineAppendsToLastLine()
  715. }
  716. writer.writeLine(" {")
  717. if !enumDesc.members.isEmpty {
  718. writer.withNestedLevel { for member in enumDesc.members { renderDeclaration(member) } }
  719. } else {
  720. writer.nextLineAppendsToLastLine()
  721. }
  722. writer.writeLine("}")
  723. }
  724. /// Renders the specified enum case associated value.
  725. func renderEnumCaseAssociatedValue(_ value: EnumCaseAssociatedValueDescription) {
  726. var words: [String] = []
  727. if let label = value.label { words.append(label + ":") }
  728. writer.writeLine(words.joinedWords())
  729. writer.nextLineAppendsToLastLine()
  730. renderExistingTypeDescription(value.type)
  731. }
  732. /// Renders the specified enum case declaration.
  733. func renderEnumCase(_ enumCase: EnumCaseDescription) {
  734. writer.writeLine("case \(enumCase.name)")
  735. switch enumCase.kind {
  736. case .nameOnly: break
  737. case .nameWithRawValue(let rawValue):
  738. writer.nextLineAppendsToLastLine()
  739. writer.writeLine(" = ")
  740. writer.nextLineAppendsToLastLine()
  741. renderLiteral(rawValue)
  742. case .nameWithAssociatedValues(let values):
  743. if values.isEmpty { break }
  744. for (value, isLast) in values.enumeratedWithLastMarker() {
  745. renderEnumCaseAssociatedValue(value)
  746. if !isLast {
  747. writer.nextLineAppendsToLastLine()
  748. writer.writeLine(", ")
  749. }
  750. }
  751. }
  752. }
  753. /// Renders the specified declaration.
  754. func renderDeclaration(_ declaration: Declaration) {
  755. switch declaration {
  756. case let .commentable(comment, nestedDeclaration):
  757. renderCommentableDeclaration(comment: comment, declaration: nestedDeclaration)
  758. case let .deprecated(deprecation, nestedDeclaration):
  759. renderDeprecatedDeclaration(deprecation: deprecation, declaration: nestedDeclaration)
  760. case let .guarded(availability, nestedDeclaration):
  761. renderGuardedDeclaration(availability: availability, declaration: nestedDeclaration)
  762. case .variable(let variableDescription): renderVariable(variableDescription)
  763. case .extension(let extensionDescription): renderExtension(extensionDescription)
  764. case .struct(let structDescription): renderStruct(structDescription)
  765. case .protocol(let protocolDescription): renderProtocol(protocolDescription)
  766. case .enum(let enumDescription): renderEnum(enumDescription)
  767. case .typealias(let typealiasDescription): renderTypealias(typealiasDescription)
  768. case .function(let functionDescription): renderFunction(functionDescription)
  769. case .enumCase(let enumCase): renderEnumCase(enumCase)
  770. }
  771. }
  772. /// Renders the specified function kind.
  773. func renderedFunctionKind(_ functionKind: FunctionKind) -> String {
  774. switch functionKind {
  775. case .initializer(let isFailable): return "init\(isFailable ? "?" : "")"
  776. case .function(let name, let isStatic):
  777. return (isStatic ? "static " : "") + "func \(name)"
  778. }
  779. }
  780. /// Renders the specified function keyword.
  781. func renderedFunctionKeyword(_ keyword: FunctionKeyword) -> String {
  782. switch keyword {
  783. case .throws: return "throws"
  784. case .async: return "async"
  785. case .rethrows: return "rethrows"
  786. }
  787. }
  788. /// Renders the specified function signature.
  789. func renderClosureSignature(_ signature: ClosureSignatureDescription) {
  790. if signature.sendable {
  791. writer.writeLine("@Sendable ")
  792. writer.nextLineAppendsToLastLine()
  793. }
  794. if signature.escaping {
  795. writer.writeLine("@escaping ")
  796. writer.nextLineAppendsToLastLine()
  797. }
  798. writer.writeLine("(")
  799. let parameters = signature.parameters
  800. let separateLines = parameters.count > 1
  801. if separateLines {
  802. writer.withNestedLevel {
  803. for (parameter, isLast) in signature.parameters.enumeratedWithLastMarker() {
  804. renderClosureParameter(parameter)
  805. if !isLast {
  806. writer.nextLineAppendsToLastLine()
  807. writer.writeLine(",")
  808. }
  809. }
  810. }
  811. } else {
  812. writer.nextLineAppendsToLastLine()
  813. if let parameter = parameters.first {
  814. renderClosureParameter(parameter)
  815. writer.nextLineAppendsToLastLine()
  816. }
  817. }
  818. writer.writeLine(")")
  819. let keywords = signature.keywords
  820. for keyword in keywords {
  821. writer.nextLineAppendsToLastLine()
  822. writer.writeLine(" " + renderedFunctionKeyword(keyword))
  823. }
  824. if let returnType = signature.returnType {
  825. writer.nextLineAppendsToLastLine()
  826. writer.writeLine(" -> ")
  827. writer.nextLineAppendsToLastLine()
  828. renderExpression(returnType)
  829. }
  830. }
  831. /// Renders the specified function signature.
  832. func renderFunctionSignature(_ signature: FunctionSignatureDescription) {
  833. do {
  834. if let accessModifier = signature.accessModifier {
  835. writer.writeLine(renderedAccessModifier(accessModifier) + " ")
  836. writer.nextLineAppendsToLastLine()
  837. }
  838. let generics = signature.generics
  839. writer.writeLine(
  840. renderedFunctionKind(signature.kind)
  841. )
  842. if !generics.isEmpty {
  843. writer.nextLineAppendsToLastLine()
  844. writer.writeLine("<")
  845. for (genericType, isLast) in generics.enumeratedWithLastMarker() {
  846. writer.nextLineAppendsToLastLine()
  847. renderExistingTypeDescription(genericType)
  848. if !isLast {
  849. writer.nextLineAppendsToLastLine()
  850. writer.writeLine(", ")
  851. }
  852. }
  853. writer.nextLineAppendsToLastLine()
  854. writer.writeLine(">")
  855. }
  856. writer.nextLineAppendsToLastLine()
  857. writer.writeLine("(")
  858. let parameters = signature.parameters
  859. let separateLines = parameters.count > 1
  860. if separateLines {
  861. writer.withNestedLevel {
  862. for (parameter, isLast) in signature.parameters.enumeratedWithLastMarker() {
  863. renderParameter(parameter)
  864. if !isLast {
  865. writer.nextLineAppendsToLastLine()
  866. writer.writeLine(",")
  867. }
  868. }
  869. }
  870. } else {
  871. writer.nextLineAppendsToLastLine()
  872. if let parameter = parameters.first { renderParameter(parameter) }
  873. writer.nextLineAppendsToLastLine()
  874. }
  875. writer.writeLine(")")
  876. }
  877. do {
  878. let keywords = signature.keywords
  879. if !keywords.isEmpty {
  880. for keyword in keywords {
  881. writer.nextLineAppendsToLastLine()
  882. writer.writeLine(" " + renderedFunctionKeyword(keyword))
  883. }
  884. }
  885. }
  886. if let returnType = signature.returnType {
  887. writer.nextLineAppendsToLastLine()
  888. writer.writeLine(" -> ")
  889. writer.nextLineAppendsToLastLine()
  890. renderExpression(returnType)
  891. }
  892. if let whereClause = signature.whereClause {
  893. writer.nextLineAppendsToLastLine()
  894. writer.writeLine(" " + renderedWhereClause(whereClause))
  895. }
  896. }
  897. /// Renders the specified function declaration.
  898. func renderFunction(_ functionDescription: FunctionDescription) {
  899. renderFunctionSignature(functionDescription.signature)
  900. guard let body = functionDescription.body else { return }
  901. writer.nextLineAppendsToLastLine()
  902. writer.writeLine(" {")
  903. if !body.isEmpty {
  904. writer.withNestedLevel { renderCodeBlocks(body) }
  905. } else {
  906. writer.nextLineAppendsToLastLine()
  907. }
  908. writer.writeLine("}")
  909. }
  910. /// Renders the specified parameter declaration.
  911. func renderParameter(_ parameterDescription: ParameterDescription) {
  912. if let label = parameterDescription.label {
  913. writer.writeLine(label)
  914. } else {
  915. writer.writeLine("_")
  916. }
  917. writer.nextLineAppendsToLastLine()
  918. if let name = parameterDescription.name, name != parameterDescription.label {
  919. // If the label and name are the same value, don't repeat it.
  920. writer.writeLine(" ")
  921. writer.nextLineAppendsToLastLine()
  922. writer.writeLine(name)
  923. writer.nextLineAppendsToLastLine()
  924. }
  925. writer.writeLine(": ")
  926. writer.nextLineAppendsToLastLine()
  927. if parameterDescription.inout {
  928. writer.writeLine("inout ")
  929. writer.nextLineAppendsToLastLine()
  930. }
  931. if let type = parameterDescription.type {
  932. renderExistingTypeDescription(type)
  933. }
  934. if let defaultValue = parameterDescription.defaultValue {
  935. writer.nextLineAppendsToLastLine()
  936. writer.writeLine(" = ")
  937. writer.nextLineAppendsToLastLine()
  938. renderExpression(defaultValue)
  939. }
  940. }
  941. /// Renders the specified parameter declaration for a closure.
  942. func renderClosureParameter(_ parameterDescription: ParameterDescription) {
  943. let name = parameterDescription.name
  944. let label: String
  945. if let declaredLabel = parameterDescription.label {
  946. label = declaredLabel
  947. } else {
  948. label = "_"
  949. }
  950. if let name = name {
  951. writer.writeLine(label)
  952. if name != parameterDescription.label {
  953. // If the label and name are the same value, don't repeat it.
  954. writer.writeLine(" ")
  955. writer.nextLineAppendsToLastLine()
  956. writer.writeLine(name)
  957. writer.nextLineAppendsToLastLine()
  958. }
  959. }
  960. if parameterDescription.inout {
  961. writer.writeLine("inout ")
  962. writer.nextLineAppendsToLastLine()
  963. }
  964. if let type = parameterDescription.type {
  965. renderExistingTypeDescription(type)
  966. }
  967. if let defaultValue = parameterDescription.defaultValue {
  968. writer.nextLineAppendsToLastLine()
  969. writer.writeLine(" = ")
  970. writer.nextLineAppendsToLastLine()
  971. renderExpression(defaultValue)
  972. }
  973. }
  974. /// Renders the specified declaration with a comment.
  975. func renderCommentableDeclaration(comment: Comment?, declaration: Declaration) {
  976. if let comment { renderComment(comment) }
  977. renderDeclaration(declaration)
  978. }
  979. /// Renders the specified declaration with a deprecation annotation.
  980. func renderDeprecatedDeclaration(deprecation: DeprecationDescription, declaration: Declaration) {
  981. renderDeprecation(deprecation)
  982. renderDeclaration(declaration)
  983. }
  984. func renderDeprecation(_ deprecation: DeprecationDescription) {
  985. let things: [String] = [
  986. "*", "deprecated", deprecation.message.map { "message: \"\($0)\"" },
  987. deprecation.renamed.map { "renamed: \"\($0)\"" },
  988. ]
  989. .compactMap({ $0 })
  990. let line = "@available(\(things.joined(separator: ", ")))"
  991. writer.writeLine(line)
  992. }
  993. /// Renders the specified declaration with an availability guard annotation.
  994. func renderGuardedDeclaration(availability: AvailabilityDescription, declaration: Declaration) {
  995. renderAvailability(availability)
  996. renderDeclaration(declaration)
  997. }
  998. func renderAvailability(_ availability: AvailabilityDescription) {
  999. var line = "@available("
  1000. for osVersion in availability.osVersions {
  1001. line.append("\(osVersion.os.name) \(osVersion.version), ")
  1002. }
  1003. line.append("*)")
  1004. writer.writeLine(line)
  1005. }
  1006. /// Renders the specified code block item.
  1007. func renderCodeBlockItem(_ description: CodeBlockItem) {
  1008. switch description {
  1009. case .declaration(let declaration): renderDeclaration(declaration)
  1010. case .expression(let expression): renderExpression(expression)
  1011. }
  1012. }
  1013. /// Renders the specified code block.
  1014. func renderCodeBlock(_ description: CodeBlock) {
  1015. if let comment = description.comment { renderComment(comment) }
  1016. let item = description.item
  1017. renderCodeBlockItem(item)
  1018. }
  1019. /// Renders the specified code blocks.
  1020. func renderCodeBlocks(_ blocks: [CodeBlock]) { blocks.forEach(renderCodeBlock) }
  1021. }
  1022. extension Array {
  1023. /// Returns a collection of tuples, where the first element is
  1024. /// the collection element and the second is a Boolean value indicating
  1025. /// whether it is the last element in the collection.
  1026. /// - Returns: A collection of tuples.
  1027. fileprivate func enumeratedWithLastMarker() -> [(Element, isLast: Bool)] {
  1028. let count = count
  1029. return enumerated().map { index, element in (element, index == count - 1) }
  1030. }
  1031. }
  1032. extension Array where Element == String {
  1033. /// Returns a string where the elements of the array are joined
  1034. /// by a space character.
  1035. /// - Returns: A string with the elements of the array joined by space characters.
  1036. fileprivate func joinedWords() -> String { joined(separator: " ") }
  1037. }
  1038. extension String {
  1039. /// Returns an array of strings, where each string represents one line
  1040. /// in the current string.
  1041. /// - Returns: An array of strings, each representing one line in the original string.
  1042. fileprivate func asLines() -> [String] {
  1043. split(omittingEmptySubsequences: false, whereSeparator: \.isNewline).map(String.init)
  1044. }
  1045. /// Returns a new string where the provided closure transforms each line.
  1046. /// The closure takes a string representing one line as a parameter.
  1047. /// - Parameter work: The closure that transforms each line.
  1048. /// - Returns: A new string where each line has been transformed using the given closure.
  1049. fileprivate func transformingLines(_ work: (String, Bool) -> String?) -> [String] {
  1050. asLines().enumeratedWithLastMarker().compactMap(work)
  1051. }
  1052. }
  1053. extension TextBasedRenderer {
  1054. /// Returns the provided expression rendered as a string.
  1055. /// - Parameter expression: The expression.
  1056. /// - Returns: The string representation of the expression.
  1057. static func renderedExpressionAsString(_ expression: Expression) -> String {
  1058. let renderer = TextBasedRenderer.default
  1059. renderer.renderExpression(expression)
  1060. return renderer.renderedContents()
  1061. }
  1062. }