-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathSwift.hs
677 lines (635 loc) · 21.1 KB
/
Swift.hs
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
{-# OPTIONS_GHC -Wno-unrecognised-pragmas #-}
{-# HLINT ignore "Avoid restricted function" #-}
-- nub, error
module Moat.Pretty.Swift
( prettySwiftData,
prettyMoatType,
)
where
import Data.Functor ((<&>))
import Data.List (intercalate, nub)
import qualified Data.Map as Map
import Data.Maybe (catMaybes)
import Moat.Pretty.Doc.DocC
import Moat.Types
-- | Convert a 'MoatData' into a canonical representation in Swift
--
-- This is a decent default if you plan to do iOS development, however you
-- could instead use this as a template to write your own version. Or, use it
-- to write an entirely new language backend :)
prettySwiftData :: MoatData -> String
prettySwiftData = prettySwiftDataWith 4
-- | Pretty-print a 'SwiftData'.
-- This function cares about indent.
prettySwiftDataWith ::
() =>
-- | indent
Int ->
MoatData ->
String
prettySwiftDataWith indent = \case
MoatEnum {..} ->
prettyTypeDoc "" enumDoc []
++ "public enum "
++ prettyMoatTypeHeader enumName (addTyVarBounds enumTyVars enumProtocols)
++ prettyRawValueAndProtocols enumRawValue enumProtocols
++ " {"
++ newlineNonEmpty enumCases
++ prettyEnumCases indents enumEnumUnknownCase enumCases
++ newlineNonEmpty enumPrivateTypes
++ prettyPrivateTypes indents enumPrivateTypes
++ prettyTags indents enumTags
++ newlineNonEmpty enumTags
++ prettyEnumCoding indents enumName enumCases enumEnumUnknownCase enumSumOfProductEncodingOption
++ "}"
MoatStruct {..} ->
prettyTypeDoc "" structDoc []
++ "public struct "
++ prettyMoatTypeHeader structName (addTyVarBounds structTyVars structProtocols)
++ prettyRawValueAndProtocols Nothing structProtocols
++ " {"
++ newlineNonEmpty structFields
++ prettyStructFields indents structFields structDeprecatedFields
++ prettyStructInitializer indents structFields structDeprecatedFields
++ newlineNonEmpty structPrivateTypes
++ prettyPrivateTypes indents structPrivateTypes
++ prettyTags indents structTags
++ newlineNonEmpty structTags
++ "}"
MoatAlias {..} ->
prettyTypeDoc "" aliasDoc []
++ "public typealias "
-- Swift aliases should not declare type parameters
++ prettyMoatTypeHeader aliasName []
++ " = "
++ prettyMoatTypeBase aliasTyp
MoatNewtype {..} ->
prettyTypeDoc "" newtypeDoc []
++ "public struct "
++ prettyMoatTypeHeader newtypeName (addTyVarBounds newtypeTyVars newtypeProtocols)
++ prettyRawValueAndProtocols Nothing newtypeProtocols
++ " {\n"
++ indents
++ if isConcrete newtypeField
then
"public let "
++ fieldName newtypeField
++ ": "
++ prettyMoatType (fieldType newtypeField)
++ "\n}"
else
"public typealias "
++ newtypeName
++ "Tag"
++ " = Tagged<"
++ newtypeName
++ ", "
++ case fieldType newtypeField of
Optional t -> prettyMoatType t
t -> prettyMoatType t
++ ">\n"
++ prettyNewtypeField indents newtypeField newtypeName
++ "}"
where
indents = replicate indent ' '
isConcrete :: Field -> Bool
isConcrete = \case
(Field _ Concrete {} _) -> True
_ -> False
prettyTypeDoc :: String -> Maybe String -> [Field] -> String
prettyTypeDoc indents doc fields =
let wrap = 100 - length indents - 4 -- "/// " doc comment prefix
docC = intercalate "\n" (catMaybes [prettyDoc wrap <$> doc, prettyFieldDoc wrap fields])
in prettyDocComment indents docC
prettyMoatTypeHeader :: String -> [String] -> String
prettyMoatTypeHeader name [] = name
prettyMoatTypeHeader name tyVars = name ++ "<" ++ intercalate ", " tyVars ++ ">"
prettyRawValueAndProtocols :: Maybe MoatType -> [Protocol] -> String
prettyRawValueAndProtocols Nothing [] = ""
prettyRawValueAndProtocols Nothing ps = ": " ++ prettyProtocols ps
prettyRawValueAndProtocols (Just ty) [] = ": " ++ prettyMoatType ty
prettyRawValueAndProtocols (Just ty) ps = ": " ++ prettyMoatType ty ++ ", " ++ prettyProtocols ps
prettyProtocol :: Protocol -> String
prettyProtocol = \case
Hashable -> "Hashable"
Codable -> "Codable"
Equatable -> "Equatable"
OtherProtocol s -> s
prettyProtocols :: [Protocol] -> String
prettyProtocols = \case
[] -> ""
ps -> intercalate ", " (prettyProtocol <$> ps)
-- TODO: Need a plan to avoid @error@ in these pure functions
{-# ANN prettyTags "HLint: ignore" #-}
prettyTags :: String -> [MoatType] -> String
prettyTags indents = go
where
go [] = ""
go (Tag {..} : ts) =
"\n"
++ prettyTagDisambiguator tagDisambiguate indents tagName
++ indents
++ "public typealias "
++ tagName
++ " = Tagged<"
++ (if tagDisambiguate then tagName ++ "Tag" else tagParent)
++ ", "
++ prettyMoatType tagTyp
++ ">"
++ go ts
go _ = error "non-tag supplied to prettyTags"
prettyTagDisambiguator ::
() =>
-- | disambiguate?
Bool ->
-- | indents
String ->
-- | parent type name
String ->
String
prettyTagDisambiguator disambiguate indents parent =
if disambiguate
then
indents
++ "public enum "
++ parent
++ "Tag { }\n"
else ""
labelCase :: Field -> String
labelCase (Field "" ty _) = prettyMoatType ty
labelCase (Field label ty _) = "_ " ++ label ++ ": " ++ prettyMoatType ty
-- | Pretty-print a 'Ty'.
prettyMoatType :: MoatType -> String
prettyMoatType = \case
Str -> "String"
Unit -> "()"
Bool -> "Bool"
Character -> "Character"
Tuple2 e1 e2 -> "(" ++ prettyMoatType e1 ++ ", " ++ prettyMoatType e2 ++ ")"
Tuple3 e1 e2 e3 -> "(" ++ prettyMoatType e1 ++ ", " ++ prettyMoatType e2 ++ ", " ++ prettyMoatType e3 ++ ")"
Optional o@(Optional _) -> prettyMoatType o
Optional e -> prettyMoatType e ++ "?"
-- Swift flips the parameters for Result, see https://developer.apple.com/documentation/swift/result
Result e1 e2 -> "Result<" ++ prettyMoatType e2 ++ ", " ++ prettyMoatType e1 ++ ">"
Set e -> "Set<" ++ prettyMoatType e ++ ">"
Dictionary e1 e2 -> "Dictionary<" ++ prettyMoatType e1 ++ ", " ++ prettyMoatType e2 ++ ">"
Array e -> "[" ++ prettyMoatType e ++ "]"
-- App is special, we recurse until we no longer
-- any applications.
App e1 e2 -> prettyApp e1 e2
I -> "Int"
I8 -> "Int8"
I16 -> "Int16"
I32 -> "Int32"
I64 -> "Int64"
U -> "UInt"
U8 -> "UInt8"
U16 -> "UInt16"
U32 -> "UInt32"
U64 -> "UInt64"
F32 -> "Float"
F64 -> "Double"
Decimal -> "Decimal"
BigInt -> "BigInteger"
Poly ty -> ty
Concrete ty [] -> ty
Concrete ty tys ->
ty
++ "<"
++ intercalate ", " (map prettyMoatType tys)
++ ">"
Tag {..} -> tagParent ++ "." ++ tagName
-- | Pretty-print a 'MoatType', omitting type parameters.
prettyMoatTypeBase :: MoatType -> String
prettyMoatTypeBase = \case
Result _ _ -> "Result"
Set _ -> "Set"
Dictionary _ _ -> "Dictionary"
Concrete ty _ -> ty
ty -> prettyMoatType ty
prettyApp :: MoatType -> MoatType -> String
prettyApp t1 t2 =
"(("
++ intercalate ", " (map prettyMoatType as)
++ ") -> "
++ prettyMoatType r
++ ")"
where
(as, r) = go t1 t2
go e1 (App e2 e3) = case go e2 e3 of
(args, ret) -> (e1 : args, ret)
go e1 e2 = ([e1], e2)
prettyEnumCases :: String -> Maybe String -> [EnumCase] -> String
prettyEnumCases indents unknown cases = go cases ++ unknownCase
where
go = \case
[] -> ""
(EnumCase caseNm caseDoc [] : xs) ->
prettyTypeDoc indents caseDoc []
++ indents
++ "case "
++ caseNm
++ "\n"
++ go xs
(EnumCase caseNm caseDoc cs : xs) ->
prettyTypeDoc indents caseDoc cs
++ indents
++ "case "
++ caseNm
++ "("
++ intercalate ", " (map labelCase cs)
++ ")\n"
++ go xs
unknownCase = case unknown of
Just caseNm -> indents ++ "case " ++ caseNm ++ "\n"
Nothing -> ""
prettyStructFields :: String -> [Field] -> [(String, Maybe String)] -> String
prettyStructFields indents fields deprecatedFields = go fields
where
deprecatedFieldsMap = Map.fromList deprecatedFields
prettyField (Field fieldName fieldType _fieldDoc) =
"public var "
++ fieldName
++ ": "
++ prettyMoatType fieldType
++ "\n"
go [] = ""
go (field@(Field fieldName _ fieldDoc) : fs) =
case Map.lookup fieldName deprecatedFieldsMap of
Just mComment ->
indents
++ maybe "" (\comment -> "// " ++ comment ++ "\n") mComment
++ indents
++ "// "
++ prettyField field
++ go fs
Nothing ->
prettyTypeDoc indents fieldDoc []
++ indents
++ prettyField field
++ go fs
prettyStructInitializer :: String -> [Field] -> [(String, Maybe String)] -> String
prettyStructInitializer indents fields deprecatedFields =
case activeFields of
[] -> "" -- No initializer needed if there are no active fields
_ ->
"\n"
++ indents
++ "public init("
++ intercalate ", " (map prettyParam activeFields)
++ ") {\n"
++ concatMap (prettyAssignment indents) activeFields
++ indents
++ "}\n"
where
deprecatedFieldNames = map fst deprecatedFields
activeFields = filter (\(Field name _ _) -> name `notElem` deprecatedFieldNames) fields
isOptional :: MoatType -> Bool
isOptional (Optional _) = True
isOptional _ = False
prettyParam :: Field -> String
prettyParam (Field fieldName fieldType _) =
fieldName ++ ": " ++ prettyMoatType fieldType ++ (if isOptional fieldType then " = nil" else "")
prettyAssignment :: String -> Field -> String
prettyAssignment indentStr (Field fieldName _ _) =
indentStr ++ " self." ++ fieldName ++ " = " ++ fieldName ++ "\n"
prettyNewtypeField :: String -> Field -> String -> String
prettyNewtypeField indents (Field alias fieldType _) fieldName =
indents
++ "public let "
++ alias
++ ": "
++ fieldName
++ "Tag"
++ case fieldType of
Optional _ -> "?"
_ -> ""
++ "\n"
prettyPrivateTypes :: String -> [MoatData] -> String
prettyPrivateTypes indents = go
where
go [] = ""
go (s : ss) = indents ++ "private " ++ unlines (onLast (indents ++) (lines (prettySwiftData s))) ++ go ss
prettyEnumCoding ::
String ->
String ->
[EnumCase] ->
Maybe String ->
SumOfProductEncodingOptions ->
String
prettyEnumCoding indents parentName cases unknownCase SumOfProductEncodingOptions {..}
| isCEnum cases = "" -- TODO Perhaps add Codable implementation for these
| otherwise =
indent $
prettyCodingKeys
++ "\n\n"
++ prettyInit
++ "\n\n"
++ prettyEncode
where
indent :: String -> String
indent = indentBy indents
prettyCodingKeys :: String
prettyCodingKeys =
"public enum CodingKeys: String, CodingKey {"
++ indent
( case encodingStyle of
TaggedObjectStyle -> prettyTaggedCodingKeys
TaggedFlatObjectStyle -> prettyFlatCodingKeys
)
++ "}"
prettyTaggedCodingKeys :: String
prettyTaggedCodingKeys =
"case "
++ tagFieldName
++ "\n"
++ "case "
++ contentsFieldName
-- We need all possible keys in the payload
prettyFlatCodingKeys =
let names = nub $ filter (not . null) (cases >>= enumCaseFields <&> fieldName)
in "case "
++ tagFieldName
++ "\n"
++ intercalate "\n" (map ("case " ++) names)
prettyInit :: String
prettyInit =
"public init(from decoder: any Decoder) throws {"
++ indent
( "let container = try decoder.container(keyedBy: CodingKeys.self)\n"
++ "let discriminator = try container.decode(String.self, forKey: ."
++ tagFieldName
++ ")\n"
++ "switch discriminator {"
++ indent
( case encodingStyle of
TaggedObjectStyle -> prettyTaggedInitCases
TaggedFlatObjectStyle -> prettyFlatInitCases
++ prettyInitUnknownCase
)
++ "}"
)
++ "}"
-- TaggedObjectStyle payloads have a single tag and contents field.
prettyTaggedInitCases :: String
prettyTaggedInitCases =
concatMap
( \case
EnumCase caseNm _ [Field _ caseTy _] ->
"case \""
++ caseNm
++ "\":"
++ indent
( "self = ."
++ caseNm
++ "(try container.decode("
++ prettyMoatType caseTy
++ ".self, forKey: ."
++ contentsFieldName
++ "))"
)
EnumCase caseNm _ [] ->
"case \""
++ caseNm
++ "\":"
++ indent
( "self = ."
++ caseNm
)
EnumCase caseNm _ _ ->
error $
"prettyTaggedEnumCoding: The data constructor "
<> caseNm
<> " can have zero or one concrete type constructor when using TaggedObjectStyle!"
)
cases
-- TaggedFlatObjectStyle payloads have a tag field and 0 or more additional fields
-- that are decoded directly into the case type.
prettyFlatInitCases :: String
prettyFlatInitCases =
concatMap
( \case
EnumCase caseNm _ [] ->
"case \""
++ caseNm
++ "\":"
++ indent
( "self = ."
++ caseNm
)
EnumCase caseNm _ [Field "" caseTy _] ->
"case \""
++ caseNm
++ "\":"
++ indent
( "self = ."
++ caseNm
++ "(try "
++ prettyMoatType caseTy
++ ".init(from: decoder))"
)
EnumCase caseNm _ fields ->
"case \""
++ caseNm
++ "\":"
++ indent
( "self = ."
++ caseNm
++ "("
++ indent
( intercalate
",\n"
( fields <&> \(Field {..}) ->
"try container.decode("
++ prettyMoatType fieldType
++ ".self, forKey: ."
++ fieldName
++ ")"
)
)
++ ")"
)
)
cases
prettyInitUnknownCase :: String
prettyInitUnknownCase = case unknownCase of
Just caseNm ->
"default:"
++ indent ("self = ." ++ caseNm)
Nothing ->
"default:"
++ indent
( "throw DecodingError.typeMismatch("
++ indent
( "CodingKeys.self,\n"
++ ".init(codingPath: decoder.codingPath, debugDescription: \"Can't decode unknown "
++ tagFieldName
++ ": "
++ parentName
++ ".\\(discriminator)\")"
)
++ ")"
)
prettyEncode :: String
prettyEncode =
"public func encode(to encoder: any Encoder) throws {"
++ indent
( "var container = encoder.container(keyedBy: CodingKeys.self)\n"
++ "switch (self) {"
++ indent
( case encodingStyle of
TaggedObjectStyle -> prettyEncodeTaggedCases
TaggedFlatObjectStyle -> prettyEncodeFlatCases
++ prettyEncodeUnknownCase
)
++ "}\n"
)
++ "}"
prettyEncodeTaggedCases :: String
prettyEncodeTaggedCases =
concatMap
( \(EnumCase {..}) ->
case enumCaseFields of
[] ->
"case ."
++ enumCaseName
++ ":"
++ indent
( "try container.encode(\""
++ enumCaseName
++ "\", forKey: ."
++ tagFieldName
++ ")"
)
[Field "" _ _] ->
"case let ."
++ enumCaseName
++ "("
++ contentsFieldName
++ "):"
++ indent
( "try container.encode(\""
++ enumCaseName
++ "\", forKey: ."
++ tagFieldName
++ ")\ntry container.encode("
++ contentsFieldName
++ ", forKey: ."
++ contentsFieldName
++ ")"
)
_ ->
error $
"prettyTaggedEnumCoding: The data constructor "
<> enumCaseName
<> " can have zero or one concrete type constructor when using TaggedObjectStyle!"
)
cases
prettyEncodeFlatCases :: String
prettyEncodeFlatCases =
concatMap
( \(EnumCase {..}) ->
case enumCaseFields of
[] ->
"case ."
++ enumCaseName
++ ":"
++ indent
( "try container.encode(\""
++ enumCaseName
++ "\", forKey: ."
++ tagFieldName
++ ")"
)
[Field "" _ _] ->
"case let ."
++ enumCaseName
++ "(value):"
++ indent
( "try container.encode(\""
++ enumCaseName
++ "\", forKey: ."
++ tagFieldName
++ ")\n"
++ "try value.encode(to: encoder)"
)
_ ->
"case let ."
++ enumCaseName
++ ":"
++ indent
( "try container.encode(\""
++ enumCaseName
++ "\", forKey: ."
++ tagFieldName
++ ")\n"
++ intercalate
"\n"
( enumCaseFields <&> \(Field {..}) ->
"try container.encode("
++ fieldName
++ ", forKey: ."
++ fieldName
++ ")"
)
)
)
cases
prettyEncodeUnknownCase :: String
prettyEncodeUnknownCase = case unknownCase of
Just caseNm ->
"case ."
++ caseNm
++ ":"
++ indent
( "throw EncodingError.invalidValue("
++ indent
( "self,\n.init(codingPath: encoder.codingPath, debugDescription: \"Can't encode value: "
++ parentName
++ "."
++ caseNm
++ "\")"
)
++ ")"
)
Nothing -> ""
-- map a function over everything but the
-- first element.
onLast :: (a -> a) -> [a] -> [a]
onLast _ [] = []
onLast f (x : xs) = x : map f xs
-- | Copy protocols from the parent type to upper bounds of generic type
-- parameters.
--
-- This is needed for protocols with compiler-synthesized implementations
-- (similar to 'deriving stock'), of which there are currently three:
--
-- - 'Equatable'
-- - 'Hashable'
-- - 'Codable'
--
-- See the [Swift documentation](https://docs.swift.org/swift-book/documentation/the-swift-programming-language/protocols#Adopting-a-Protocol-Using-a-Synthesized-Implementation).
addTyVarBounds :: [String] -> [Protocol] -> [String]
addTyVarBounds tyVars protos =
let isSynthesized :: Protocol -> Bool
isSynthesized = \case
Hashable -> True
Codable -> True
Equatable -> True
OtherProtocol _ -> False
synthesizedProtos = filter isSynthesized protos
bounds = ": " ++ intercalate " & " (map prettyProtocol synthesizedProtos)
in case synthesizedProtos of
[] -> tyVars
_ -> map (++ bounds) tyVars
newlineNonEmpty :: [a] -> String
newlineNonEmpty [] = ""
newlineNonEmpty _ = "\n"
indentBy :: String -> String -> String
indentBy indents str = "\n" ++ unlines (map indentLine $ lines str)
where
indentLine :: String -> String
indentLine "" = ""
indentLine ln = indents ++ ln
isCEnum :: [EnumCase] -> Bool
isCEnum = all ((== []) . enumCaseFields)