TextBasedRenderer.swift 41 KB

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