2
0

TextBasedRenderer.swift 39 KB

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