StructuredSwiftRepresentation.swift 58 KB

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