StructuredSwiftRepresentation.swift 54 KB

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