/
Python.hs
1346 lines (1232 loc) · 50.9 KB
/
Python.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
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
{-# LANGUAGE DeriveDataTypeable, ExtendedDefaultRules, OverloadedLists,
QuasiQuotes, TypeFamilies, TypeSynonymInstances,
MultiParamTypeClasses #-}
module Nirum.Targets.Python ( Code
, CodeGen
, CodeGenContext ( localImports
, standardImports
, thirdPartyImports
)
, CompileError
, InstallRequires ( InstallRequires
, dependencies
, optionalDependencies
)
, Source ( Source
, sourceModule
, sourcePackage
)
, Python (Python)
, PythonVersion ( Python2
, Python3
)
, RenameMap
, addDependency
, addOptionalDependency
, compileModule
, compilePrimitiveType
, compileTypeDeclaration
, compileTypeExpression
, empty
, insertLocalImport
, insertStandardImport
, insertThirdPartyImports
, insertThirdPartyImportsA
, localImportsMap
, minimumRuntime
, parseModulePath
, renameModulePath
, runCodeGen
, stringLiteral
, toAttributeName
, toClassName
, toImportPath
, toImportPaths
, toNamePair
, unionInstallRequires
) where
import Control.Monad (forM)
import qualified Control.Monad.State as ST
import qualified Data.List as L
import Data.Maybe (catMaybes, fromMaybe)
import Data.Typeable (Typeable)
import GHC.Exts (IsList (toList))
import Text.Printf (printf)
import qualified Data.HashMap.Strict as HM
import qualified Data.Map.Strict as M
import qualified Data.SemVer as SV
import qualified Data.Set as S
import qualified Data.Text as T
import Data.Text.Encoding (decodeUtf8, encodeUtf8)
import Data.Function (on)
import System.FilePath (joinPath)
import qualified Text.Email.Validate as E
import Text.InterpolatedString.Perl6 (q, qq)
import qualified Nirum.CodeGen as C
import Nirum.CodeGen (Failure)
import qualified Nirum.Constructs.Annotation as A
import qualified Nirum.Constructs.DeclarationSet as DS
import qualified Nirum.Constructs.Identifier as I
import Nirum.Constructs.Declaration (Documented (docsBlock))
import Nirum.Constructs.ModulePath ( ModulePath
, fromIdentifiers
, hierarchy
, hierarchies
, replacePrefix
)
import Nirum.Constructs.Name (Name (Name))
import qualified Nirum.Constructs.Name as N
import Nirum.Constructs.Service ( Method ( Method
, errorType
, methodName
, parameters
, returnType
)
, Parameter (Parameter)
, Service (Service)
)
import Nirum.Constructs.TypeDeclaration ( EnumMember (EnumMember)
, Field (Field, fieldName)
, PrimitiveTypeIdentifier (..)
, Tag (Tag)
, Type ( Alias
, EnumType
, PrimitiveType
, RecordType
, UnboxedType
, UnionType
)
, TypeDeclaration (..)
)
import Nirum.Constructs.TypeExpression ( TypeExpression ( ListModifier
, MapModifier
, OptionModifier
, SetModifier
, TypeIdentifier
)
)
import Nirum.Docs.ReStructuredText (ReStructuredText, render)
import Nirum.Package ( BoundModule
, Package (Package, metadata, modules)
, TypeLookup (Imported, Local, Missing)
, lookupType
, resolveBoundModule
, types
)
import Nirum.Package.Metadata ( Author (Author, name, email)
, Metadata ( Metadata
, authors
, target
, version
, description
, license
)
, MetadataError ( FieldError
, FieldTypeError
, FieldValueError
)
, Node (VString)
, Target ( CompileError
, CompileResult
, compilePackage
, parseTarget
, showCompileError
, targetName
, toByteString
)
, fieldType
, stringField
, tableField
, versionField
)
import qualified Nirum.Package.ModuleSet as MS
import qualified Nirum.Package.Metadata as MD
minimumRuntime :: SV.Version
minimumRuntime = SV.version 0 6 0 [] []
data Python = Python { packageName :: T.Text
, minimumRuntimeVersion :: SV.Version
, renames :: RenameMap
} deriving (Eq, Ord, Show, Typeable)
type RenameMap = M.Map ModulePath ModulePath
type Package' = Package Python
type CompileError' = T.Text
data PythonVersion = Python2
| Python3
deriving (Eq, Ord, Show)
data Source = Source { sourcePackage :: Package'
, sourceModule :: BoundModule Python
} deriving (Eq, Ord, Show)
type Code = T.Text
instance Failure CodeGenContext CompileError' where
fromString = return . T.pack
data CodeGenContext
= CodeGenContext { standardImports :: S.Set T.Text
, thirdPartyImports :: M.Map T.Text (M.Map T.Text T.Text)
, localImports :: M.Map T.Text (S.Set T.Text)
, pythonVersion :: PythonVersion
}
deriving (Eq, Ord, Show)
localImportsMap :: CodeGenContext -> M.Map T.Text (M.Map T.Text T.Text)
localImportsMap CodeGenContext { localImports = imports } =
M.map (M.fromSet id) imports
sourceDirectory :: PythonVersion -> T.Text
sourceDirectory Python2 = "src-py2"
sourceDirectory Python3 = "src"
empty :: PythonVersion -> CodeGenContext
empty pythonVersion' = CodeGenContext { standardImports = []
, thirdPartyImports = []
, localImports = []
, pythonVersion = pythonVersion'
}
type CodeGen = C.CodeGen CodeGenContext CompileError'
runCodeGen :: CodeGen a
-> CodeGenContext
-> (Either CompileError' a, CodeGenContext)
runCodeGen = C.runCodeGen
insertStandardImport :: T.Text -> CodeGen ()
insertStandardImport module' = ST.modify insert'
where
insert' c@CodeGenContext { standardImports = si } =
c { standardImports = S.insert module' si }
insertThirdPartyImports :: [(T.Text, S.Set T.Text)] -> CodeGen ()
insertThirdPartyImports imports =
insertThirdPartyImportsA [ (from, M.fromSet id objects)
| (from, objects) <- imports
]
insertThirdPartyImportsA :: [(T.Text, M.Map T.Text T.Text)] -> CodeGen ()
insertThirdPartyImportsA imports =
ST.modify insert'
where
insert' c@CodeGenContext { thirdPartyImports = ti } =
c { thirdPartyImports = L.foldl (M.unionWith M.union) ti importList }
importList :: [M.Map T.Text (M.Map T.Text T.Text)]
importList = [ M.singleton from objects
| (from, objects) <- imports
]
insertLocalImport :: T.Text -> T.Text -> CodeGen ()
insertLocalImport module' object = ST.modify insert'
where
insert' c@CodeGenContext { localImports = li } =
c { localImports = M.insertWith S.union module' [object] li }
importTypingForPython3 :: CodeGen ()
importTypingForPython3 = do
pyVer <- getPythonVersion
case pyVer of
Python2 -> return ()
Python3 -> insertStandardImport "typing"
insertEnumImport :: CodeGen ()
insertEnumImport = insertStandardImport "enum"
getPythonVersion :: CodeGen PythonVersion
getPythonVersion = fmap pythonVersion ST.get
renameModulePath :: RenameMap -> ModulePath -> ModulePath
renameModulePath renameMap path' =
rename (M.toDescList renameMap)
-- longest paths should be processed first
where
rename :: [(ModulePath, ModulePath)] -> ModulePath
rename ((from, to) : xs) = let r = replacePrefix from to path'
in if r == path'
then rename xs
else r
rename [] = path'
renameMP :: Python -> ModulePath -> ModulePath
renameMP Python { renames = table } = renameModulePath table
-- | The set of Python reserved keywords.
-- See also: https://docs.python.org/3/reference/lexical_analysis.html#keywords
keywords :: S.Set T.Text
keywords = [ "False", "None", "True"
, "and", "as", "assert", "break", "class", "continue"
, "def", "del" , "elif", "else", "except", "finally"
, "for", "from", "global", "if", "import", "in", "is"
, "lambda", "nonlocal", "not", "or", "pass", "raise"
, "return", "try", "while", "with", "yield"
]
toClassName :: I.Identifier -> T.Text
toClassName identifier =
if className `S.member` keywords then className `T.snoc` '_' else className
where
className :: T.Text
className = I.toPascalCaseText identifier
toClassName' :: Name -> T.Text
toClassName' = toClassName . N.facialName
toAttributeName :: I.Identifier -> T.Text
toAttributeName identifier =
if attrName `S.member` keywords then attrName `T.snoc` '_' else attrName
where
attrName :: T.Text
attrName = I.toSnakeCaseText identifier
toAttributeName' :: Name -> T.Text
toAttributeName' = toAttributeName . N.facialName
toImportPath' :: ModulePath -> T.Text
toImportPath' = T.intercalate "." . map toAttributeName . toList
toImportPath :: Python -> ModulePath -> T.Text
toImportPath target' = toImportPath' . renameMP target'
toImportPaths :: Python -> S.Set ModulePath -> [T.Text]
toImportPaths target' paths =
S.toAscList $ S.map toImportPath' $ hierarchies renamedPaths
where
renamedPaths :: S.Set ModulePath
renamedPaths = S.map (renameMP target') paths
toNamePair :: Name -> T.Text
toNamePair (Name f b) = [qq|('{toAttributeName f}', '{I.toSnakeCaseText b}')|]
stringLiteral :: T.Text -> T.Text
stringLiteral string =
open $ T.concatMap esc string `T.snoc` '"'
where
open :: T.Text -> T.Text
open = if T.any (> '\xff') string then T.append [qq|u"|] else T.cons '"'
esc :: Char -> T.Text
esc '"' = "\\\""
esc '\\' = "\\\\"
esc '\t' = "\\t"
esc '\n' = "\\n"
esc '\r' = "\\r"
esc c
| c >= '\x10000' = T.pack $ printf "\\U%08x" c
| c >= '\xff' = T.pack $ printf "\\u%04x" c
| c < ' ' || c >= '\x7f' = T.pack $ printf "\\x%02x" c
| otherwise = T.singleton c
toIndentedCodes :: (a -> T.Text) -> [a] -> T.Text -> T.Text
toIndentedCodes f traversable concatenator =
T.intercalate concatenator $ map f traversable
compileParameters :: (ParameterName -> ParameterType -> Code)
-> [(T.Text, Code, Bool)]
-> Code
compileParameters gen nameTypeTriples =
toIndentedCodes
(\ (n, t, o) -> gen n t `T.append` if o then "=None" else "")
nameTypeTriples ", "
compileFieldInitializers :: DS.DeclarationSet Field -> Int -> CodeGen Code
compileFieldInitializers fields depth = do
initializers <- forM (toList fields) compileFieldInitializer
return $ T.intercalate indentSpaces initializers
where
indentSpaces :: T.Text
indentSpaces = "\n" `T.append` T.replicate depth " "
compileFieldInitializer :: Field -> CodeGen Code
compileFieldInitializer (Field fieldName' fieldType' _) =
case fieldType' of
SetModifier _ ->
return [qq|self.$attributeName = frozenset($attributeName)|]
ListModifier _ -> do
insertThirdPartyImportsA [ ( "nirum.datastructures"
, [("list_type", "List")]
)
]
return [qq|self.$attributeName = list_type($attributeName)|]
_ -> return [qq|self.$attributeName = $attributeName|]
where
attributeName :: Code
attributeName = toAttributeName' fieldName'
compileDocs :: Documented a => a -> Maybe ReStructuredText
compileDocs = fmap render . docsBlock
quoteDocstring :: ReStructuredText -> Code
quoteDocstring rst = T.concat ["r'''", rst, "\n'''\n"]
compileDocstring' :: Documented a => Code -> a -> [ReStructuredText] -> Code
compileDocstring' indentSpace d extra =
case (compileDocs d, extra) of
(Nothing, []) -> "\n"
(result, extra') -> indent indentSpace $ quoteDocstring $
T.append (fromMaybe "" result) $
T.concat ['\n' `T.cons` e `T.snoc` '\n' | e <- extra']
compileDocstring :: Documented a => Code -> a -> Code
compileDocstring indentSpace d = compileDocstring' indentSpace d []
compileDocstringWithFields :: Documented a
=> Code -> a -> DS.DeclarationSet Field -> Code
compileDocstringWithFields indentSpace decl fields =
compileDocstring' indentSpace decl extra
where
extra :: [ReStructuredText]
extra =
[ case compileDocs f of
Nothing -> T.concat [ ".. attribute:: "
, toAttributeName' n
, "\n"
]
Just docs' -> T.concat [ ".. attribute:: "
, toAttributeName' n
, "\n\n"
, indent " " docs'
]
| f@(Field n _ _) <- toList fields
]
compileDocsComment :: Documented a => Code -> a -> Code
compileDocsComment indentSpace d =
case compileDocs d of
Nothing -> "\n"
Just rst -> indent (indentSpace `T.append` "#: ") rst
indent :: Code -> Code -> Code
indent space =
T.intercalate "\n" . map indentLn . T.lines
where
indentLn :: Code -> Code
indentLn line
| T.null line = T.empty
| otherwise = space `T.append` line
typeReprCompiler :: CodeGen (Code -> Code)
typeReprCompiler = do
ver <- getPythonVersion
case ver of
Python2 -> return $ \ t -> [qq|($t.__module__ + '.' + $t.__name__)|]
Python3 -> do
insertStandardImport "typing"
return $ \ t -> [qq|typing._type_repr($t)|]
type ParameterName = Code
type ParameterType = Code
type ReturnType = Code
parameterCompiler :: CodeGen (ParameterName -> ParameterType -> Code)
parameterCompiler = do
ver <- getPythonVersion
return $ \ n t -> case ver of
Python2 -> n
Python3 -> [qq|$n: '{t}'|]
returnCompiler :: CodeGen (ReturnType -> Code)
returnCompiler = do
ver <- getPythonVersion
return $ \ r ->
case (ver, r) of
(Python2, _) -> ""
(Python3, "None") -> [qq| -> None|]
(Python3, _) -> [qq| -> '{r}'|]
compileUnionTag :: Source -> Name -> Tag -> CodeGen Code
compileUnionTag source parentname d@(Tag typename' fields _) = do
typeExprCodes <- mapM (compileTypeExpression source)
[typeExpr | (Field _ typeExpr _) <- toList fields]
let optionFlags = [ case typeExpr of
OptionModifier _ -> True
_ -> False
| (Field _ typeExpr _) <- toList fields
]
className = toClassName' typename'
tagNames = map (toAttributeName' . fieldName) (toList fields)
getOptFlag :: (T.Text, Code, Bool) -> Bool
getOptFlag (_, _, flag) = flag
nameTypeTriples = L.sortBy (compare `on` getOptFlag)
(zip3 tagNames typeExprCodes optionFlags)
slotTypes = toIndentedCodes
(\ (n, t, _) -> [qq|('{n}', {t})|]) nameTypeTriples ",\n "
slots = if length tagNames == 1
then [qq|'{head tagNames}'|] `T.snoc` ','
else toIndentedCodes (\ n -> [qq|'{n}'|]) tagNames ",\n "
hashTuple = if null tagNames
then "self.__nirum_tag__"
else [qq|({attributes},)|] :: T.Text
where
attributes :: T.Text
attributes = toIndentedCodes (\ n -> [qq|self.{n}|]) tagNames ", "
nameMaps = toIndentedCodes
toNamePair
(map fieldName $ toList fields)
",\n "
parentClass = toClassName' parentname
insertThirdPartyImportsA
[ ("nirum.validate", [("validate_union_type", "validate_union_type")])
, ("nirum.constructs", [("name_dict_type", "NameDict")])
]
typeRepr <- typeReprCompiler
arg <- parameterCompiler
ret <- returnCompiler
pyVer <- getPythonVersion
initializers <- compileFieldInitializers fields $ case pyVer of
Python3 -> 2
Python2 -> 3
let initParams = compileParameters arg nameTypeTriples
inits = case pyVer of
Python2 -> [qq|
def __init__(self, **kwargs):
def __init__($initParams):
$initializers
pass
__init__(**kwargs)
validate_union_type(self)
|]
Python3 -> [qq|
def __init__(self{ if null nameTypeTriples
then T.empty
else ", *, " `T.append` initParams }) -> None:
$initializers
validate_union_type(self)
|]
return [qq|
class $className($parentClass):
{compileDocstringWithFields " " d fields}
__slots__ = (
$slots
)
__nirum_tag__ = $parentClass.Tag.{toAttributeName' typename'}
__nirum_tag_names__ = name_dict_type([
$nameMaps
])
@staticmethod
def __nirum_tag_types__():
return [$slotTypes]
{ inits :: T.Text }
def __repr__(self){ ret "str" }:
return '\{0\}(\{1\})'.format(
{typeRepr "type(self)"},
', '.join('\{\}=\{\}'.format(attr, getattr(self, attr))
for attr in self.__slots__)
)
def __eq__(self, other){ ret "bool" }:
return isinstance(other, $className) and all(
getattr(self, attr) == getattr(other, attr)
for attr in self.__slots__
)
def __ne__(self, other){ ret "bool" }:
return not self == other
def __hash__(self){ ret "int" }:
return hash($hashTuple)
|]
compilePrimitiveType :: PrimitiveTypeIdentifier -> CodeGen Code
compilePrimitiveType primitiveTypeIdentifier = do
pyVer <- getPythonVersion
case (primitiveTypeIdentifier, pyVer) of
(Bool, _) -> return "bool"
(Bigint, _) -> return "int"
(Decimal, _) -> do
insertStandardImport "decimal"
return "decimal.Decimal"
(Int32, _) -> return "int"
(Int64, Python2) -> do
insertStandardImport "numbers"
return "numbers.Integral"
(Int64, Python3) -> return "int"
(Float32, _) -> return "float"
(Float64, _) -> return "float"
(Text, Python2) -> return "unicode"
(Text, Python3) -> return "str"
(Binary, _) -> return "bytes"
(Date, _) -> do
insertStandardImport "datetime"
return "datetime.date"
(Datetime, _) -> do
insertStandardImport "datetime"
return "datetime.datetime"
(Uuid, _) -> insertStandardImport "uuid" >> return "uuid.UUID"
(Uri, Python2) -> return "unicode"
(Uri, Python3) -> return "str"
compileTypeExpression :: Source -> TypeExpression -> CodeGen Code
compileTypeExpression Source { sourcePackage = Package { metadata = meta }
, sourceModule = boundModule
}
(TypeIdentifier i) =
case lookupType i boundModule of
Missing -> fail $ "undefined identifier: " ++ I.toString i
Imported _ (PrimitiveType p _) -> compilePrimitiveType p
Imported m _ -> do
insertThirdPartyImports [(toImportPath target' m, [toClassName i])]
return $ toClassName i
Local _ -> return $ toClassName i
where
target' :: Python
target' = target meta
compileTypeExpression source (MapModifier k v) = do
kExpr <- compileTypeExpression source k
vExpr <- compileTypeExpression source v
insertStandardImport "typing"
return [qq|typing.Mapping[$kExpr, $vExpr]|]
compileTypeExpression source modifier = do
expr <- compileTypeExpression source typeExpr
insertStandardImport "typing"
return [qq|typing.$className[$expr]|]
where
typeExpr :: TypeExpression
className :: T.Text
(typeExpr, className) = case modifier of
OptionModifier t' -> (t', "Optional")
SetModifier t' -> (t', "AbstractSet")
ListModifier t' -> (t', "Sequence")
TypeIdentifier _ -> undefined -- never happen!
MapModifier _ _ -> undefined -- never happen!
compileTypeDeclaration :: Source -> TypeDeclaration -> CodeGen Code
compileTypeDeclaration _ TypeDeclaration { type' = PrimitiveType {} } =
return "" -- never used
compileTypeDeclaration src d@TypeDeclaration { typename = typename'
, type' = Alias ctype
} = do
ctypeExpr <- compileTypeExpression src ctype
return [qq|
$docsComment
{toClassName' typename'} = $ctypeExpr
|]
where
docsComment :: Code
docsComment =
case compileDocs d of
Nothing -> ""
Just rst -> indent "#: " rst
compileTypeDeclaration src d@TypeDeclaration { typename = typename'
, type' = UnboxedType itype
} = do
let className = toClassName' typename'
itypeExpr <- compileTypeExpression src itype
insertThirdPartyImports [ ("nirum.validate", ["validate_boxed_type"])
, ("nirum.serialize", ["serialize_boxed_type"])
, ("nirum.deserialize", ["deserialize_boxed_type"])
]
arg <- parameterCompiler
typeRepr <- typeReprCompiler
ret <- returnCompiler
return [qq|
class $className(object):
{compileDocstring " " d}
@staticmethod
def __nirum_get_inner_type__():
return $itypeExpr
def __init__(self, { arg "value" itypeExpr }){ ret "None" }:
validate_boxed_type(value, $itypeExpr)
self.value = value # type: $itypeExpr
def __eq__(self, other){ ret "bool" }:
return (isinstance(other, $className) and
self.value == other.value)
def __ne__(self, other){ ret "bool" }:
return not self == other
def __hash__(self){ ret "int" }:
return hash(self.value)
def __nirum_serialize__(self){ ret "typing.Any" }:
return serialize_boxed_type(self)
@classmethod
def __nirum_deserialize__(
{arg "cls" "type"},
{arg "value" "typing.Any"}
){ ret className }:
return deserialize_boxed_type(cls, value)
def __repr__(self){ ret "str" }:
return '\{0\}(\{1!r\})'.format(
{typeRepr "type(self)"}, self.value
)
def __hash__(self){ ret "int" }:
return hash(self.value)
|]
compileTypeDeclaration _ d@TypeDeclaration { typename = typename'
, type' = EnumType members
} = do
let className = toClassName' typename'
memberNames = T.intercalate
"\n"
[ T.concat [ compileDocsComment " " m
, "\n "
, toAttributeName' memberName
, " = '"
, I.toSnakeCaseText bn
, "'"
]
| m@(EnumMember memberName@(Name _ bn) _) <- toList members
]
insertEnumImport
arg <- parameterCompiler
ret <- returnCompiler
return [qq|
class $className(enum.Enum):
{compileDocstring " " d}
$memberNames
def __nirum_serialize__(self){ ret "str" }:
return self.value
@classmethod
def __nirum_deserialize__(
{arg "cls" "type"},
{arg "value" "str"}
){ ret className }:
return cls(value.replace('-', '_')) # FIXME: validate input
|]
compileTypeDeclaration src d@TypeDeclaration { typename = typename'
, type' = RecordType fields
} = do
let className = toClassName' typename'
fieldList = toList fields
typeExprCodes <- mapM (compileTypeExpression src)
[typeExpr | (Field _ typeExpr _) <- fieldList]
let optionFlags = [ case typeExpr of
OptionModifier _ -> True
_ -> False
| (Field _ typeExpr _) <- fieldList
]
fieldNames = map toAttributeName' [ name'
| (Field name' _ _) <- fieldList
]
getOptFlag :: (T.Text, Code, Bool) -> Bool
getOptFlag (_, _, flag) = flag
nameTypeTriples = L.sortBy (compare `on` getOptFlag)
(zip3 fieldNames typeExprCodes optionFlags)
slotTypes = toIndentedCodes
(\ (n, t, _) -> [qq|'{n}': {t}|]) nameTypeTriples ",\n "
slots = toIndentedCodes (\ n -> [qq|'{n}'|]) fieldNames ",\n "
nameMaps = toIndentedCodes
toNamePair
(map fieldName $ toList fields)
",\n "
hashText = toIndentedCodes (\ n -> [qq|self.{n}|]) fieldNames ", "
importTypingForPython3
insertThirdPartyImports [ ("nirum.validate", ["validate_record_type"])
, ("nirum.serialize", ["serialize_record_type"])
, ("nirum.deserialize", ["deserialize_record_type"])
]
insertThirdPartyImportsA [ ( "nirum.constructs"
, [("name_dict_type", "NameDict")]
)
]
arg <- parameterCompiler
ret <- returnCompiler
typeRepr <- typeReprCompiler
pyVer <- getPythonVersion
initializers <- compileFieldInitializers fields $ case pyVer of
Python3 -> 2
Python2 -> 3
let initParams = compileParameters arg nameTypeTriples
inits = case pyVer of
Python2 -> [qq|
def __init__(self, **kwargs):
def __init__($initParams):
$initializers
pass
__init__(**kwargs)
validate_record_type(self)
|]
Python3 -> [qq|
def __init__(self{ if null nameTypeTriples
then T.empty
else ", *, " `T.append` initParams }) -> None:
$initializers
validate_record_type(self)
|]
let clsType = arg "cls" "type"
return [qq|
class $className(object):
{compileDocstringWithFields " " d fields}
__slots__ = (
$slots,
)
__nirum_record_behind_name__ = (
'{I.toSnakeCaseText $ N.behindName typename'}'
)
__nirum_field_names__ = name_dict_type([$nameMaps])
@staticmethod
def __nirum_field_types__():
return \{$slotTypes\}
{inits :: T.Text}
def __repr__(self){ret "bool"}:
return '\{0\}(\{1\})'.format(
{typeRepr "type(self)"},
', '.join('\{\}=\{\}'.format(attr, getattr(self, attr))
for attr in self.__slots__)
)
def __eq__(self, other){ret "bool"}:
return isinstance(other, $className) and all(
getattr(self, attr) == getattr(other, attr)
for attr in self.__slots__
)
def __ne__(self, other){ ret "bool" }:
return not self == other
def __nirum_serialize__(self){ret "typing.Mapping[str, typing.Any]"}:
return serialize_record_type(self)
@classmethod
def __nirum_deserialize__($clsType, value){ ret className }:
return deserialize_record_type(cls, value)
def __hash__(self){ret "int"}:
return hash(($hashText,))
|]
compileTypeDeclaration src
d@TypeDeclaration { typename = typename'
, type' = UnionType tags
, typeAnnotations = annotations
} = do
tagCodes <- mapM (compileUnionTag src typename') $ toList tags
let className = toClassName' typename'
tagCodes' = T.intercalate "\n\n" tagCodes
enumMembers = toIndentedCodes
(\ (t, b) -> [qq|$t = '{b}'|]) enumMembers' "\n "
importTypingForPython3
insertEnumImport
insertThirdPartyImports [ ("nirum.serialize", ["serialize_union_type"])
, ("nirum.deserialize", ["deserialize_union_type"])
]
insertThirdPartyImportsA [ ( "nirum.constructs"
, [("name_dict_type", "NameDict")]
)
]
typeRepr <- typeReprCompiler
ret <- returnCompiler
arg <- parameterCompiler
return [qq|
class $className({T.intercalate "," $ compileExtendClasses annotations}):
{compileDocstring " " d}
__nirum_union_behind_name__ = '{I.toSnakeCaseText $ N.behindName typename'}'
__nirum_field_names__ = name_dict_type([$nameMaps])
class Tag(enum.Enum):
$enumMembers
def __init__(self, *args, **kwargs):
raise NotImplementedError(
"\{0\} cannot be instantiated "
"since it is an abstract class. Instantiate a concrete subtype "
"of it instead.".format({typeRepr "type(self)"})
)
def __nirum_serialize__(self){ ret "typing.Mapping[str, typing.Any]" }:
return serialize_union_type(self)
@classmethod
def __nirum_deserialize__(
{arg "cls" "type"}, value
){ ret className }:
return deserialize_union_type(cls, value)
$tagCodes'
|]
where
enumMembers' :: [(T.Text, T.Text)]
enumMembers' = [ ( toAttributeName' tagName
, I.toSnakeCaseText $ N.behindName tagName
)
| (Tag tagName _ _) <- toList tags
]
nameMaps :: T.Text
nameMaps = toIndentedCodes
toNamePair
[name' | Tag name' _ _ <- toList tags]
",\n "
compileExtendClasses :: A.AnnotationSet -> [Code]
compileExtendClasses annotations' =
if null extendClasses
then ["object"]
else extendClasses
where
extendsClassMap :: M.Map I.Identifier Code
extendsClassMap = [("error", "Exception")]
extendClasses :: [Code]
extendClasses = catMaybes
[ M.lookup annotationName extendsClassMap
| (A.Annotation annotationName _) <- A.toList annotations'
]
compileTypeDeclaration
src@Source { sourcePackage = Package { metadata = metadata' } }
d@ServiceDeclaration { serviceName = name'
, service = Service methods
} = do
let methods' = toList methods
methodMetadata <- mapM compileMethodMetadata methods'
let methodMetadata' = commaNl methodMetadata
dummyMethods <- mapM compileMethod methods'
clientMethods <- mapM compileClientMethod methods'
methodErrorTypes <- mapM compileErrorType methods'
let dummyMethods' = T.intercalate "\n\n" dummyMethods
clientMethods' = T.intercalate "\n\n" clientMethods
methodErrorTypes' =
T.intercalate "," $ catMaybes methodErrorTypes
param <- parameterCompiler
ret <- returnCompiler
insertStandardImport "json"
insertThirdPartyImports [ ("nirum.deserialize", ["deserialize_meta"])
, ("nirum.serialize", ["serialize_meta"])
]
insertThirdPartyImportsA
[ ("nirum.constructs", [("name_dict_type", "NameDict")])
, ("nirum.service", [("service_type", "Service")])
, ("nirum.transport", [("transport_type", "Transport")])
]
return [qq|
class $className(service_type):
{compileDocstring " " d}
__nirum_schema_version__ = \'{SV.toText $ version metadata'}\'
__nirum_service_methods__ = \{
{methodMetadata'}
\}
__nirum_method_names__ = name_dict_type([
$methodNameMap
])
@staticmethod
def __nirum_method_error_types__(k, d=None):
return dict([
$methodErrorTypes'
]).get(k, d)
{dummyMethods'}
# FIXME client MUST be generated & saved on diffrent module
# where service isn't included.
class {className}_Client($className):
"""The client object of :class:`{className}`."""
def __init__(self,
{ param "transport" "transport_type" }){ ret "None" }:
if not isinstance(transport, transport_type):
raise TypeError(
'expected an instance of \{0.__module__\}.\{0.__name__\}, not '
'\{1!r\}'.format(transport_type, transport)
)
self.__nirum_transport__ = transport # type: transport_type
{clientMethods'}
|]
where
className :: T.Text
className = toClassName' name'
commaNl :: [T.Text] -> T.Text
commaNl = T.intercalate ",\n"
compileErrorType :: Method -> CodeGen (Maybe Code)
compileErrorType (Method mn _ _ me _) =
case me of
Just errorTypeExpression -> do
et <- compileTypeExpression src errorTypeExpression
return $ Just [qq|('{toAttributeName' mn}', $et)|]
Nothing -> return Nothing
compileMethod :: Method -> CodeGen Code
compileMethod m@(Method mName params rtype _etype _anno) = do
let mName' = toAttributeName' mName
params' <- mapM compileMethodParameter $ toList params
let paramDocs = [ T.concat [ ":param "
, toAttributeName' pName
, maybe "" (T.append ": ") $ compileDocs p
-- TODO: types
]
| p@(Parameter pName _ _) <- toList params
]
rtypeExpr <- compileTypeExpression src rtype
ret <- returnCompiler
return [qq|
def {mName'}(self, {commaNl params'}){ ret rtypeExpr }:
{compileDocstring' " " m paramDocs}
raise NotImplementedError('$className has to implement {mName'}()')
|]
compileMethodParameter :: Parameter -> CodeGen Code
compileMethodParameter (Parameter pName pType _) = do
pTypeExpr <- compileTypeExpression src pType
arg <- parameterCompiler
return [qq|{arg (toAttributeName' pName) pTypeExpr}|]
compileMethodMetadata :: Method -> CodeGen Code
compileMethodMetadata Method { methodName = mName
, parameters = params
, returnType = rtype
} = do
let params' = toList params :: [Parameter]
rtypeExpr <- compileTypeExpression src rtype
paramMetadata <- mapM compileParameterMetadata params'
let paramMetadata' = commaNl paramMetadata
insertThirdPartyImportsA
[("nirum.constructs", [("name_dict_type", "NameDict")])]
return [qq|'{toAttributeName' mName}': \{
'_v': 2,
'_return': lambda: $rtypeExpr,
'_names': name_dict_type([{paramNameMap params'}]),
{paramMetadata'}
\}|]
compileParameterMetadata :: Parameter -> CodeGen Code
compileParameterMetadata (Parameter pName pType _) = do
let pName' = toAttributeName' pName
pTypeExpr <- compileTypeExpression src pType