TextBasedRenderer.swift 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200
  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 let .guarded(availability, nestedDeclaration):
  796. renderGuardedDeclaration(availability: availability, declaration: nestedDeclaration)
  797. case .variable(let variableDescription): renderVariable(variableDescription)
  798. case .extension(let extensionDescription): renderExtension(extensionDescription)
  799. case .struct(let structDescription): renderStruct(structDescription)
  800. case .protocol(let protocolDescription): renderProtocol(protocolDescription)
  801. case .enum(let enumDescription): renderEnum(enumDescription)
  802. case .typealias(let typealiasDescription): renderTypealias(typealiasDescription)
  803. case .function(let functionDescription): renderFunction(functionDescription)
  804. case .enumCase(let enumCase): renderEnumCase(enumCase)
  805. }
  806. }
  807. /// Renders the specified function kind.
  808. func renderedFunctionKind(_ functionKind: FunctionKind) -> String {
  809. switch functionKind {
  810. case .initializer(let isFailable): return "init\(isFailable ? "?" : "")"
  811. case .function(let name, let isStatic):
  812. return (isStatic ? "static " : "") + "func \(name)"
  813. }
  814. }
  815. /// Renders the specified function keyword.
  816. func renderedFunctionKeyword(_ keyword: FunctionKeyword) -> String {
  817. switch keyword {
  818. case .throws: return "throws"
  819. case .async: return "async"
  820. case .rethrows: return "rethrows"
  821. }
  822. }
  823. /// Renders the specified function signature.
  824. func renderClosureSignature(_ signature: ClosureSignatureDescription) {
  825. if signature.sendable {
  826. writer.writeLine("@Sendable ")
  827. writer.nextLineAppendsToLastLine()
  828. }
  829. if signature.escaping {
  830. writer.writeLine("@escaping ")
  831. writer.nextLineAppendsToLastLine()
  832. }
  833. writer.writeLine("(")
  834. let parameters = signature.parameters
  835. let separateLines = parameters.count > 1
  836. if separateLines {
  837. writer.withNestedLevel {
  838. for (parameter, isLast) in signature.parameters.enumeratedWithLastMarker() {
  839. renderClosureParameter(parameter)
  840. if !isLast {
  841. writer.nextLineAppendsToLastLine()
  842. writer.writeLine(",")
  843. }
  844. }
  845. }
  846. } else {
  847. writer.nextLineAppendsToLastLine()
  848. if let parameter = parameters.first {
  849. renderClosureParameter(parameter)
  850. writer.nextLineAppendsToLastLine()
  851. }
  852. }
  853. writer.writeLine(")")
  854. let keywords = signature.keywords
  855. for keyword in keywords {
  856. writer.nextLineAppendsToLastLine()
  857. writer.writeLine(" " + renderedFunctionKeyword(keyword))
  858. }
  859. if let returnType = signature.returnType {
  860. writer.nextLineAppendsToLastLine()
  861. writer.writeLine(" -> ")
  862. writer.nextLineAppendsToLastLine()
  863. renderExpression(returnType)
  864. }
  865. }
  866. /// Renders the specified function signature.
  867. func renderFunctionSignature(_ signature: FunctionSignatureDescription) {
  868. do {
  869. if let accessModifier = signature.accessModifier {
  870. writer.writeLine(renderedAccessModifier(accessModifier) + " ")
  871. writer.nextLineAppendsToLastLine()
  872. }
  873. let generics = signature.generics
  874. writer.writeLine(
  875. renderedFunctionKind(signature.kind)
  876. )
  877. if !generics.isEmpty {
  878. writer.nextLineAppendsToLastLine()
  879. writer.writeLine("<")
  880. for (genericType, isLast) in generics.enumeratedWithLastMarker() {
  881. writer.nextLineAppendsToLastLine()
  882. renderExistingTypeDescription(genericType)
  883. if !isLast {
  884. writer.nextLineAppendsToLastLine()
  885. writer.writeLine(", ")
  886. }
  887. }
  888. writer.nextLineAppendsToLastLine()
  889. writer.writeLine(">")
  890. }
  891. writer.nextLineAppendsToLastLine()
  892. writer.writeLine("(")
  893. let parameters = signature.parameters
  894. let separateLines = parameters.count > 1
  895. if separateLines {
  896. writer.withNestedLevel {
  897. for (parameter, isLast) in signature.parameters.enumeratedWithLastMarker() {
  898. renderParameter(parameter)
  899. if !isLast {
  900. writer.nextLineAppendsToLastLine()
  901. writer.writeLine(",")
  902. }
  903. }
  904. }
  905. } else {
  906. writer.nextLineAppendsToLastLine()
  907. if let parameter = parameters.first { renderParameter(parameter) }
  908. writer.nextLineAppendsToLastLine()
  909. }
  910. writer.writeLine(")")
  911. }
  912. do {
  913. let keywords = signature.keywords
  914. if !keywords.isEmpty {
  915. for keyword in keywords {
  916. writer.nextLineAppendsToLastLine()
  917. writer.writeLine(" " + renderedFunctionKeyword(keyword))
  918. }
  919. }
  920. }
  921. if let returnType = signature.returnType {
  922. writer.nextLineAppendsToLastLine()
  923. writer.writeLine(" -> ")
  924. writer.nextLineAppendsToLastLine()
  925. renderExpression(returnType)
  926. }
  927. if let whereClause = signature.whereClause {
  928. writer.nextLineAppendsToLastLine()
  929. writer.writeLine(" " + renderedWhereClause(whereClause))
  930. }
  931. }
  932. /// Renders the specified function declaration.
  933. func renderFunction(_ functionDescription: FunctionDescription) {
  934. renderFunctionSignature(functionDescription.signature)
  935. guard let body = functionDescription.body else { return }
  936. writer.nextLineAppendsToLastLine()
  937. writer.writeLine(" {")
  938. if !body.isEmpty {
  939. writer.withNestedLevel { renderCodeBlocks(body) }
  940. } else {
  941. writer.nextLineAppendsToLastLine()
  942. }
  943. writer.writeLine("}")
  944. }
  945. /// Renders the specified parameter declaration.
  946. func renderParameter(_ parameterDescription: ParameterDescription) {
  947. if let label = parameterDescription.label {
  948. writer.writeLine(label)
  949. } else {
  950. writer.writeLine("_")
  951. }
  952. writer.nextLineAppendsToLastLine()
  953. if let name = parameterDescription.name, name != parameterDescription.label {
  954. // If the label and name are the same value, don't repeat it.
  955. writer.writeLine(" ")
  956. writer.nextLineAppendsToLastLine()
  957. writer.writeLine(name)
  958. writer.nextLineAppendsToLastLine()
  959. }
  960. writer.writeLine(": ")
  961. writer.nextLineAppendsToLastLine()
  962. if parameterDescription.inout {
  963. writer.writeLine("inout ")
  964. writer.nextLineAppendsToLastLine()
  965. }
  966. if let type = parameterDescription.type {
  967. renderExistingTypeDescription(type)
  968. }
  969. if let defaultValue = parameterDescription.defaultValue {
  970. writer.nextLineAppendsToLastLine()
  971. writer.writeLine(" = ")
  972. writer.nextLineAppendsToLastLine()
  973. renderExpression(defaultValue)
  974. }
  975. }
  976. /// Renders the specified parameter declaration for a closure.
  977. func renderClosureParameter(_ parameterDescription: ParameterDescription) {
  978. let name = parameterDescription.name
  979. let label: String
  980. if let declaredLabel = parameterDescription.label {
  981. label = declaredLabel
  982. } else {
  983. label = "_"
  984. }
  985. if let name = name {
  986. writer.writeLine(label)
  987. if name != parameterDescription.label {
  988. // If the label and name are the same value, don't repeat it.
  989. writer.writeLine(" ")
  990. writer.nextLineAppendsToLastLine()
  991. writer.writeLine(name)
  992. writer.nextLineAppendsToLastLine()
  993. }
  994. }
  995. if parameterDescription.inout {
  996. writer.writeLine("inout ")
  997. writer.nextLineAppendsToLastLine()
  998. }
  999. if let type = parameterDescription.type {
  1000. renderExistingTypeDescription(type)
  1001. }
  1002. if let defaultValue = parameterDescription.defaultValue {
  1003. writer.nextLineAppendsToLastLine()
  1004. writer.writeLine(" = ")
  1005. writer.nextLineAppendsToLastLine()
  1006. renderExpression(defaultValue)
  1007. }
  1008. }
  1009. /// Renders the specified declaration with a comment.
  1010. func renderCommentableDeclaration(comment: Comment?, declaration: Declaration) {
  1011. if let comment { renderComment(comment) }
  1012. renderDeclaration(declaration)
  1013. }
  1014. /// Renders the specified declaration with a deprecation annotation.
  1015. func renderDeprecatedDeclaration(deprecation: DeprecationDescription, declaration: Declaration) {
  1016. renderDeprecation(deprecation)
  1017. renderDeclaration(declaration)
  1018. }
  1019. func renderDeprecation(_ deprecation: DeprecationDescription) {
  1020. let things: [String] = [
  1021. "*", "deprecated", deprecation.message.map { "message: \"\($0)\"" },
  1022. deprecation.renamed.map { "renamed: \"\($0)\"" },
  1023. ]
  1024. .compactMap({ $0 })
  1025. let line = "@available(\(things.joined(separator: ", ")))"
  1026. writer.writeLine(line)
  1027. }
  1028. /// Renders the specified declaration with an availability guard annotation.
  1029. func renderGuardedDeclaration(availability: AvailabilityDescription, declaration: Declaration) {
  1030. renderAvailability(availability)
  1031. renderDeclaration(declaration)
  1032. }
  1033. func renderAvailability(_ availability: AvailabilityDescription) {
  1034. var line = "@available("
  1035. for osVersion in availability.osVersions {
  1036. line.append("\(osVersion.os.name) \(osVersion.version), ")
  1037. }
  1038. line.append("*)")
  1039. writer.writeLine(line)
  1040. }
  1041. /// Renders the specified code block item.
  1042. func renderCodeBlockItem(_ description: CodeBlockItem) {
  1043. switch description {
  1044. case .declaration(let declaration): renderDeclaration(declaration)
  1045. case .expression(let expression): renderExpression(expression)
  1046. }
  1047. }
  1048. /// Renders the specified code block.
  1049. func renderCodeBlock(_ description: CodeBlock) {
  1050. if let comment = description.comment { renderComment(comment) }
  1051. if let item = description.item {
  1052. renderCodeBlockItem(item)
  1053. }
  1054. }
  1055. /// Renders the specified code blocks.
  1056. func renderCodeBlocks(_ blocks: [CodeBlock]) { blocks.forEach(renderCodeBlock) }
  1057. }
  1058. extension Array {
  1059. /// Returns a collection of tuples, where the first element is
  1060. /// the collection element and the second is a Boolean value indicating
  1061. /// whether it is the last element in the collection.
  1062. /// - Returns: A collection of tuples.
  1063. fileprivate func enumeratedWithLastMarker() -> [(Element, isLast: Bool)] {
  1064. let count = count
  1065. return enumerated().map { index, element in (element, index == count - 1) }
  1066. }
  1067. }
  1068. extension Array where Element == String {
  1069. /// Returns a string where the elements of the array are joined
  1070. /// by a space character.
  1071. /// - Returns: A string with the elements of the array joined by space characters.
  1072. fileprivate func joinedWords() -> String { joined(separator: " ") }
  1073. }
  1074. extension String {
  1075. /// Returns an array of strings, where each string represents one line
  1076. /// in the current string.
  1077. /// - Returns: An array of strings, each representing one line in the original string.
  1078. fileprivate func asLines() -> [String] {
  1079. split(omittingEmptySubsequences: false, whereSeparator: \.isNewline).map(String.init)
  1080. }
  1081. /// Returns a new string where the provided closure transforms each line.
  1082. /// The closure takes a string representing one line as a parameter.
  1083. /// - Parameter work: The closure that transforms each line.
  1084. /// - Returns: A new string where each line has been transformed using the given closure.
  1085. fileprivate func transformingLines(_ work: (String, Bool) -> String?) -> [String] {
  1086. asLines().enumeratedWithLastMarker().compactMap(work)
  1087. }
  1088. }
  1089. extension TextBasedRenderer {
  1090. /// Returns the provided expression rendered as a string.
  1091. /// - Parameter expression: The expression.
  1092. /// - Returns: The string representation of the expression.
  1093. static func renderedExpressionAsString(_ expression: Expression) -> String {
  1094. let renderer = TextBasedRenderer.default
  1095. renderer.renderExpression(expression)
  1096. return renderer.renderedContents()
  1097. }
  1098. }