TextBasedRenderer.swift 41 KB

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