TextBasedRenderer.swift 38 KB

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