-
Notifications
You must be signed in to change notification settings - Fork 42
/
TransTy.hs
1248 lines (1056 loc) · 51.6 KB
/
TransTy.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 DataKinds #-}
{-# LANGUAGE EmptyDataDecls #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE ImplicitParams #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE PatternGuards #-}
{-# LANGUAGE PatternSynonyms #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE ViewPatterns #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE PartialTypeSignatures #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE TemplateHaskell #-}
module Mir.TransTy where
import Control.Monad
import Control.Lens
import qualified Data.BitVector.Sized as BV
import Data.List (findIndices)
import Data.String (fromString)
import Data.Text (Text)
import qualified Data.Vector as V
import GHC.Stack
-- parameterized-utils
import qualified Data.Parameterized.Context as Ctx
import Data.Parameterized.Classes
import Data.Parameterized.NatRepr
import Data.Parameterized.Some
import Data.Parameterized.TraversableFC
-- crucible
import qualified Lang.Crucible.Types as C
import qualified Lang.Crucible.CFG.Expr as E
import qualified Lang.Crucible.CFG.Generator as G
import qualified Lang.Crucible.CFG.Reg as R
import qualified Lang.Crucible.Syntax as S
import qualified Mir.DefId as M
import qualified Mir.Mir as M
import qualified Debug.Trace as Debug
import Mir.Generator
( MirExp(..), MirPlace(..), PtrMetadata(..), MirGenerator, mirFail
, subanyRef, subfieldRef, subvariantRef, subjustRef
, mirVector_fromVector
, cs, collection, discrMap, findAdt, mirVector_uninit, arrayZeroed )
import Mir.Intrinsics
( MIR, pattern MirSliceRepr, pattern MirReferenceRepr, MirReferenceType
, pattern MirVectorRepr
, SizeBits, pattern UsizeRepr, pattern IsizeRepr
, isizeLit
, RustEnumType, pattern RustEnumRepr, SomeRustEnumRepr(..)
, mkRustEnum, rustEnumVariant, rustEnumDiscriminant
, pattern MethodSpecRepr, pattern MethodSpecBuilderRepr
, DynRefType, usizeLit , pattern BaseUsizeRepr )
-----------------------------------------------------------------------
-- ** Type translation: MIR types to Crucible types
-- Type translation and type-level list utilities.
-- References have the exact same semantics as their referent type.
-- Arrays and slices are both crucible vectors; no difference between them.
-- Tuples are crucible structs.
-- Non-custom ADTs are encoded as Any. The underlying type is either a Struct
-- or a Variant of Structs, depending on whether the Rust type is a struct or
-- enum.
--
-- Custom type translation is on the bottom of this file.
type TransTyConstraint = (HasCallStack) -- (HasCallStack, ?col::M.Collection)
-- | convert a baseSize to a nat repr
-- Precondition: The BaseSize must *not* be USize.
baseSizeToNatCont :: HasCallStack => M.BaseSize -> (forall w. (1 <= w) => C.NatRepr w -> a) -> a
baseSizeToNatCont M.B8 k = k (knownNat :: NatRepr 8)
baseSizeToNatCont M.B16 k = k (knownNat :: NatRepr 16)
baseSizeToNatCont M.B32 k = k (knownNat :: NatRepr 32)
baseSizeToNatCont M.B64 k = k (knownNat :: NatRepr 64)
baseSizeToNatCont M.B128 k = k (knownNat :: NatRepr 128)
baseSizeToNatCont M.USize k = k (knownNat :: NatRepr SizeBits)
-- Custom type aliases
pattern CTyInt512 <- M.TyAdt _ $(M.explodedDefIdPat ["int512", "Int512"]) (M.Substs [])
pattern CTyBox t <- M.TyAdt _ $(M.explodedDefIdPat ["alloc", "boxed", "Box"]) (M.Substs [t])
pattern CTyMaybeUninit t <- M.TyAdt _ $(M.explodedDefIdPat ["core", "mem", "maybe_uninit", "MaybeUninit"]) (M.Substs [t])
maybeUninitExplodedDefId :: M.ExplodedDefId
maybeUninitExplodedDefId = ["core", "mem", "maybe_uninit", "MaybeUninit"]
-- `UnsafeCell` isn't handled specially inside baseline `crucible-mir`, but
-- `crux-mir-comp` looks for it (using this pattern synonym).
pattern CTyUnsafeCell t <- M.TyAdt _ $(M.explodedDefIdPat ["core", "cell", "UnsafeCell"]) (M.Substs [t])
pattern CTyVector t <- M.TyAdt _ $(M.explodedDefIdPat ["crucible", "vector", "Vector"]) (M.Substs [t])
vectorExplodedDefId :: M.ExplodedDefId
vectorExplodedDefId = ["crucible", "vector", "Vector"]
pattern CTyArray t <- M.TyAdt _ $(M.explodedDefIdPat ["crucible", "array", "Array"]) (M.Substs [t])
pattern CTyBvSize128 <- M.TyAdt _ $(M.explodedDefIdPat ["crucible", "bitvector", "_128"]) (M.Substs [])
pattern CTyBvSize256 <- M.TyAdt _ $(M.explodedDefIdPat ["crucible", "bitvector", "_256"]) (M.Substs [])
pattern CTyBvSize512 <- M.TyAdt _ $(M.explodedDefIdPat ["crucible", "bitvector", "_512"]) (M.Substs [])
pattern CTyBv t <- M.TyAdt _ $(M.explodedDefIdPat ["crucible", "bitvector", "Bv"]) (M.Substs [t])
pattern CTyBv128 <- CTyBv CTyBvSize128
pattern CTyBv256 <- CTyBv CTyBvSize256
pattern CTyBv512 <- CTyBv CTyBvSize512
bvExplodedDefId :: M.ExplodedDefId
bvExplodedDefId = ["crucible", "bitvector", "Bv"]
pattern CTyAny <- M.TyAdt _ $(M.explodedDefIdPat ["core", "crucible", "any", "Any"]) (M.Substs [])
pattern CTyMethodSpec <- M.TyAdt _ $(M.explodedDefIdPat ["crucible", "method_spec", "raw", "MethodSpec"]) (M.Substs [])
pattern CTyMethodSpecBuilder <- M.TyAdt _ $(M.explodedDefIdPat ["crucible", "method_spec", "raw", "MethodSpecBuilder"]) (M.Substs [])
-- These don't have custom representation, but are referenced in various
-- places.
pattern CTyOption t <- M.TyAdt _ $(M.explodedDefIdPat ["core", "option", "Option"]) (M.Substs [t])
optionExplodedDefId :: M.ExplodedDefId
optionExplodedDefId = ["core", "option", "Option"]
optionDiscrNone :: Int
optionDiscrNone = 0
optionDiscrSome :: Int
optionDiscrSome = 1
tyToRepr :: TransTyConstraint => M.Collection -> M.Ty -> Some C.TypeRepr
tyToRepr col t0 = case t0 of
CTyInt512 -> Some $ C.BVRepr (knownNat :: NatRepr 512)
CTyBv128 -> Some $ C.BVRepr (knownNat :: NatRepr 128)
CTyBv256 -> Some $ C.BVRepr (knownNat :: NatRepr 256)
CTyBv512 -> Some $ C.BVRepr (knownNat :: NatRepr 512)
CTyVector t -> tyToReprCont col t $ \repr -> Some (C.VectorRepr repr)
CTyArray t
| Some tpr <- tyToRepr col t
, C.AsBaseType btr <- C.asBaseType tpr ->
Some (C.SymbolicArrayRepr (Ctx.Empty Ctx.:> C.BaseBVRepr (knownNat @SizeBits)) btr)
| otherwise -> error $ "unsupported: crucible arrays of non-base type"
CTyAny -> Some C.AnyRepr
CTyMethodSpec -> Some MethodSpecRepr
CTyMethodSpecBuilder -> Some MethodSpecBuilderRepr
-- CMaybeUninit is handled by the normal repr(transparent) TyAdt case.
M.TyBool -> Some C.BoolRepr
M.TyTuple [] -> Some C.UnitRepr
-- non-empty tuples are mapped to structures of "maybe" types so
-- that they can be allocated without being initialized
M.TyTuple ts -> tyListToCtxMaybe col ts $ \repr -> Some (C.StructRepr repr)
-- Closures are just tuples with a fancy name
M.TyClosure ts -> tyListToCtxMaybe col ts $ \repr -> Some (C.StructRepr repr)
M.TyArray t _sz -> tyToReprCont col t $ \repr -> Some (MirVectorRepr repr)
M.TyInt M.USize -> Some IsizeRepr
M.TyUint M.USize -> Some UsizeRepr
M.TyInt base -> baseSizeToNatCont base $ \n -> Some $ C.BVRepr n
M.TyUint base -> baseSizeToNatCont base $ \n -> Some $ C.BVRepr n
-- These definitions are *not* compositional
M.TyRef (M.TySlice t) _ -> tyToReprCont col t $ \repr -> Some (MirSliceRepr repr)
M.TyRef M.TyStr _ -> Some (MirSliceRepr (C.BVRepr (knownNat @8)))
-- Both `&dyn Tr` and `&mut dyn Tr` use the same representation: a pair of a
-- data value (which is either `&Ty` or `&mut Ty`) and a vtable. Both are
-- type-erased (`AnyRepr`), the first because it has to be, and the second
-- because we'd need to thread the `Collection` into this function (which we
-- don't want to do) in order to construct the precise vtable type.
M.TyRef (M.TyDynamic _) _ -> Some $ C.StructRepr $
Ctx.empty Ctx.:> C.AnyRepr Ctx.:> C.AnyRepr
-- TODO: DSTs not behind a reference - these should never appear in real code
M.TySlice t -> tyToReprCont col t $ \repr -> Some (MirSliceRepr repr)
M.TyStr -> Some (MirSliceRepr (C.BVRepr (knownNat :: NatRepr 8)))
M.TyRef t _ -> tyToReprCont col t $ \repr -> Some (MirReferenceRepr repr)
-- Raw pointers are represented like references, including the fat pointer
-- cases that are special-cased above.
M.TyRawPtr t mutbl -> tyToRepr col (M.TyRef t mutbl)
M.TyChar -> Some $ C.BVRepr (knownNat :: NatRepr 32) -- rust chars are four bytes
-- An ADT is a `concreteAdtRepr` wrapped in `ANY`
M.TyAdt name _ _
| Just adt <- col ^? M.adts . ix name,
Just ty <- reprTransparentFieldTy col adt ->
tyToRepr col ty
| otherwise -> Some C.AnyRepr
M.TyDowncast _adt _i -> Some C.AnyRepr
M.TyFloat _ -> Some C.RealValRepr
-- non polymorphic function types go to FunctionHandleRepr
M.TyFnPtr sig@(M.FnSig args ret _abi _spread) ->
tyListToCtx col args $ \argsr ->
tyToReprCont col ret $ \retr ->
Some (C.FunctionHandleRepr argsr retr)
-- We don't support unsized rvalues. Currently we error only for standalone
-- standalone (i.e., not under `TyRef`/`TyRawPtr`) use of `TyDynamic` - we
-- should do the same for TySlice and TyStr as well.
M.TyDynamic _trait -> error $ unwords ["standalone use of `dyn` is not supported:", show t0]
M.TyFnDef _def -> Some C.UnitRepr
M.TyNever -> Some C.AnyRepr
M.TyLifetime -> Some C.AnyRepr
M.TyForeign -> Some C.AnyRepr
M.TyErased -> Some C.AnyRepr
_ -> error $ unwords ["unknown type?", show t0]
pattern DynRefCtx :: () => (ctx ~ (Ctx.EmptyCtx Ctx.::> C.AnyType Ctx.::> C.AnyType)) => Ctx.Assignment C.TypeRepr ctx
pattern DynRefCtx = Ctx.Empty Ctx.:> C.AnyRepr Ctx.:> C.AnyRepr
pattern DynRefRepr :: () => (tp ~ DynRefType) => C.TypeRepr tp
pattern DynRefRepr = C.StructRepr DynRefCtx
tyToReprM :: M.Ty -> MirGenerator h s ret (Some C.TypeRepr)
tyToReprM ty = do
col <- use $ cs . collection
return $ tyToRepr col ty
-- Checks whether a type can be default-initialized. Any time this returns
-- `True`, `Trans.initialValue` must also return `Just`. Non-initializable ADT
-- fields are wrapped in `Maybe` to support field-by-field initialization.
canInitialize :: M.Collection -> M.Ty -> Bool
canInitialize col ty = case ty of
-- Custom types
CTyAny -> False
CTyMethodSpec -> False
CTyMethodSpecBuilder -> False
-- Primitives
M.TyBool -> True
M.TyChar -> True
M.TyInt _ -> True
M.TyUint _ -> True
-- ADTs and related data structures
M.TyTuple _ -> True
M.TyAdt _ _ _
| Just ty' <- tyAdtDef col ty >>= reprTransparentFieldTy col -> canInitialize col ty'
| otherwise -> True
M.TyClosure _ -> True
-- Others
M.TyArray _ _ -> True
-- TODO: workaround for a ref init bug - see initialValue for details
--M.TyRef ty' _ -> canInitialize col ty'
_ -> False
isUnsized :: M.Ty -> Bool
isUnsized ty = case ty of
M.TyStr -> True
M.TySlice _ -> True
M.TyDynamic _ -> True
-- TODO: struct types whose last field is unsized ("custom DSTs")
_ -> False
isZeroSized :: M.Collection -> M.Ty -> Bool
isZeroSized col ty = go ty
where
go ty = case ty of
M.TyTuple tys -> all go tys
M.TyClosure tys -> all go tys
M.TyArray ty n -> n == 0 || go ty
M.TyAdt name _ _ | Just adt <- col ^? M.adts . ix name -> adt ^. M.adtSize == 0
M.TyNever -> True
_ -> False
-- | Look up the `Adt` definition, if this `Ty` is `TyAdt`.
tyAdtDef :: M.Collection -> M.Ty -> Maybe M.Adt
tyAdtDef col (M.TyAdt name _ _) = col ^? M.adts . ix name
tyAdtDef _ _ = Nothing
-- | If the `Adt` is a `repr(transparent)` struct with at most one
-- non-zero-sized field, return the index of that field.
findReprTransparentField :: M.Collection -> M.Adt -> Maybe Int
findReprTransparentField col adt = do
guard $ adt ^. M.adtReprTransparent
[v] <- return $ adt ^. M.adtvariants
-- We want to always return a valid field index, which we can't do if there
-- are no fields.
guard $ not $ null $ v ^. M.vfields
let idxs = findIndices (\f -> not $ isZeroSized col $ f ^. M.fty) (v ^. M.vfields)
guard $ length idxs <= 1
return $ maybe 0 id (idxs ^? ix 0)
reprTransparentFieldTy :: M.Collection -> M.Adt -> Maybe M.Ty
reprTransparentFieldTy col adt = do
idx <- findReprTransparentField col adt
adt ^? M.adtvariants . ix 0 . M.vfields . ix idx . M.fty
variantFields :: TransTyConstraint => M.Collection -> M.Variant -> Some C.CtxRepr
variantFields col (M.Variant _vn _vd vfs _vct _mbVal _inh) =
tyReprListToCtx
(map (mapSome fieldType . tyToFieldRepr col . (^. M.fty)) vfs)
(\repr -> Some repr)
variantFieldsM :: TransTyConstraint => M.Variant -> MirGenerator h s ret (Some C.CtxRepr)
variantFieldsM v = do
col <- use $ cs . collection
return $ variantFields col v
data FieldRepr tp' = forall tp. FieldRepr (FieldKind tp tp')
instance Show (FieldRepr tp') where
showsPrec d (FieldRepr kind) = showParen (d > 10) $
showString "FieldRepr " . showsPrec 11 kind
instance ShowF FieldRepr
fieldType :: FieldRepr tp -> C.TypeRepr tp
fieldType (FieldRepr (FkInit tpr)) = tpr
fieldType (FieldRepr (FkMaybe tpr)) = C.MaybeRepr tpr
-- `FieldCtxRepr ctx` is like `C.CtxRepr ctx`, but also records whether each
-- field is wrapped or not.
type FieldCtxRepr = Ctx.Assignment FieldRepr
fieldCtxType :: FieldCtxRepr ctx -> C.CtxRepr ctx
fieldCtxType Ctx.Empty = Ctx.Empty
fieldCtxType (ctx Ctx.:> fr) = fieldCtxType ctx Ctx.:> fieldType fr
tyToFieldRepr :: M.Collection -> M.Ty -> Some FieldRepr
tyToFieldRepr col ty
| canInitialize col ty = viewSome (\tpr -> Some $ FieldRepr $ FkInit tpr) (tyToRepr col ty)
| otherwise = viewSome (\tpr -> Some $ FieldRepr $ FkMaybe tpr) (tyToRepr col ty)
variantFields' :: TransTyConstraint => M.Collection -> M.Variant -> Some FieldCtxRepr
variantFields' col (M.Variant _vn _vd vfs _vct _mbVal _inh) =
fieldReprListToCtx
(map (tyToFieldRepr col . (^. M.fty)) vfs)
(\x -> Some x)
variantFieldsM' :: TransTyConstraint => M.Variant -> MirGenerator h s ret (Some FieldCtxRepr)
variantFieldsM' v = do
col <- use $ cs . collection
return $ variantFields' col v
enumVariants :: TransTyConstraint => M.Collection -> M.Adt -> SomeRustEnumRepr
enumVariants col (M.Adt name kind vs _ _ _ _) =
case kind of
M.Enum discrTy
| Some discrTpr <- tyToRepr col discrTy
-> reprsToCtx variantReprs $ \variantsCxt ->
SomeRustEnumRepr discrTpr variantsCxt
_ -> error $ "expected " ++ show name ++ " to have kind Enum"
where
variantReprs :: [Some C.TypeRepr]
variantReprs = map (\v ->
viewSome (\ctx -> Some $ C.StructRepr ctx) $
variantFields col v) vs
enumVariantsM :: TransTyConstraint => M.Adt -> MirGenerator h s ret SomeRustEnumRepr
enumVariantsM adt = do
col <- use $ cs . collection
return $ enumVariants col adt
-- As in the CPS translation, functions which manipulate types must be
-- in CPS form, since type tags are generally hidden underneath an
-- existential.
tyToReprCont :: forall a. TransTyConstraint =>
M.Collection -> M.Ty -> (forall tp. HasCallStack => C.TypeRepr tp -> a) -> a
tyToReprCont col t f = case tyToRepr col t of
Some x -> f x
tyReprListToCtx :: forall a. TransTyConstraint => [Some C.TypeRepr] -> (forall ctx. C.CtxRepr ctx -> a) -> a
tyReprListToCtx ts f = go ts Ctx.empty
where go :: forall ctx. [Some C.TypeRepr] -> C.CtxRepr ctx -> a
go [] ctx = f ctx
go (Some tp:tps) ctx = go tps (ctx Ctx.:> tp)
fieldReprListToCtx :: forall a. TransTyConstraint => [Some FieldRepr] -> (forall ctx. FieldCtxRepr ctx -> a) -> a
fieldReprListToCtx frs f = go frs Ctx.empty
where go :: forall ctx. [Some FieldRepr] -> FieldCtxRepr ctx -> a
go [] ctx = f ctx
go (Some fr:frs) ctx = go frs (ctx Ctx.:> fr)
tyListToCtx :: forall a. TransTyConstraint =>
M.Collection -> [M.Ty] -> (forall ctx. C.CtxRepr ctx -> a) -> a
tyListToCtx col ts f = tyReprListToCtx (map (tyToRepr col) ts) f
reprsToCtx :: forall a. [Some C.TypeRepr] -> (forall ctx. C.CtxRepr ctx -> a) -> a
reprsToCtx rs f = go rs Ctx.empty
where go :: forall ctx. [Some C.TypeRepr] -> C.CtxRepr ctx -> a
go [] ctx = f ctx
go (Some tp:tps) ctx = go tps (ctx Ctx.:> tp)
-- same as tyListToCtx, but each type in the list is wrapped in a Maybe
tyListToCtxMaybe :: forall a. TransTyConstraint =>
M.Collection -> [M.Ty] -> (forall ctx. C.CtxRepr ctx -> a) -> a
tyListToCtxMaybe col ts f = go (map (tyToRepr col) ts) Ctx.empty
where go :: forall ctx. [Some C.TypeRepr] -> C.CtxRepr ctx -> a
go [] ctx = f ctx
go (Some tp:tps) ctx = go tps (ctx Ctx.:> C.MaybeRepr tp)
-----------------------------------------------------------------------
-- ** Basic operations
exp_to_assgn :: HasCallStack => [MirExp s] -> (forall ctx. C.CtxRepr ctx -> Ctx.Assignment (R.Expr MIR s) ctx -> a) -> a
exp_to_assgn =
go Ctx.empty Ctx.empty
where go :: C.CtxRepr ctx -> Ctx.Assignment (R.Expr MIR s) ctx -> [MirExp s] -> (forall ctx'. C.CtxRepr ctx' -> Ctx.Assignment (R.Expr MIR s) ctx' -> a) -> a
go ctx asgn [] k = k ctx asgn
go ctx asgn ((MirExp tyr ex):vs) k = go (ctx Ctx.:> tyr) (asgn Ctx.:> ex) vs k
exp_to_assgn_Maybe :: HasCallStack => M.Collection -> [M.Ty] -> [Maybe (MirExp s)]
-> (forall ctx. C.CtxRepr ctx -> Ctx.Assignment (R.Expr MIR s) ctx -> a) -> a
exp_to_assgn_Maybe col =
go Ctx.empty Ctx.empty
where go :: C.CtxRepr ctx -> Ctx.Assignment (R.Expr MIR s) ctx -> [M.Ty] -> [Maybe (MirExp s)]
-> (forall ctx'. C.CtxRepr ctx' -> Ctx.Assignment (R.Expr MIR s) ctx' -> a) -> a
go ctx asgn [] [] k = k ctx asgn
go ctx asgn (_:tys) (Just (MirExp tyr ex):vs) k =
go (ctx Ctx.:> C.MaybeRepr tyr) (asgn Ctx.:> (R.App $ E.JustValue tyr ex)) tys vs k
go ctx asgn (ty:tys) (Nothing:vs) k =
tyToReprCont col ty $ \tyr ->
go (ctx Ctx.:> C.MaybeRepr tyr) (asgn Ctx.:> (R.App $ E.NothingValue tyr)) tys vs k
go _ _ _ _ _ = error "BUG in crux-mir: exp_to_assgn_Maybe"
packAny :: MirExp s -> (MirExp s)
packAny (MirExp e_ty e) = MirExp C.AnyRepr (S.app $ E.PackAny e_ty e)
unpackAnyE :: HasCallStack => C.TypeRepr t -> MirExp s -> MirExp s
unpackAnyE tpr e = MirExp tpr $ unpackAnyC tpr e
unpackAnyC :: HasCallStack => C.TypeRepr tp -> MirExp s -> R.Expr MIR s tp
unpackAnyC tpr (MirExp C.AnyRepr e) =
R.App $ E.FromJustValue tpr
(R.App $ E.UnpackAny tpr e)
(R.App $ E.StringLit $ fromString $ "bad unpack: Any as " ++ show tpr)
unpackAnyC _ (MirExp tpr' _) = error $ "bad anytype unpack of " ++ show tpr'
-- array in haskell -> crucible array
buildArrayLit :: forall h s tp ret. C.TypeRepr tp -> [MirExp s] -> MirGenerator h s ret (MirExp s)
buildArrayLit trep exps = do
vec <- go exps V.empty
exp <- mirVector_fromVector trep $ S.app $ E.VectorLit trep vec
return $ MirExp (MirVectorRepr trep) exp
where go :: [MirExp s] -> V.Vector (R.Expr MIR s tp) -> MirGenerator h s ret (V.Vector (R.Expr MIR s tp))
go [] v = return v
go ((MirExp erepr e):es) v = do
case (testEquality erepr trep) of
Just Refl -> do
v' <- go es v
return $ V.cons e v'
Nothing -> mirFail "bad type in build array"
buildTuple :: [MirExp s] -> MirExp s
buildTuple xs = exp_to_assgn (xs) $ \ctx asgn ->
MirExp (C.StructRepr ctx) (S.app $ E.MkStruct ctx asgn)
buildTupleMaybe :: M.Collection -> [M.Ty] -> [Maybe (MirExp s)] -> MirExp s
buildTupleMaybe col tys xs = exp_to_assgn_Maybe col tys xs $ \ctx asgn ->
MirExp (C.StructRepr ctx) (S.app $ E.MkStruct ctx asgn)
buildTupleMaybeM :: [M.Ty] -> [Maybe (MirExp s)] -> MirGenerator h s ret (MirExp s)
buildTupleMaybeM tys xs = do
col <- use $ cs . collection
return $ buildTupleMaybe col tys xs
accessAggregateMaybe :: HasCallStack => MirExp s -> Int -> MirGenerator h s ret (MirExp s)
accessAggregateMaybe (MirExp (C.StructRepr ctx) ag) i
| Just (Some idx) <- Ctx.intIndex (fromIntegral i) (Ctx.size ctx) = do
let tpr = ctx Ctx.! idx
case tpr of
C.MaybeRepr tpr' ->
let mv = R.App $ E.FromJustValue tpr' (S.getStruct idx ag)
(R.App $ E.StringLit "Unitialized aggregate value")
in return $ MirExp tpr' mv
_ -> mirFail "accessAggregateMaybe: non-maybe struct"
accessAggregateMaybe (MirExp ty a) b = mirFail $ "invalid access of " ++ show ty ++ " at field (maybe) " ++ (show b)
modifyAggregateIdxMaybe :: MirExp s -> -- aggregate to modify
MirExp s -> -- thing to insert
Int -> -- index
MirGenerator h s ret (MirExp s)
modifyAggregateIdxMaybe (MirExp (C.StructRepr agctx) ag) (MirExp instr ins) i
| Just (Some idx) <- Ctx.intIndex (fromIntegral i) (Ctx.size agctx) = do
let tpr = agctx Ctx.! idx
case tpr of
C.MaybeRepr tpr' ->
case (testEquality tpr' instr) of
Just Refl -> do
let ins' = R.App (E.JustValue tpr' ins)
return $ MirExp (C.StructRepr agctx) (S.setStruct agctx ag idx ins')
_ -> mirFail "bad modify"
_ -> mirFail "modifyAggregateIdxMaybe: expecting maybe type for struct component"
| otherwise = mirFail ("modifyAggregateIdxMaybe: Index " ++ show i ++ " out of range for struct")
modifyAggregateIdxMaybe (MirExp ty _) _ _ =
do mirFail ("modifyAggregateIdxMaybe: Expected Crucible structure type, but got:" ++ show ty)
-- TODO: most of the `testEqualityOrFail` in here should be replaced with an
-- `error`ing version
readAnyE :: C.TypeRepr tp -> MirExp s -> MirGenerator h s ret (R.Expr MIR s tp)
readAnyE tpr (MirExp tpr' e) = do
Refl <- testEqualityOrFail tpr' C.AnyRepr $
"readAnyE: expected Any, but got " ++ show tpr'
let valOpt = R.App $ E.UnpackAny tpr e
val <- G.fromJustExpr valOpt $ R.App $ E.StringLit $ fromString $
"readAnyE: bad unpack at type " ++ show tpr ++ ": " ++ show e
return val
buildAnyE :: C.TypeRepr tp -> R.Expr MIR s tp -> MirGenerator h s ret (MirExp s)
buildAnyE tpr e = return $ MirExp C.AnyRepr $ R.App $ E.PackAny tpr e
adjustAnyE :: C.TypeRepr tp ->
(R.Expr MIR s tp -> MirGenerator h s ret (R.Expr MIR s tp)) ->
MirExp s -> MirGenerator h s ret (MirExp s)
adjustAnyE tpr f me = do
x <- readAnyE tpr me
y <- f x
buildAnyE tpr y
readEnumVariant :: C.TypeRepr discrTp -> C.CtxRepr variantsCtx -> Ctx.Index variantsCtx tp ->
R.Expr MIR s (RustEnumType discrTp variantsCtx) -> MirGenerator h s ret (R.Expr MIR s tp)
readEnumVariant tp ctx idx e = do
let tpr = ctx Ctx.! idx
let optVal = R.App $ E.ProjectVariant ctx idx $ R.App $ rustEnumVariant ctx e
readJust' tpr optVal $
"readEnumVariant: wrong variant; expected " ++ show idx
buildEnumVariant :: C.TypeRepr discrTp -> C.CtxRepr variantsCtx -> Ctx.Index variantsCtx tp ->
R.Expr MIR s tp -> MirGenerator h s ret (R.Expr MIR s (RustEnumType discrTp variantsCtx))
buildEnumVariant tp ctx idx e = do
discr <- enumDiscrLit tp $ fromIntegral $ Ctx.indexVal idx
let var = R.App $ E.InjectVariant ctx idx e
return $ R.App $ mkRustEnum tp ctx (R.App discr) var
adjustEnumVariant :: C.TypeRepr discrTp -> C.CtxRepr variantsCtx -> Ctx.Index variantsCtx tp ->
(R.Expr MIR s tp -> MirGenerator h s ret (R.Expr MIR s tp)) ->
R.Expr MIR s (RustEnumType discrTp variantsCtx) -> MirGenerator h s ret (R.Expr MIR s (RustEnumType discrTp variantsCtx))
adjustEnumVariant tp ctx idx f e = do
x <- readEnumVariant tp ctx idx e
y <- f x
buildEnumVariant tp ctx idx y
readStructField :: C.CtxRepr ctx -> Ctx.Index ctx tp ->
R.Expr MIR s (C.StructType ctx) -> MirGenerator h s ret (R.Expr MIR s tp)
readStructField ctx idx e = do
let tpr = ctx Ctx.! idx
return $ R.App $ E.GetStruct e idx tpr
writeStructField :: C.CtxRepr ctx -> Ctx.Index ctx tp ->
R.Expr MIR s (C.StructType ctx) -> R.Expr MIR s tp ->
MirGenerator h s ret (R.Expr MIR s (C.StructType ctx))
writeStructField ctx idx e e' = do
let tpr = ctx Ctx.! idx
return $ R.App $ E.SetStruct ctx e idx e'
adjustStructField :: C.CtxRepr ctx -> Ctx.Index ctx tp ->
(R.Expr MIR s tp -> MirGenerator h s ret (R.Expr MIR s tp)) ->
R.Expr MIR s (C.StructType ctx) -> MirGenerator h s ret (R.Expr MIR s (C.StructType ctx))
adjustStructField ctx idx f e = do
x <- readStructField ctx idx e
y <- f x
writeStructField ctx idx e y
readJust' :: C.TypeRepr tp -> R.Expr MIR s (C.MaybeType tp) -> String ->
MirGenerator h s ret (R.Expr MIR s tp)
readJust' tpr e msg =
G.fromJustExpr e $ R.App $ E.StringLit $ fromString msg
buildNothing :: C.TypeRepr tp ->
MirGenerator h s ret (R.Expr MIR s (C.MaybeType tp))
buildNothing tpr = return $ R.App $ E.NothingValue tpr
buildJust :: C.TypeRepr tp -> R.Expr MIR s tp ->
MirGenerator h s ret (R.Expr MIR s (C.MaybeType tp))
buildJust tpr e = return $ R.App $ E.JustValue tpr e
adjustJust' :: C.TypeRepr tp -> String ->
(R.Expr MIR s tp -> MirGenerator h s ret (R.Expr MIR s tp)) ->
R.Expr MIR s (C.MaybeType tp) -> MirGenerator h s ret (R.Expr MIR s (C.MaybeType tp))
adjustJust' tpr msg f e = do
x <- readJust' tpr e msg
y <- f x
buildJust tpr y
-- `tp` is the type of the inner data. `tp'` is the type of the struct field,
-- which may involve a wrapper.
data FieldKind (tp :: C.CrucibleType) (tp' :: C.CrucibleType) where
FkInit :: forall tp. C.TypeRepr tp -> FieldKind tp tp
FkMaybe :: forall tp. C.TypeRepr tp -> FieldKind tp (C.MaybeType tp)
instance Show (FieldKind tp tp') where
showsPrec d (FkInit tpr) = showParen (d > 10) $
showString "FkInit " . showsPrec 11 tpr
showsPrec d (FkMaybe tpr) = showParen (d > 10) $
showString "FkMaybe " . showsPrec 11 tpr
fieldDataType :: FieldKind tp tp' -> C.TypeRepr tp
fieldDataType (FkInit tpr) = tpr
fieldDataType (FkMaybe tpr) = tpr
readFieldData' :: FieldKind tp tp' -> String ->
R.Expr MIR s tp' -> MirGenerator h s ret (R.Expr MIR s tp)
readFieldData' (FkInit tpr) msg e = return e
readFieldData' (FkMaybe tpr) msg e = readJust' tpr e msg
buildFieldData :: FieldKind tp tp' ->
R.Expr MIR s tp -> MirGenerator h s ret (R.Expr MIR s tp')
buildFieldData (FkInit tpr) e = return e
buildFieldData (FkMaybe tpr) e = buildJust tpr e
-- Adjust the data inside a field. If `wrapped`, then `tp' ~ MaybeType tp`,
-- and we expect the value to be `Just`. Otherwise, `tp' ~ tp`, and we modify
-- the value directly.
adjustFieldData :: FieldKind tp tp' ->
(R.Expr MIR s tp -> MirGenerator h s ret (R.Expr MIR s tp)) ->
R.Expr MIR s tp' -> MirGenerator h s ret (R.Expr MIR s tp')
adjustFieldData (FkInit tpr) f e = f e
adjustFieldData (FkMaybe tpr) f e =
adjustJust' tpr "adjustFieldData: expected Just, but got Nothing" f e
data StructInfo = forall ctx tp tp'. StructInfo
(C.CtxRepr ctx)
(Ctx.Index ctx tp')
(FieldKind tp tp')
-- First argument is `True` if a wrapper is expected.
checkFieldKind :: Bool -> C.TypeRepr tp -> C.TypeRepr tp' -> String ->
MirGenerator h s ret (FieldKind tp tp')
checkFieldKind False tpr tpr' desc = do
Refl <- testEqualityOrFail tpr tpr' $
"checkFieldKind: type mismatch: " ++ show tpr ++ " /= " ++ show tpr' ++
"(at " ++ desc ++ ")"
return $ FkInit tpr
checkFieldKind True tpr tpr' desc = do
Refl <- testEqualityOrFail (C.MaybeRepr tpr) tpr' $
"checkFieldKind: type mismatch: " ++ show (C.MaybeRepr tpr) ++ " /= " ++ show tpr' ++
"(at " ++ desc ++ ")"
return $ FkMaybe tpr
structInfo :: M.Adt -> Int -> MirGenerator h s ret StructInfo
structInfo adt i = do
when (adt ^. M.adtkind /= M.Struct) $ mirFail $
"expected struct, but got adt " ++ show (adt ^. M.adtname)
let var = M.onlyVariant adt
fldTy <- case var ^? M.vfields . ix i of
Just fld -> return $ fld ^. M.fty
Nothing -> mirFail errFieldIndex
Some ctx <- variantFieldsM var
Some idx <- case Ctx.intIndex (fromIntegral i) (Ctx.size ctx) of
Just x -> return x
Nothing -> mirFail errFieldIndex
let tpr' = ctx Ctx.! idx
Some tpr <- tyToReprM fldTy
col <- use $ cs . collection
kind <- checkFieldKind (not $ canInitialize col fldTy) tpr tpr' $
"field " ++ show i ++ " of struct " ++ show (adt ^. M.adtname)
return $ StructInfo ctx idx kind
where
errFieldIndex = "field index " ++ show i ++ " is out of range for struct " ++
show (adt ^. M.adtname)
getStructField :: M.Adt -> Int -> MirExp s -> MirGenerator h s ret (MirExp s)
getStructField adt i me = do
StructInfo ctx idx fld <- structInfo adt i
e <- readAnyE (C.StructRepr ctx) me
e <- readStructField ctx idx e
e <- readFieldData' fld errFieldUninit e
return $ MirExp (fieldDataType fld) e
where
errFieldUninit = "field " ++ show i ++ " of " ++ show (adt^.M.adtname) ++
" read while uninitialized"
setStructField :: M.Adt -> Int ->
MirExp s -> MirExp s -> MirGenerator h s ret (MirExp s)
setStructField adt i me (MirExp tpr e') = do
StructInfo ctx idx fld <- structInfo adt i
Refl <- testEqualityOrFail tpr (fieldDataType fld) (errFieldType fld)
e' <- buildFieldData fld e'
let f' = adjustAnyE (C.StructRepr ctx) $
\e -> writeStructField ctx idx e e'
f' me
where
errFieldType :: FieldKind tp tp' -> String
errFieldType fld = "expected field value for " ++ show (adt^.M.adtname, i) ++
" to have type " ++ show (fieldDataType fld) ++ ", but got " ++ show tpr
-- Run `f`, checking that its return type is the same as its argument. Fails
-- if `f` returns a different type.
checkSameType :: String ->
(MirExp s -> MirGenerator h s ret (MirExp s)) ->
R.Expr MIR s tp -> MirGenerator h s ret (R.Expr MIR s tp)
checkSameType desc f e = do
let tpr = R.exprType e
MirExp tpr' e' <- f (MirExp tpr e)
Refl <- testEqualityOrFail tpr tpr' $ "checkSameType: bad result type: expected " ++
show tpr ++ ", but got " ++ show tpr' ++ " (in " ++ show desc ++ ")"
return e
mapStructField :: M.Adt -> Int ->
(MirExp s -> MirGenerator h s ret (MirExp s)) ->
MirExp s -> MirGenerator h s ret (MirExp s)
mapStructField adt i f me = do
StructInfo ctx idx fld <- structInfo adt i
let f' = adjustAnyE (C.StructRepr ctx) $
adjustStructField ctx idx $
adjustFieldData fld $
checkSameType ("mapStructField " ++ show i ++ " of " ++ show (adt ^. M.adtname)) $
f
f' me
data EnumInfo = forall discrTp ctx ctx' tp tp'. EnumInfo
(C.TypeRepr discrTp)
(C.CtxRepr ctx)
(Ctx.Index ctx (C.StructType ctx'))
(C.CtxRepr ctx')
(Ctx.Index ctx' tp')
(FieldKind tp tp')
data IsStructType (tp :: C.CrucibleType) where
IsStructType :: forall ctx. C.CtxRepr ctx -> IsStructType (C.StructType ctx)
checkStructType :: C.TypeRepr tp -> Maybe (IsStructType tp)
checkStructType (C.StructRepr ctx) = Just (IsStructType ctx)
checkStructType _ = Nothing
enumInfo :: M.Adt -> Int -> Int -> MirGenerator h s ret EnumInfo
enumInfo adt i j = do
Some discrTp <- case adt ^. M.adtkind of
M.Enum discrTy -> tyToReprM discrTy
_ -> mirFail $ "expected enum, but got adt " ++ show (adt ^. M.adtname)
when (isn't M._Enum (adt ^. M.adtkind)) $ mirFail $
"expected enum, but got adt " ++ show (adt ^. M.adtname)
var <- case adt ^? M.adtvariants . ix i of
Just var -> return var
Nothing -> mirFail $ "variant index " ++ show i ++ " is out of range for enum " ++
show (adt ^. M.adtname)
fldTy <- case var ^? M.vfields . ix j of
Just fld -> return $ fld ^. M.fty
Nothing -> mirFail $ "field index " ++ show j ++ " is out of range for enum " ++
show (adt ^. M.adtname) ++ " variant " ++ show i
SomeRustEnumRepr _ ctx <- enumVariantsM adt
Some idx <- case Ctx.intIndex (fromIntegral i) (Ctx.size ctx) of
Just x -> return x
Nothing -> mirFail $ "variant index " ++ show i ++ " is out of range for enum " ++
show (adt ^. M.adtname)
IsStructType ctx' <- case checkStructType $ ctx Ctx.! idx of
Just x -> return x
Nothing -> mirFail $ "variant " ++ show i ++ " of enum " ++
show (adt ^. M.adtname) ++ " is not a struct?"
Some idx' <- case Ctx.intIndex (fromIntegral j) (Ctx.size ctx') of
Just x -> return x
Nothing -> mirFail $ "field index " ++ show j ++ " is out of range for enum " ++
show (adt ^. M.adtname) ++ " variant " ++ show i
let tpr' = ctx' Ctx.! idx'
Some tpr <- tyToReprM fldTy
col <- use $ cs . collection
kind <- checkFieldKind (not $ canInitialize col fldTy) tpr tpr' $
"field " ++ show j ++ " of enum " ++ show (adt ^. M.adtname) ++ " variant " ++ show i
return $ EnumInfo discrTp ctx idx ctx' idx' kind
getEnumField :: M.Adt -> Int -> Int -> MirExp s -> MirGenerator h s ret (MirExp s)
getEnumField adt i j me = do
EnumInfo discrTp ctx idx ctx' idx' fld <- enumInfo adt i j
e <- readAnyE (RustEnumRepr discrTp ctx) me
e <- readEnumVariant discrTp ctx idx e
e <- readStructField ctx' idx' e
e <- readFieldData' fld errFieldUninit e
return $ MirExp (R.exprType e) e
where
errFieldUninit = "field " ++ show j ++ " of " ++ show (adt^.M.adtname) ++
" variant " ++ show i ++ " read while uninitialized"
setEnumField :: M.Adt -> Int -> Int ->
MirExp s -> MirExp s -> MirGenerator h s ret (MirExp s)
setEnumField adt i j me (MirExp tpr e') = do
EnumInfo discrTp ctx idx ctx' idx' fld <- enumInfo adt i j
Refl <- testEqualityOrFail tpr (fieldDataType fld) (errFieldType fld)
e' <- buildFieldData fld e'
let f' = adjustAnyE (RustEnumRepr discrTp ctx) $
adjustEnumVariant discrTp ctx idx $
\e -> writeStructField ctx' idx' e e'
f' me
where
errFieldType :: FieldKind tp tp' -> String
errFieldType fld = "expected field value for " ++ show (adt^.M.adtname, i, j) ++
" to have type " ++ show (fieldDataType fld) ++ ", but got " ++ show tpr
buildStructAssign' :: HasCallStack => FieldCtxRepr ctx -> [Maybe (Some (R.Expr MIR s))] ->
Either String (Ctx.Assignment (R.Expr MIR s) ctx)
buildStructAssign' ctx es = go ctx $ reverse es
where
go :: forall ctx s. FieldCtxRepr ctx -> [Maybe (Some (R.Expr MIR s))] ->
Either String (Ctx.Assignment (R.Expr MIR s) ctx)
go ctx [] = case Ctx.viewAssign ctx of
Ctx.AssignEmpty -> return Ctx.empty
_ -> Left "not enough expressions"
go ctx (optExp : rest) = case Ctx.viewAssign ctx of
Ctx.AssignExtend ctx' fldr -> case (fldr, optExp) of
(FieldRepr (FkInit tpr), Nothing) ->
case tpr of
C.UnitRepr -> continue ctx' rest tpr (R.App $ E.NothingValue tpr)
_ -> Left $ "got Nothing for mandatory field " ++ show (length rest) ++ " type:" ++ show tpr
(FieldRepr (FkInit tpr), Just (Some e)) ->
continue ctx' rest tpr e
(FieldRepr (FkMaybe tpr), Nothing) ->
continue ctx' rest (C.MaybeRepr tpr) (R.App $ E.NothingValue tpr)
(FieldRepr (FkMaybe tpr), Just (Some e)) ->
continue ctx' rest (C.MaybeRepr tpr)
(R.App $ E.JustValue (R.exprType e) e)
_ -> Left "too many expressions"
continue :: forall ctx tp tp' s. FieldCtxRepr ctx -> [Maybe (Some (R.Expr MIR s))] ->
C.TypeRepr tp -> R.Expr MIR s tp' ->
Either String (Ctx.Assignment (R.Expr MIR s) (ctx Ctx.::> tp))
continue ctx' rest tpr e = case testEquality tpr (R.exprType e) of
Just Refl -> go ctx' rest >>= \flds -> return $ Ctx.extend flds e
Nothing -> Left $ "type mismatch: expected " ++ show tpr ++ " but got " ++
show (R.exprType e) ++ " in field " ++ show (length rest) ++ ": " ++ show (ctx, es)
buildStruct' :: HasCallStack => M.Adt -> [Maybe (MirExp s)] ->
MirGenerator h s ret (MirExp s)
buildStruct' adt es = do
when (adt ^. M.adtkind /= M.Struct) $ mirFail $
"expected struct, but got adt " ++ show (adt ^. M.adtname)
let var = M.onlyVariant adt
Some fctx <- variantFieldsM' var
asn <- case buildStructAssign' fctx $ map (fmap (\(MirExp _ e) -> Some e)) es of
Left err -> mirFail $ "error building struct " ++ show (var^.M.vname) ++ ": " ++ err
Right x -> return x
let ctx = fieldCtxType fctx
buildAnyE (C.StructRepr ctx) $ R.App $ E.MkStruct ctx asn
buildStruct :: HasCallStack => M.Adt -> [MirExp s] ->
MirGenerator h s ret (MirExp s)
buildStruct adt es =
buildStruct' adt (map Just es)
buildEnum' :: HasCallStack => M.Adt -> Int -> [Maybe (MirExp s)] ->
MirGenerator h s ret (MirExp s)
buildEnum' adt i es = do
Some discrTp <- case adt ^. M.adtkind of
M.Enum discrTy -> tyToReprM discrTy
_ -> mirFail $ "expected enum, but got adt " ++ show (adt ^. M.adtname)
var <- case adt ^? M.adtvariants . ix i of
Just var -> return var
Nothing -> mirFail $ "variant index " ++ show i ++ " is out of range for enum " ++
show (adt ^. M.adtname)
SomeRustEnumRepr _ ctx <- enumVariantsM adt
Some idx <- case Ctx.intIndex (fromIntegral i) (Ctx.size ctx) of
Just x -> return x
Nothing -> mirFail $ "variant index " ++ show i ++ " is out of range for enum " ++
show (adt ^. M.adtname)
IsStructType ctx' <- case checkStructType $ ctx Ctx.! idx of
Just x -> return x
Nothing -> mirFail $ "variant " ++ show i ++ " of enum " ++
show (adt ^. M.adtname) ++ " is not a struct?"
Some fctx' <- variantFieldsM' var
let ftys = map (^. M.fty) (var ^. M.vfields)
es' <- inferElidedVariantFields ftys es
asn <- case buildStructAssign' fctx' $ map (fmap (\(MirExp _ e) -> Some e)) es' of
Left err ->
mirFail $ "error building variant " ++ show (var^.M.vname) ++ ": " ++ err ++ " -- " ++ show es'
Right x -> return x
Refl <- testEqualityOrFail (fieldCtxType fctx') ctx' $
"got wrong fields for " ++ show (adt ^. M.adtname, i) ++ "?"
discrs <- use $ cs . discrMap . ix (adt ^. M.adtname)
discr <- case discrs ^? ix i of
Just x -> enumDiscrLit discrTp x
Nothing -> mirFail $ "can't find discr for variant " ++ show (adt ^. M.adtname, i)
buildAnyE (RustEnumRepr discrTp ctx) $
R.App $ mkRustEnum discrTp ctx (R.App discr) $
R.App $ E.InjectVariant ctx idx $
R.App $ E.MkStruct ctx' asn
-- It is possible for an enum to be initialized in MIR without providing
-- explicit assignments for all of its fields. As an example, imagine the value
-- @Ok(())@ of type @Result<(), i32>@. MIR is liable to construct this like so:
--
-- @
-- let mut _0 : Result<(), i32>;
-- discr(_0) = 0
-- @
--
-- Note that there is no statement for explicitly initializing the first field
-- of @Ok@ to @()@. This is by design, as @()@ is a zero-sized type (ZST). While
-- ZSTs need not appear explicitly in MIR, we would like to have explicit
-- representations for them in Crucible. This function is responsible for
-- constructing these explicit representations.
--
-- The approach that this function takes is pretty simple: if we encounter a
-- variant with the same number of types as field values, then return the values
-- unchanged. If there are fewer values than types, then we assume that any ZSTs
-- have elided the fields of the corresponding types, so we insert these values
-- into the list ourselves. We use 'initialValue' to construct a reasonable
-- value of each ZST.
--
-- Note that we are doing this step somewhat late in the pipeline. An
-- alternative approach would be to infer these missing values in
-- "Mir.Pass.AllocateEnum", when the enum variant initialization is first
-- handled. This would require some additional refactoring, so we have not yet
-- pursued this option.
inferElidedVariantFields :: [M.Ty] -> [Maybe (MirExp s)]
-> MirGenerator h s ret [Maybe (MirExp s)]
inferElidedVariantFields ftys fes
| length ftys == length fes
= pure fes
| otherwise
= go ftys fes
where
go [] [] = pure []
go [] (_:_) = mirFail $ unlines [ "inferElidedVariantFields: too many expressions"
, "types: " ++ show ftys
, "expressions: " ++ show fes
]
go (ty:tys) exps = do
col <- use $ cs . collection
if isZeroSized col ty
then do val <- initialValue ty
exps' <- go tys exps
pure $ val : exps'
else
case exps of
e:es -> do
es' <- go tys es
pure $ e : es'
[] -> mirFail "inferElidedVariantFields: not enough expressions"
buildEnum :: HasCallStack => M.Adt -> Int -> [MirExp s] ->
MirGenerator h s ret (MirExp s)
buildEnum adt i es =
buildEnum' adt i (map Just es)
enumDiscrLit :: C.TypeRepr tp -> Integer
-> MirGenerator h s ret (E.App ext f tp)
enumDiscrLit tp discr =
case tp of
C.BVRepr w -> pure $ E.BVLit w $ BV.mkBV w discr
_ -> mirFail $ "Unknown enum discriminant type: " ++ show tp
fieldDataRef ::
FieldKind tp tp' ->
R.Expr MIR s (MirReferenceType tp') ->
MirGenerator h s ret (R.Expr MIR s (MirReferenceType tp))