TextBasedRenderer.swift 40 KB

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