TextBasedRenderer.swift 33 KB

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