StructuredSwiftRepresentation.swift 53 KB

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