-
Notifications
You must be signed in to change notification settings - Fork 35
Expand file tree
/
Copy pathBespoke.hs
More file actions
1348 lines (1252 loc) · 48.8 KB
/
Bespoke.hs
File metadata and controls
1348 lines (1252 loc) · 48.8 KB
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 NamedFieldPuns #-}
{-# language QuasiQuotes #-}
{-# language TemplateHaskell #-}
{-# OPTIONS_GHC -Wno-incomplete-uni-patterns #-}
module Bespoke
( forbiddenConstants
, neverExtendedStructs
, forceDisabledExtensions
, assignBespokeModules
, bespokeStructsAndUnions
, bespokeElements
, bespokeSizes
, bespokeOptionality
, bespokeLengths
, bespokeZeroInstances
, bespokeZeroCStruct
, bespokeSchemes
, BespokeScheme(..)
, structChainVar
, zeroNextPointer
) where
import qualified Data.List.Extra as List
import qualified Data.Map as Map
import qualified Data.Text as T
import Prettyprinter
import Data.Vector ( Vector )
import qualified Data.Vector.Extra as V
import Foreign.C.Types
import Foreign.Ptr
import Language.Haskell.TH ( mkName )
import qualified Language.Haskell.TH.Syntax as TH
import Polysemy
import Polysemy.Input
import Relude hiding ( Const )
import Text.InterpolatedString.Perl6.Unindented
import Control.Monad.Trans.Cont ( ContT )
import Data.Bits
import qualified Data.ByteString as BS
import qualified Data.ByteString.Unsafe as BS
import Foreign.Marshal.Alloc
import Foreign.Marshal.Utils
import Numeric
import CType
import Data.List ( lookup )
import Error
import Foreign.C.String ( CString )
import Foreign.Storable ( Storable(poke) )
import Haskell as H
import Marshal.Marshalable
import Marshal.Scheme
import Render.Element
import Render.Peek ( storablePeek
, vectorPeekWithLenRef
)
import Render.SpecInfo
import Render.Stmts
import Render.Stmts.Poke
import Render.Stmts.Utils
import Render.Type
import Render.Utils
import Spec.Types
import Language.Haskell.TH.Syntax (mkNameG_v)
----------------------------------------------------------------
-- Changes to the spec
----------------------------------------------------------------
-- | These constants are defined elsewhere
forbiddenConstants :: [CName]
forbiddenConstants = ["VK_TRUE", "VK_FALSE", "XR_TRUE", "XR_FALSE"]
-- | Structs which are never extended because they're special, and only used
-- for low-level operations
neverExtendedStructs :: [CName]
neverExtendedStructs = ["VkBaseOutStructure", "VkBaseInStructure"]
forceDisabledExtensions :: [ByteString]
forceDisabledExtensions =
[ "XR_EXT_conformance_automation"
-- Video extensions will make it into the xml registry it seems, disable
-- them until then.
, "VK_KHR_video_decode_av1"
, "VK_KHR_video_encode_av1"
, "VK_KHR_video_encode_quantization_map"
, "VK_EXT_video_decode_h264"
, "VK_EXT_video_encode_h264"
, "VK_EXT_video_decode_h265"
, "VK_EXT_video_encode_h265"
, "VK_KHR_video_decode_h264"
, "VK_KHR_video_encode_h264"
, "VK_KHR_video_decode_h265"
, "VK_KHR_video_encode_h265"
, "VK_KHR_video_decode_queue"
, "VK_KHR_video_encode_queue"
, "VK_KHR_video_queue"
, "VK_KHR_video_maintenance1"
, "VK_KHR_video_maintenance2"
, "VK_KHR_video_decode_vp9"
, "VK_KHR_video_encode_intra_refresh"
, "VK_VALVE_video_encode_rgb_conversion"
-- C parser can't handle members where type name == member name
, "VK_SEC_ubm_surface"
-- Bitfield structs: size calculator can't handle C bitfields
, "VK_NV_cluster_acceleration_structure"
, "VK_NV_partitioned_acceleration_structure"
-- Marshaling: const VkDeviceAddress* without len attribute
, "VK_ARM_performance_counters_by_region"
-- Platform-specific: OHOS types not available
, "VK_OHOS_external_memory"
, "VK_OHOS_surface"
-- Unresolved queries in Vulkan-Docs
-- , "VK_HUAWEI_subpass_shading" -- https://github.com/KhronosGroup/Vulkan-Docs/issues/1564
]
----------------------------------------------------------------
-- Module assignments
----------------------------------------------------------------
assignBespokeModules
:: (HasErr r, HasRenderParams r, Traversable t)
=> t RenderElement
-> Sem r (t RenderElement)
assignBespokeModules es = do
bespokeModules <- bespokeModules
forV es $ \case
r@RenderElement {..}
| exports <- fmap exportName . toList $ reExports
, bespokeMods <-
List.nubOrd . mapMaybe (`List.lookup` bespokeModules) $ exports
-> case bespokeMods of
[] -> pure r
[x] -> case reExplicitModule of
Just m | m /= x ->
throw "Render element already has an explicit module"
_ -> pure $ r { reExplicitModule = Just x }
_ -> throw "Multiple bespoke module names found for render element"
bespokeModules :: HasRenderParams r => Sem r [(HName, ModName)]
bespokeModules = do
RenderParams {..} <- input
mod' <- mkMkModuleName
pure
$ [ ( mkTyName "VkAllocationCallbacks"
, mod' ["Core10", "AllocationCallbacks"]
)
, (mkTyName "VkBaseInStructure" , mod' ["CStruct", "Extends"])
, (mkTyName "VkBaseOutStructure", mod' ["CStruct", "Extends"])
, (mkTyName "XrBaseInStructure" , mod' ["CStruct", "Extends"])
, (mkTyName "XrBaseOutStructure", mod' ["CStruct", "Extends"])
, (mkTyName "XrFovf" , mod' ["Core10", "OtherTypes"])
, (mkTyName "XrPosef" , mod' ["Core10", "Space"])
, ( mkTyName "PFN_vkFaultCallbackFunction"
, mod' ["Core10", "FaultHandlingFunctionality"]
)
, ( mkTyName "FN_vkFaultCallbackFunction"
, mod' ["Core10", "FaultHandlingFunctionality"]
)
]
<> ( (, mod' ["Core10", "FundamentalTypes"])
<$> [ mkTyName "VkBool32"
, TermName "boolToBool32"
, TermName "bool32ToBool"
, mkTyName "XrBool32"
, mkTyName "XrOffset2Df"
, mkTyName "XrExtent2Df"
, mkTyName "XrRect2Df"
, mkTyName "XrOffset2Di"
, mkTyName "XrExtent2Di"
, mkTyName "XrRect2Di"
]
)
----------------------------------------------------------------
-- Schemes
----------------------------------------------------------------
data BespokeScheme where
BespokeScheme ::(forall a. Marshalable a => CName -> a -> Maybe (MarshalScheme a)) -> BespokeScheme
--- ^ Parent name -> child -> scheme
bespokeSchemes :: KnownSpecFlavor t => Spec t -> Sem r [BespokeScheme]
bespokeSchemes spec =
pure $
[baseInOut, wsiScheme, dualPurposeBytestrings, nextPointers spec]
<> difficultLengths
<> [ bitfields
, accelerationStructureGeometry
, buildingAccelerationStructures
, micromapUsageCounts
, cuLaunchSchemes
]
<> openXRSchemes
baseInOut :: BespokeScheme
baseInOut = BespokeScheme $ \case
n | n `elem` ["VkBaseInStructure", "VkBaseOutStructure"] -> \case
m | "pNext" <- name m -> Just $ Normal (type' m)
_ -> Nothing
n | n `elem` ["XrBaseInStructure", "XrBaseOutStructure"] -> \case
m | "next" <- name m -> Just $ Normal (type' m)
_ -> Nothing
_ -> const Nothing
data NextType = NextElided | NextChain
nextPointers :: forall t . KnownSpecFlavor t => Spec t -> BespokeScheme
nextPointers Spec {..} =
let schemeMap :: Map (CName, CName) NextType
schemeMap = Map.fromList
[ ((sName s, nextName), scheme)
| s <- toList specStructs
, let scheme = case sExtendedBy s of
V.Empty -> NextElided
_ -> NextChain
]
in BespokeScheme $ \n c -> case Map.lookup (n, name c) schemeMap of
Nothing -> Nothing
Just NextElided -> Just (ElidedUnivalued "nullPtr")
Just NextChain -> Just (Custom chainScheme)
where
nextName :: CName
nextName = case specFlavor @t of
SpecVk -> "pNext"
SpecXr -> "next"
chainVarT = VarT (mkName structChainVar)
chainT = ConT (mkName "Chain") :@ chainVarT
chainScheme = CustomScheme
{ csName = "Chain"
, csZero = Just "()"
, csZeroIsZero = False -- Pointer to chain
-- , csType = pure $ ForallT [] [ConT (mkName "PokeChain") :@ chainVarT] chainT
, csType = pure $ ForallT [] [] chainT
, csDirectPoke = APoke $ \chainRef ->
stmt (Just (ConT ''Ptr :@ chainT)) (Just (unCName nextName)) $ do
tellImportWithAll (TyConName "PokeChain")
tellImport (TyConName "Chain")
tellImport 'castPtr
tellImportWithAll ''ContT
ValueDoc chain <- use chainRef
pure
. ContTAction
. ValueDoc
$ "fmap castPtr . ContT $ withChain"
<+> chain
, csPeek = \addrRef -> stmt (Just chainT) (Just "next") $ do
chainPtr <- use
=<< storablePeek nextName addrRef (Ptr Const (Ptr Const Void))
tellImportWithAll (TyConName "PeekChain")
tellImport (TyConName "Chain")
tellImport 'castPtr
pure $ IOAction . ValueDoc $ "peekChain" <+> parens
("castPtr" <+> chainPtr)
}
-- | A special poke which writes a zero chain
zeroNextPointer
:: forall r s
. (HasRenderElem r, HasRenderParams r, HasErr r, HasStmts r)
=> Stmt s r (Ref s ValueDoc)
zeroNextPointer = do
let chainVarT = VarT (mkName structChainVar)
chainT = ConT (mkName "Chain") :@ chainVarT
varTDoc <- renderTypeHighPrec chainVarT
stmt (Just (ConT ''Ptr :@ chainT)) (Just "pNext") $ do
tellImportWithAll (TyConName "PokeChain")
tellImport (TyConName "Chain")
tellImport 'castPtr
tellImportWithAll ''ContT
pure
. ContTAction
. ValueDoc
$ "fmap castPtr . ContT $ withZeroChain @"
<> varTDoc
wsiScheme :: BespokeScheme
wsiScheme = BespokeScheme $ const $ \case
a | t@(Ptr _ (TypeName "xcb_connection_t")) <- type' a -> Just (Normal t)
a | t@(Ptr _ (TypeName "wl_display")) <- type' a -> Just (Normal t)
a | t@(Ptr _ (TypeName "Display")) <- type' a -> Just (Normal t)
_ -> Nothing
-- So we render the dual purpose command properly
dualPurposeBytestrings :: BespokeScheme
dualPurposeBytestrings = BespokeScheme $ \case
c
| c `elem` ["vkGetPipelineCacheData", "vkGetValidationCacheDataEXT"] -> \case
a | (Ptr NonConst Void) <- type' a, "pData" <- name a ->
Just (Returned ByteString)
_ -> Nothing
| c == "vkGetPipelineBinaryDataKHR" -> \case
a | (Ptr NonConst Void) <- type' a, "pPipelineBinaryData" <- name a ->
Just (Returned ByteString)
_ -> Nothing
| c == "vkGetShaderInfoAMD" -> \case
a | (Ptr NonConst Void) <- type' a, "pInfo" <- name a ->
Just (Returned ByteString)
_ -> Nothing
| c == "vkGetShaderBinaryDataEXT" -> \case
a | (Ptr NonConst Void) <- type' a, "pData" <- name a ->
Just (Returned ByteString)
_ -> Nothing
| c == "vkGetCudaModuleCacheNV" -> \case
a | (Ptr NonConst Void) <- type' a, "pCacheData" <- name a ->
Just (Returned ByteString)
_ -> Nothing
_ -> const Nothing
difficultLengths :: [BespokeScheme]
difficultLengths =
[ BespokeScheme $ \case
"VkPipelineMultisampleStateCreateInfo" -> \case
p | "rasterizationSamples" <- name p -> Just $ Normal (type' p)
(p :: a) | "pSampleMask" <- name p -> Just . Custom $ CustomScheme
{ csName = "Sample mask array"
, csZero = Just "mempty"
, csZeroIsZero = True
, csType = do
RenderParams {..} <- input
let TyConName sm = mkTyName "VkSampleMask"
pure $ ConT ''Vector :@ ConT (mkName (T.unpack sm))
, csDirectPoke = APoke $ \vecRef -> do
RenderParams {..} <- input
stmt (Just (ConT ''Ptr :@ ConT ''Word32)) (Just "pSampleMask") $ do
tellQualImport 'V.length
tellQualImport 'nullPtr
ValueDoc vec <- use vecRef
ValueDoc samples <- useViaName "rasterizationSamples"
let
sampleTy = mkTyName "VkSampleCountFlagBits"
sampleCon =
mkConName "VkSampleCountFlagBits" "VkSampleCountFlagBits"
cond = parens "requiredLen == fromIntegral vecLen"
err
= "sampleMask must be either empty or contain enough bits to cover all the sample specified by 'rasterizationSamples'"
tellImportWith sampleTy sampleCon
throwErr <- renderSubStmtsIO (unitStmt (throwErrDoc err cond))
vecPoke <- renderSubStmts $ do
vecRef' <- pureStmt =<< raise (use vecRef)
getVectorPoke @a "pSampleMask"
(Ptr Const (TypeName "VkSampleMask"))
(Normal (TypeName "VkSampleMask"))
NotNullable
vecRef'
vecPokeDoc <- case vecPoke of
ContTStmts d -> pure d
IOStmts d -> do
tellImportWithAll 'lift
pure $ "lift $" <+> d
pure
. ContTAction
. ValueDoc
$ "case Data.Vector.length"
<+> vec
<+> "of"
<> line
<> indent
2
(vsep
[ "0 -> pure nullPtr"
, "vecLen ->" <+> doBlock
[ "let" <+> indent
0
( "requiredLen ="
<+> "case"
<+> samples
<+> "of"
<> line
<> indent
2
(pretty sampleCon <+> "n -> (n + 31) `quot` 32")
)
, "lift $" <+> throwErr
, vecPokeDoc
]
]
)
, csPeek = \addrRef -> do
RenderParams {..} <- input
stmt (Just (ConT ''Vector :@ ConT ''Word32)) (Just "pSampleMask") $ do
ptr <- use =<< storablePeek
"pSampleMask"
addrRef
(Ptr Const (Ptr Const (TypeName "VkSampleMask")))
vecPeek <- renderSubStmtsIO $ do
addrRef <- pureStmt (AddrDoc ptr)
ValueDoc samples <- useViaName "rasterizationSamples"
let sampleTy = mkTyName "VkSampleCountFlagBits"
sampleCon =
mkConName "VkSampleCountFlagBits" "VkSampleCountFlagBits"
tellImportWith sampleTy sampleCon
len <-
pureStmt
. ValueDoc
$ "case"
<+> samples
<+> "of"
<> line
<> indent
2
( pretty sampleCon
<+> "n -> (fromIntegral n + 31) `quot` 32"
)
-- TODO: pass Nullable here and don't reimplement that logic
vectorPeekWithLenRef @a "sampleMask"
(Normal (TypeName "VkSampleMask"))
addrRef
(TypeName "VkSampleMask")
mempty
len
NotNullable
pure
. IOAction
. ValueDoc
$ "if"
<+> ptr
<+> "== nullPtr"
<> line
<> indent 2 (vsep ["then pure mempty", "else" <+> vecPeek])
}
_ -> Nothing
_ -> const Nothing
, BespokeScheme $ \case
"VkShaderModuleCreateInfo" -> \case
p | "codeSize" <- name p -> Just . ElidedCustom $ CustomSchemeElided
{ cseName = "Shader code length"
, cseDirectPoke = stmt (Just (ConT ''Int)) (Just "codeSizeBytes") $ do
tellQualImport 'BS.length
ValueDoc bs <- useViaName "pCode"
pure
. Pure InlineOnce
. ValueDoc
$ "fromIntegral $ Data.ByteString.length"
<+> bs
, csePeek = Just $ \addrRef ->
storablePeek "codeSize" addrRef (Ptr Const (TypeName "size_t"))
}
p | "pCode" <- name p -> Just . Custom $ CustomScheme
{ csName = "Shader code"
, csZero = Just "mempty"
, csZeroIsZero = True
, csType = pure $ ConT ''ByteString
, csDirectPoke = APoke $ \bsRef -> do
assertMul4 <- unitStmt $ do
ValueDoc bs <- use bsRef
tellQualImport 'BS.length
tellImport (mkNameG_v "base" "Data.Bits" ".&.")
let err = "code size must be a multiple of 4"
cond =
parens $ "Data.ByteString.length" <+> bs <+> ".&. 3 == 0"
throwErrDoc err cond
stmt (Just (ConT ''Ptr :@ ConT ''Word32)) (Just "pCode") $ do
after assertMul4
ValueDoc bs <- use bsRef
maybeAligned <- use =<< stmt
Nothing
(Just "unalignedCode")
(do
tellImportWithAll ''ContT
tellImport 'BS.unsafeUseAsCString
pure . ContTAction $ "ContT $ unsafeUseAsCString" <+> bs
)
tellImport 'ptrToWordPtr
tellImport (mkNameG_v "base" "Data.Bits" ".&.")
tellImport 'castPtr
tellImport ''CChar
tellImport ''Word32
tellImportWithAll ''ContT
tellImport 'allocaBytes
tellImport 'lift
tellQualImport 'BS.length
tellImport 'copyBytes
let len = "Data.ByteString.length" <+> bs
pure
. ContTAction
. ValueDoc
$ "if ptrToWordPtr"
<+> maybeAligned
<+> ".&. 3 == 0"
<> line
<> indent
2
(vsep
[ "-- If this pointer is already aligned properly then use it"
, "then pure $ castPtr @CChar @Word32" <+> maybeAligned
, "-- Otherwise allocate and copy the bytes"
, "else" <+> doBlock
[ "let len =" <+> len
, "mem <- ContT $ allocaBytes @Word32"
<+> "len"
, "lift $ copyBytes mem (castPtr @CChar @Word32"
<+> maybeAligned
<> ")"
<+> "len"
, "pure mem"
]
]
)
, csPeek = \addrRef ->
stmt (Just (ConT ''ByteString)) (Just "code") $ do
ValueDoc len <- useViaName "codeSize"
let bytes = "fromIntegral $" <+> len <+> "* 4"
ptr <- use =<< storablePeek
"pCode"
addrRef
(Ptr Const (Ptr Const (TypeName "uint32_t")))
tellImport 'castPtr
tellImport ''Word32
tellImport ''CChar
let castPtr = "castPtr @Word32 @CChar" <+> ptr
tellImport 'BS.packCStringLen
pure . IOAction . ValueDoc $ "packCStringLen" <+> align (tupled
[castPtr, bytes])
}
_ -> Nothing
_ -> const Nothing
, BespokeScheme $ \case
structName
| -- Handle before and after 1.2.162
structName
`elem` [ "VkAccelerationStructureVersionInfoKHR"
, "VkAccelerationStructureVersionKHR"
, "VkMicromapVersionInfoEXT"
]
-> \case
p
| memberName <- name p
, memberName `elem` ["pVersionData", "versionData"]
, Ptr Const (TypeName "uint8_t") <- type' p
, -- TODO, This should be a "MultipleLength" or something
V.Singleton (NamedLength (CName len)) <- lengths p
, len == "2*VK_UUID_SIZE"
-> Just . Custom $ CustomScheme
{ csName = "Acceleration structure version"
, csZero = Just "mempty"
, csZeroIsZero = True
, csType = pure $ ConT ''ByteString
, csDirectPoke = APoke $ \bsRef -> do
assertCorrectLength <- unitStmt $ do
RenderParams {..} <- input
ValueDoc bs <- use bsRef
tellQualImport 'BS.length
let
err =
unCName structName
<> "::versionData must be "
<> len
<> " bytes"
uuidSizeDoc = mkPatternName "VK_UUID_SIZE"
cond =
parens
$ "Data.ByteString.length"
<+> bs
<+> "== 2 *"
<+> pretty uuidSizeDoc
tellImport uuidSizeDoc
throwErrDoc err cond
stmt (Just (ConT ''Ptr :@ ConT ''Word8)) (Just "versionData'")
$ do
after assertCorrectLength
ValueDoc bs <- use bsRef
tellImportWithAll ''ContT
tellImport 'BS.unsafeUseAsCString
tellImport 'castPtr
tellImport ''Word8
tellImport ''CChar
pure
. ContTAction
. ValueDoc
$ "fmap (castPtr @CChar @Word8) . ContT $ unsafeUseAsCString"
<+> bs
, csPeek = \addrRef ->
stmt (Just (ConT ''ByteString)) (Just "versionData") $ do
RenderParams {..} <- input
let uuidSizeDoc = mkPatternName "VK_UUID_SIZE"
bytes = "2 *" <+> pretty uuidSizeDoc
tellImport uuidSizeDoc
ptr <- use =<< storablePeek
"versionData"
addrRef
(Ptr Const (Ptr Const (TypeName "uint8_t")))
tellImport 'castPtr
tellImport ''Word8
tellImport ''CChar
let castPtr = "castPtr @Word8 @CChar" <+> ptr
tellImport 'BS.packCStringLen
pure . IOAction . ValueDoc $ "packCStringLen" <+> align (tupled
[castPtr, bytes])
}
_ -> Nothing
_ -> const Nothing
]
-- | Bitfields at the moment are handled by writing both fields when the first
-- (lower bits) one is written and not doing anything for the second one.
bitfields :: BespokeScheme
bitfields = BespokeScheme $ \case
"VkAccelerationStructureInstanceKHR" -> rtFields
"VkAccelerationStructureSRTMotionInstanceNV" -> rtFields
"VkAccelerationStructureMatrixMotionInstanceNV" -> rtFields
_ -> const Nothing
where
rtFields :: Marshalable a => a -> Maybe (MarshalScheme a)
rtFields = \case
p
| "instanceCustomIndex" <- name p -> Just $ bitfieldMaster p ("mask", 8)
| "mask" <- name p -> Just $ bitfieldSlave 24 p
| "instanceShaderBindingTableRecordOffset" <- name p -> Just
$ bitfieldMaster p ("flags", 8)
| "flags" <- name p -> Just $ bitfieldSlave 24 p
_ -> Nothing
peekBitfield
:: (HasRenderElem r, HasErr r, HasSpecInfo r, HasRenderParams r)
=> CName
-> CType
-> Int
-> Int
-> Ref s AddrDoc
-> Stmt s r (Ref s ValueDoc)
peekBitfield name ty bitSize bitShift addr = do
tyH <- cToHsType DoNotPreserve ty
base <- storablePeek name addr (Ptr Const ty)
shifted <- if bitShift == 0
then pure base
else stmt Nothing Nothing $ do
ValueDoc base <- use base
tellImport (mkName "Data.Bits.shiftR")
pure . Pure InlineOnce . ValueDoc $ parens
(base <+> "`shiftR`" <+> viaShow bitShift)
masked <- if bitSize == 32
then pure shifted
else stmt Nothing Nothing $ do
ValueDoc shifted <- use shifted
tellImport (mkNameG_v "base" "Data.Bits" ".&.")
tellImport 'coerce
let mask = "coerce @Word32 0x"
<> pretty (showHex ((1 `shiftL` bitSize :: Int) - 1) "")
pure . Pure InlineOnce . ValueDoc $ parens (shifted <+> ".&." <+> mask)
stmt (Just tyH) (Just (unCName name)) $ do
masked <- use masked
pure . Pure NeverInline $ masked
bitfieldSlave :: Marshalable a => Int -> a -> MarshalScheme a
bitfieldSlave bitShift = \case
p
| Bitfield ty bitSize <- type' p -> Custom CustomScheme
{ csName = "bitfield slave " <> unCName (name p)
, csZero = Just "zero"
, csZeroIsZero = True
, csType = cToHsType DoNotPreserve ty
, csDirectPoke = NoPoke
, csPeek = peekBitfield (name p) ty bitSize bitShift
}
| otherwise -> error "bitfield slave type isn't a bitfield "
bitfieldMaster :: Marshalable a => a -> (CName, Int) -> MarshalScheme a
bitfieldMaster master (slaveName, _slaveBitSize) = case type' master of
Bitfield ty masterBitSize -> Custom CustomScheme
{ csName = "bitfield master " <> unCName (name master)
, csZero = Just "zero"
, csZeroIsZero = True
, csType = cToHsType DoNotPreserve ty
, csDirectPoke = APoke $ \masterRef -> do
tyH <- cToHsType DoPreserve ty
stmt (Just tyH) Nothing $ do
ValueDoc slaveDoc <- useViaName (unCName slaveName)
ValueDoc masterDoc <- use masterRef
tellImport (mkName "Data.Bits.shiftL")
tellImport (mkNameG_v "base" "Data.Bits" ".|.")
tellImport 'coerce
pure
. Pure InlineOnce
. ValueDoc
$ parens
( parens ("coerce @_ @Word32" <+> slaveDoc)
<+> "`shiftL`"
<+> viaShow masterBitSize
)
<+> ".|."
<+> masterDoc
, csPeek = peekBitfield (name master) ty masterBitSize 0
}
_ -> error "bitfield master isn't a bitfield"
accelerationStructureGeometry :: BespokeScheme
accelerationStructureGeometry = BespokeScheme $ \case
"VkAccelerationStructureBuildGeometryInfoKHR" -> \case
(p :: a) | "ppGeometries" <- name p, Ptr Const (Ptr Const _) <- type' p ->
Just $ ElidedUnivalued "nullPtr"
_ -> Nothing
_ -> const Nothing
-- TODO: Select this when compiling an older spec
_accelerationStructureGeometryPre1_2_162 :: BespokeScheme
_accelerationStructureGeometryPre1_2_162 = BespokeScheme $ \case
"VkAccelerationStructureBuildGeometryInfoKHR" -> \case
(p :: a)
| "geometryArrayOfPointers" <- name p
-> Just . ElidedCustom $ CustomSchemeElided
{ cseName = "geometry array type"
, cseDirectPoke = do
RenderParams {..} <- input
let t = mkPatternName "VK_FALSE"
tellImport t
tyH <- cToHsType DoNotPreserve (type' p)
stmt (Just tyH) Nothing $ pure . Pure AlwaysInline . ValueDoc $ pretty
t
, csePeek = Nothing -- TODO assert it's VK_FALSE here
}
| "geometryCount" <- name p
-> Just . ElidedCustom $ CustomSchemeElided
{ cseName = "geometryCount"
, cseDirectPoke = elidedLengthPoke @_ @a (name p)
(type' p)
mempty
(V.fromList ["ppGeometries"])
, csePeek = Just $ \addr -> storablePeek (name p) addr (type' p)
}
| "ppGeometries" <- name p, Ptr Const unPtrTy@(Ptr Const elemTy) <- type'
p
-> Just . Custom $ CustomScheme
{ csName = "ppGeometries"
, csZero = Just "mempty"
, csZeroIsZero = True -- Pointer to empty array
, csType = (ConT ''Vector :@) <$> cToHsType DoNotPreserve elemTy
, csDirectPoke = APoke $ \vecRef -> do
ptrRef <- getPokeDirect' @a (name p)
unPtrTy
(Vector NotNullable (Normal elemTy))
vecRef
tyH <- cToHsType DoPreserve (Ptr Const unPtrTy)
stmt (Just tyH) (Just "ppGeometries") $ do
ValueDoc ptr <- use ptrRef
tellImportWithAll ''ContT
tellImport 'with
pure . ContTAction . ValueDoc $ "ContT $ with" <+> ptr
, csPeek = error "unused csPeek for ppGeometries"
}
_ -> Nothing
_ -> const Nothing
-- TODO: These should have length annotations which check that they match their
-- siblings
buildingAccelerationStructures :: BespokeScheme
buildingAccelerationStructures = BespokeScheme $ \case
commandName
| commandName
`elem` [ "vkCmdBuildAccelerationStructuresKHR"
, "vkBuildAccelerationStructuresKHR"
]
-> \case
(p :: a)
| "ppBuildRangeInfos" <- name p, Ptr Const (Ptr Const elemTy) <- type' p
-> Just $ Vector NotNullable (Vector NotNullable (Normal elemTy))
_ -> Nothing
"vkCmdBuildAccelerationStructuresIndirectKHR" -> \case
(p :: a)
| "ppMaxPrimitiveCounts" <- name p, Ptr Const (Ptr Const elemTy) <- type'
p
-> Just $ Vector NotNullable (Vector NotNullable (Normal elemTy))
_ -> Nothing
_ -> const Nothing
micromapUsageCounts :: BespokeScheme
micromapUsageCounts = BespokeScheme $ \case
"VkMicromapBuildInfoEXT" -> \case
(p :: a) | "ppUsageCounts" <- name p, Ptr Const (Ptr Const _) <- type' p ->
Just $ ElidedUnivalued "nullPtr"
_ -> Nothing
"VkAccelerationStructureTrianglesOpacityMicromapEXT" -> \case
(p :: a) | "ppUsageCounts" <- name p, Ptr Const (Ptr Const _) <- type' p ->
Just $ ElidedUnivalued "nullPtr"
_ -> Nothing
"VkAccelerationStructureTrianglesDisplacementMicromapNV" -> \case
(p :: a) | "ppUsageCounts" <- name p, Ptr Const (Ptr Const _) <- type' p ->
Just $ ElidedUnivalued "nullPtr"
_ -> Nothing
_ -> const Nothing
structChainVar :: String
structChainVar = "es"
----------------------------------------------------------------
-- Things which are easier to write by hand
----------------------------------------------------------------
-- | These override the description in the spec, make sure they're correct!
bespokeStructsAndUnions :: [StructOrUnion a WithoutSize WithoutChildren]
bespokeStructsAndUnions =
[ Struct
{ sName = "VkTransformMatrixKHR"
, sMembers = V.fromList
[ StructMember
{ smName = "matrixRow0"
, smType = Array NonConst (NumericArraySize 4) Float
, smValues = mempty
, smLengths = mempty
, smIsOptional = mempty
, smOffset = ()
}
, StructMember
{ smName = "matrixRow1"
, smType = Array NonConst (NumericArraySize 4) Float
, smValues = mempty
, smLengths = mempty
, smIsOptional = mempty
, smOffset = ()
}
, StructMember
{ smName = "matrixRow2"
, smType = Array NonConst (NumericArraySize 4) Float
, smValues = mempty
, smLengths = mempty
, smIsOptional = mempty
, smOffset = ()
}
]
, sSize = ()
, sAlignment = ()
, sExtends = mempty
, sExtendedBy = mempty
, sInherits = mempty
, sInheritedBy = mempty
}
]
bespokeSizes :: SpecFlavor -> [(CName, (Int, Int))]
bespokeSizes t =
let
xrSizes =
[ ("XrFlags64" , (8, 8))
, ("XrTime" , (8, 8))
, ("XrDuration" , (8, 8))
, ("XrVersion" , (8, 8))
, ("timespec" , (16, 8))
-- TODO: Can these be got elsewhere?
, ("VkResult" , (4, 4))
, ("VkFormat" , (4, 4))
, ("VkInstance" , (8, 8))
, ("VkPhysicalDevice" , (8, 8))
, ("VkImage" , (8, 8))
, ("VkDevice" , (8, 8))
, ("PFN_vkGetDeviceProcAddr" , (8, 8))
, ("PFN_vkGetInstanceProcAddr", (8, 8))
]
<> (fst <$> concat
[win32Xr @'[Input RenderParams], x11Shared, xcb2Xr, egl, gl, d3d, metalSized]
)
vkSizes =
[ ("VkSampleMask" , (4, 4))
, ("VkFlags" , (4, 4))
, ("VkDeviceSize" , (8, 8))
, ("VkDeviceAddress" , (8, 8))
, ("VkRemoteAddressNV", (8, 8))
]
<> (fst <$> concat
[win32 @'[Input RenderParams], x11Shared, x11, xcb2, zircon, ggp, metalSized]
)
sharedSizes = []
in
sharedSizes <> case t of
SpecVk -> vkSizes
SpecXr -> xrSizes
bespokeOptionality :: CName -> CName -> Maybe (Vector Bool)
bespokeOptionality = \case
-- These are optional depending on the value of `descriptorType`, treat them
-- as unconditionally optional and rely on the programmer (and validation
-- layers) to keep it safe
"VkWriteDescriptorSet" -> \case
"pImageInfo" -> Just (fromList [True])
"pBufferInfo" -> Just (fromList [True])
"pTexelBufferView" -> Just (fromList [True])
_ -> Nothing
-- Because we don't marshal ppGeometries, this is not actually optional
-- See https://github.com/expipiplus1/vulkan/issues/239
"VkAccelerationStructureBuildGeometryInfoKHR" -> \case
"pGeometries" -> Just mempty
_ -> Nothing
-- similar for ppUsageCounts
"VkMicromapBuildInfoEXT" -> \case
"pUsageCounts" -> Just mempty
_ -> Nothing
"VkAccelerationStructureTrianglesOpacityMicromapEXT" -> \case
"pUsageCounts" -> Just mempty
_ -> Nothing
"VkAccelerationStructureTrianglesDisplacementMicromapNV" -> \case
"pUsageCounts" -> Just mempty
_ -> Nothing
_ -> const Nothing
bespokeLengths :: CName -> CName -> Maybe (Vector ParameterLength)
bespokeLengths = \case
-- Work around https://github.com/KhronosGroup/Vulkan-Docs/issues/1414
"VkDescriptorSetAllocateInfo" -> \case
"pSetLayouts" -> Just (fromList [NamedLength "descriptorSetCount"])
_ -> Nothing
_ -> const Nothing
bespokeZeroInstances
:: ( HasErr r
, HasRenderElem r
, HasSpecInfo r
, HasRenderParams r
, HasSiblingInfo StructMember r
, HasStmts r
)
=> HasRenderElem r => CName -> Maybe (Sem r ())
bespokeZeroInstances = flip
lookup
[ ( "VkTransformMatrixKHR"
, do
tellImportWithAll (TyConName "Zero")
tellDoc [qqi|
-- | The Identity Matrix
instance Zero TransformMatrixKHR where
zero = TransformMatrixKHR
(1,0,0,0)
(0,1,0,0)
(0,0,1,0)
|]
)
]
bespokeZeroCStruct
:: ( HasErr r
, HasRenderElem r
, HasSpecInfo r
, HasRenderParams r
, HasSiblingInfo StructMember r
, HasStmts r
)
=> HasRenderElem r => CName -> Maybe (Sem r (Doc ()))
bespokeZeroCStruct = flip
lookup
[ ( "VkTransformMatrixKHR"
, do
tellImport ''CFloat
tellImport 'plusPtr
tellImportWith ''Storable 'poke
pure [qqi|
pokeZeroCStruct p f = do
poke (p `plusPtr` 0) (CFloat 1)
poke (p `plusPtr` 20) (CFloat 1)
poke (p `plusPtr` 40) (CFloat 1)
f
|]
)
]
bespokeElements
:: forall t r
. (HasErr r, HasRenderParams r, HasSpecInfo r)
=> Spec t
-> Vector (Sem r RenderElement)
bespokeElements Spec {..} = case specHeaderVersion of
VkVersion v ->
fromList
$ shared
<> [ baseType "VkSampleMask" ''Word32
, baseType "VkFlags" ''Word32
, baseType "VkFlags64" ''Word64
, baseType "VkDeviceSize" ''Word64
, baseType "VkDeviceAddress" ''Word64
]
<> wsiTypes SpecVk
<> [ extensionBaseType "VkRemoteAddressNV" (Ptr NonConst Void)
| v >= 184
]
XrVersion{} ->
fromList
$ shared
<> [ baseType "XrFlags64" ''Word64
, baseType "XrTime" ''Int64
, baseType "XrDuration" ''Int64
]
<> wsiTypes SpecXr
<> [resultMatchers]
where
shared = [namedType, nullHandle, boolConversion] :: [Sem r RenderElement]
boolConversion :: HasRenderParams r => Sem r RenderElement
boolConversion = genRe "Bool conversion" $ do
RenderParams {..} <- input
tellNotReexportable
let true = mkPatternName (CName $ upperPrefix <> "_TRUE")
false = mkPatternName (CName $ upperPrefix <> "_FALSE")
bool32 = mkTyName (CName $ camelPrefix <> "Bool32")
tellExport (ETerm (TermName "boolToBool32"))
tellExport (ETerm (TermName "bool32ToBool"))
tellImport 'bool
tellImportWithAll bool32
tellDoc [qqi|
boolToBool32 :: Bool -> {bool32}
boolToBool32 = bool {false} {true}