StructuredSwiftRepresentation.swift 56 KB

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