StructuredSwiftRepresentation.swift 57 KB

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