TextBasedRenderer.swift 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198
  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. for (wrap, isLast) in wrapped.enumeratedWithLastMarker() {
  563. renderExistingTypeDescription(wrap)
  564. writer.nextLineAppendsToLastLine()
  565. if !isLast {
  566. writer.writeLine(", ")
  567. writer.nextLineAppendsToLastLine()
  568. }
  569. }
  570. writer.nextLineAppendsToLastLine()
  571. writer.writeLine(">")
  572. case .optional(let existingTypeDescription):
  573. renderExistingTypeDescription(existingTypeDescription)
  574. writer.nextLineAppendsToLastLine()
  575. writer.writeLine("?")
  576. case .member(let components):
  577. writer.writeLine(components.joined(separator: "."))
  578. case .array(let existingTypeDescription):
  579. writer.writeLine("[")
  580. writer.nextLineAppendsToLastLine()
  581. renderExistingTypeDescription(existingTypeDescription)
  582. writer.nextLineAppendsToLastLine()
  583. writer.writeLine("]")
  584. case .dictionaryValue(let existingTypeDescription):
  585. writer.writeLine("[String: ")
  586. writer.nextLineAppendsToLastLine()
  587. renderExistingTypeDescription(existingTypeDescription)
  588. writer.nextLineAppendsToLastLine()
  589. writer.writeLine("]")
  590. case .some(let existingTypeDescription):
  591. writer.writeLine("some ")
  592. writer.nextLineAppendsToLastLine()
  593. renderExistingTypeDescription(existingTypeDescription)
  594. case .closure(let closureSignatureDescription):
  595. renderClosureSignature(closureSignatureDescription)
  596. }
  597. }
  598. /// Renders the specified typealias declaration.
  599. func renderTypealias(_ alias: TypealiasDescription) {
  600. var words: [String] = []
  601. if let accessModifier = alias.accessModifier {
  602. words.append(renderedAccessModifier(accessModifier))
  603. }
  604. words.append(contentsOf: [
  605. "typealias", alias.name, "=",
  606. ])
  607. writer.writeLine(words.joinedWords() + " ")
  608. writer.nextLineAppendsToLastLine()
  609. renderExistingTypeDescription(alias.existingType)
  610. }
  611. /// Renders the specified binding kind.
  612. func renderedBindingKind(_ kind: BindingKind) -> String {
  613. switch kind {
  614. case .var: return "var"
  615. case .let: return "let"
  616. }
  617. }
  618. /// Renders the specified variable declaration.
  619. func renderVariable(_ variable: VariableDescription) {
  620. do {
  621. if let accessModifier = variable.accessModifier {
  622. writer.writeLine(renderedAccessModifier(accessModifier) + " ")
  623. writer.nextLineAppendsToLastLine()
  624. }
  625. if variable.isStatic {
  626. writer.writeLine("static ")
  627. writer.nextLineAppendsToLastLine()
  628. }
  629. writer.writeLine(renderedBindingKind(variable.kind) + " ")
  630. writer.nextLineAppendsToLastLine()
  631. renderExpression(variable.left)
  632. if let type = variable.type {
  633. writer.nextLineAppendsToLastLine()
  634. writer.writeLine(": ")
  635. writer.nextLineAppendsToLastLine()
  636. renderExistingTypeDescription(type)
  637. }
  638. }
  639. if let right = variable.right {
  640. writer.nextLineAppendsToLastLine()
  641. writer.writeLine(" = ")
  642. writer.nextLineAppendsToLastLine()
  643. renderExpression(right)
  644. }
  645. if let body = variable.getter {
  646. writer.nextLineAppendsToLastLine()
  647. writer.writeLine(" {")
  648. writer.withNestedLevel {
  649. let hasExplicitGetter =
  650. !variable.getterEffects.isEmpty || variable.setter != nil || variable.modify != nil
  651. if hasExplicitGetter {
  652. let keywords = variable.getterEffects.map(renderedFunctionKeyword).joined(separator: " ")
  653. let line = "get \(keywords) {"
  654. writer.writeLine(line)
  655. writer.push()
  656. }
  657. renderCodeBlocks(body)
  658. if hasExplicitGetter {
  659. writer.pop()
  660. writer.writeLine("}")
  661. }
  662. if let modify = variable.modify {
  663. writer.writeLine("_modify {")
  664. writer.withNestedLevel { renderCodeBlocks(modify) }
  665. writer.writeLine("}")
  666. }
  667. if let setter = variable.setter {
  668. writer.writeLine("set {")
  669. writer.withNestedLevel { renderCodeBlocks(setter) }
  670. writer.writeLine("}")
  671. }
  672. }
  673. writer.writeLine("}")
  674. }
  675. }
  676. /// Renders the specified struct declaration.
  677. func renderStruct(_ structDesc: StructDescription) {
  678. if let accessModifier = structDesc.accessModifier {
  679. writer.writeLine(renderedAccessModifier(accessModifier) + " ")
  680. writer.nextLineAppendsToLastLine()
  681. }
  682. writer.writeLine("struct \(structDesc.name)")
  683. writer.nextLineAppendsToLastLine()
  684. if !structDesc.conformances.isEmpty {
  685. writer.writeLine(": \(structDesc.conformances.joined(separator: ", "))")
  686. writer.nextLineAppendsToLastLine()
  687. }
  688. writer.writeLine(" {")
  689. if !structDesc.members.isEmpty {
  690. writer.withNestedLevel {
  691. for (member, isLast) in structDesc.members.enumeratedWithLastMarker() {
  692. renderDeclaration(member)
  693. if !isLast {
  694. writer.writeLine("")
  695. }
  696. }
  697. }
  698. } else {
  699. writer.nextLineAppendsToLastLine()
  700. }
  701. writer.writeLine("}")
  702. }
  703. /// Renders the specified protocol declaration.
  704. func renderProtocol(_ protocolDesc: ProtocolDescription) {
  705. if let accessModifier = protocolDesc.accessModifier {
  706. writer.writeLine("\(renderedAccessModifier(accessModifier)) ")
  707. writer.nextLineAppendsToLastLine()
  708. }
  709. writer.writeLine("protocol \(protocolDesc.name)")
  710. writer.nextLineAppendsToLastLine()
  711. if !protocolDesc.conformances.isEmpty {
  712. let conformances = protocolDesc.conformances.joined(separator: ", ")
  713. writer.writeLine(": \(conformances)")
  714. writer.nextLineAppendsToLastLine()
  715. }
  716. writer.writeLine(" {")
  717. if !protocolDesc.members.isEmpty {
  718. writer.withNestedLevel {
  719. for (member, isLast) in protocolDesc.members.enumeratedWithLastMarker() {
  720. renderDeclaration(member)
  721. if !isLast {
  722. writer.writeLine("")
  723. }
  724. }
  725. }
  726. } else {
  727. writer.nextLineAppendsToLastLine()
  728. }
  729. writer.writeLine("}")
  730. }
  731. /// Renders the specified enum declaration.
  732. func renderEnum(_ enumDesc: EnumDescription) {
  733. if enumDesc.isFrozen {
  734. writer.writeLine("@frozen ")
  735. writer.nextLineAppendsToLastLine()
  736. }
  737. if let accessModifier = enumDesc.accessModifier {
  738. writer.writeLine("\(renderedAccessModifier(accessModifier)) ")
  739. writer.nextLineAppendsToLastLine()
  740. }
  741. if enumDesc.isIndirect {
  742. writer.writeLine("indirect ")
  743. writer.nextLineAppendsToLastLine()
  744. }
  745. writer.writeLine("enum \(enumDesc.name)")
  746. writer.nextLineAppendsToLastLine()
  747. if !enumDesc.conformances.isEmpty {
  748. writer.writeLine(": \(enumDesc.conformances.joined(separator: ", "))")
  749. writer.nextLineAppendsToLastLine()
  750. }
  751. writer.writeLine(" {")
  752. if !enumDesc.members.isEmpty {
  753. writer.withNestedLevel { for member in enumDesc.members { renderDeclaration(member) } }
  754. } else {
  755. writer.nextLineAppendsToLastLine()
  756. }
  757. writer.writeLine("}")
  758. }
  759. /// Renders the specified enum case associated value.
  760. func renderEnumCaseAssociatedValue(_ value: EnumCaseAssociatedValueDescription) {
  761. var words: [String] = []
  762. if let label = value.label { words.append(label + ":") }
  763. writer.writeLine(words.joinedWords())
  764. writer.nextLineAppendsToLastLine()
  765. renderExistingTypeDescription(value.type)
  766. }
  767. /// Renders the specified enum case declaration.
  768. func renderEnumCase(_ enumCase: EnumCaseDescription) {
  769. writer.writeLine("case \(enumCase.name)")
  770. switch enumCase.kind {
  771. case .nameOnly: break
  772. case .nameWithRawValue(let rawValue):
  773. writer.nextLineAppendsToLastLine()
  774. writer.writeLine(" = ")
  775. writer.nextLineAppendsToLastLine()
  776. renderLiteral(rawValue)
  777. case .nameWithAssociatedValues(let values):
  778. if values.isEmpty { break }
  779. for (value, isLast) in values.enumeratedWithLastMarker() {
  780. renderEnumCaseAssociatedValue(value)
  781. if !isLast {
  782. writer.nextLineAppendsToLastLine()
  783. writer.writeLine(", ")
  784. }
  785. }
  786. }
  787. }
  788. /// Renders the specified declaration.
  789. func renderDeclaration(_ declaration: Declaration) {
  790. switch declaration {
  791. case let .commentable(comment, nestedDeclaration):
  792. renderCommentableDeclaration(comment: comment, declaration: nestedDeclaration)
  793. case let .deprecated(deprecation, nestedDeclaration):
  794. renderDeprecatedDeclaration(deprecation: deprecation, declaration: nestedDeclaration)
  795. case .variable(let variableDescription): renderVariable(variableDescription)
  796. case .extension(let extensionDescription): renderExtension(extensionDescription)
  797. case .struct(let structDescription): renderStruct(structDescription)
  798. case .protocol(let protocolDescription): renderProtocol(protocolDescription)
  799. case .enum(let enumDescription): renderEnum(enumDescription)
  800. case .typealias(let typealiasDescription): renderTypealias(typealiasDescription)
  801. case .function(let functionDescription): renderFunction(functionDescription)
  802. case .enumCase(let enumCase): renderEnumCase(enumCase)
  803. }
  804. }
  805. /// Renders the specified function kind.
  806. func renderedFunctionKind(_ functionKind: FunctionKind) -> String {
  807. switch functionKind {
  808. case .initializer(let isFailable): return "init\(isFailable ? "?" : "")"
  809. case .function(let name, let isStatic):
  810. return (isStatic ? "static " : "") + "func \(name)"
  811. }
  812. }
  813. /// Renders the specified function keyword.
  814. func renderedFunctionKeyword(_ keyword: FunctionKeyword) -> String {
  815. switch keyword {
  816. case .throws: return "throws"
  817. case .async: return "async"
  818. case .rethrows: return "rethrows"
  819. }
  820. }
  821. /// Renders the specified function signature.
  822. func renderClosureSignature(_ signature: ClosureSignatureDescription) {
  823. if signature.sendable {
  824. writer.writeLine("@Sendable ")
  825. writer.nextLineAppendsToLastLine()
  826. }
  827. if signature.escaping {
  828. writer.writeLine("@escaping ")
  829. writer.nextLineAppendsToLastLine()
  830. }
  831. writer.writeLine("(")
  832. let parameters = signature.parameters
  833. let separateLines = parameters.count > 1
  834. if separateLines {
  835. writer.withNestedLevel {
  836. for (parameter, isLast) in signature.parameters.enumeratedWithLastMarker() {
  837. renderClosureParameter(parameter)
  838. if !isLast {
  839. writer.nextLineAppendsToLastLine()
  840. writer.writeLine(",")
  841. }
  842. }
  843. }
  844. } else {
  845. writer.nextLineAppendsToLastLine()
  846. if let parameter = parameters.first {
  847. renderClosureParameter(parameter)
  848. writer.nextLineAppendsToLastLine()
  849. }
  850. }
  851. writer.writeLine(")")
  852. let keywords = signature.keywords
  853. for keyword in keywords {
  854. writer.nextLineAppendsToLastLine()
  855. writer.writeLine(" " + renderedFunctionKeyword(keyword))
  856. }
  857. if let returnType = signature.returnType {
  858. writer.nextLineAppendsToLastLine()
  859. writer.writeLine(" -> ")
  860. writer.nextLineAppendsToLastLine()
  861. renderExpression(returnType)
  862. }
  863. }
  864. /// Renders the specified function signature.
  865. func renderFunctionSignature(_ signature: FunctionSignatureDescription) {
  866. do {
  867. if let accessModifier = signature.accessModifier {
  868. writer.writeLine(renderedAccessModifier(accessModifier) + " ")
  869. writer.nextLineAppendsToLastLine()
  870. }
  871. let generics = signature.generics
  872. writer.writeLine(
  873. renderedFunctionKind(signature.kind)
  874. )
  875. if !generics.isEmpty {
  876. writer.nextLineAppendsToLastLine()
  877. writer.writeLine("<")
  878. for (genericType, isLast) in generics.enumeratedWithLastMarker() {
  879. writer.nextLineAppendsToLastLine()
  880. renderExistingTypeDescription(genericType)
  881. if !isLast {
  882. writer.nextLineAppendsToLastLine()
  883. writer.writeLine(", ")
  884. }
  885. }
  886. writer.nextLineAppendsToLastLine()
  887. writer.writeLine(">")
  888. }
  889. writer.nextLineAppendsToLastLine()
  890. writer.writeLine("(")
  891. let parameters = signature.parameters
  892. let separateLines = parameters.count > 1
  893. if separateLines {
  894. writer.withNestedLevel {
  895. for (parameter, isLast) in signature.parameters.enumeratedWithLastMarker() {
  896. renderParameter(parameter)
  897. if !isLast {
  898. writer.nextLineAppendsToLastLine()
  899. writer.writeLine(",")
  900. }
  901. }
  902. }
  903. } else {
  904. writer.nextLineAppendsToLastLine()
  905. if let parameter = parameters.first { renderParameter(parameter) }
  906. writer.nextLineAppendsToLastLine()
  907. }
  908. writer.writeLine(")")
  909. }
  910. do {
  911. let keywords = signature.keywords
  912. if !keywords.isEmpty {
  913. for keyword in keywords {
  914. writer.nextLineAppendsToLastLine()
  915. writer.writeLine(" " + renderedFunctionKeyword(keyword))
  916. }
  917. }
  918. }
  919. if let returnType = signature.returnType {
  920. writer.nextLineAppendsToLastLine()
  921. writer.writeLine(" -> ")
  922. writer.nextLineAppendsToLastLine()
  923. renderExpression(returnType)
  924. }
  925. if let whereClause = signature.whereClause {
  926. writer.nextLineAppendsToLastLine()
  927. writer.writeLine(" " + renderedWhereClause(whereClause))
  928. }
  929. }
  930. /// Renders the specified function declaration.
  931. func renderFunction(_ functionDescription: FunctionDescription) {
  932. renderFunctionSignature(functionDescription.signature)
  933. guard let body = functionDescription.body else { return }
  934. writer.nextLineAppendsToLastLine()
  935. writer.writeLine(" {")
  936. if !body.isEmpty {
  937. writer.withNestedLevel { renderCodeBlocks(body) }
  938. } else {
  939. writer.nextLineAppendsToLastLine()
  940. }
  941. writer.writeLine("}")
  942. }
  943. /// Renders the specified parameter declaration.
  944. func renderParameter(_ parameterDescription: ParameterDescription) {
  945. if let label = parameterDescription.label {
  946. writer.writeLine(label)
  947. } else {
  948. writer.writeLine("_")
  949. }
  950. writer.nextLineAppendsToLastLine()
  951. if let name = parameterDescription.name, name != parameterDescription.label {
  952. // If the label and name are the same value, don't repeat it.
  953. writer.writeLine(" ")
  954. writer.nextLineAppendsToLastLine()
  955. writer.writeLine(name)
  956. writer.nextLineAppendsToLastLine()
  957. }
  958. writer.writeLine(": ")
  959. writer.nextLineAppendsToLastLine()
  960. if parameterDescription.inout {
  961. writer.writeLine("inout ")
  962. writer.nextLineAppendsToLastLine()
  963. }
  964. if let type = parameterDescription.type {
  965. renderExistingTypeDescription(type)
  966. }
  967. if let defaultValue = parameterDescription.defaultValue {
  968. writer.nextLineAppendsToLastLine()
  969. writer.writeLine(" = ")
  970. writer.nextLineAppendsToLastLine()
  971. renderExpression(defaultValue)
  972. }
  973. }
  974. /// Renders the specified parameter declaration for a closure.
  975. func renderClosureParameter(_ parameterDescription: ParameterDescription) {
  976. let name = parameterDescription.name
  977. let label: String
  978. if let declaredLabel = parameterDescription.label {
  979. label = declaredLabel
  980. } else {
  981. label = "_"
  982. }
  983. if let name = name {
  984. writer.writeLine(label)
  985. if name != parameterDescription.label {
  986. // If the label and name are the same value, don't repeat it.
  987. writer.writeLine(" ")
  988. writer.nextLineAppendsToLastLine()
  989. writer.writeLine(name)
  990. writer.nextLineAppendsToLastLine()
  991. }
  992. }
  993. if parameterDescription.inout {
  994. writer.writeLine("inout ")
  995. writer.nextLineAppendsToLastLine()
  996. }
  997. if let type = parameterDescription.type {
  998. renderExistingTypeDescription(type)
  999. }
  1000. if let defaultValue = parameterDescription.defaultValue {
  1001. writer.nextLineAppendsToLastLine()
  1002. writer.writeLine(" = ")
  1003. writer.nextLineAppendsToLastLine()
  1004. renderExpression(defaultValue)
  1005. }
  1006. }
  1007. /// Renders the specified declaration with a comment.
  1008. func renderCommentableDeclaration(comment: Comment?, declaration: Declaration) {
  1009. if let comment { renderComment(comment) }
  1010. renderDeclaration(declaration)
  1011. }
  1012. /// Renders the specified declaration with a deprecation annotation.
  1013. func renderDeprecatedDeclaration(deprecation: DeprecationDescription, declaration: Declaration) {
  1014. renderDeprecation(deprecation)
  1015. renderDeclaration(declaration)
  1016. }
  1017. func renderDeprecation(_ deprecation: DeprecationDescription) {
  1018. let things: [String] = [
  1019. "*", "deprecated", deprecation.message.map { "message: \"\($0)\"" },
  1020. deprecation.renamed.map { "renamed: \"\($0)\"" },
  1021. ]
  1022. .compactMap({ $0 })
  1023. let line = "@available(\(things.joined(separator: ", ")))"
  1024. writer.writeLine(line)
  1025. }
  1026. /// Renders the specified declaration with an availability guard annotation.
  1027. func renderGuardedDeclaration(availability: AvailabilityDescription, declaration: Declaration) {
  1028. renderAvailability(availability)
  1029. renderDeclaration(declaration)
  1030. }
  1031. func renderAvailability(_ availability: AvailabilityDescription) {
  1032. var line = "@available("
  1033. for osVersion in availability.osVersions {
  1034. line.append("\(osVersion.os.name) \(osVersion.version), ")
  1035. }
  1036. line.append("*)")
  1037. writer.writeLine(line)
  1038. }
  1039. /// Renders the specified code block item.
  1040. func renderCodeBlockItem(_ description: CodeBlockItem) {
  1041. switch description {
  1042. case .declaration(let declaration): renderDeclaration(declaration)
  1043. case .expression(let expression): renderExpression(expression)
  1044. }
  1045. }
  1046. /// Renders the specified code block.
  1047. func renderCodeBlock(_ description: CodeBlock) {
  1048. if let comment = description.comment { renderComment(comment) }
  1049. if let item = description.item {
  1050. renderCodeBlockItem(item)
  1051. }
  1052. }
  1053. /// Renders the specified code blocks.
  1054. func renderCodeBlocks(_ blocks: [CodeBlock]) { blocks.forEach(renderCodeBlock) }
  1055. }
  1056. extension Array {
  1057. /// Returns a collection of tuples, where the first element is
  1058. /// the collection element and the second is a Boolean value indicating
  1059. /// whether it is the last element in the collection.
  1060. /// - Returns: A collection of tuples.
  1061. fileprivate func enumeratedWithLastMarker() -> [(Element, isLast: Bool)] {
  1062. let count = count
  1063. return enumerated().map { index, element in (element, index == count - 1) }
  1064. }
  1065. }
  1066. extension Array where Element == String {
  1067. /// Returns a string where the elements of the array are joined
  1068. /// by a space character.
  1069. /// - Returns: A string with the elements of the array joined by space characters.
  1070. fileprivate func joinedWords() -> String { joined(separator: " ") }
  1071. }
  1072. extension String {
  1073. /// Returns an array of strings, where each string represents one line
  1074. /// in the current string.
  1075. /// - Returns: An array of strings, each representing one line in the original string.
  1076. fileprivate func asLines() -> [String] {
  1077. split(omittingEmptySubsequences: false, whereSeparator: \.isNewline).map(String.init)
  1078. }
  1079. /// Returns a new string where the provided closure transforms each line.
  1080. /// The closure takes a string representing one line as a parameter.
  1081. /// - Parameter work: The closure that transforms each line.
  1082. /// - Returns: A new string where each line has been transformed using the given closure.
  1083. fileprivate func transformingLines(_ work: (String, Bool) -> String?) -> [String] {
  1084. asLines().enumeratedWithLastMarker().compactMap(work)
  1085. }
  1086. }
  1087. extension TextBasedRenderer {
  1088. /// Returns the provided expression rendered as a string.
  1089. /// - Parameter expression: The expression.
  1090. /// - Returns: The string representation of the expression.
  1091. static func renderedExpressionAsString(_ expression: Expression) -> String {
  1092. let renderer = TextBasedRenderer.default
  1093. renderer.renderExpression(expression)
  1094. return renderer.renderedContents()
  1095. }
  1096. }