StructuredSwiftRepresentation.swift 59 KB

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