TextBasedRenderer.swift 39 KB

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