summaryrefslogtreecommitdiff
path: root/Yices/Painless/Language.hs
blob: a607f60d96a50e385db9782d0511e334210a52e6 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
{-# LANGUAGE GADTs                  #-}
{-# LANGUAGE ScopedTypeVariables    #-}
{-# LANGUAGE PatternGuards          #-}
{-# LANGUAGE FlexibleInstances      #-}
{-# LANGUAGE OverlappingInstances   #-}
{-# LANGUAGE UndecidableInstances   #-}
{-# LANGUAGE MultiParamTypeClasses  #-}
{-# LANGUAGE FunctionalDependencies #-}

{-# OPTIONS_GHC -fno-warn-orphans #-}

-- |
-- Module    : Yices.Painless.Language
-- Copyright : (c) Don Stewart 2010
-- License   : BSD3
-- Maintainer: Don Stewart <dons@galois.com>
-- Stability : experimental
--
-- This module defines an embedded language of propositions for use by
-- the Yices SMT solver. Propositions are represented as 
-- first-order, typed, pure functions with quantified variables
-- in the proposition encoded as (Haskell) variables bound at the outer scope.
--
-- Propositions are represented as higher-order abstract syntax
-- embedded in Haskell.
-- 
-- Terms and types are embedded in Haskell, so all the usual type
-- inference and checking works for Yices propositions.
--
-- /A simple example: integers/
--
-- > import Yices.Painless.Language
-- >
-- > main = print =<< solve p
-- >
-- > p :: Exp Int -> Exp Int -> Exp Int -> Exp Bool
-- > p x y z = (3 * x) + (6 * y) ==* 1
--
-- /A simple example: bitvectors/
--
-- > solve $ \b1 (b2 :: Exp BitVector) 
-- >      -> b1 + 1 ==* b2 &&* b2 /=* b2 `xor` 7 + (1 + b1) 
--
-- Constructs the AST term:
--
-- > \x1 x0 -> (&&*) ((==*) ((+) (x1, 0b1), x0),
-- >                  (/=*) (x0, (+) (xor (x0, 0b111), (+) (0b1, x1))))
--
-- And the satisfying assignment:
--
-- > x0 => 0b101
-- > x1 => 0b100
-- > Satisfiable
--

module Yices.Painless.Language (

    -- * Running the solver
    solve,

    -- * Building Yices propositions.
    Yices, Exp,

    -- ** Scalar introduction
    -- constant,
    true, false,

    -- ** Arithmetic.
    -- $Instances

    -- ** Bit vectors
    -- $BitInstances

    -- ** Conditional expressions
    (?),

    -- ** Comparisons.
    (==*), (/=*), (<*), (<=*), (>*), (>=*),

    -- ** Logical operations.
    (&&*), (||*), not,

    -- ** Implication, /n/-ary operations.
    (-->), and, or, max, min,

    -- * Design discussion
    -- $Notes

  ) where

import Prelude hiding (not, or, and, min, max)

import Data.Typeable
import qualified Data.Map as M

import Data.Bits

import Control.Monad
import Control.Applicative ((<$>))
import Foreign.Storable (sizeOf)

import Text.PrettyPrint

import qualified Yices.Painless.Base as Yices

import Yices.Painless.Type

import Yices.Painless.Tuple hiding    (Tuple)
import qualified Yices.Painless.Tuple as Tuple

-- $Notes
--
-- /Future work/:
--
-- * BitVectors are sized, yet we do not represent their size at all
-- currently.  Size types would let us statically check e.g. bit vector
-- concatenation.
--
-- * BitVectors are represented under the hood as 'Vector Bool'. Yices
-- supports construction also via a 'Word' literal. Support both forms
-- (similar to the 'Integer' type)
--
-- * A 'Monoid' instance for bit vectors?
--
-- * A monoid for conjunction?
--
-- * Support other numeric types.
--
-- * Support function types in the core language.
--
-- * Support more SMT types: functions, tuples, records, recursive types.
--
-- * Deriving Exp. A (derivable) class for lifting Haskell data types
-- into their symbolic form.
--

------------------------------------------------------------------------
-- Language

-- We use the dictionary view of overloaded operations (such as arithmetic and
-- bit manipulation) to reify such expressions.  With non-overloaded
-- operations (such as, the logical connectives) and partially overloaded
-- operations (such as comparisons), we use the standard operator names with a
-- '*' attached.  We keep the standard alphanumeric names as they can be
-- easily qualified.

-- Methods from H98 classes, where we need other signatures

infix 4 ==*, /=*,  <*, <=*, >*, >=*

-- | Equality lifted into Yices expressions.
--
(==*) :: (IsScalar t) => Exp t -> Exp t -> Exp Bool
(==*) = mkEq

-- |Inequality lifted into Yices expressions.
--
(/=*) :: (IsScalar t) => Exp t -> Exp t -> Exp Bool
(/=*) = mkNEq

-- | '<' lifted into Yices expressions.
--
(<*) :: (IsScalar t) => Exp t -> Exp t -> Exp Bool
(<*)  = mkLt

-- | '<=' lifted into Yices expressions.
--
(>=*) :: (IsScalar t) => Exp t -> Exp t -> Exp Bool
(>=*) = mkGtEq

-- | '>' lifted into Yices expressions.
--
(>*) :: (IsScalar t) => Exp t -> Exp t -> Exp Bool
(>*)  = mkGt

-- | '<=' lifted into Yices expressions.
--
(<=*) :: (IsScalar t) => Exp t -> Exp t -> Exp Bool
(<=*) = mkLtEq

-- Conditional expressions
-- -----------------------

-- |Conditional expression.
--
infix 0 ?
(?) :: Exp Bool -> (Exp t, Exp t) -> Exp t
c ? (t, e) = Cond c t e

-- Non-overloaded standard functions, where we need other signatures
-- -----------------------------------------------------------------

-- |Conjunction
--
infixr 3 &&*
(&&*) :: Exp Bool -> Exp Bool -> Exp Bool
(&&*) = mkLAnd

-- |Disjunction
--
infixr 2 ||*
(||*) :: Exp Bool -> Exp Bool -> Exp Bool
(||*) = mkLOr

-- | 'and' returns the conjunction of a Boolean list.
and   :: [Exp Bool] -> Exp Bool
and   = foldr (&&*) true

-- | 'or' returns the disjunction of a Boolean list.
or    :: [Exp Bool] -> Exp Bool
or    = foldr (||*) false

-- TODO: implement in terms of underlying primitive conjunction and
-- disjunction, which accepts lists.

-- |Negation
--
not :: Exp Bool -> Exp Bool
not = mkLNot

-- | Implication
infixr 1 -->
(-->) :: Exp Bool -> Exp Bool -> Exp Bool
x --> y = not x ||* y

------------------------------------------------------------------------

{-
instance (IsScalar t) => Enum (Exp t)
--  succ = mkSucc
--  pred = mkPred
  -- FIXME: ops
-}

instance (IsScalar t) => Prelude.Eq (Exp t) where
  -- instance makes no sense with standard signatures
  (==)        = error "Prelude.Eq.== applied to EDSL types"

instance (IsScalar t) => Prelude.Ord (Exp t) where
  -- instance makes no sense with standard signatures
  compare     = error "Prelude.Ord.compare applied to EDSL types"

------------------------------------------------------------------------
-- Bit vector operations

    -- TODO: fromInteger should probably build from mkBVConstant
    -- TOD0: need size information.
    -- TOD0: support construction of a specific size

-- TODO monoid instance
-- instance Monoid (Exp BitVector) where
   --  mappend = mkBVAppend
   -- needs size types!

-- $BitInstances
-- The 'Exp BitVector' type is an instance of 'Bits' and 'Num', allowing the usual
-- Haskell bitwise operators to be used to construct propositions involving
-- bitwise operations on bit vectors.
--
-- > (.&.) :: Exp BitVector -> Exp BitVector -> Exp BitVector
-- > (.|.)
-- > xor
-- > complement
-- > shiftL
-- > shiftR
--
-- Currently bit vectors are fixed at 'sizeOf (undefined :: Word)' bits.
--
-- Bit vector constants can be constructed using overloaded numeric
-- literals.
--
-- TODO: instance Bits a => Bits (Exp a)
--

instance Bits (Exp BitVector) where
    (.&.)       = mkBVAnd
    (.|.)       = mkBVOr
    xor         = mkBVXor
    complement  = mkBVNot
    shiftL      = mkBVShiftL0
    shiftR      = mkBVShiftR0
    isSigned _  = False
    bitSize  _  = 8 * sizeOf (undefined :: Word) -- TODO! size type

------------------------------------------------------------------------

-- $Instances
-- 'Exp' is an instance of 'Num' at the usual types.
--
-- > (+) :: IsNum t => Exp t -> Exp t -> Exp t
--
-- > (-) :: IsNum t => Exp t -> Exp t -> Exp t
--
-- > (*) :: IsNum t => Exp t -> Exp t -> Exp t
--
-- > negate :: IsNum t => Exp t -> Exp t
--
-- Numeric literals are overloaded at Exp t type, so you may write, e.g.
--
-- In addition, 'Exp BitVector' allows for bit vector arithmetic
-- instances.
--

instance (IsNum t) => Num (Exp t) where
  (+)         = mkAdd
  (-)         = mkSub
  (*)         = mkMul

  negate x    = 0 - x

  abs _       = error "Prelude.Num.abs applied to EDSL types"
    -- if n >= 0 then n else negate n
  signum _    = error "Prelude.Num.signum applied to EDSL types"

{-
  signum n | n <  0     = negate 1
           | n == 0     = 0
           | otherwise  = 1
-}

  fromInteger = constant . fromInteger

{-

instance (Elem t, IsNum t, IsIntegral t) => Bits (Exp t) where
    (.&.)      = mkBAnd
    (.|.)      = mkBOr
    xor        = mkBXor
    complement = mkBNot

-}

------------------------------------------------------------------------

-- |Determine the maximum of two scalars.
max :: IsScalar t => Exp t -> Exp t -> Exp t
max x y = x <* y ? (y , x)

-- |Determine the minimum of two scalars.
min :: IsScalar t => Exp t -> Exp t -> Exp t
min x y = x <* y ? (x , y)

------------------------------------------------------------------------
-- Smart

-- This modules defines the AST of the user-visible embedded language using
-- more convenient higher-order abstract syntax (instead of de Bruijn
-- indices). Moreover, it defines smart constructors to construct programs.

-- Bit vector operators

-- mkBVNeg :: Exp BitVector -> Exp BitVector
-- mkBVNeg x = PrimBVNeg `PrimApp` x

-- Bits instance

mkBVAnd :: Exp BitVector -> Exp BitVector -> Exp BitVector
mkBVAnd x y = PrimBVAnd `PrimApp` tup2 (x, y)

mkBVOr  :: Exp BitVector -> Exp BitVector -> Exp BitVector
mkBVOr x y = PrimBVOr `PrimApp` tup2 (x, y)

mkBVXor  :: Exp BitVector -> Exp BitVector -> Exp BitVector
mkBVXor x y = PrimBVXor `PrimApp` tup2 (x, y)

mkBVNot :: Exp BitVector -> Exp BitVector
mkBVNot x = PrimBVNot `PrimApp` x

mkBVShiftL0 :: Exp BitVector -> Int -> Exp BitVector
mkBVShiftL0 x n = PrimBVSL0 `PrimApp` tup2 (x, constant n) -- lift the int shift.

mkBVShiftR0 :: Exp BitVector -> Int -> Exp BitVector
mkBVShiftR0 x n = PrimBVSR0 `PrimApp` tup2 (x, constant n) -- shiftR fills with 0

------------------------------------------------------------------------
-- Scalar operations

-- Operators from Num, also includes BitVector operations

mkAdd :: (IsNum t) => Exp t -> Exp t -> Exp t
mkAdd x y = PrimAdd numType `PrimApp` tup2 (x, y)

mkSub :: (IsNum t) => Exp t -> Exp t -> Exp t
mkSub x y = PrimSub numType `PrimApp` tup2 (x, y)

mkMul :: (IsNum t) => Exp t -> Exp t -> Exp t
mkMul x y = PrimMul numType `PrimApp` tup2 (x, y)

-- Relational and equality operators

mkLt   :: (IsScalar t) => Exp t -> Exp t -> Exp Bool
mkLt   x y = PrimLt scalarType `PrimApp` tup2 (x, y)

mkGt   :: (IsScalar t) => Exp t -> Exp t -> Exp Bool
mkGt   x y = PrimGt scalarType `PrimApp` tup2 (x, y)

mkLtEq :: (IsScalar t) => Exp t -> Exp t -> Exp Bool
mkLtEq x y = PrimLtEq scalarType `PrimApp` tup2 (x, y)

mkGtEq :: (IsScalar t) => Exp t -> Exp t -> Exp Bool
mkGtEq x y = PrimGtEq scalarType `PrimApp` tup2 (x, y)

mkEq   :: (IsScalar t) => Exp t -> Exp t -> Exp Bool
mkEq   x y = PrimEq  scalarType `PrimApp` tup2 (x, y)

mkNEq  :: (IsScalar t) => Exp t -> Exp t -> Exp Bool
mkNEq  x y = PrimNEq scalarType `PrimApp` tup2 (x, y)

-- Logical operators

mkLAnd :: Exp Bool -> Exp Bool -> Exp Bool
mkLAnd x y = PrimLAnd `PrimApp` tup2 (x, y)

mkLOr :: Exp Bool -> Exp Bool -> Exp Bool
mkLOr x y = PrimLOr `PrimApp` tup2 (x, y)

mkLNot :: Exp Bool -> Exp Bool
mkLNot x = PrimLNot `PrimApp` x

------------------------------------------------------------------------
-- Smart constructor for literals

-- | Literal 'True'
true :: Exp Bool
true  = constant True

-- | Literal 'False'
false :: Exp Bool
false = constant False

-- |Constant scalar expression
--
constant :: (Show t, IsScalar t) => t -> Exp t
constant = Const

-- Smart constructor and destructors for tuples

tup2 :: (Exp a, Exp b) -> Exp (a, b)
tup2 (x1, x2) = Tuple (NilTup `SnocTup` x1 `SnocTup` x2)

------------------------------------------------------------------------

-- Embedded expressions of the surface language

-- HOAS expressions mirror the constructors of `OpenExp', but with the
-- `Tag' constructor instead of variables in the form of de Bruijn indices.
-- Moreover, HOAS expression use n-tuples and the type class 'Elem' to
-- constrain element types, whereas `OpenExp' uses nested pairs and the 
-- GADT 'TupleType'.

--
-- Yices programs should be closed wrt. scalar variables.
-- All /variables/ must be 'defined' in Yices before use.
-- Nesting should be ok. So bound under a lambda.
--
-- To restrict functions to first-order, we separate function
-- abstraction from the main expression type.  Functions are represented
-- using de Bruijn indices.

-- Helpful wrapper
data YicesProg r where
    Y :: Yices f r => f -> YicesProg r

--
-- Allow embedded functions??

-- | Yices scalar formula.
--
data Exp t where

    -- Needed for conversion to de Bruijn form
    Tag         :: (IsScalar t) => Int          ->  Exp t
                 -- environment size at defining occurrence

    Const       :: (Show t, IsScalar t)
                => t                             -> Exp t

    Tuple       :: (IsTuple t)
                => Tuple.Tuple Exp (TupleRepr t) -> Exp t

    Cond        :: Exp Bool -> Exp t -> Exp t    -> Exp t

    PrimApp     :: PrimFun (a -> r) -> Exp a     -> Exp r

{-

  Lam :: (Typeable s, Typeable t,
          Show s, Show t)
      => (Term s -> Term t)      -> Term (s -> t)

  App :: (Typeable s, Typeable t,
          Show s, Show t)
      => Term (s -> t) -> Term s -> Term t

 -}

------------------------------------------------------------------------

-- | Well-formed Yices propositions (with /n/ quantified variables).
--
-- The current design requires all free variables in the proposition to
-- be bound at the outermost level. In higher-order abstract syntax,
-- this represents an n-ary, polyvariadic function.
--
-- Examples:
--
-- > true
--
-- > \(x :: Exp Int) -> x >* 8 &&* x <* 10
--
-- > \x y -> x ==* y + 1
--
-- The language supports polymorphic scalar and numerical operations, so
-- some explicit type information may be required to resolve overloading.
-- 
-- E.g.
-- 
-- > > solve $ \x y -> x ==* y + (1 :: Exp Int) 
-- >
-- > \x1 x0 -> (==*) (x1, (+) (x0, 1))
-- >
-- > x0 => 1
-- > x1 => 2
-- > Satisfiable
--
class Yices f r | f -> r where
  -- Convert a HOAS fragment into its deBruijn form, binding variables in a typed environment
  convert :: Layout env env -> f -> OpenFun env r

instance Yices (Exp b) b where
  -- Convert expressions
  convert lyt e = OBody (convertOpenExp lyt e)

instance (IsScalar a, Yices f r) => Yices (Exp a -> f) (a -> r) where
  -- Convert binders, one bind at a time.
  convert lyt f = OLam (convert lyt' (f a))
    where
    a    = Tag (size lyt)
    lyt' = inc lyt `PushLayout` ZeroIdx

------------------------------------------------------------------------

-- |Conversion from HOAS to de Bruijn expression AST
--
-- Based on:
--
-- * Chakravarty. /Converting a HOAS term GADT into a de Bruijn term GADT/, 2009.
-- <http://www.cse.unsw.edu.au/~chak/haskell/term-conv/>
--

-- |Convert a closed Yices program.
--
convertYices :: YicesProg r -> OpenYices r
convertYices (Y f) = OY $ convert EmptyLayout f

------------------------------------------------------------------------

-- |Convert an open expression with a given environment layout.
--             
convertOpenExp :: forall t env.
                  Layout env  env       -- scalar environment 
               -> Exp t                 -- expression to be converted
               -> OpenExp env t
convertOpenExp lyt = cvt
  where
    cvt :: Exp t' -> OpenExp env t'
    cvt (Tag i)             = Var (prjIdx (size lyt - i - 1) lyt) -- indexing!
    cvt (Const v)           = OConst v
    cvt (Tuple tup)         = OTuple (convertTuple lyt tup)
    cvt (Cond e1 e2 e3)     = OCond (cvt e1) (cvt e2) (cvt e3)
    cvt (PrimApp p e)       = OPrimApp p (cvt e)

-- |Convert a tuple expression
--
convertTuple :: Layout env env
             -> Tuple.Tuple Exp t
             -> Tuple.Tuple (OpenExp env) t
convertTuple _lyt NilTup           = NilTup
convertTuple lyt  (es `SnocTup` e) = convertTuple lyt es `SnocTup` convertOpenExp lyt e

-- |Convert an expression closed wrt to scalar variables
--
convertExp :: Exp t -> OExp t
convertExp = convertOpenExp EmptyLayout

------------------------------------------------------------------------

-- |
-- A layout of an environment an entry for each entry of the environment.
-- Each entry in the layout holds the deBruijn index that refers to the
-- corresponding entry in the environment.
--
-- TODO: explain the two type variables
--
data Layout env env' where
  EmptyLayout :: Layout env ()
  PushLayout  :: Typeable t
              => Layout env env' -> Idx env t -> Layout env (env', t)

-- Project the nth index out of an environment layout.
--
prjIdx :: forall t env env'. Typeable t => Int -> Layout env env' -> Idx env t
prjIdx 0 (PushLayout _ (ix :: Idx env u)) = case gcast ix of
   Just ix' -> ix'
   Nothing  -> error $
                "EDSL Compiler Type Error.\n" ++
                "Couldn't match expected type `" ++ show (typeOf (undefined :: t)) ++
                     "' against inferred type `" ++ show (typeOf (undefined :: u)) ++ "'"

prjIdx n (PushLayout l _)  = prjIdx (n - 1) l
prjIdx _ EmptyLayout       =
  error "Yices.Painless.Language.prjIdx" "inconsistent valuation"

-- | More functions on layouts, from 
-- <http://www.cse.unsw.edu.au/~chak/haskell/term-conv/Convert.hs>
--

-- Yield the number of entries in an environment layout
--
size :: Layout env env' -> Int
size EmptyLayout        = 0
size (PushLayout lyt _) = size lyt + 1

-- Add an entry to a layout, incrementing all indices
--
inc :: Layout env env' -> Layout (env, t) env'
inc EmptyLayout         = EmptyLayout
inc (PushLayout lyt ix) = PushLayout (inc lyt) (SuccIdx ix)

------------------------------------------------------------------------
-- AST 

--
-- The embedded language is marginally two-levels. Formula with free variables 
-- are bound with Define. Thus Yices programs are closed expressions of yices formula.
--
-- There is no explicit sharing in the initial AST form, but sharing can be recovered
-- subsequently by common subexpression elimination.
--
-- TODO: add functions to the Exp type.
--
-- The AST contains both reified dictionaries and type class constraints.  
-- Type classes are used for yices-related functionality that is uniformly
-- available for all supported types.  In contrast, reified dictionaries are
-- used for functionality that is only available for certain types, such as
-- arithmetic operations.
--

-- | Yices computations parameterized by Yices /variables/ represented with de
-- Bruijn indices.
--
-- * Scalar functions and expressions embedded in well-formed Yices
--   computations cannot contain free scalar variable indices.  The latter
--   cannot be bound in Yices computations, and hence, cannot appear in any
--   well-formed program.
--
-- The data type is parametrised over the surface types (not the representation
-- type).

-- data OpenYices a where
--    ODefine :: IsScalar t => Fun (t -> u) -> OpenYices u

-- | Yices programs with an environment.
--        
data OpenYices t where
    OY :: OFun t -> OpenYices t

-- execF shows nicely how to recurse over the OpenFun structure.
  
-- |Function abstraction
--
data OpenFun env t where
  OBody ::               OpenExp env      t -> OpenFun env t
  OLam  :: IsScalar a => OpenFun (env, a) t -> OpenFun env (a -> t)

-- |Function without free scalar variables
--
type OFun t = OpenFun () t

-- |Open expressions using de Bruijn indices for variables ranging over tuples
-- of scalars.  All code, except Cond, is evaluated eagerly.  N-tuples are
-- represented as nested pairs. 
--
-- The data type is parametrised over the surface types (not the representation
-- type).
--
data OpenExp env t where

  -- Variable index, ranging only over tuples or scalars
  Var         :: IsScalar t
              => Idx env t
              -> OpenExp env t

  -- Constant values
  OConst      :: (Show t, IsScalar t)
              => t
              -> OpenExp env t

  -- Tuples   
  OTuple      :: (IsTuple t)
              => Tuple.Tuple (OpenExp env) (TupleRepr t)
              -> OpenExp env t

  -- Conditional expression
  OCond       :: OpenExp env Bool
              -> OpenExp env t
              -> OpenExp env t
              -> OpenExp env t

  -- Primitive scalar operations
  OPrimApp     :: PrimFun (a -> r)
               -> OpenExp env a
               -> OpenExp env r


-- |Expression without free scalar variables
--
type OExp t = OpenExp () t

------------------------------------------------------------------------

-- Typed de Bruijn indices
-- -----------------------

-- De Bruijn variable index projecting a specific type from a type
-- environment.  Type envionments are nested pairs (..((), t1), t2, ..., tn). 
--
data Idx env t where
  ZeroIdx ::              Idx (env, t) t
  SuccIdx :: Idx env t -> Idx (env, s) t

-- Environments
-- ------------

-- Valuation for an environment
--
{-
data Val env where
--  Empty :: Val ()
--  Push  :: Val env -> t -> Val (env, t)

-- Projection of a value from a valuation using a de Bruijn index
--
prj :: Idx env t -> Val env -> t
prj ZeroIdx       (Push _   v) = v
prj (SuccIdx idx) (Push val _) = prj idx val
prj _             _            =
  error "Yices.Painless.Language.prj" "inconsistent valuation"
-}

-- Convert a typed de Brujin index to the corresponding integer
--
idxToInt :: Idx env t -> Int
idxToInt ZeroIdx       = 0
idxToInt (SuccIdx idx) = 1 + idxToInt idx

------------------------------------------------------------------------
-- AST

-- |Primitive scalar operations
--
data PrimFun sig where
    -- relational and equality operators
    PrimLt   :: ScalarType a -> PrimFun ((a, a) -> Bool)
    PrimGt   :: ScalarType a -> PrimFun ((a, a) -> Bool)
    PrimLtEq :: ScalarType a -> PrimFun ((a, a) -> Bool)
    PrimGtEq :: ScalarType a -> PrimFun ((a, a) -> Bool)
    PrimEq   :: ScalarType a -> PrimFun ((a, a) -> Bool)
    PrimNEq  :: ScalarType a -> PrimFun ((a, a) -> Bool)

    -- operators from Num
    PrimAdd  :: NumType a -> PrimFun ((a, a) -> a)
    PrimSub  :: NumType a -> PrimFun ((a, a) -> a)
    PrimMul  :: NumType a -> PrimFun ((a, a) -> a)

    -- logical operators
    PrimLAnd :: PrimFun ((Bool, Bool) -> Bool)
    PrimLOr  :: PrimFun ((Bool, Bool) -> Bool)
    PrimLNot :: PrimFun (Bool         -> Bool)

    -- TODO: just use the overloaded instance?

    -- bit vector arithmetic
    PrimBVAdd :: PrimFun ((BitVector,BitVector) -> BitVector)
    PrimBVSub :: PrimFun ((BitVector,BitVector) -> BitVector)
    PrimBVMul :: PrimFun ((BitVector,BitVector) -> BitVector)
    PrimBVNeg :: PrimFun (BitVector -> BitVector)

    -- bit vector bit operations
    PrimBVAnd :: PrimFun ((BitVector,BitVector) -> BitVector)
    PrimBVOr  :: PrimFun ((BitVector,BitVector) -> BitVector)
    PrimBVXor :: PrimFun ((BitVector,BitVector) -> BitVector)
    PrimBVNot :: PrimFun (BitVector -> BitVector)
    -- Todo: enforce size constraints.

    PrimBVSL0 :: PrimFun ((BitVector,Int) -> BitVector)
    PrimBVSR0 :: PrimFun ((BitVector,Int) -> BitVector)

    -- Others are already overloaded on Eq/Neq/Lt/Lte/Ge/Gte

-- Bit vector logical operators
{-
    mkBVConcat, mkBVExtract,
    mkBVSignExtend,
    mkBVShiftLeft1,
    mkBVShiftRight1,
    mkBVSlt, mkBVSle, -- can be interpreted as signed types.
    mkBVSgt, mkBVSge,
-}

------------------------------------------------------------------------
-- Pretty printing

-- Generic instance for the AST, to avoid a wrapper type.
instance Yices f r => Show f where
    show = show . Y

instance Show (YicesProg as) where
  show = show . convertYices

instance Show (Exp a) where
  show = show . convertExp

instance Show (OpenYices a) where
  show c = render $ prettyYices 0 c

instance Show (OpenFun env f) where
  show f = render $ prettyFun 0 f

instance Show (OpenExp env t) where
  show e = render $ prettyExp 0 noParens e

------------------------------------------------------------------------

prettyYices  :: Int -> OpenYices a -> Doc
prettyYices n (OY f) = prettyFun n f

prettyFun ::  Int -> OpenFun env a -> Doc
prettyFun lvl fun =
  let (n, bodyDoc) = count fun
  in
    if n < 0 
        then bodyDoc
        else 
          char '\\' <> hsep [text $ "x" ++ show idx | idx <- reverse [0..n]] <+>
          text "->" <+> bodyDoc
  where
     count :: OpenFun env fun -> (Int, Doc)
     count (OBody body) = (-1, prettyExp lvl noParens body)
     count (OLam fun')  = let (n, body) = count fun' in (1 + n, body)

-- Pretty print an expression.
--
-- * Apply the wrapping combinator (1st argument) to any compound expressions.
--
prettyExp :: forall t env .
             Int -> (Doc -> Doc) -> OpenExp env t -> Doc

prettyExp _   _    (Var idx)         = text $ "x" ++ show (idxToInt idx)
prettyExp _   _    (OConst v)        = text $ show (v :: t) -- dispatch differently for BitVector types
prettyExp lvl _    (OTuple tup)      = prettyTuple lvl tup

-- prettyExp lvl wrap (Prj idx e)
--  = wrap $ prettyTupleIdx idx <+> prettyExp lvl parens e

prettyExp lvl wrap (OCond c t e)
     = wrap $ sep [prettyExp lvl parens c <+> char '?',
                parens (prettyExp lvl noParens t <> comma <+>
                        prettyExp lvl noParens e)]

prettyExp lvl wrap (OPrimApp p a)
    = wrap $ prettyPrim p <+> prettyExp lvl parens a

-- Pretty print nested pairs as a proper tuple.
--
prettyTuple :: Int -> Tuple.Tuple (OpenExp env) t -> Doc
prettyTuple lvl e = parens $ sep (map (<> comma) (init es) ++ [last es])
  where
    es = collect e

    collect :: Tuple.Tuple (OpenExp env) t -> [Doc]
    collect NilTup          = []
    collect (SnocTup tup e') = collect tup ++ [prettyExp lvl noParens e']
    
-- Pretty print a primitive operation
--
prettyPrim :: PrimFun a -> Doc
prettyPrim (PrimAdd _)         = text "(+)"
prettyPrim (PrimSub _)         = text "(-)"
prettyPrim (PrimMul _)         = text "(*)"
prettyPrim (PrimLt _)          = text "(<*)"
prettyPrim (PrimGt _)          = text "(>*)"
prettyPrim (PrimLtEq _)        = text "(<=*)"
prettyPrim (PrimGtEq _)        = text "(>=*)"
prettyPrim (PrimEq _)          = text "(==*)"
prettyPrim (PrimNEq _)         = text "(/=*)"
prettyPrim PrimLAnd            = text "(&&*)"
prettyPrim PrimLOr             = text "(||*)"
prettyPrim PrimLNot            = text "not"

-- Overloaded bit vector ops
prettyPrim PrimBVAdd           = text "(+)"
prettyPrim PrimBVMul           = text "(*)"
prettyPrim PrimBVSub           = text "(-)"
prettyPrim PrimBVNeg           = text "negate"
prettyPrim PrimBVAnd           = text "(.&.)"
prettyPrim PrimBVOr            = text "(.|.)"
prettyPrim PrimBVXor           = text "xor"
prettyPrim PrimBVNot           = text "complement"
prettyPrim PrimBVSL0           = text "shiftL"
prettyPrim PrimBVSR0           = text "shiftR"

-- Auxilliary pretty printing combinators
-- 
noParens :: Doc -> Doc
noParens = id


------------------------------------------------------------------------
--
-- Execute the AST.
--
-- TODO: check use of 'Context' is pure.
--

-- | Run Yices on a well-formed proposition, returning either a
-- satisfying assignment of variables that makes the proposition hold, or
-- establish that the proposition is unsatisfiable.
--
solve :: (Yices f r) => f -> IO Yices.Result
solve q' = do
    let q = Y q'
    c <- Yices.mkContext 
    Yices.setTypeChecker True

    let t = convertYices q -- bind all the variables
    print t

    (g,e) <- execY c t 

    Yices.assert c e

--    Yices.ctxDump c
--    Yices.ppExpr e

    sat <- Yices.check c
    case sat of
        Yices.Unsatisfiable -> return $ Yices.Unsatisfiable
        Yices.Undefined     -> return $ Yices.Undefined
        Yices.Satisfiable   -> do
            mm <- Yices.getModel c 
            case mm of
                Nothing -> return Yices.Satisfiable
                Just m  -> do

                    vs <- sequence
                            [ get m v t' d
                            | (v,(t',d)) <- M.toList g ]

                    forM_ vs (\(n, YValue mv) -> do
                                putStr (n ++ " => ")
                                case mv of
                                    Nothing -> putStrLn "_"
                                    Just v  -> print v)

                    -- print cs
                    return Yices.Satisfiable

-- | Retrieving bindings by type
--
get :: Yices.Model -> String -> YType -> Yices.Decl -> IO (String, YValue)
get m v (YType (ty :: ScalarType t)) d

    | NumScalarType (IntegralNumType (TypeInt _))  <- ty
    = do mn <- Yices.getValueInt m d
         return (v, YValue mn)

    | NonNumScalarType (TypeBool _)                <- ty
    = do mn <- Yices.getValueBool m d
         return (v, YValue mn)

    | NumScalarType (IntegralNumType (TypeVectorBool _))               <- ty
    = do mn <- Yices.getValueBitVector m d (fromIntegral $ 8 * sizeOf (undefined :: Word))
         return (v, YValue $ fmap BitVector mn)
            
    | otherwise = error "Yices.Painless.get: don't know how to get this type yet"


-- | Map free variable names that we come up with to their type and decl
-- in the context. This will then be used to extract solutions after
-- solving.
--
type YEnv = M.Map String (YType, Yices.Decl)

data YType  = forall a. IsScalar a => YType (ScalarType a)

data YValue = forall a. (Show a, IsScalar a) => YValue (Maybe a)

--
-- To run,
--
--   * take the Exp
--   * extract the set of declared variables
--   * bind them in a context
--   * evaluate the assertions.
-- 
-- return the bindings.
--
execY :: Yices.Context -> OpenYices t -> IO (YEnv, Yices.Expr)
execY c (OY f) = execF c f

--
-- Declaring variables. Begin with a closed Yices program.
--
execF :: Yices.Context -> OFun t -> IO (YEnv, Yices.Expr)
execF c fn = go fn 0 M.empty
    where
        go :: OpenFun env u -> Int -> YEnv -> IO (YEnv, Yices.Expr)
        go (OBody b) _ g = (,) g <$> exec c b

        -- Numbers
        go (OLam (f :: OpenFun (env, a) t)) n g
            | ty@(NumScalarType (IntegralNumType (TypeInt _)))  <- scalarType :: ScalarType a
            = do
                let nm = "x" ++ show n -- we get to actually name things
                tynm <- Yices.mkType c "int"
                d    <- Yices.mkVarDecl c nm tynm
                go f (n + 1) (M.insert nm (YType ty, d) g)
        
        -- Booleans
        go (OLam (f :: OpenFun (env, a) t)) n g
            | ty@(NonNumScalarType (TypeBool _))                <- scalarType :: ScalarType a
            = do
                let nm = "x" ++ show n
                d <- Yices.mkBoolDecl c nm
                go f (n + 1) (M.insert nm (YType ty, d) g)

        -- Bit vectors
        go (OLam (f :: OpenFun (env, a) t)) n g
            | ty@(NumScalarType (IntegralNumType (TypeVectorBool _)))   <- scalarType :: ScalarType a
            = do
                let nm = "x" ++ show n
                -- TODO: hack, no size information for bit vectors yet.
                -- TODO: show bvs in a better form.
                tynm <- Yices.mkBitVectorType c (fromIntegral $ 8 * sizeOf (undefined :: Word))
                d    <- Yices.mkVarDecl c nm tynm
                go f (n + 1) (M.insert nm (YType ty, d) g)


        go _ _ _ = error "Yices.execF: don't know how to bind variables of this type yet"

-- | Execute an expression with free variables.
--
-- /TODO:/
--
-- * support bit vector operations.
-- 
-- * function application and creation other than at the top level
--
-- * Rational, Double types.
--
-- * Tuples
--
exec :: forall env t. Yices.Context -> OpenExp env t -> IO Yices.Expr

-- GADTs are magic
exec c (OConst n)
    | NumScalarType (IntegralNumType (TypeInt _))   <- scalarType :: ScalarType t
    = Yices.mkNum c n

    | NonNumScalarType (TypeBool _)                 <- scalarType :: ScalarType t
    = if n then Yices.mkTrue  c
           else Yices.mkFalse c

    | NumScalarType (IntegralNumType (TypeVectorBool _))  <- scalarType :: ScalarType t
    = Yices.mkBVConstantFromVector c (unBV n)


exec c (Var i) = do
    let n = "x" ++ show (idxToInt i)
--    print n

    v <- Yices.getVarDeclFromName c n -- sneaky. using Yices environment. TODO: use YEnv
    case v of
        Nothing -> error "Undefined variable"
        Just d  -> Yices.mkVarFromDecl c d

-- Conditionals
exec c (OCond b t e) = do
            eb <- exec c b
            et <- exec c t
            ee <- exec c e
            Yices.mkIte c eb et ee

-- Works on bitvectors straight up.
exec c (OPrimApp  (PrimEq _)
        (OTuple (NilTup `SnocTup` x1 `SnocTup` x2))) = do
            e1 <- exec c x1
            e2 <- exec c x2
            Yices.mkEq c e1 e2

-- Ok for bitvectors
exec c (OPrimApp  (PrimNEq _)
        (OTuple (NilTup `SnocTup` x1 `SnocTup` x2))) = do
            e1 <- exec c x1
            e2 <- exec c x2
            Yices.mkNeq c e1 e2

-- Specialize for BitVector first
exec c (OPrimApp  (PrimLt (NumScalarType (IntegralNumType (TypeVectorBool _))))
        (OTuple (NilTup `SnocTup` x1 `SnocTup` x2))) = do
            e1 <- exec c x1
            e2 <- exec c x2
            Yices.mkBVLt c e1 e2

-- Only numeric types?
exec c (OPrimApp  (PrimLt _)
        (OTuple (NilTup `SnocTup` x1 `SnocTup` x2))) = do
            e1 <- exec c x1
            e2 <- exec c x2
            Yices.mkLt c e1 e2

-- Specialize for BitVector first
exec c (OPrimApp  (PrimLtEq (NumScalarType (IntegralNumType (TypeVectorBool _))))
        (OTuple (NilTup `SnocTup` x1 `SnocTup` x2))) = do
            e1 <- exec c x1
            e2 <- exec c x2
            Yices.mkBVLe c e1 e2

exec c (OPrimApp  (PrimLtEq _)
        (OTuple (NilTup `SnocTup` x1 `SnocTup` x2))) = do
            e1 <- exec c x1
            e2 <- exec c x2
            Yices.mkLe c e1 e2

-- Specialize for BitVector first
exec c (OPrimApp  (PrimGt (NumScalarType (IntegralNumType (TypeVectorBool _))))
        (OTuple (NilTup `SnocTup` x1 `SnocTup` x2))) = do
            e1 <- exec c x1
            e2 <- exec c x2
            Yices.mkBVGt c e1 e2

exec c (OPrimApp  (PrimGt _)
        (OTuple (NilTup `SnocTup` x1 `SnocTup` x2))) = do
            e1 <- exec c x1
            e2 <- exec c x2
            Yices.mkGt c e1 e2

-- TODO think about what gets through the overloading incorrectly.
-- Specialize for BitVector first
exec c (OPrimApp  (PrimGtEq (NumScalarType (IntegralNumType (TypeVectorBool _))))
        (OTuple (NilTup `SnocTup` x1 `SnocTup` x2))) = do
            e1 <- exec c x1
            e2 <- exec c x2
            Yices.mkBVGe c e1 e2

exec c (OPrimApp  (PrimGtEq _)
        (OTuple (NilTup `SnocTup` x1 `SnocTup` x2))) = do
            e1 <- exec c x1
            e2 <- exec c x2
            Yices.mkGe c e1 e2

exec c (OPrimApp  PrimLAnd
        (OTuple (NilTup `SnocTup` x1 `SnocTup` x2))) = do
            e1 <- exec c x1
            e2 <- exec c x2
            Yices.mkAnd c [e1, e2]

exec c (OPrimApp  PrimLOr
        (OTuple (NilTup `SnocTup` x1 `SnocTup` x2))) = do
            e1 <- exec c x1
            e2 <- exec c x2
            Yices.mkOr c [e1, e2]

exec c (OPrimApp PrimLNot x) = do
            e <- exec c x
            Yices.mkNot c e

-- Numerical operations

-- overloaded on bit vectors
exec c (OPrimApp  (PrimAdd (IntegralNumType (TypeVectorBool _)))
          (OTuple (NilTup `SnocTup` x1 `SnocTup` x2))) = do
            e1 <- exec c x1
            e2 <- exec c x2
            Yices.mkBVAdd c e1 e2

exec c (OPrimApp  (PrimAdd _)
        (OTuple (NilTup `SnocTup` x1 `SnocTup` x2))) = do
            e1 <- exec c x1
            e2 <- exec c x2
            Yices.mkSum c [e1,e2]

-- overloaded on bit vectors
exec c (OPrimApp  (PrimSub (IntegralNumType (TypeVectorBool _)))
          (OTuple (NilTup `SnocTup` x1 `SnocTup` x2))) = do
            e1 <- exec c x1
            e2 <- exec c x2
            Yices.mkBVSub c e1 e2

exec c (OPrimApp  (PrimSub _)
        (OTuple (NilTup `SnocTup` x1 `SnocTup` x2))) = do
            e1 <- exec c x1
            e2 <- exec c x2
            Yices.mkSub c [e1,e2]

-- overloaded on bit vectors
exec c (OPrimApp  (PrimMul (IntegralNumType (TypeVectorBool _)))
          (OTuple (NilTup `SnocTup` x1 `SnocTup` x2))) = do
            e1 <- exec c x1
            e2 <- exec c x2
            Yices.mkBVMul c e1 e2

exec c (OPrimApp  (PrimMul _)
          (OTuple (NilTup `SnocTup` x1 `SnocTup` x2))) = do
            e1 <- exec c x1
            e2 <- exec c x2
            Yices.mkMul c [e1,e2]

------------------------------------------------------------------------
-- Bit Vector operations

-- TODO
exec c (OPrimApp PrimBVNeg
          (OTuple (NilTup `SnocTup` x1))) = do
            e1 <- exec c x1
            Yices.mkBVMinus c e1

exec c (OPrimApp PrimBVAnd
          (OTuple (NilTup `SnocTup` x1 `SnocTup` x2))) = do
            e1 <- exec c x1
            e2 <- exec c x2
            Yices.mkBVAnd c e1 e2

exec c (OPrimApp PrimBVOr
          (OTuple (NilTup `SnocTup` x1 `SnocTup` x2))) = do
            e1 <- exec c x1
            e2 <- exec c x2
            Yices.mkBVOr c e1 e2

exec c (OPrimApp PrimBVXor
          (OTuple (NilTup `SnocTup` x1 `SnocTup` x2))) = do
            e1 <- exec c x1
            e2 <- exec c x2
            Yices.mkBVXor c e1 e2

exec c (OPrimApp PrimBVNot
          (OTuple (NilTup `SnocTup` x1))) = do
            e1 <- exec c x1
            Yices.mkBVNot c e1

exec c (OPrimApp PrimBVSL0
          (OTuple (NilTup `SnocTup` x1 `SnocTup` (OConst n)))) = do
            e1 <- exec c x1
            Yices.mkBVShiftLeft0 c e1 n

exec c (OPrimApp PrimBVSR0
          (OTuple (NilTup `SnocTup` x1 `SnocTup` (OConst n)))) = do
            e1 <- exec c x1
            Yices.mkBVShiftRight0 c e1 n

exec _ _ = error "Not implemented"

{-
 _ (Tuple _)
 _ (Const _)
 _ (PrimApp (PrimEq _) (Const _))
-}

-- exec _ e = error (show e)

{-
evalTuple :: Tuple (OpenExp env aenv) t -> Val env -> Val aenv -> t
evalTuple NilTup            _env _aenv = ()
evalTuple (tup `SnocTup` e) env  aenv  = (evalTuple tup env aenv, 
                                          evalOpenExp e env aenv)
-}