StructuredSwiftRepresentation.swift 58 KB

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