StructuredSwiftRepresentation.swift 57 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901
  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. /// A description of an import declaration.
  30. ///
  31. /// For example: `import Foo`.
  32. struct ImportDescription: Equatable, Codable {
  33. /// The name of the imported module.
  34. ///
  35. /// For example, the `Foo` in `import Foo`.
  36. var moduleName: String
  37. /// An array of module types imported from the module, if applicable.
  38. ///
  39. /// For example, if there are type imports like `import Foo.Bar`, they would be listed here.
  40. var moduleTypes: [String]?
  41. /// The name of the private interface for an `@_spi` import.
  42. ///
  43. /// For example, if `spi` was "Secret" and the module name was "Foo" then the import
  44. /// would be `@_spi(Secret) import Foo`.
  45. var spi: String? = nil
  46. /// Requirements for the `@preconcurrency` attribute.
  47. var preconcurrency: PreconcurrencyRequirement = .never
  48. /// If the dependency is an item, the property's value is the item representation.
  49. /// If the dependency is a module, this property is nil.
  50. var item: Item? = nil
  51. /// Describes any requirement for the `@preconcurrency` attribute.
  52. enum PreconcurrencyRequirement: Equatable, Codable {
  53. /// The attribute is always required.
  54. case always
  55. /// The attribute is not required.
  56. case never
  57. /// The attribute is required only on the named operating systems.
  58. case onOS([String])
  59. }
  60. /// Represents an item imported from a module.
  61. struct Item: Equatable, Codable {
  62. /// The keyword that specifies the item's kind (e.g. `func`, `struct`).
  63. var kind: Kind
  64. /// The name of the imported item.
  65. var name: String
  66. init(kind: Kind, name: String) {
  67. self.kind = kind
  68. self.name = name
  69. }
  70. }
  71. enum Kind: String, Equatable, Codable {
  72. case `typealias`
  73. case `struct`
  74. case `class`
  75. case `enum`
  76. case `protocol`
  77. case `let`
  78. case `var`
  79. case `func`
  80. }
  81. }
  82. /// A description of an access modifier.
  83. ///
  84. /// For example: `public`.
  85. internal enum AccessModifier: String, Sendable, Equatable, Codable {
  86. /// A declaration accessible outside of the module.
  87. case `public`
  88. /// A declaration accessible outside of the module but only inside the containing package or project.
  89. case `package`
  90. /// A declaration only accessible inside of the module.
  91. case `internal`
  92. /// A declaration only accessible inside the same Swift file.
  93. case `fileprivate`
  94. /// A declaration only accessible inside the same type or scope.
  95. case `private`
  96. }
  97. /// A description of a comment.
  98. ///
  99. /// For example `/// Hello`.
  100. enum Comment: Equatable, Codable {
  101. /// An inline comment.
  102. ///
  103. /// For example: `// Great code below`.
  104. case inline(String)
  105. /// A documentation comment.
  106. ///
  107. /// For example: `/// Important type`.
  108. case doc(String)
  109. /// A mark comment.
  110. ///
  111. /// For example: `// MARK: - Public methods`, with the optional
  112. /// section break (`-`).
  113. case mark(String, sectionBreak: Bool)
  114. /// A comment that is already formatted,
  115. /// meaning that it already has the `///` and
  116. /// can contain multiple lines
  117. ///
  118. /// For example both the string and the comment
  119. /// can look like `/// Important type`.
  120. case preFormatted(String)
  121. }
  122. /// A description of a literal.
  123. ///
  124. /// For example `"hello"` or `42`.
  125. enum LiteralDescription: Equatable, Codable {
  126. /// A string literal.
  127. ///
  128. /// For example `"hello"`.
  129. case string(String)
  130. /// An integer literal.
  131. ///
  132. /// For example `42`.
  133. case int(Int)
  134. /// A Boolean literal.
  135. ///
  136. /// For example `true`.
  137. case bool(Bool)
  138. /// The nil literal: `nil`.
  139. case `nil`
  140. /// An array literal.
  141. ///
  142. /// For example `["hello", 42]`.
  143. case array([Expression])
  144. }
  145. /// A description of an identifier, such as a variable name.
  146. ///
  147. /// For example, in `let foo = 42`, `foo` is an identifier.
  148. enum IdentifierDescription: Equatable, Codable {
  149. /// A pattern identifier.
  150. ///
  151. /// For example, `foo` in `let foo = 42`.
  152. case pattern(String)
  153. /// A type identifier.
  154. ///
  155. /// For example, `Swift.String` in `let foo: Swift.String = "hi"`.
  156. case type(ExistingTypeDescription)
  157. }
  158. /// A description of a member access expression.
  159. ///
  160. /// For example `foo.bar`.
  161. struct MemberAccessDescription: Equatable, Codable {
  162. /// The expression of which a member `right` is accessed.
  163. ///
  164. /// For example, in `foo.bar`, `left` represents `foo`.
  165. var left: Expression?
  166. /// The member name to access.
  167. ///
  168. /// For example, in `foo.bar`, `right` is `bar`.
  169. var right: String
  170. }
  171. /// A description of a function argument.
  172. ///
  173. /// For example in `foo(bar: 42)`, the function argument is `bar: 42`.
  174. struct FunctionArgumentDescription: Equatable, Codable {
  175. /// An optional label of the function argument.
  176. ///
  177. /// For example, in `foo(bar: 42)`, the `label` is `bar`.
  178. var label: String?
  179. /// The expression passed as the function argument value.
  180. ///
  181. /// For example, in `foo(bar: 42)`, `expression` represents `42`.
  182. var expression: Expression
  183. }
  184. /// A description of a function call.
  185. ///
  186. /// For example `foo(bar: 42)`.
  187. struct FunctionCallDescription: Equatable, Codable {
  188. /// The expression that returns the function to be called.
  189. ///
  190. /// For example, in `foo(bar: 42)`, `calledExpression` represents `foo`.
  191. var calledExpression: Expression
  192. /// The arguments to be passed to the function.
  193. var arguments: [FunctionArgumentDescription]
  194. /// A trailing closure.
  195. var trailingClosure: ClosureInvocationDescription?
  196. /// Creates a new function call description.
  197. /// - Parameters:
  198. /// - calledExpression: An expression that returns the function to be called.
  199. /// - arguments: Arguments to be passed to the function.
  200. /// - trailingClosure: A trailing closure.
  201. init(
  202. calledExpression: Expression,
  203. arguments: [FunctionArgumentDescription] = [],
  204. trailingClosure: ClosureInvocationDescription? = nil
  205. ) {
  206. self.calledExpression = calledExpression
  207. self.arguments = arguments
  208. self.trailingClosure = trailingClosure
  209. }
  210. /// Creates a new function call description.
  211. /// - Parameters:
  212. /// - calledExpression: An expression that returns the function to be called.
  213. /// - arguments: Arguments to be passed to the function.
  214. /// - trailingClosure: A trailing closure.
  215. init(
  216. calledExpression: Expression,
  217. arguments: [Expression],
  218. trailingClosure: ClosureInvocationDescription? = nil
  219. ) {
  220. self.init(
  221. calledExpression: calledExpression,
  222. arguments: arguments.map { .init(label: nil, expression: $0) },
  223. trailingClosure: trailingClosure
  224. )
  225. }
  226. }
  227. /// A type of a variable binding: `let` or `var`.
  228. enum BindingKind: Equatable, Codable {
  229. /// A mutable variable.
  230. case `var`
  231. /// An immutable variable.
  232. case `let`
  233. }
  234. /// A description of a variable declaration.
  235. ///
  236. /// For example `let foo = 42`.
  237. struct VariableDescription: Equatable, Codable {
  238. /// An access modifier.
  239. var accessModifier: AccessModifier?
  240. /// A Boolean value that indicates whether the variable is static.
  241. var isStatic: Bool = false
  242. /// The variable binding kind.
  243. var kind: BindingKind
  244. /// The name of the variable.
  245. ///
  246. /// For example, in `let foo = 42`, `left` is `foo`.
  247. var left: Expression
  248. /// The type of the variable.
  249. ///
  250. /// For example, in `let foo: Int = 42`, `type` is `Int`.
  251. var type: ExistingTypeDescription?
  252. /// The expression to be assigned to the variable.
  253. ///
  254. /// For example, in `let foo = 42`, `right` represents `42`.
  255. var right: Expression? = nil
  256. /// Body code for the getter.
  257. ///
  258. /// For example, in `var foo: Int { 42 }`, `body` represents `{ 42 }`.
  259. var getter: [CodeBlock]? = nil
  260. /// Effects for the getter.
  261. ///
  262. /// For example, in `var foo: Int { get throws { 42 } }`, effects are `[.throws]`.
  263. var getterEffects: [FunctionKeyword] = []
  264. /// Body code for the setter.
  265. ///
  266. /// For example, in `var foo: Int { set { _foo = newValue } }`, `body`
  267. /// represents `{ _foo = newValue }`.
  268. var setter: [CodeBlock]? = nil
  269. /// Body code for the `_modify` accessor.
  270. ///
  271. /// For example, in `var foo: Int { _modify { yield &_foo } }`, `body`
  272. /// represents `{ yield &_foo }`.
  273. var modify: [CodeBlock]? = nil
  274. }
  275. /// A requirement of a where clause.
  276. enum WhereClauseRequirement: Equatable, Codable {
  277. /// A conformance requirement.
  278. ///
  279. /// For example, in `extension Array where Element: Foo {`, the first tuple value is `Element` and the second `Foo`.
  280. case conformance(String, String)
  281. }
  282. /// A description of a where clause.
  283. ///
  284. /// For example: `extension Array where Element: Foo {`.
  285. struct WhereClause: Equatable, Codable {
  286. /// One or more requirements to be added after the `where` keyword.
  287. var requirements: [WhereClauseRequirement]
  288. }
  289. /// A description of an extension declaration.
  290. ///
  291. /// For example `extension Foo {`.
  292. struct ExtensionDescription: Equatable, Codable {
  293. /// An access modifier.
  294. var accessModifier: AccessModifier? = nil
  295. /// The name of the extended type.
  296. ///
  297. /// For example, in `extension Foo {`, `onType` is `Foo`.
  298. var onType: String
  299. /// Additional type names that the extension conforms to.
  300. ///
  301. /// For example: `["Sendable", "Codable"]`.
  302. var conformances: [String] = []
  303. /// A where clause constraining the extension declaration.
  304. var whereClause: WhereClause? = nil
  305. /// The declarations that the extension adds on the extended type.
  306. var declarations: [Declaration]
  307. }
  308. /// A description of a struct declaration.
  309. ///
  310. /// For example `struct Foo {`.
  311. struct StructDescription: Equatable, Codable {
  312. /// An access modifier.
  313. var accessModifier: AccessModifier? = nil
  314. /// The name of the struct.
  315. ///
  316. /// For example, in `struct Foo {`, `name` is `Foo`.
  317. var name: String
  318. /// The type names that the struct conforms to.
  319. ///
  320. /// For example: `["Sendable", "Codable"]`.
  321. var conformances: [String] = []
  322. /// The declarations that make up the main struct body.
  323. var members: [Declaration] = []
  324. }
  325. /// A description of an enum declaration.
  326. ///
  327. /// For example `enum Bar {`.
  328. struct EnumDescription: Equatable, Codable {
  329. /// A Boolean value that indicates whether the enum has a `@frozen`
  330. /// attribute.
  331. var isFrozen: Bool = false
  332. /// A Boolean value that indicates whether the enum has the `indirect`
  333. /// keyword.
  334. var isIndirect: Bool = false
  335. /// An access modifier.
  336. var accessModifier: AccessModifier? = nil
  337. /// The name of the enum.
  338. ///
  339. /// For example, in `enum Bar {`, `name` is `Bar`.
  340. var name: String
  341. /// The type names that the enum conforms to.
  342. ///
  343. /// For example: `["Sendable", "Codable"]`.
  344. var conformances: [String] = []
  345. /// The declarations that make up the enum body.
  346. var members: [Declaration] = []
  347. }
  348. /// A description of a type reference.
  349. indirect enum ExistingTypeDescription: Equatable, Codable {
  350. /// A type with the `any` keyword in front of it.
  351. ///
  352. /// For example, `any Foo`.
  353. case any(ExistingTypeDescription)
  354. /// An optional type.
  355. ///
  356. /// For example, `Foo?`.
  357. case optional(ExistingTypeDescription)
  358. /// A wrapper type generic over a wrapped type.
  359. ///
  360. /// For example, `Wrapper<Wrapped>`.
  361. case generic(wrapper: ExistingTypeDescription, wrapped: ExistingTypeDescription)
  362. /// A type reference represented by the components.
  363. ///
  364. /// For example, `MyModule.Foo`.
  365. case member([String])
  366. /// An array with an element type.
  367. ///
  368. /// For example, `[Foo]`.
  369. case array(ExistingTypeDescription)
  370. /// A dictionary where the key is `Swift.String` and the value is
  371. /// the provided type.
  372. ///
  373. /// For example, `[String: Foo]`.
  374. case dictionaryValue(ExistingTypeDescription)
  375. /// A type with the `some` keyword in front of it.
  376. ///
  377. /// For example, `some Foo`.
  378. case some(ExistingTypeDescription)
  379. /// A closure signature as a type.
  380. ///
  381. /// For example: `(String) async throws -> Int`.
  382. case closure(ClosureSignatureDescription)
  383. }
  384. /// A description of a typealias declaration.
  385. ///
  386. /// For example `typealias Foo = Int`.
  387. struct TypealiasDescription: Equatable, Codable {
  388. /// An access modifier.
  389. var accessModifier: AccessModifier?
  390. /// The name of the typealias.
  391. ///
  392. /// For example, in `typealias Foo = Int`, `name` is `Foo`.
  393. var name: String
  394. /// The existing type that serves as the underlying type of the alias.
  395. ///
  396. /// For example, in `typealias Foo = Int`, `existingType` is `Int`.
  397. var existingType: ExistingTypeDescription
  398. }
  399. /// A description of a protocol declaration.
  400. ///
  401. /// For example `protocol Foo {`.
  402. struct ProtocolDescription: Equatable, Codable {
  403. /// An access modifier.
  404. var accessModifier: AccessModifier? = nil
  405. /// The name of the protocol.
  406. ///
  407. /// For example, in `protocol Foo {`, `name` is `Foo`.
  408. var name: String
  409. /// The type names that the protocol conforms to.
  410. ///
  411. /// For example: `["Sendable", "Codable"]`.
  412. var conformances: [String] = []
  413. /// The function and property declarations that make up the protocol
  414. /// requirements.
  415. var members: [Declaration] = []
  416. }
  417. /// A description of a function parameter declaration.
  418. ///
  419. /// For example, in `func foo(bar baz: String = "hi")`, the parameter
  420. /// description represents `bar baz: String = "hi"`
  421. struct ParameterDescription: Equatable, Codable {
  422. /// An external parameter label.
  423. ///
  424. /// For example, in `bar baz: String = "hi"`, `label` is `bar`.
  425. var label: String? = nil
  426. /// An internal parameter name.
  427. ///
  428. /// For example, in `bar baz: String = "hi"`, `name` is `baz`.
  429. var name: String? = nil
  430. /// The type name of the parameter.
  431. ///
  432. /// For example, in `bar baz: String = "hi"`, `type` is `String`.
  433. var type: ExistingTypeDescription? = nil
  434. /// A default value of the parameter.
  435. ///
  436. /// For example, in `bar baz: String = "hi"`, `defaultValue`
  437. /// represents `"hi"`.
  438. var defaultValue: Expression? = nil
  439. /// An inout parameter type.
  440. ///
  441. /// For example, `bar baz: inout String`.
  442. var `inout`: Bool = false
  443. }
  444. /// A function kind: `func` or `init`.
  445. enum FunctionKind: Equatable, Codable {
  446. /// An initializer.
  447. ///
  448. /// For example: `init()`, or `init?()` when `failable` is `true`.
  449. case initializer(failable: Bool)
  450. /// A function or a method. Can be static.
  451. ///
  452. /// For example `foo()`, where `name` is `foo`.
  453. case function(
  454. name: String,
  455. isStatic: Bool
  456. )
  457. }
  458. /// A function keyword, such as `async` and `throws`.
  459. enum FunctionKeyword: Equatable, Codable {
  460. /// An asynchronous function.
  461. case `async`
  462. /// A function that can throw an error.
  463. case `throws`
  464. /// A function that can rethrow an error.
  465. case `rethrows`
  466. }
  467. /// A description of a function signature.
  468. ///
  469. /// For example: `func foo(bar: String) async throws -> Int`.
  470. struct FunctionSignatureDescription: Equatable, Codable {
  471. /// An access modifier.
  472. var accessModifier: AccessModifier? = nil
  473. /// The kind of the function.
  474. var kind: FunctionKind
  475. /// The generic types of the function.
  476. var generics: [ExistingTypeDescription] = []
  477. /// The parameters of the function.
  478. var parameters: [ParameterDescription] = []
  479. /// The keywords of the function, such as `async` and `throws.`
  480. var keywords: [FunctionKeyword] = []
  481. /// The return type name of the function, such as `Int`.
  482. var returnType: Expression? = nil
  483. /// The where clause for a generic function.
  484. var whereClause: WhereClause?
  485. }
  486. /// A description of a function definition.
  487. ///
  488. /// For example: `func foo() { }`.
  489. struct FunctionDescription: Equatable, Codable {
  490. /// The signature of the function.
  491. var signature: FunctionSignatureDescription
  492. /// The body definition of the function.
  493. ///
  494. /// If nil, does not generate `{` and `}` at all for the body scope.
  495. var body: [CodeBlock]? = nil
  496. /// Creates a new function description.
  497. /// - Parameters:
  498. /// - signature: The signature of the function.
  499. /// - body: The body definition of the function.
  500. init(signature: FunctionSignatureDescription, body: [CodeBlock]? = nil) {
  501. self.signature = signature
  502. self.body = body
  503. }
  504. /// Creates a new function description.
  505. /// - Parameters:
  506. /// - accessModifier: An access modifier.
  507. /// - kind: The kind of the function.
  508. /// - parameters: The parameters of the function.
  509. /// - keywords: The keywords of the function, such as `async`.
  510. /// - returnType: The return type name of the function, such as `Int`.
  511. /// - body: The body definition of the function.
  512. init(
  513. accessModifier: AccessModifier? = nil,
  514. kind: FunctionKind,
  515. generics: [ExistingTypeDescription] = [],
  516. parameters: [ParameterDescription] = [],
  517. keywords: [FunctionKeyword] = [],
  518. returnType: Expression? = nil,
  519. whereClause: WhereClause? = nil,
  520. body: [CodeBlock]? = nil
  521. ) {
  522. self.signature = .init(
  523. accessModifier: accessModifier,
  524. kind: kind,
  525. generics: generics,
  526. parameters: parameters,
  527. keywords: keywords,
  528. returnType: returnType,
  529. whereClause: whereClause
  530. )
  531. self.body = body
  532. }
  533. /// Creates a new function description.
  534. /// - Parameters:
  535. /// - accessModifier: An access modifier.
  536. /// - kind: The kind of the function.
  537. /// - parameters: The parameters of the function.
  538. /// - keywords: The keywords of the function, such as `async`.
  539. /// - returnType: The return type name of the function, such as `Int`.
  540. /// - body: The body definition of the function.
  541. init(
  542. accessModifier: AccessModifier? = nil,
  543. kind: FunctionKind,
  544. generics: [ExistingTypeDescription] = [],
  545. parameters: [ParameterDescription] = [],
  546. keywords: [FunctionKeyword] = [],
  547. returnType: Expression? = nil,
  548. whereClause: WhereClause? = nil,
  549. body: [Expression]
  550. ) {
  551. self.init(
  552. accessModifier: accessModifier,
  553. kind: kind,
  554. generics: generics,
  555. parameters: parameters,
  556. keywords: keywords,
  557. returnType: returnType,
  558. whereClause: whereClause,
  559. body: body.map { .expression($0) }
  560. )
  561. }
  562. }
  563. /// A description of a closure signature.
  564. ///
  565. /// For example: `(String) async throws -> Int`.
  566. struct ClosureSignatureDescription: Equatable, Codable {
  567. /// The parameters of the function.
  568. var parameters: [ParameterDescription] = []
  569. /// The keywords of the function, such as `async` and `throws.`
  570. var keywords: [FunctionKeyword] = []
  571. /// The return type name of the function, such as `Int`.
  572. var returnType: Expression? = nil
  573. /// The ``@Sendable`` attribute.
  574. var sendable: Bool = false
  575. /// The ``@escaping`` attribute.
  576. var escaping: Bool = false
  577. }
  578. /// A description of the associated value of an enum case.
  579. ///
  580. /// For example, in `case foo(bar: String)`, the associated value
  581. /// represents `bar: String`.
  582. struct EnumCaseAssociatedValueDescription: Equatable, Codable {
  583. /// A variable label.
  584. ///
  585. /// For example, in `bar: String`, `label` is `bar`.
  586. var label: String?
  587. /// A variable type name.
  588. ///
  589. /// For example, in `bar: String`, `type` is `String`.
  590. var type: ExistingTypeDescription
  591. }
  592. /// An enum case kind.
  593. ///
  594. /// For example: `case foo` versus `case foo(String)`, and so on.
  595. enum EnumCaseKind: Equatable, Codable {
  596. /// A case with only a name.
  597. ///
  598. /// For example: `case foo`.
  599. case nameOnly
  600. /// A case with a name and a raw value.
  601. ///
  602. /// For example: `case foo = "Foo"`.
  603. case nameWithRawValue(LiteralDescription)
  604. /// A case with a name and associated values.
  605. ///
  606. /// For example: `case foo(String)`.
  607. case nameWithAssociatedValues([EnumCaseAssociatedValueDescription])
  608. }
  609. /// A description of an enum case.
  610. ///
  611. /// For example: `case foo(String)`.
  612. struct EnumCaseDescription: Equatable, Codable {
  613. /// The name of the enum case.
  614. ///
  615. /// For example, in `case foo`, `name` is `foo`.
  616. var name: String
  617. /// The kind of the enum case.
  618. var kind: EnumCaseKind = .nameOnly
  619. }
  620. /// A declaration of a Swift entity.
  621. indirect enum Declaration: Equatable, Codable {
  622. /// A declaration that adds a comment on top of the provided declaration.
  623. case commentable(Comment?, Declaration)
  624. /// A declaration that adds a comment on top of the provided declaration.
  625. case deprecated(DeprecationDescription, Declaration)
  626. /// A declaration that adds an availability guard on top of the provided declaration.
  627. case guarded(AvailabilityDescription, Declaration)
  628. /// A variable declaration.
  629. case variable(VariableDescription)
  630. /// An extension declaration.
  631. case `extension`(ExtensionDescription)
  632. /// A struct declaration.
  633. case `struct`(StructDescription)
  634. /// An enum declaration.
  635. case `enum`(EnumDescription)
  636. /// A typealias declaration.
  637. case `typealias`(TypealiasDescription)
  638. /// A protocol declaration.
  639. case `protocol`(ProtocolDescription)
  640. /// A function declaration.
  641. case function(FunctionDescription)
  642. /// An enum case declaration.
  643. case enumCase(EnumCaseDescription)
  644. }
  645. /// A description of a deprecation notice.
  646. ///
  647. /// For example: `@available(*, deprecated, message: "This is going away", renamed: "other(param:)")`
  648. struct DeprecationDescription: Equatable, Codable {
  649. /// A message used by the deprecation attribute.
  650. var message: String?
  651. /// A new name of the symbol, allowing the user to get a fix-it.
  652. var renamed: String?
  653. }
  654. /// A description of an availability guard.
  655. ///
  656. /// For example: `@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)`
  657. struct AvailabilityDescription: Equatable, Codable {
  658. /// The array of OSes and versions which are specified in the availability guard.
  659. var osVersions: [OSVersion]
  660. init(osVersions: [OSVersion]) {
  661. self.osVersions = osVersions
  662. }
  663. /// An OS and its version.
  664. struct OSVersion: Equatable, Codable {
  665. var os: OS
  666. var version: String
  667. init(os: OS, version: String) {
  668. self.os = os
  669. self.version = version
  670. }
  671. }
  672. /// One of the possible OSes.
  673. // swift-format-ignore: DontRepeatTypeInStaticProperties
  674. struct OS: Equatable, Codable {
  675. var name: String
  676. init(name: String) {
  677. self.name = name
  678. }
  679. static let macOS = Self(name: "macOS")
  680. static let iOS = Self(name: "iOS")
  681. static let watchOS = Self(name: "watchOS")
  682. static let tvOS = Self(name: "tvOS")
  683. static let visionOS = Self(name: "visionOS")
  684. }
  685. }
  686. /// A description of an assignment expression.
  687. ///
  688. /// For example: `foo = 42`.
  689. struct AssignmentDescription: Equatable, Codable {
  690. /// The left-hand side expression, the variable to assign to.
  691. ///
  692. /// For example, in `foo = 42`, `left` is `foo`.
  693. var left: Expression
  694. /// The right-hand side expression, the value to assign.
  695. ///
  696. /// For example, in `foo = 42`, `right` is `42`.
  697. var right: Expression
  698. }
  699. /// A switch case kind, either a `case` or a `default`.
  700. enum SwitchCaseKind: Equatable, Codable {
  701. /// A case.
  702. ///
  703. /// For example: `case let foo(bar):`.
  704. case `case`(Expression, [String])
  705. /// A case with multiple comma-separated expressions.
  706. ///
  707. /// For example: `case "foo", "bar":`.
  708. case multiCase([Expression])
  709. /// A default. Spelled as `default:`.
  710. case `default`
  711. }
  712. /// A description of a switch case definition.
  713. ///
  714. /// For example: `case foo: print("foo")`.
  715. struct SwitchCaseDescription: Equatable, Codable {
  716. /// The kind of the switch case.
  717. var kind: SwitchCaseKind
  718. /// The body of the switch case.
  719. ///
  720. /// For example, in `case foo: print("foo")`, `body`
  721. /// represents `print("foo")`.
  722. var body: [CodeBlock]
  723. }
  724. /// A description of a switch statement expression.
  725. ///
  726. /// For example: `switch foo {`.
  727. struct SwitchDescription: Equatable, Codable {
  728. /// The expression evaluated by the switch statement.
  729. ///
  730. /// For example, in `switch foo {`, `switchedExpression` is `foo`.
  731. var switchedExpression: Expression
  732. /// The cases defined in the switch statement.
  733. var cases: [SwitchCaseDescription]
  734. }
  735. /// A description of an if branch and the corresponding code block.
  736. ///
  737. /// For example: in `if foo { bar }`, the condition pair represents
  738. /// `foo` + `bar`.
  739. struct IfBranch: Equatable, Codable {
  740. /// The expressions evaluated by the if statement and their corresponding
  741. /// body blocks. If more than one is provided, an `else if` branch is added.
  742. ///
  743. /// For example, in `if foo { bar }`, `condition` is `foo`.
  744. var condition: Expression
  745. /// The body executed if the `condition` evaluates to true.
  746. ///
  747. /// For example, in `if foo { bar }`, `body` is `bar`.
  748. var body: [CodeBlock]
  749. }
  750. /// A description of an if[[/elseif]/else] statement expression.
  751. ///
  752. /// For example: `if foo { } else if bar { } else { }`.
  753. struct IfStatementDescription: Equatable, Codable {
  754. /// The primary `if` branch.
  755. var ifBranch: IfBranch
  756. /// Additional `else if` branches.
  757. var elseIfBranches: [IfBranch]
  758. /// The body of an else block.
  759. ///
  760. /// No `else` statement is added when `elseBody` is nil.
  761. var elseBody: [CodeBlock]?
  762. }
  763. /// A description of a do statement.
  764. ///
  765. /// For example: `do { try foo() } catch { return bar }`.
  766. struct DoStatementDescription: Equatable, Codable {
  767. /// The code blocks in the `do` statement body.
  768. ///
  769. /// For example, in `do { try foo() } catch { return bar }`,
  770. /// `doBody` is `try foo()`.
  771. var doStatement: [CodeBlock]
  772. /// The code blocks in the `catch` statement.
  773. ///
  774. /// If nil, no `catch` statement is added.
  775. ///
  776. /// For example, in `do { try foo() } catch { return bar }`,
  777. /// `catchBody` is `return bar`.
  778. var catchBody: [CodeBlock]?
  779. }
  780. /// A description of a value binding used in enums with associated values.
  781. ///
  782. /// For example: `let foo(bar)`.
  783. struct ValueBindingDescription: Equatable, Codable {
  784. /// The binding kind: `let` or `var`.
  785. var kind: BindingKind
  786. /// The bound values in a function call expression syntax.
  787. ///
  788. /// For example, in `let foo(bar)`, `value` represents `foo(bar)`.
  789. var value: FunctionCallDescription
  790. }
  791. /// A kind of a keyword.
  792. enum KeywordKind: Equatable, Codable {
  793. /// The return keyword.
  794. case `return`
  795. /// The try keyword.
  796. case `try`(hasPostfixQuestionMark: Bool)
  797. /// The await keyword.
  798. case `await`
  799. /// The throw keyword.
  800. case `throw`
  801. /// The yield keyword.
  802. case `yield`
  803. }
  804. /// A description of an expression that places a keyword before an expression.
  805. struct UnaryKeywordDescription: Equatable, Codable {
  806. /// The keyword to place before the expression.
  807. ///
  808. /// For example, in `return foo`, `kind` represents `return`.
  809. var kind: KeywordKind
  810. /// The expression prefixed by the keyword.
  811. ///
  812. /// For example, in `return foo`, `expression` represents `foo`.
  813. var expression: Expression? = nil
  814. }
  815. /// A description of a closure invocation.
  816. ///
  817. /// For example: `{ foo in return foo + "bar" }`.
  818. struct ClosureInvocationDescription: Equatable, Codable {
  819. /// The names of the arguments taken by the closure.
  820. ///
  821. /// For example, in `{ foo in return foo + "bar" }`, `argumentNames`
  822. /// is `["foo"]`.
  823. var argumentNames: [String] = []
  824. /// The code blocks of the closure body.
  825. ///
  826. /// For example, in `{ foo in return foo + "bar" }`, `body`
  827. /// represents `return foo + "bar"`.
  828. var body: [CodeBlock]? = nil
  829. }
  830. /// A binary operator.
  831. ///
  832. /// For example: `+=` in `a += b`.
  833. enum BinaryOperator: String, Equatable, Codable {
  834. /// The += operator, adds and then assigns another value.
  835. case plusEquals = "+="
  836. /// The == operator, checks equality between two values.
  837. case equals = "=="
  838. /// The ... operator, creates an end-inclusive range between two numbers.
  839. case rangeInclusive = "..."
  840. /// The || operator, used between two Boolean values.
  841. case booleanOr = "||"
  842. }
  843. /// A description of a binary operation expression.
  844. ///
  845. /// For example: `foo += 1`.
  846. struct BinaryOperationDescription: Equatable, Codable {
  847. /// The left-hand side expression of the operation.
  848. ///
  849. /// For example, in `foo += 1`, `left` is `foo`.
  850. var left: Expression
  851. /// The binary operator tying the two expressions together.
  852. ///
  853. /// For example, in `foo += 1`, `operation` represents `+=`.
  854. var operation: BinaryOperator
  855. /// The right-hand side expression of the operation.
  856. ///
  857. /// For example, in `foo += 1`, `right` is `1`.
  858. var right: Expression
  859. }
  860. /// A description of an inout expression, which provides a read-write
  861. /// reference to a variable.
  862. ///
  863. /// For example, `&foo` passes a reference to the `foo` variable.
  864. struct InOutDescription: Equatable, Codable {
  865. /// The referenced expression.
  866. ///
  867. /// For example, in `&foo`, `referencedExpr` is `foo`.
  868. var referencedExpr: Expression
  869. }
  870. /// A description of an optional chaining expression.
  871. ///
  872. /// For example, in `foo?`, `referencedExpr` is `foo`.
  873. struct OptionalChainingDescription: Equatable, Codable {
  874. /// The referenced expression.
  875. ///
  876. /// For example, in `foo?`, `referencedExpr` is `foo`.
  877. var referencedExpr: Expression
  878. }
  879. /// A description of a tuple.
  880. ///
  881. /// For example: `(foo, bar)`.
  882. struct TupleDescription: Equatable, Codable {
  883. /// The member expressions.
  884. ///
  885. /// For example, in `(foo, bar)`, `members` is `[foo, bar]`.
  886. var members: [Expression]
  887. }
  888. /// A Swift expression.
  889. indirect enum Expression: Equatable, Codable {
  890. /// A literal.
  891. ///
  892. /// For example `"hello"` or `42`.
  893. case literal(LiteralDescription)
  894. /// An identifier, such as a variable name.
  895. ///
  896. /// For example, in `let foo = 42`, `foo` is an identifier.
  897. case identifier(IdentifierDescription)
  898. /// A member access expression.
  899. ///
  900. /// For example: `foo.bar`.
  901. case memberAccess(MemberAccessDescription)
  902. /// A function call.
  903. ///
  904. /// For example: `foo(bar: 42)`.
  905. case functionCall(FunctionCallDescription)
  906. /// An assignment expression.
  907. ///
  908. /// For example `foo = 42`.
  909. case assignment(AssignmentDescription)
  910. /// A switch statement expression.
  911. ///
  912. /// For example: `switch foo {`.
  913. case `switch`(SwitchDescription)
  914. /// An if statement, with optional else if's and an else statement attached.
  915. ///
  916. /// For example: `if foo { bar } else if baz { boo } else { bam }`.
  917. case ifStatement(IfStatementDescription)
  918. /// A do statement.
  919. ///
  920. /// For example: `do { try foo() } catch { return bar }`.
  921. case doStatement(DoStatementDescription)
  922. /// A value binding used in enums with associated values.
  923. ///
  924. /// For example: `let foo(bar)`.
  925. case valueBinding(ValueBindingDescription)
  926. /// An expression that places a keyword before an expression.
  927. case unaryKeyword(UnaryKeywordDescription)
  928. /// A closure invocation.
  929. ///
  930. /// For example: `{ foo in return foo + "bar" }`.
  931. case closureInvocation(ClosureInvocationDescription)
  932. /// A binary operation expression.
  933. ///
  934. /// For example: `foo += 1`.
  935. case binaryOperation(BinaryOperationDescription)
  936. /// An inout expression, which provides a reference to a variable.
  937. ///
  938. /// For example, `&foo` passes a reference to the `foo` variable.
  939. case inOut(InOutDescription)
  940. /// An optional chaining expression.
  941. ///
  942. /// For example, in `foo?`, `referencedExpr` is `foo`.
  943. case optionalChaining(OptionalChainingDescription)
  944. /// A tuple expression.
  945. ///
  946. /// For example: `(foo, bar)`.
  947. case tuple(TupleDescription)
  948. }
  949. /// A code block item, either a declaration or an expression.
  950. enum CodeBlockItem: Equatable, Codable {
  951. /// A declaration, such as of a new type or function.
  952. case declaration(Declaration)
  953. /// An expression, such as a call of a declared function.
  954. case expression(Expression)
  955. }
  956. /// A code block, with an optional comment.
  957. struct CodeBlock: Equatable, Codable {
  958. /// The comment to prepend to the code block item.
  959. var comment: Comment?
  960. /// The code block item that appears below the comment.
  961. var item: CodeBlockItem
  962. }
  963. /// A description of a Swift file.
  964. struct FileDescription: Equatable, Codable {
  965. /// A comment placed at the top of the file.
  966. var topComment: Comment?
  967. /// Import statements placed below the top comment, but before the code
  968. /// blocks.
  969. var imports: [ImportDescription]?
  970. /// The code blocks that represent the main contents of the file.
  971. var codeBlocks: [CodeBlock]
  972. }
  973. /// A description of a named Swift file.
  974. struct NamedFileDescription: Equatable, Codable {
  975. /// A file name, including the file extension.
  976. ///
  977. /// For example: `Foo.swift`.
  978. var name: String
  979. /// The contents of the file.
  980. var contents: FileDescription
  981. }
  982. /// A file with contents made up of structured Swift code.
  983. struct StructuredSwiftRepresentation: Equatable, Codable {
  984. /// The contents of the file.
  985. var file: NamedFileDescription
  986. }
  987. // MARK: - Conveniences
  988. extension Declaration {
  989. /// A variable declaration.
  990. ///
  991. /// For example: `let foo = 42`.
  992. /// - Parameters:
  993. /// - accessModifier: An access modifier.
  994. /// - isStatic: A Boolean value that indicates whether the variable
  995. /// is static.
  996. /// - kind: The variable binding kind.
  997. /// - left: The name of the variable.
  998. /// - type: The type of the variable.
  999. /// - right: The expression to be assigned to the variable.
  1000. /// - getter: Body code for the getter of the variable.
  1001. /// - getterEffects: Effects of the getter.
  1002. /// - setter: Body code for the setter of the variable.
  1003. /// - modify: Body code for the `_modify` accessor.
  1004. /// - Returns: Variable declaration.
  1005. static func variable(
  1006. accessModifier: AccessModifier? = nil,
  1007. isStatic: Bool = false,
  1008. kind: BindingKind,
  1009. left: String,
  1010. type: ExistingTypeDescription? = nil,
  1011. right: Expression? = nil,
  1012. getter: [CodeBlock]? = nil,
  1013. getterEffects: [FunctionKeyword] = [],
  1014. setter: [CodeBlock]? = nil,
  1015. modify: [CodeBlock]? = nil
  1016. ) -> Self {
  1017. .variable(
  1018. accessModifier: accessModifier,
  1019. isStatic: isStatic,
  1020. kind: kind,
  1021. left: .identifierPattern(left),
  1022. type: type,
  1023. right: right,
  1024. getter: getter,
  1025. getterEffects: getterEffects,
  1026. setter: setter,
  1027. modify: modify
  1028. )
  1029. }
  1030. /// A variable declaration.
  1031. ///
  1032. /// For example: `let foo = 42`.
  1033. /// - Parameters:
  1034. /// - accessModifier: An access modifier.
  1035. /// - isStatic: A Boolean value that indicates whether the variable
  1036. /// is static.
  1037. /// - kind: The variable binding kind.
  1038. /// - left: The name of the variable.
  1039. /// - type: The type of the variable.
  1040. /// - right: The expression to be assigned to the variable.
  1041. /// - getter: Body code for the getter of the variable.
  1042. /// - getterEffects: Effects of the getter.
  1043. /// - setter: Body code for the setter of the variable.
  1044. /// - modify: Body code for the `_modify` accessor.
  1045. /// - Returns: Variable declaration.
  1046. static func variable(
  1047. accessModifier: AccessModifier? = nil,
  1048. isStatic: Bool = false,
  1049. kind: BindingKind,
  1050. left: Expression,
  1051. type: ExistingTypeDescription? = nil,
  1052. right: Expression? = nil,
  1053. getter: [CodeBlock]? = nil,
  1054. getterEffects: [FunctionKeyword] = [],
  1055. setter: [CodeBlock]? = nil,
  1056. modify: [CodeBlock]? = nil
  1057. ) -> Self {
  1058. .variable(
  1059. .init(
  1060. accessModifier: accessModifier,
  1061. isStatic: isStatic,
  1062. kind: kind,
  1063. left: left,
  1064. type: type,
  1065. right: right,
  1066. getter: getter,
  1067. getterEffects: getterEffects,
  1068. setter: setter,
  1069. modify: modify
  1070. )
  1071. )
  1072. }
  1073. /// A description of an enum case.
  1074. ///
  1075. /// For example: `case foo(String)`.
  1076. /// - Parameters:
  1077. /// - name: The name of the enum case.
  1078. /// - kind: The kind of the enum case.
  1079. /// - Returns: An enum case declaration.
  1080. static func enumCase(name: String, kind: EnumCaseKind = .nameOnly) -> Self {
  1081. .enumCase(.init(name: name, kind: kind))
  1082. }
  1083. /// A description of a typealias declaration.
  1084. ///
  1085. /// For example `typealias Foo = Int`.
  1086. /// - Parameters:
  1087. /// - accessModifier: An access modifier.
  1088. /// - name: The name of the typealias.
  1089. /// - existingType: The existing type that serves as the
  1090. /// underlying type of the alias.
  1091. /// - Returns: A typealias declaration.
  1092. static func `typealias`(
  1093. accessModifier: AccessModifier? = nil,
  1094. name: String,
  1095. existingType: ExistingTypeDescription
  1096. )
  1097. -> Self
  1098. { .typealias(.init(accessModifier: accessModifier, name: name, existingType: existingType)) }
  1099. /// A description of a function definition.
  1100. ///
  1101. /// For example: `func foo() { }`.
  1102. /// - Parameters:
  1103. /// - accessModifier: An access modifier.
  1104. /// - kind: The kind of the function.
  1105. /// - parameters: The parameters of the function.
  1106. /// - keywords: The keywords of the function, such as `async` and
  1107. /// `throws.`
  1108. /// - returnType: The return type name of the function, such as `Int`.
  1109. /// - body: The body definition of the function.
  1110. /// - Returns: A function declaration.
  1111. static func function(
  1112. accessModifier: AccessModifier? = nil,
  1113. kind: FunctionKind,
  1114. generics: [ExistingTypeDescription] = [],
  1115. parameters: [ParameterDescription],
  1116. keywords: [FunctionKeyword] = [],
  1117. returnType: Expression? = nil,
  1118. whereClause: WhereClause?,
  1119. body: [CodeBlock]? = nil
  1120. ) -> Self {
  1121. .function(
  1122. .init(
  1123. accessModifier: accessModifier,
  1124. kind: kind,
  1125. generics: generics,
  1126. parameters: parameters,
  1127. keywords: keywords,
  1128. returnType: returnType,
  1129. whereClause: whereClause,
  1130. body: body
  1131. )
  1132. )
  1133. }
  1134. /// A description of a function definition.
  1135. ///
  1136. /// For example: `func foo() { }`.
  1137. /// - Parameters:
  1138. /// - signature: The signature of the function.
  1139. /// - body: The body definition of the function.
  1140. /// - Returns: A function declaration.
  1141. static func function(signature: FunctionSignatureDescription, body: [CodeBlock]? = nil) -> Self {
  1142. .function(.init(signature: signature, body: body))
  1143. }
  1144. /// A description of an enum declaration.
  1145. ///
  1146. /// For example `enum Bar {`.
  1147. /// - Parameters:
  1148. /// - isFrozen: A Boolean value that indicates whether the enum has
  1149. /// a `@frozen` attribute.
  1150. /// - accessModifier: An access modifier.
  1151. /// - name: The name of the enum.
  1152. /// - conformances: The type names that the enum conforms to.
  1153. /// - members: The declarations that make up the enum body.
  1154. /// - Returns: An enum declaration.
  1155. static func `enum`(
  1156. isFrozen: Bool = false,
  1157. accessModifier: AccessModifier? = nil,
  1158. name: String,
  1159. conformances: [String] = [],
  1160. members: [Declaration] = []
  1161. ) -> Self {
  1162. .enum(
  1163. .init(
  1164. isFrozen: isFrozen,
  1165. accessModifier: accessModifier,
  1166. name: name,
  1167. conformances: conformances,
  1168. members: members
  1169. )
  1170. )
  1171. }
  1172. /// A description of an extension declaration.
  1173. ///
  1174. /// For example `extension Foo {`.
  1175. /// - Parameters:
  1176. /// - accessModifier: An access modifier.
  1177. /// - onType: The name of the extended type.
  1178. /// - conformances: Additional type names that the extension conforms to.
  1179. /// - whereClause: A where clause constraining the extension declaration.
  1180. /// - declarations: The declarations that the extension adds on the
  1181. /// extended type.
  1182. /// - Returns: An extension declaration.
  1183. static func `extension`(
  1184. accessModifier: AccessModifier? = nil,
  1185. onType: String,
  1186. conformances: [String] = [],
  1187. whereClause: WhereClause? = nil,
  1188. declarations: [Declaration]
  1189. ) -> Self {
  1190. .extension(
  1191. .init(
  1192. accessModifier: accessModifier,
  1193. onType: onType,
  1194. conformances: conformances,
  1195. whereClause: whereClause,
  1196. declarations: declarations
  1197. )
  1198. )
  1199. }
  1200. }
  1201. extension FunctionKind {
  1202. /// Returns a non-failable initializer, for example `init()`.
  1203. static var initializer: Self { .initializer(failable: false) }
  1204. /// Returns a non-static function kind.
  1205. static func function(name: String) -> Self {
  1206. .function(name: name, isStatic: false)
  1207. }
  1208. }
  1209. extension CodeBlock {
  1210. /// Returns a new declaration code block wrapping the provided declaration.
  1211. /// - Parameter declaration: The declaration to wrap.
  1212. /// - Returns: A new `CodeBlock` instance containing the provided declaration.
  1213. static func declaration(_ declaration: Declaration) -> Self {
  1214. CodeBlock(item: .declaration(declaration))
  1215. }
  1216. /// Returns a new expression code block wrapping the provided expression.
  1217. /// - Parameter expression: The expression to wrap.
  1218. /// - Returns: A new `CodeBlock` instance containing the provided declaration.
  1219. static func expression(_ expression: Expression) -> Self {
  1220. CodeBlock(item: .expression(expression))
  1221. }
  1222. }
  1223. extension Expression {
  1224. /// A string literal.
  1225. ///
  1226. /// For example: `"hello"`.
  1227. /// - Parameter value: The string value of the literal.
  1228. /// - Returns: A new `Expression` representing a string literal.
  1229. static func literal(_ value: String) -> Self { .literal(.string(value)) }
  1230. /// An integer literal.
  1231. ///
  1232. /// For example `42`.
  1233. /// - Parameter value: The integer value of the literal.
  1234. /// - Returns: A new `Expression` representing an integer literal.
  1235. static func literal(_ value: Int) -> Self { .literal(.int(value)) }
  1236. /// Returns a new expression that accesses the member on the current
  1237. /// expression.
  1238. /// - Parameter member: The name of the member to access on the expression.
  1239. /// - Returns: A new expression representing member access.
  1240. func dot(_ member: String) -> Expression { .memberAccess(.init(left: self, right: member)) }
  1241. /// Returns a new expression that calls the current expression as a function
  1242. /// with the specified arguments.
  1243. /// - Parameter arguments: The arguments used to call the expression.
  1244. /// - Returns: A new expression representing a function call.
  1245. func call(_ arguments: [FunctionArgumentDescription]) -> Expression {
  1246. .functionCall(.init(calledExpression: self, arguments: arguments))
  1247. }
  1248. /// Returns a new member access expression without a receiver,
  1249. /// starting with dot.
  1250. ///
  1251. /// For example: `.foo`, where `member` is `foo`.
  1252. /// - Parameter member: The name of the member to access.
  1253. /// - Returns: A new expression representing member access with a dot prefix.
  1254. static func dot(_ member: String) -> Self { Self.memberAccess(.init(right: member)) }
  1255. /// Returns a new identifier expression for the provided pattern, such
  1256. /// as a variable or function name.
  1257. /// - Parameter name: The name of the identifier.
  1258. /// - Returns: A new expression representing an identifier with
  1259. /// the specified name.
  1260. static func identifierPattern(_ name: String) -> Self { .identifier(.pattern(name)) }
  1261. /// Returns a new identifier expression for the provided type name.
  1262. /// - Parameter type: The description of the type.
  1263. /// - Returns: A new expression representing an identifier with
  1264. /// the specified name.
  1265. static func identifierType(_ type: ExistingTypeDescription) -> Self { .identifier(.type(type)) }
  1266. /// Returns a new identifier expression for the provided type name.
  1267. /// - Parameter type: The name of the type.
  1268. /// - Returns: A new expression representing an identifier with
  1269. /// the specified name.
  1270. static func identifierType(_ type: TypeName) -> Self { .identifier(.type(.init(type))) }
  1271. /// Returns a new identifier expression for the provided type name.
  1272. /// - Parameter type: The usage of the type.
  1273. /// - Returns: A new expression representing an identifier with
  1274. /// the specified name.
  1275. static func identifierType(_ type: TypeUsage) -> Self { .identifier(.type(.init(type))) }
  1276. /// Returns a new switch statement expression.
  1277. /// - Parameters:
  1278. /// - switchedExpression: The expression evaluated by the switch
  1279. /// statement.
  1280. /// - cases: The cases defined in the switch statement.
  1281. /// - Returns: A new expression representing a switch statement with the specified switched expression and cases
  1282. static func `switch`(switchedExpression: Expression, cases: [SwitchCaseDescription]) -> Self {
  1283. .`switch`(.init(switchedExpression: switchedExpression, cases: cases))
  1284. }
  1285. /// Returns an if statement, with optional else if's and an else
  1286. /// statement attached.
  1287. /// - Parameters:
  1288. /// - ifBranch: The primary `if` branch.
  1289. /// - elseIfBranches: Additional `else if` branches.
  1290. /// - elseBody: The body of an else block.
  1291. /// - Returns: A new expression representing an `if` statement with the specified branches and blocks.
  1292. static func ifStatement(
  1293. ifBranch: IfBranch,
  1294. elseIfBranches: [IfBranch] = [],
  1295. elseBody: [CodeBlock]? = nil
  1296. ) -> Self {
  1297. .ifStatement(.init(ifBranch: ifBranch, elseIfBranches: elseIfBranches, elseBody: elseBody))
  1298. }
  1299. /// Returns a new function call expression.
  1300. ///
  1301. /// For example `foo(bar: 42)`.
  1302. /// - Parameters:
  1303. /// - calledExpression: The expression to be called as a function.
  1304. /// - arguments: The arguments to be passed to the function call.
  1305. /// - trailingClosure: A trailing closure.
  1306. /// - Returns: A new expression representing a function call with the specified called expression and arguments.
  1307. static func functionCall(
  1308. calledExpression: Expression,
  1309. arguments: [FunctionArgumentDescription] = [],
  1310. trailingClosure: ClosureInvocationDescription? = nil
  1311. ) -> Self {
  1312. .functionCall(
  1313. .init(
  1314. calledExpression: calledExpression,
  1315. arguments: arguments,
  1316. trailingClosure: trailingClosure
  1317. )
  1318. )
  1319. }
  1320. /// Returns a new function call expression.
  1321. ///
  1322. /// For example: `foo(bar: 42)`.
  1323. /// - Parameters:
  1324. /// - calledExpression: The expression called as a function.
  1325. /// - arguments: The arguments passed to the function call.
  1326. /// - trailingClosure: A trailing closure.
  1327. /// - Returns: A new expression representing a function call with the specified called expression and arguments.
  1328. static func functionCall(
  1329. calledExpression: Expression,
  1330. arguments: [Expression],
  1331. trailingClosure: ClosureInvocationDescription? = nil
  1332. ) -> Self {
  1333. .functionCall(
  1334. .init(
  1335. calledExpression: calledExpression,
  1336. arguments: arguments.map { .init(label: nil, expression: $0) },
  1337. trailingClosure: trailingClosure
  1338. )
  1339. )
  1340. }
  1341. /// Returns a new expression that places a keyword before an expression.
  1342. /// - Parameters:
  1343. /// - kind: The keyword to place before the expression.
  1344. /// - expression: The expression prefixed by the keyword.
  1345. /// - Returns: A new expression with the specified keyword placed before the expression.
  1346. static func unaryKeyword(kind: KeywordKind, expression: Expression? = nil) -> Self {
  1347. .unaryKeyword(.init(kind: kind, expression: expression))
  1348. }
  1349. /// Returns a new expression that puts the return keyword before
  1350. /// an expression.
  1351. /// - Parameter expression: The expression to prepend.
  1352. /// - Returns: A new expression with the `return` keyword placed before the expression.
  1353. static func `return`(_ expression: Expression? = nil) -> Self {
  1354. .unaryKeyword(kind: .return, expression: expression)
  1355. }
  1356. /// Returns a new expression that puts the try keyword before
  1357. /// an expression.
  1358. /// - Parameter expression: The expression to prepend.
  1359. /// - Returns: A new expression with the `try` keyword placed before the expression.
  1360. static func `try`(_ expression: Expression) -> Self {
  1361. .unaryKeyword(kind: .try, expression: expression)
  1362. }
  1363. /// Returns a new expression that puts the try? keyword before
  1364. /// an expression.
  1365. /// - Parameter expression: The expression to prepend.
  1366. /// - Returns: A new expression with the `try?` keyword placed before the expression.
  1367. static func optionalTry(_ expression: Expression) -> Self {
  1368. .unaryKeyword(kind: .try(hasPostfixQuestionMark: true), expression: expression)
  1369. }
  1370. /// Returns a new expression that puts the await keyword before
  1371. /// an expression.
  1372. /// - Parameter expression: The expression to prepend.
  1373. /// - Returns: A new expression with the `await` keyword placed before the expression.
  1374. static func `await`(_ expression: Expression) -> Self {
  1375. .unaryKeyword(kind: .await, expression: expression)
  1376. }
  1377. /// Returns a new expression that puts the yield keyword before
  1378. /// an expression.
  1379. /// - Parameter expression: The expression to prepend.
  1380. /// - Returns: A new expression with the `yield` keyword placed before the expression.
  1381. static func `yield`(_ expression: Expression) -> Self {
  1382. .unaryKeyword(kind: .yield, expression: expression)
  1383. }
  1384. /// Returns a new expression that puts the provided code blocks into
  1385. /// a do/catch block.
  1386. /// - Parameter:
  1387. /// - doStatement: The code blocks in the `do` statement body.
  1388. /// - catchBody: The code blocks in the `catch` statement.
  1389. /// - Returns: The expression.
  1390. static func `do`(_ doStatement: [CodeBlock], catchBody: [CodeBlock]? = nil) -> Self {
  1391. .doStatement(.init(doStatement: doStatement, catchBody: catchBody))
  1392. }
  1393. /// Returns a new value binding used in enums with associated values.
  1394. ///
  1395. /// For example: `let foo(bar)`.
  1396. /// - Parameters:
  1397. /// - kind: The binding kind: `let` or `var`.
  1398. /// - value: The bound values in a function call expression syntax.
  1399. /// - Returns: A new expression representing the value binding.
  1400. static func valueBinding(kind: BindingKind, value: FunctionCallDescription) -> Self {
  1401. .valueBinding(.init(kind: kind, value: value))
  1402. }
  1403. /// Returns a new closure invocation expression.
  1404. ///
  1405. /// For example: such as `{ foo in return foo + "bar" }`.
  1406. /// - Parameters:
  1407. /// - argumentNames: The names of the arguments taken by the closure.
  1408. /// - body: The code blocks of the closure body.
  1409. /// - Returns: A new expression representing the closure invocation
  1410. static func `closureInvocation`(argumentNames: [String] = [], body: [CodeBlock]? = nil) -> Self {
  1411. .closureInvocation(.init(argumentNames: argumentNames, body: body))
  1412. }
  1413. /// Creates a new binary operation expression.
  1414. ///
  1415. /// For example: `foo += 1`.
  1416. /// - Parameters:
  1417. /// - left: The left-hand side expression of the operation.
  1418. /// - operation: The binary operator tying the two expressions together.
  1419. /// - right: The right-hand side expression of the operation.
  1420. /// - Returns: A new expression representing the binary operation.
  1421. static func `binaryOperation`(
  1422. left: Expression,
  1423. operation: BinaryOperator,
  1424. right: Expression
  1425. ) -> Self {
  1426. .binaryOperation(.init(left: left, operation: operation, right: right))
  1427. }
  1428. /// Creates a new inout expression, which provides a read-write
  1429. /// reference to a variable.
  1430. ///
  1431. /// For example, `&foo` passes a reference to the `foo` variable.
  1432. /// - Parameter referencedExpr: The referenced expression.
  1433. /// - Returns: A new expression representing the inout expression.
  1434. static func inOut(_ referencedExpr: Expression) -> Self {
  1435. .inOut(.init(referencedExpr: referencedExpr))
  1436. }
  1437. /// Creates a new assignment expression.
  1438. ///
  1439. /// For example: `foo = 42`.
  1440. /// - Parameters:
  1441. /// - left: The left-hand side expression, the variable to assign to.
  1442. /// - right: The right-hand side expression, the value to assign.
  1443. /// - Returns: Assignment expression.
  1444. static func assignment(left: Expression, right: Expression) -> Self {
  1445. .assignment(.init(left: left, right: right))
  1446. }
  1447. /// Returns a new optional chaining expression wrapping the current
  1448. /// expression.
  1449. ///
  1450. /// For example, for the current expression `foo`, returns `foo?`.
  1451. /// - Returns: A new expression representing the optional chaining operation.
  1452. func optionallyChained() -> Self { .optionalChaining(.init(referencedExpr: self)) }
  1453. /// Returns a new tuple expression.
  1454. ///
  1455. /// For example, in `(foo, bar)`, `members` is `[foo, bar]`.
  1456. /// - Parameter expressions: The member expressions.
  1457. /// - Returns: A tuple expression.
  1458. static func tuple(_ expressions: [Expression]) -> Self { .tuple(.init(members: expressions)) }
  1459. }
  1460. extension MemberAccessDescription {
  1461. /// Creates a new member access expression without a receiver, starting
  1462. /// with dot.
  1463. ///
  1464. /// For example, `.foo`, where `member` is `foo`.
  1465. /// - Parameter member: The name of the member to access.
  1466. /// - Returns: A new member access expression.
  1467. static func dot(_ member: String) -> Self { .init(right: member) }
  1468. }
  1469. extension LiteralDescription: ExpressibleByStringLiteral, ExpressibleByNilLiteral,
  1470. ExpressibleByArrayLiteral
  1471. {
  1472. init(arrayLiteral elements: Expression...) { self = .array(elements) }
  1473. init(stringLiteral value: String) { self = .string(value) }
  1474. init(nilLiteral: ()) { self = .nil }
  1475. }
  1476. extension VariableDescription {
  1477. /// Returns a new mutable variable declaration.
  1478. ///
  1479. /// For example `var foo = 42`.
  1480. /// - Parameter name: The name of the variable.
  1481. /// - Returns: A new mutable variable declaration.
  1482. static func `var`(_ name: String) -> Self {
  1483. Self.init(kind: .var, left: .identifierPattern(name))
  1484. }
  1485. /// Returns a new immutable variable declaration.
  1486. ///
  1487. /// For example `let foo = 42`.
  1488. /// - Parameter name: The name of the variable.
  1489. /// - Returns: A new immutable variable declaration.
  1490. static func `let`(_ name: String) -> Self {
  1491. Self.init(kind: .let, left: .identifierPattern(name))
  1492. }
  1493. }
  1494. extension Expression {
  1495. /// Creates a new assignment description where the called expression is
  1496. /// assigned the value of the specified expression.
  1497. /// - Parameter rhs: The right-hand side of the assignment expression.
  1498. /// - Returns: An assignment description representing the assignment.
  1499. func equals(_ rhs: Expression) -> AssignmentDescription { .init(left: self, right: rhs) }
  1500. }
  1501. extension FunctionSignatureDescription {
  1502. /// Returns a new function signature description that has the access
  1503. /// modifier updated to the specified one.
  1504. /// - Parameter accessModifier: The access modifier to use.
  1505. /// - Returns: A function signature description with the specified access modifier.
  1506. func withAccessModifier(_ accessModifier: AccessModifier?) -> Self {
  1507. var value = self
  1508. value.accessModifier = accessModifier
  1509. return value
  1510. }
  1511. }
  1512. extension SwitchCaseKind {
  1513. /// Returns a new switch case kind with no argument names, only the
  1514. /// specified expression as the name.
  1515. /// - Parameter expression: The expression for the switch case label.
  1516. /// - Returns: A switch case kind with the specified expression as the label.
  1517. static func `case`(_ expression: Expression) -> Self { .case(expression, []) }
  1518. }
  1519. extension KeywordKind {
  1520. /// Returns the try keyword without the postfix question mark.
  1521. static var `try`: Self { .try(hasPostfixQuestionMark: false) }
  1522. }
  1523. extension Declaration {
  1524. /// Returns a new deprecated variant of the declaration if `shouldDeprecate` is true.
  1525. func deprecate(if shouldDeprecate: Bool) -> Self {
  1526. if shouldDeprecate { return .deprecated(.init(), self) }
  1527. return self
  1528. }
  1529. /// Returns the declaration one level deeper, nested inside the commentable
  1530. /// declaration, if present.
  1531. var strippingTopComment: Self {
  1532. guard case let .commentable(_, underlyingDecl) = self else { return self }
  1533. return underlyingDecl
  1534. }
  1535. }
  1536. extension Declaration {
  1537. /// An access modifier.
  1538. var accessModifier: AccessModifier? {
  1539. get {
  1540. switch self {
  1541. case .commentable(_, let declaration): return declaration.accessModifier
  1542. case .deprecated(_, let declaration): return declaration.accessModifier
  1543. case .guarded(_, let declaration): return declaration.accessModifier
  1544. case .variable(let variableDescription): return variableDescription.accessModifier
  1545. case .extension(let extensionDescription): return extensionDescription.accessModifier
  1546. case .struct(let structDescription): return structDescription.accessModifier
  1547. case .enum(let enumDescription): return enumDescription.accessModifier
  1548. case .typealias(let typealiasDescription): return typealiasDescription.accessModifier
  1549. case .protocol(let protocolDescription): return protocolDescription.accessModifier
  1550. case .function(let functionDescription): return functionDescription.signature.accessModifier
  1551. case .enumCase: return nil
  1552. }
  1553. }
  1554. set {
  1555. switch self {
  1556. case .commentable(let comment, var declaration):
  1557. declaration.accessModifier = newValue
  1558. self = .commentable(comment, declaration)
  1559. case .deprecated(let deprecationDescription, var declaration):
  1560. declaration.accessModifier = newValue
  1561. self = .deprecated(deprecationDescription, declaration)
  1562. case .guarded(let availability, var declaration):
  1563. declaration.accessModifier = newValue
  1564. self = .guarded(availability, declaration)
  1565. case .variable(var variableDescription):
  1566. variableDescription.accessModifier = newValue
  1567. self = .variable(variableDescription)
  1568. case .extension(var extensionDescription):
  1569. extensionDescription.accessModifier = newValue
  1570. self = .extension(extensionDescription)
  1571. case .struct(var structDescription):
  1572. structDescription.accessModifier = newValue
  1573. self = .struct(structDescription)
  1574. case .enum(var enumDescription):
  1575. enumDescription.accessModifier = newValue
  1576. self = .enum(enumDescription)
  1577. case .typealias(var typealiasDescription):
  1578. typealiasDescription.accessModifier = newValue
  1579. self = .typealias(typealiasDescription)
  1580. case .protocol(var protocolDescription):
  1581. protocolDescription.accessModifier = newValue
  1582. self = .protocol(protocolDescription)
  1583. case .function(var functionDescription):
  1584. functionDescription.signature.accessModifier = newValue
  1585. self = .function(functionDescription)
  1586. case .enumCase: break
  1587. }
  1588. }
  1589. }
  1590. }
  1591. extension ExistingTypeDescription {
  1592. /// Creates a member type description with the provided single component.
  1593. /// - Parameter singleComponent: A single component of the name.
  1594. /// - Returns: The new type description.
  1595. static func member(_ singleComponent: String) -> Self { .member([singleComponent]) }
  1596. }