StructuredSwiftRepresentation.swift 54 KB

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