StructuredSwiftRepresentation.swift 56 KB

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