StructuredSwiftRepresentation.swift 58 KB

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