TextBasedRenderer.swift 38 KB

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