forked from grpc/grpc-swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTextBasedRenderer.swift
1192 lines (1090 loc) · 40.3 KB
/
TextBasedRenderer.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2023, gRPC Authors All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftOpenAPIGenerator open source project
//
// Copyright (c) 2023 Apple Inc. and the SwiftOpenAPIGenerator project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftOpenAPIGenerator project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import Foundation
/// An object for building up a generated file line-by-line.
///
/// After creation, make calls such as `writeLine` to build up the file,
/// and call `rendered` at the end to get the full file contents.
final class StringCodeWriter {
/// The stored lines of code.
private var lines: [String]
/// The current nesting level.
private var level: Int
/// The indentation for each level as the number of spaces.
internal let indentation: Int
/// Whether the next call to `writeLine` will continue writing to the last
/// stored line. Otherwise a new line is appended.
private var nextWriteAppendsToLastLine: Bool = false
/// Creates a new empty writer.
init(indentation: Int) {
self.level = 0
self.lines = []
self.indentation = indentation
}
/// Concatenates the stored lines of code into a single string.
/// - Returns: The contents of the full file in a single string.
func rendered() -> String { lines.joined(separator: "\n") }
/// Writes a line of code.
///
/// By default, a new line is appended to the file.
///
/// To continue the last line, make a call to `nextLineAppendsToLastLine`
/// before calling `writeLine`.
/// - Parameter line: The contents of the line to write.
func writeLine(_ line: String) {
let newLine: String
if nextWriteAppendsToLastLine && !lines.isEmpty {
let existingLine = lines.removeLast()
newLine = existingLine + line
} else if line.isEmpty {
// Skip indentation to avoid trailing whitespace on blank lines.
newLine = line
} else {
let indentation = Array(repeating: " ", count: self.indentation * level).joined()
newLine = indentation + line
}
lines.append(newLine)
nextWriteAppendsToLastLine = false
}
/// Increases the indentation level by 1.
func push() { level += 1 }
/// Decreases the indentation level by 1.
/// - Precondition: Current level must be greater than 0.
func pop() {
precondition(level > 0, "Cannot pop below 0")
level -= 1
}
/// Executes the provided closure with one level deeper indentation.
/// - Parameter work: The closure to execute.
/// - Returns: The result of the closure execution.
func withNestedLevel<R>(_ work: () -> R) -> R {
push()
defer { pop() }
return work()
}
/// Sets a flag on the writer so that the next call to `writeLine` continues
/// the last stored line instead of starting a new line.
///
/// Safe to call repeatedly, it gets reset by `writeLine`.
func nextLineAppendsToLastLine() { nextWriteAppendsToLastLine = true }
}
@available(*, unavailable)
extension TextBasedRenderer: Sendable {}
/// A renderer that uses string interpolation and concatenation
/// to convert the provided structure code into raw string form.
struct TextBasedRenderer: RendererProtocol {
func render(
structured: StructuredSwiftRepresentation
) throws
-> SourceFile
{
let namedFile = structured.file
renderFile(namedFile.contents)
let string = writer.rendered()
return SourceFile(name: namedFile.name, contents: string)
}
/// The underlying writer.
private let writer: StringCodeWriter
/// Creates a new empty renderer.
static var `default`: TextBasedRenderer { .init(indentation: 4) }
init(indentation: Int) {
self.writer = StringCodeWriter(indentation: indentation)
}
// MARK: - Internals
/// Returns the current contents of the writer as a string.
func renderedContents() -> String { writer.rendered() }
/// Renders the specified Swift file.
func renderFile(_ description: FileDescription) {
if let topComment = description.topComment {
renderComment(topComment)
writer.writeLine("")
}
if let imports = description.imports {
renderImports(imports)
writer.writeLine("")
}
for (codeBlock, isLast) in description.codeBlocks.enumeratedWithLastMarker() {
renderCodeBlock(codeBlock)
if !isLast {
writer.writeLine("")
}
}
}
/// Renders the specified comment.
func renderComment(_ comment: Comment) {
let prefix: String
let commentString: String
switch comment {
case .inline(let string):
prefix = "//"
commentString = string
case .doc(let string):
prefix = "///"
commentString = string
case .mark(let string, sectionBreak: true):
prefix = "// MARK: -"
commentString = string
case .mark(let string, sectionBreak: false):
prefix = "// MARK:"
commentString = string
case .preFormatted(let string):
prefix = ""
commentString = string
}
let lines = commentString.transformingLines { line, isLast in
// The last line of a comment that is blank should be dropped.
// Pre formatted documentation might contain such lines.
if line.isEmpty && prefix.isEmpty && isLast {
return nil
} else {
let formattedPrefix = !prefix.isEmpty && !line.isEmpty ? "\(prefix) " : prefix
return "\(formattedPrefix)\(line)"
}
}
lines.forEach(writer.writeLine)
}
/// Renders the specified import statements.
func renderImports(_ imports: [ImportDescription]?) { (imports ?? []).forEach(renderImport) }
/// Renders a single import statement.
func renderImport(_ description: ImportDescription) {
func render(preconcurrency: Bool) {
let spiPrefix = description.spi.map { "@_spi(\($0)) " } ?? ""
let preconcurrencyPrefix = preconcurrency ? "@preconcurrency " : ""
let accessLevel = description.accessLevel.map { "\($0) " } ?? ""
if let item = description.item {
writer.writeLine(
"\(preconcurrencyPrefix)\(spiPrefix)\(accessLevel)import \(item.kind) \(description.moduleName).\(item.name)"
)
} else if let moduleTypes = description.moduleTypes {
for type in moduleTypes {
writer.writeLine("\(preconcurrencyPrefix)\(spiPrefix)\(accessLevel)import \(type)")
}
} else {
writer.writeLine(
"\(preconcurrencyPrefix)\(spiPrefix)\(accessLevel)import \(description.moduleName)"
)
}
}
switch description.preconcurrency {
case .always: render(preconcurrency: true)
case .never: render(preconcurrency: false)
case .onOS(let operatingSystems):
writer.writeLine("#if \(operatingSystems.map { "os(\($0))" }.joined(separator: " || "))")
render(preconcurrency: true)
writer.writeLine("#else")
render(preconcurrency: false)
writer.writeLine("#endif")
}
}
/// Renders the specified access modifier.
func renderedAccessModifier(_ accessModifier: AccessModifier) -> String {
switch accessModifier {
case .public: return "public"
case .package: return "package"
case .internal: return "internal"
case .fileprivate: return "fileprivate"
case .private: return "private"
}
}
/// Renders the specified identifier.
func renderIdentifier(_ identifier: IdentifierDescription) {
switch identifier {
case .pattern(let string): writer.writeLine(string)
case .type(let existingTypeDescription):
renderExistingTypeDescription(existingTypeDescription)
}
}
/// Renders the specified member access expression.
func renderMemberAccess(_ memberAccess: MemberAccessDescription) {
if let left = memberAccess.left {
renderExpression(left)
writer.nextLineAppendsToLastLine()
}
writer.writeLine(".\(memberAccess.right)")
}
/// Renders the specified function call argument.
func renderFunctionCallArgument(_ arg: FunctionArgumentDescription) {
if let left = arg.label {
writer.writeLine("\(left): ")
writer.nextLineAppendsToLastLine()
}
renderExpression(arg.expression)
}
/// Renders the specified function call.
func renderFunctionCall(_ functionCall: FunctionCallDescription) {
renderExpression(functionCall.calledExpression)
writer.nextLineAppendsToLastLine()
writer.writeLine("(")
let arguments = functionCall.arguments
if arguments.count > 1 {
writer.withNestedLevel {
for (argument, isLast) in arguments.enumeratedWithLastMarker() {
renderFunctionCallArgument(argument)
if !isLast {
writer.nextLineAppendsToLastLine()
writer.writeLine(",")
}
}
}
} else {
writer.nextLineAppendsToLastLine()
if let argument = arguments.first { renderFunctionCallArgument(argument) }
writer.nextLineAppendsToLastLine()
}
writer.writeLine(")")
if let trailingClosure = functionCall.trailingClosure {
writer.nextLineAppendsToLastLine()
writer.writeLine(" ")
renderClosureInvocation(trailingClosure)
}
}
/// Renders the specified assignment expression.
func renderAssignment(_ assignment: AssignmentDescription) {
renderExpression(assignment.left)
writer.nextLineAppendsToLastLine()
writer.writeLine(" = ")
writer.nextLineAppendsToLastLine()
renderExpression(assignment.right)
}
/// Renders the specified switch case kind.
func renderSwitchCaseKind(_ kind: SwitchCaseKind) {
switch kind {
case let .`case`(expression, associatedValueNames):
let associatedValues: String
let maybeLet: String
if !associatedValueNames.isEmpty {
associatedValues = "(" + associatedValueNames.joined(separator: ", ") + ")"
maybeLet = "let "
} else {
associatedValues = ""
maybeLet = ""
}
writer.writeLine("case \(maybeLet)")
writer.nextLineAppendsToLastLine()
renderExpression(expression)
writer.nextLineAppendsToLastLine()
writer.writeLine(associatedValues)
case .multiCase(let expressions):
writer.writeLine("case ")
writer.nextLineAppendsToLastLine()
for (expression, isLast) in expressions.enumeratedWithLastMarker() {
renderExpression(expression)
writer.nextLineAppendsToLastLine()
if !isLast { writer.writeLine(", ") }
writer.nextLineAppendsToLastLine()
}
case .`default`: writer.writeLine("default")
}
}
/// Renders the specified switch case.
func renderSwitchCase(_ switchCase: SwitchCaseDescription) {
renderSwitchCaseKind(switchCase.kind)
writer.nextLineAppendsToLastLine()
writer.writeLine(":")
writer.withNestedLevel { renderCodeBlocks(switchCase.body) }
}
/// Renders the specified switch expression.
func renderSwitch(_ switchDesc: SwitchDescription) {
writer.writeLine("switch ")
writer.nextLineAppendsToLastLine()
renderExpression(switchDesc.switchedExpression)
writer.nextLineAppendsToLastLine()
writer.writeLine(" {")
for caseDesc in switchDesc.cases { renderSwitchCase(caseDesc) }
writer.writeLine("}")
}
/// Renders the specified if statement.
func renderIf(_ ifDesc: IfStatementDescription) {
let ifBranch = ifDesc.ifBranch
writer.writeLine("if ")
writer.nextLineAppendsToLastLine()
renderExpression(ifBranch.condition)
writer.nextLineAppendsToLastLine()
writer.writeLine(" {")
writer.withNestedLevel { renderCodeBlocks(ifBranch.body) }
writer.writeLine("}")
for branch in ifDesc.elseIfBranches {
writer.nextLineAppendsToLastLine()
writer.writeLine(" else if ")
writer.nextLineAppendsToLastLine()
renderExpression(branch.condition)
writer.nextLineAppendsToLastLine()
writer.writeLine(" {")
writer.withNestedLevel { renderCodeBlocks(branch.body) }
writer.writeLine("}")
}
if let elseBody = ifDesc.elseBody {
writer.nextLineAppendsToLastLine()
writer.writeLine(" else {")
writer.withNestedLevel { renderCodeBlocks(elseBody) }
writer.writeLine("}")
}
}
/// Renders the specified switch expression.
func renderDoStatement(_ description: DoStatementDescription) {
writer.writeLine("do {")
writer.withNestedLevel { renderCodeBlocks(description.doStatement) }
if let catchBody = description.catchBody {
writer.writeLine("} catch {")
if !catchBody.isEmpty {
writer.withNestedLevel { renderCodeBlocks(catchBody) }
} else {
writer.nextLineAppendsToLastLine()
}
}
writer.writeLine("}")
}
/// Renders the specified value binding expression.
func renderValueBinding(_ valueBinding: ValueBindingDescription) {
writer.writeLine("\(renderedBindingKind(valueBinding.kind)) ")
writer.nextLineAppendsToLastLine()
renderFunctionCall(valueBinding.value)
}
/// Renders the specified keyword.
func renderedKeywordKind(_ kind: KeywordKind) -> String {
switch kind {
case .return: return "return"
case .try(hasPostfixQuestionMark: let hasPostfixQuestionMark):
return "try\(hasPostfixQuestionMark ? "?" : "")"
case .await: return "await"
case .throw: return "throw"
case .yield: return "yield"
}
}
/// Renders the specified unary keyword expression.
func renderUnaryKeywordExpression(_ expression: UnaryKeywordDescription) {
writer.writeLine(renderedKeywordKind(expression.kind))
guard let expr = expression.expression else { return }
writer.nextLineAppendsToLastLine()
writer.writeLine(" ")
writer.nextLineAppendsToLastLine()
renderExpression(expr)
}
/// Renders the specified closure invocation.
func renderClosureInvocation(_ invocation: ClosureInvocationDescription) {
writer.writeLine("{")
if !invocation.argumentNames.isEmpty {
writer.nextLineAppendsToLastLine()
writer.writeLine(" \(invocation.argumentNames.joined(separator: ", ")) in")
}
if let body = invocation.body { writer.withNestedLevel { renderCodeBlocks(body) } }
writer.writeLine("}")
}
/// Renders the specified binary operator.
func renderedBinaryOperator(_ op: BinaryOperator) -> String { op.rawValue }
/// Renders the specified binary operation.
func renderBinaryOperation(_ operation: BinaryOperationDescription) {
renderExpression(operation.left)
writer.nextLineAppendsToLastLine()
writer.writeLine(" \(renderedBinaryOperator(operation.operation)) ")
writer.nextLineAppendsToLastLine()
renderExpression(operation.right)
}
/// Renders the specified inout expression.
func renderInOutDescription(_ description: InOutDescription) {
writer.writeLine("&")
writer.nextLineAppendsToLastLine()
renderExpression(description.referencedExpr)
}
/// Renders the specified optional chaining expression.
func renderOptionalChainingDescription(_ description: OptionalChainingDescription) {
renderExpression(description.referencedExpr)
writer.nextLineAppendsToLastLine()
writer.writeLine("?")
}
/// Renders the specified tuple expression.
func renderTupleDescription(_ description: TupleDescription) {
writer.writeLine("(")
writer.nextLineAppendsToLastLine()
let members = description.members
for (member, isLast) in members.enumeratedWithLastMarker() {
renderExpression(member)
if !isLast {
writer.nextLineAppendsToLastLine()
writer.writeLine(", ")
}
writer.nextLineAppendsToLastLine()
}
writer.writeLine(")")
}
/// Renders the specified expression.
func renderExpression(_ expression: Expression) {
switch expression {
case .literal(let literalDescription): renderLiteral(literalDescription)
case .identifier(let identifierDescription):
renderIdentifier(identifierDescription)
case .memberAccess(let memberAccessDescription): renderMemberAccess(memberAccessDescription)
case .functionCall(let functionCallDescription): renderFunctionCall(functionCallDescription)
case .assignment(let assignment): renderAssignment(assignment)
case .switch(let switchDesc): renderSwitch(switchDesc)
case .ifStatement(let ifDesc): renderIf(ifDesc)
case .doStatement(let doStmt): renderDoStatement(doStmt)
case .valueBinding(let valueBinding): renderValueBinding(valueBinding)
case .unaryKeyword(let unaryKeyword): renderUnaryKeywordExpression(unaryKeyword)
case .closureInvocation(let closureInvocation): renderClosureInvocation(closureInvocation)
case .binaryOperation(let binaryOperation): renderBinaryOperation(binaryOperation)
case .inOut(let inOut): renderInOutDescription(inOut)
case .optionalChaining(let optionalChaining):
renderOptionalChainingDescription(optionalChaining)
case .tuple(let tuple): renderTupleDescription(tuple)
}
}
/// Renders the specified literal expression.
func renderLiteral(_ literal: LiteralDescription) {
func write(_ string: String) { writer.writeLine(string) }
switch literal {
case let .string(string):
// Use a raw literal if the string contains a quote/backslash.
if string.contains("\"") || string.contains("\\") {
write("#\"\(string)\"#")
} else {
write("\"\(string)\"")
}
case let .int(int): write("\(int)")
case let .bool(bool): write(bool ? "true" : "false")
case .nil: write("nil")
case .array(let items):
writer.writeLine("[")
if !items.isEmpty {
writer.withNestedLevel {
for (item, isLast) in items.enumeratedWithLastMarker() {
renderExpression(item)
if !isLast {
writer.nextLineAppendsToLastLine()
writer.writeLine(",")
}
}
}
} else {
writer.nextLineAppendsToLastLine()
}
writer.writeLine("]")
case .dictionary(let items):
writer.writeLine("[")
if items.isEmpty {
writer.nextLineAppendsToLastLine()
writer.writeLine(":")
writer.nextLineAppendsToLastLine()
} else {
writer.withNestedLevel {
for (item, isLast) in items.enumeratedWithLastMarker() {
renderExpression(item.key)
writer.nextLineAppendsToLastLine()
writer.writeLine(": ")
writer.nextLineAppendsToLastLine()
renderExpression(item.value)
if !isLast {
writer.nextLineAppendsToLastLine()
writer.writeLine(",")
}
}
}
}
writer.writeLine("]")
}
}
/// Renders the specified where clause requirement.
func renderedWhereClauseRequirement(_ requirement: WhereClauseRequirement) -> String {
switch requirement {
case .conformance(let left, let right): return "\(left): \(right)"
}
}
/// Renders the specified where clause.
func renderedWhereClause(_ clause: WhereClause) -> String {
let renderedRequirements = clause.requirements.map(renderedWhereClauseRequirement)
return "where \(renderedRequirements.joined(separator: ", "))"
}
/// Renders the specified extension declaration.
func renderExtension(_ extensionDescription: ExtensionDescription) {
if let accessModifier = extensionDescription.accessModifier {
writer.writeLine(renderedAccessModifier(accessModifier) + " ")
writer.nextLineAppendsToLastLine()
}
writer.writeLine("extension \(extensionDescription.onType)")
writer.nextLineAppendsToLastLine()
if !extensionDescription.conformances.isEmpty {
writer.writeLine(": \(extensionDescription.conformances.joined(separator: ", "))")
writer.nextLineAppendsToLastLine()
}
if let whereClause = extensionDescription.whereClause {
writer.writeLine(" " + renderedWhereClause(whereClause))
writer.nextLineAppendsToLastLine()
}
writer.writeLine(" {")
for (declaration, isLast) in extensionDescription.declarations.enumeratedWithLastMarker() {
writer.withNestedLevel {
renderDeclaration(declaration)
if !isLast {
writer.writeLine("")
}
}
}
writer.writeLine("}")
}
/// Renders the specified type reference to an existing type.
func renderExistingTypeDescription(_ type: ExistingTypeDescription) {
switch type {
case .any(let existingTypeDescription):
writer.writeLine("any ")
writer.nextLineAppendsToLastLine()
renderExistingTypeDescription(existingTypeDescription)
case .generic(let wrapper, let wrapped):
renderExistingTypeDescription(wrapper)
writer.nextLineAppendsToLastLine()
writer.writeLine("<")
writer.nextLineAppendsToLastLine()
renderExistingTypeDescription(wrapped)
writer.nextLineAppendsToLastLine()
writer.writeLine(">")
case .optional(let existingTypeDescription):
renderExistingTypeDescription(existingTypeDescription)
writer.nextLineAppendsToLastLine()
writer.writeLine("?")
case .member(let components):
writer.writeLine(components.joined(separator: "."))
case .array(let existingTypeDescription):
writer.writeLine("[")
writer.nextLineAppendsToLastLine()
renderExistingTypeDescription(existingTypeDescription)
writer.nextLineAppendsToLastLine()
writer.writeLine("]")
case .dictionaryValue(let existingTypeDescription):
writer.writeLine("[String: ")
writer.nextLineAppendsToLastLine()
renderExistingTypeDescription(existingTypeDescription)
writer.nextLineAppendsToLastLine()
writer.writeLine("]")
case .some(let existingTypeDescription):
writer.writeLine("some ")
writer.nextLineAppendsToLastLine()
renderExistingTypeDescription(existingTypeDescription)
case .closure(let closureSignatureDescription):
renderClosureSignature(closureSignatureDescription)
}
}
/// Renders the specified typealias declaration.
func renderTypealias(_ alias: TypealiasDescription) {
var words: [String] = []
if let accessModifier = alias.accessModifier {
words.append(renderedAccessModifier(accessModifier))
}
words.append(contentsOf: [
"typealias", alias.name, "=",
])
writer.writeLine(words.joinedWords() + " ")
writer.nextLineAppendsToLastLine()
renderExistingTypeDescription(alias.existingType)
}
/// Renders the specified binding kind.
func renderedBindingKind(_ kind: BindingKind) -> String {
switch kind {
case .var: return "var"
case .let: return "let"
}
}
/// Renders the specified variable declaration.
func renderVariable(_ variable: VariableDescription) {
do {
if let accessModifier = variable.accessModifier {
writer.writeLine(renderedAccessModifier(accessModifier) + " ")
writer.nextLineAppendsToLastLine()
}
if variable.isStatic {
writer.writeLine("static ")
writer.nextLineAppendsToLastLine()
}
writer.writeLine(renderedBindingKind(variable.kind) + " ")
writer.nextLineAppendsToLastLine()
renderExpression(variable.left)
if let type = variable.type {
writer.nextLineAppendsToLastLine()
writer.writeLine(": ")
writer.nextLineAppendsToLastLine()
renderExistingTypeDescription(type)
}
}
if let right = variable.right {
writer.nextLineAppendsToLastLine()
writer.writeLine(" = ")
writer.nextLineAppendsToLastLine()
renderExpression(right)
}
if let body = variable.getter {
writer.nextLineAppendsToLastLine()
writer.writeLine(" {")
writer.withNestedLevel {
let hasExplicitGetter =
!variable.getterEffects.isEmpty || variable.setter != nil || variable.modify != nil
if hasExplicitGetter {
let keywords = variable.getterEffects.map(renderedFunctionKeyword).joined(separator: " ")
let line = "get \(keywords) {"
writer.writeLine(line)
writer.push()
}
renderCodeBlocks(body)
if hasExplicitGetter {
writer.pop()
writer.writeLine("}")
}
if let modify = variable.modify {
writer.writeLine("_modify {")
writer.withNestedLevel { renderCodeBlocks(modify) }
writer.writeLine("}")
}
if let setter = variable.setter {
writer.writeLine("set {")
writer.withNestedLevel { renderCodeBlocks(setter) }
writer.writeLine("}")
}
}
writer.writeLine("}")
}
}
/// Renders the specified struct declaration.
func renderStruct(_ structDesc: StructDescription) {
if let accessModifier = structDesc.accessModifier {
writer.writeLine(renderedAccessModifier(accessModifier) + " ")
writer.nextLineAppendsToLastLine()
}
writer.writeLine("struct \(structDesc.name)")
writer.nextLineAppendsToLastLine()
if !structDesc.conformances.isEmpty {
writer.writeLine(": \(structDesc.conformances.joined(separator: ", "))")
writer.nextLineAppendsToLastLine()
}
writer.writeLine(" {")
if !structDesc.members.isEmpty {
writer.withNestedLevel {
for (member, isLast) in structDesc.members.enumeratedWithLastMarker() {
renderDeclaration(member)
if !isLast {
writer.writeLine("")
}
}
}
} else {
writer.nextLineAppendsToLastLine()
}
writer.writeLine("}")
}
/// Renders the specified protocol declaration.
func renderProtocol(_ protocolDesc: ProtocolDescription) {
if let accessModifier = protocolDesc.accessModifier {
writer.writeLine("\(renderedAccessModifier(accessModifier)) ")
writer.nextLineAppendsToLastLine()
}
writer.writeLine("protocol \(protocolDesc.name)")
writer.nextLineAppendsToLastLine()
if !protocolDesc.conformances.isEmpty {
let conformances = protocolDesc.conformances.joined(separator: ", ")
writer.writeLine(": \(conformances)")
writer.nextLineAppendsToLastLine()
}
writer.writeLine(" {")
if !protocolDesc.members.isEmpty {
writer.withNestedLevel {
for (member, isLast) in protocolDesc.members.enumeratedWithLastMarker() {
renderDeclaration(member)
if !isLast {
writer.writeLine("")
}
}
}
} else {
writer.nextLineAppendsToLastLine()
}
writer.writeLine("}")
}
/// Renders the specified enum declaration.
func renderEnum(_ enumDesc: EnumDescription) {
if enumDesc.isFrozen {
writer.writeLine("@frozen ")
writer.nextLineAppendsToLastLine()
}
if let accessModifier = enumDesc.accessModifier {
writer.writeLine("\(renderedAccessModifier(accessModifier)) ")
writer.nextLineAppendsToLastLine()
}
if enumDesc.isIndirect {
writer.writeLine("indirect ")
writer.nextLineAppendsToLastLine()
}
writer.writeLine("enum \(enumDesc.name)")
writer.nextLineAppendsToLastLine()
if !enumDesc.conformances.isEmpty {
writer.writeLine(": \(enumDesc.conformances.joined(separator: ", "))")
writer.nextLineAppendsToLastLine()
}
writer.writeLine(" {")
if !enumDesc.members.isEmpty {
writer.withNestedLevel { for member in enumDesc.members { renderDeclaration(member) } }
} else {
writer.nextLineAppendsToLastLine()
}
writer.writeLine("}")
}
/// Renders the specified enum case associated value.
func renderEnumCaseAssociatedValue(_ value: EnumCaseAssociatedValueDescription) {
var words: [String] = []
if let label = value.label { words.append(label + ":") }
writer.writeLine(words.joinedWords())
writer.nextLineAppendsToLastLine()
renderExistingTypeDescription(value.type)
}
/// Renders the specified enum case declaration.
func renderEnumCase(_ enumCase: EnumCaseDescription) {
writer.writeLine("case \(enumCase.name)")
switch enumCase.kind {
case .nameOnly: break
case .nameWithRawValue(let rawValue):
writer.nextLineAppendsToLastLine()
writer.writeLine(" = ")
writer.nextLineAppendsToLastLine()
renderLiteral(rawValue)
case .nameWithAssociatedValues(let values):
if values.isEmpty { break }
for (value, isLast) in values.enumeratedWithLastMarker() {
renderEnumCaseAssociatedValue(value)
if !isLast {
writer.nextLineAppendsToLastLine()
writer.writeLine(", ")
}
}
}
}
/// Renders the specified declaration.
func renderDeclaration(_ declaration: Declaration) {
switch declaration {
case let .commentable(comment, nestedDeclaration):
renderCommentableDeclaration(comment: comment, declaration: nestedDeclaration)
case let .deprecated(deprecation, nestedDeclaration):
renderDeprecatedDeclaration(deprecation: deprecation, declaration: nestedDeclaration)
case let .guarded(availability, nestedDeclaration):
renderGuardedDeclaration(availability: availability, declaration: nestedDeclaration)
case .variable(let variableDescription): renderVariable(variableDescription)
case .extension(let extensionDescription): renderExtension(extensionDescription)
case .struct(let structDescription): renderStruct(structDescription)
case .protocol(let protocolDescription): renderProtocol(protocolDescription)
case .enum(let enumDescription): renderEnum(enumDescription)
case .typealias(let typealiasDescription): renderTypealias(typealiasDescription)
case .function(let functionDescription): renderFunction(functionDescription)
case .enumCase(let enumCase): renderEnumCase(enumCase)
}
}
/// Renders the specified function kind.
func renderedFunctionKind(_ functionKind: FunctionKind) -> String {
switch functionKind {
case .initializer(let isFailable): return "init\(isFailable ? "?" : "")"
case .function(let name, let isStatic):
return (isStatic ? "static " : "") + "func \(name)"
}
}
/// Renders the specified function keyword.
func renderedFunctionKeyword(_ keyword: FunctionKeyword) -> String {
switch keyword {
case .throws: return "throws"
case .async: return "async"
case .rethrows: return "rethrows"
}
}
/// Renders the specified function signature.
func renderClosureSignature(_ signature: ClosureSignatureDescription) {
if signature.sendable {
writer.writeLine("@Sendable ")
writer.nextLineAppendsToLastLine()
}
if signature.escaping {
writer.writeLine("@escaping ")
writer.nextLineAppendsToLastLine()
}
writer.writeLine("(")
let parameters = signature.parameters
let separateLines = parameters.count > 1
if separateLines {
writer.withNestedLevel {
for (parameter, isLast) in signature.parameters.enumeratedWithLastMarker() {
renderClosureParameter(parameter)
if !isLast {
writer.nextLineAppendsToLastLine()
writer.writeLine(",")
}
}
}
} else {
writer.nextLineAppendsToLastLine()
if let parameter = parameters.first {
renderClosureParameter(parameter)
writer.nextLineAppendsToLastLine()
}
}
writer.writeLine(")")
let keywords = signature.keywords
for keyword in keywords {
writer.nextLineAppendsToLastLine()
writer.writeLine(" " + renderedFunctionKeyword(keyword))
}
if let returnType = signature.returnType {
writer.nextLineAppendsToLastLine()
writer.writeLine(" -> ")
writer.nextLineAppendsToLastLine()
renderExpression(returnType)
}
}
/// Renders the specified function signature.
func renderFunctionSignature(_ signature: FunctionSignatureDescription) {
do {
if let accessModifier = signature.accessModifier {
writer.writeLine(renderedAccessModifier(accessModifier) + " ")
writer.nextLineAppendsToLastLine()
}
let generics = signature.generics
writer.writeLine(
renderedFunctionKind(signature.kind)
)
if !generics.isEmpty {
writer.nextLineAppendsToLastLine()
writer.writeLine("<")
for (genericType, isLast) in generics.enumeratedWithLastMarker() {
writer.nextLineAppendsToLastLine()
renderExistingTypeDescription(genericType)
if !isLast {
writer.nextLineAppendsToLastLine()
writer.writeLine(", ")
}
}
writer.nextLineAppendsToLastLine()
writer.writeLine(">")
}
writer.nextLineAppendsToLastLine()
writer.writeLine("(")
let parameters = signature.parameters
let separateLines = parameters.count > 1
if separateLines {
writer.withNestedLevel {
for (parameter, isLast) in signature.parameters.enumeratedWithLastMarker() {
renderParameter(parameter)
if !isLast {
writer.nextLineAppendsToLastLine()
writer.writeLine(",")
}
}
}
} else {
writer.nextLineAppendsToLastLine()
if let parameter = parameters.first { renderParameter(parameter) }
writer.nextLineAppendsToLastLine()
}
writer.writeLine(")")
}
do {
let keywords = signature.keywords
if !keywords.isEmpty {
for keyword in keywords {
writer.nextLineAppendsToLastLine()
writer.writeLine(" " + renderedFunctionKeyword(keyword))
}
}
}
if let returnType = signature.returnType {
writer.nextLineAppendsToLastLine()
writer.writeLine(" -> ")
writer.nextLineAppendsToLastLine()
renderExpression(returnType)
}
if let whereClause = signature.whereClause {
writer.nextLineAppendsToLastLine()
writer.writeLine(" " + renderedWhereClause(whereClause))
}
}