StructuredSwiftRepresentation.swift 59 KB

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