TextBasedRenderer.swift 40 KB

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