File: SExpr.hs

package info (click to toggle)
haskell-sbv 10.2-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 8,148 kB
  • sloc: haskell: 31,176; makefile: 4
file content (624 lines) | stat: -rw-r--r-- 35,411 bytes parent folder | download
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
-----------------------------------------------------------------------------
-- |
-- Module    : Data.SBV.Utils.SExpr
-- Copyright : (c) Levent Erkok
-- License   : BSD3
-- Maintainer: erkokl@gmail.com
-- Stability : experimental
--
-- Parsing of S-expressions (mainly used for parsing SMT-Lib get-value output)
-----------------------------------------------------------------------------

{-# LANGUAGE BangPatterns #-}

{-# OPTIONS_GHC -Wall -Werror #-}

module Data.SBV.Utils.SExpr (SExpr(..), parenDeficit, parseSExpr, parseSExprFunction, makeHaskellFunction) where

import Data.Bits   (setBit, testBit)
import Data.Char   (isDigit, ord, isSpace)
import Data.Either (partitionEithers)
import Data.List   (isPrefixOf, nubBy, intercalate)
import Data.Maybe  (fromMaybe, listToMaybe)
import Data.Word   (Word32, Word64)

import Control.Monad (foldM)

import Numeric    (readInt, readSigned, readDec, readHex, fromRat)

import Data.SBV.Core.AlgReals
import Data.SBV.Core.SizedFloats
import Data.SBV.Core.Data (nan, infinity, RoundingMode(..))

import Data.SBV.Utils.Numeric (fpIsEqualObjectH, wordToFloat, wordToDouble)

-- | ADT S-Expression format, suitable for representing get-model output of SMT-Lib
data SExpr = ECon           String
           | ENum           (Integer, Maybe Int)  -- Second argument is how wide the field was in bits, if known. Useful in FP parsing.
           | EReal          AlgReal
           | EFloat         Float
           | EFloatingPoint FP
           | EDouble        Double
           | EApp           [SExpr]
           deriving Show

-- | Extremely simple minded tokenizer, good for our use model.
tokenize :: String -> [String]
tokenize inp = go inp []
 where go "" sofar = reverse sofar

       go (c:cs) sofar
          | isSpace c = go (dropWhile isSpace cs) sofar

       go ('(':cs) sofar = go cs ("(" : sofar)
       go (')':cs) sofar = go cs (")" : sofar)

       go (':':':':cs) sofar = go cs ("::" : sofar)

       go (':':cs) sofar = case break (`elem` stopper) cs of
                            (pre, rest) -> go rest ((':':pre) : sofar)

       go ('|':r) sofar = case span (/= '|') r of
                            (pre, '|':rest) -> go rest (pre : sofar)
                            (pre, rest)     -> go rest (pre : sofar)

       go ('"':r) sofar = go rest (finalStr : sofar)
           where grabString []             acc = (reverse acc, [])         -- Strictly speaking, this is the unterminated string case; but let's ignore
                 grabString ('"' :'"':cs)  acc = grabString cs ('"' :acc)
                 grabString ('"':cs)       acc = (reverse acc, cs)
                 grabString (c:cs)         acc = grabString cs (c:acc)

                 (str, rest) = grabString r []
                 finalStr    = '"' : str ++ "\""

       go cs sofar = case span (`notElem` stopper) cs of
                       (pre, post) -> go post (pre : sofar)

       -- characters that can stop the current token
       -- it is *crucial* that this list contains every character
       -- we can match in one of the previous cases!
       stopper = " \t\n():|\""

-- | The balance of parens in this string. If 0, this means it's a legit line!
parenDeficit :: String -> Int
parenDeficit = go 0 . tokenize
  where go :: Int -> [String] -> Int
        go !balance []           = balance
        go !balance ("(" : rest) = go (balance+1) rest
        go !balance (")" : rest) = go (balance-1) rest
        go !balance (_   : rest) = go balance     rest

-- | Parse a string into an SExpr, potentially failing with an error message
parseSExpr :: String -> Either String SExpr
parseSExpr inp = do (sexp, extras) <- parse inpToks
                    if null extras
                       then case sexp of
                              EApp [ECon "error", ECon er] -> Left $ "Solver returned an error: " ++ er
                              _                            -> return sexp

                       else die "Extra tokens after valid input"
  where inpToks = tokenize inp

        die w = Left $  "SBV.Provers.SExpr: Failed to parse S-Expr: " ++ w
                     ++ "\n*** Input : <" ++ inp ++ ">"

        parse []         = die "ran out of tokens"
        parse ("(":toks) = do (f, r) <- parseApp toks []
                              f' <- cvt (EApp f)
                              return (f', r)
        parse (")":_)    = die "extra tokens after close paren"
        parse [tok]      = do t <- pTok tok
                              return (t, [])
        parse _          = die "ill-formed s-expr"

        parseApp []         _     = die "failed to grab s-expr application"
        parseApp (")":toks) sofar = return (reverse sofar, toks)
        parseApp ("(":toks) sofar = do (f, r) <- parse ("(":toks)
                                       parseApp r (f : sofar)
        parseApp (tok:toks) sofar = do t <- pTok tok
                                       parseApp toks (t : sofar)

        pTok "false" = return $ ENum (0, Nothing)
        pTok "true"  = return $ ENum (1, Nothing)

        pTok ('0':'b':r)                                 = mkNum (Just (length r))     $ readInt 2 (`elem` "01") (\c -> ord c - ord '0') r
        pTok ('b':'v':r) | not (null r) && all isDigit r = mkNum Nothing               $ readDec (takeWhile (/= '[') r)
        pTok ('#':'b':r)                                 = mkNum (Just (length r))     $ readInt 2 (`elem` "01") (\c -> ord c - ord '0') r
        pTok ('#':'x':r)                                 = mkNum (Just (4 * length r)) $ readHex r

        pTok n | possiblyNum n = if all intChar n then mkNum Nothing $ readSigned readDec n else getReal n
        pTok n                 = return $ ECon (constantMap n)

        -- crude, but effective!
        possiblyNum s = case s of
                          ""        -> False
                          ('-':c:_) -> isDigit c
                          (c:_)     -> isDigit c

        intChar c = c == '-' || isDigit c

        mkNum l [(n, "")] = return $ ENum (n, l)
        mkNum _ _         = die "cannot read number"

        getReal n = return $ EReal $ mkPolyReal (Left (exact, n'))
          where exact = not ("?" `isPrefixOf` reverse n)
                n' | exact = n
                   | True  = init n

        -- simplify numbers and root-obj values
        cvt (EApp [ECon "to_int",  EReal a])                       = return $ EReal a   -- ignore the "casting"
        cvt (EApp [ECon "to_real", EReal a])                       = return $ EReal a   -- ignore the "casting"
        cvt (EApp [ECon "/", EReal a, EReal b])                    = return $ EReal (a / b)
        cvt (EApp [ECon "/", EReal a, ENum  b])                    = return $ EReal (a                   / fromInteger (fst b))
        cvt (EApp [ECon "/", ENum  a, EReal b])                    = return $ EReal (fromInteger (fst a) /             b      )
        cvt (EApp [ECon "/", ENum  a, ENum  b])                    = return $ EReal (fromInteger (fst a) / fromInteger (fst b))
        cvt (EApp [ECon "-", EReal a])                             = return $ EReal (-a)
        cvt (EApp [ECon "-", ENum a])                              = return $ ENum  (-(fst a), snd a)

        -- bit-vector value as CVC4 prints: (_ bv0 16) for instance
        cvt (EApp [ECon "_", ENum a, ENum _b])                     = return $ ENum a
        cvt (EApp [ECon "root-obj", EApp (ECon "+":trms), ENum k]) = do ts <- mapM getCoeff trms
                                                                        return $ EReal $ mkPolyReal (Right (fst k, ts))
        cvt (EApp [ECon "as", n, EApp [ECon "_", ECon "FloatingPoint", ENum (11, _), ENum (53, _)]]) = getDouble n
        cvt (EApp [ECon "as", n, EApp [ECon "_", ECon "FloatingPoint", ENum ( 8, _), ENum (24, _)]]) = getFloat  n
        cvt (EApp [ECon "as", n, ECon "Float64"])                                                    = getDouble n
        cvt (EApp [ECon "as", n, ECon "Float32"])                                                    = getFloat  n

        -- Deal with CVC4's approximate reals
        cvt x@(EApp [ECon "witness", EApp [EApp [ECon v, ECon "Real"]]
                                   , EApp [ECon "or", EApp [ECon "=", ECon v', val], _]]) | v == v'   = do
                                                approx <- cvt val
                                                case approx of
                                                  ENum (s, _) -> return $ EReal $ mkPolyReal (Left (False, show s))
                                                  EReal aval  -> case aval of
                                                                   AlgRational _ r -> return $ EReal $ AlgRational False r
                                                                   _               -> return $ EReal aval
                                                  _           -> die $ "Cannot parse a CVC4 approximate value from: " ++ show x

        -- Deal with CVC5's algebraic reals. This is very crude!
        cvt x@(EApp (ECon "_" : ECon "real_algebraic_number" : rest)) =
            let isComma (ECon ",") = True
                isComma _          = False

                get (ENum    (n, _))               = return $ fromIntegral n
                get (EReal   (AlgRational True r)) = return r
                get (EFloat  f)                    = return $ toRational f
                get (EDouble d)                    = return $ toRational d
                get t                              = die $ "Cannot get a CVC5 real-algebraic bound from: " ++ show t

            in case drop 1 (dropWhile (not . isComma) rest) of
                [EApp [n1, n2], _] -> do low  <- get n1
                                         high <- get n2
                                         return $ EReal $ AlgInterval (OpenPoint low) (OpenPoint high)
                _                  -> die $ "Cannot parse a CVC5 real-algebraic number from: " ++ show x

        -- NB. Note the lengths on the mantissa for the following two are 23/52; not 24/53!
        cvt (EApp [ECon "fp",    ENum (s, Just 1), ENum ( e, Just 8),  ENum (m, Just 23)])           = return $ EFloat         $ getTripleFloat  s e m
        cvt (EApp [ECon "fp",    ENum (s, Just 1), ENum ( e, Just 11), ENum (m, Just 52)])           = return $ EDouble        $ getTripleDouble s e m
        cvt (EApp [ECon "fp",    ENum (s, Just 1), ENum ( e, Just eb), ENum (m, Just sb)])           = return $ EFloatingPoint $ fpFromRawRep (s == 1) (e, eb) (m, sb+1)

        cvt (EApp [ECon "_",     ECon "NaN",       ENum ( 8, _),       ENum (24,      _)])           = return $ EFloat           nan
        cvt (EApp [ECon "_",     ECon "NaN",       ENum (11, _),       ENum (53,      _)])           = return $ EDouble          nan
        cvt (EApp [ECon "_",     ECon "NaN",       ENum (eb, _),       ENum (sb,      _)])           = return $ EFloatingPoint $ fpNaN (fromIntegral eb) (fromIntegral sb)

        cvt (EApp [ECon "_",     ECon "+oo",       ENum ( 8, _),       ENum (24,      _)])           = return $ EFloat           infinity
        cvt (EApp [ECon "_",     ECon "+oo",       ENum (11, _),       ENum (53,      _)])           = return $ EDouble          infinity
        cvt (EApp [ECon "_",     ECon "+oo",       ENum (eb, _),       ENum (sb,      _)])           = return $ EFloatingPoint $ fpInf False (fromIntegral eb) (fromIntegral sb)

        cvt (EApp [ECon "_",     ECon "-oo",       ENum ( 8, _),       ENum (24,      _)])           = return $ EFloat         $ -infinity
        cvt (EApp [ECon "_",     ECon "-oo",       ENum (11, _),       ENum (53,      _)])           = return $ EDouble        $ -infinity
        cvt (EApp [ECon "_",     ECon "-oo",       ENum (eb, _),       ENum (sb,      _)])           = return $ EFloatingPoint $ fpInf True (fromIntegral eb) (fromIntegral sb)

        cvt (EApp [ECon "_",     ECon "+zero",     ENum ( 8, _),       ENum (24,      _)])           = return $ EFloat  0
        cvt (EApp [ECon "_",     ECon "+zero",     ENum (11, _),       ENum (53,      _)])           = return $ EDouble 0
        cvt (EApp [ECon "_",     ECon "+zero",     ENum (eb, _),       ENum (sb,      _)])           = return $ EFloatingPoint $ fpZero False (fromIntegral eb) (fromIntegral sb)

        cvt (EApp [ECon "_",     ECon "-zero",     ENum ( 8, _),       ENum (24,      _)])           = return $ EFloat         $ -0
        cvt (EApp [ECon "_",     ECon "-zero",     ENum (11, _),       ENum (53,      _)])           = return $ EDouble        $ -0
        cvt (EApp [ECon "_",     ECon "-zero",     ENum (eb, _),       ENum (sb,      _)])           = return $ EFloatingPoint $ fpZero True (fromIntegral eb) (fromIntegral sb)

        cvt x                                                                                        = return x

        getCoeff (EApp [ECon "*", ENum k, EApp [ECon "^", ECon "x", ENum p]]) = return (fst k, fst p)  -- kx^p
        getCoeff (EApp [ECon "*", ENum k,                 ECon "x"        ] ) = return (fst k,     1)  -- kx
        getCoeff (                        EApp [ECon "^", ECon "x", ENum p] ) = return (    1, fst p)  --  x^p
        getCoeff (                                        ECon "x"          ) = return (    1,     1)  --  x
        getCoeff (                ENum k                                    ) = return (fst k,     0)  -- k
        getCoeff x = die $ "Cannot parse a root-obj,\nProcessing term: " ++ show x
        getDouble (ECon s)  = case (s, rdFP (dropWhile (== '+') s)) of
                                ("plusInfinity",  _     ) -> return $ EDouble infinity
                                ("minusInfinity", _     ) -> return $ EDouble (-infinity)
                                ("oo",            _     ) -> return $ EDouble infinity
                                ("-oo",           _     ) -> return $ EDouble (-infinity)
                                ("zero",          _     ) -> return $ EDouble 0
                                ("-zero",         _     ) -> return $ EDouble (-0)
                                ("NaN",           _     ) -> return $ EDouble nan
                                (_,               Just v) -> return $ EDouble v
                                _               -> die $ "Cannot parse a double value from: " ++ s
        getDouble (EApp [_, s, _, _]) = getDouble s
        getDouble (EReal r) = return $ EDouble $ fromRat $ toRational r
        getDouble x         = die $ "Cannot parse a double value from: " ++ show x
        getFloat (ECon s)   = case (s, rdFP (dropWhile (== '+') s)) of
                                ("plusInfinity",  _     ) -> return $ EFloat infinity
                                ("minusInfinity", _     ) -> return $ EFloat (-infinity)
                                ("oo",            _     ) -> return $ EFloat infinity
                                ("-oo",           _     ) -> return $ EFloat (-infinity)
                                ("zero",          _     ) -> return $ EFloat 0
                                ("-zero",         _     ) -> return $ EFloat (-0)
                                ("NaN",           _     ) -> return $ EFloat nan
                                (_,               Just v) -> return $ EFloat v
                                _               -> die $ "Cannot parse a float value from: " ++ s
        getFloat (EReal r)  = return $ EFloat $ fromRat $ toRational r
        getFloat (EApp [_, s, _, _]) = getFloat s
        getFloat x          = die $ "Cannot parse a float value from: " ++ show x

-- | Parses the Z3 floating point formatted numbers like so: 1.321p5/1.2123e9 etc.
rdFP :: (Read a, RealFloat a) => String -> Maybe a
rdFP s = case break (`elem` "pe") s of
           (m, 'p':e) -> rd m >>= \m' -> rd e >>= \e' -> return $ m' * ( 2 ** e')
           (m, 'e':e) -> rd m >>= \m' -> rd e >>= \e' -> return $ m' * (10 ** e')
           (m, "")    -> rd m
           _          -> Nothing
 where rd v = case reads v of
                [(n, "")] -> Just n
                _         -> Nothing

-- | Convert an (s, e, m) triple to a float value
getTripleFloat :: Integer -> Integer -> Integer -> Float
getTripleFloat s e m = wordToFloat w32
  where sign      = [s == 1]
        expt      = [e `testBit` i | i <- [ 7,  6 .. 0]]
        mantissa  = [m `testBit` i | i <- [22, 21 .. 0]]
        positions = [i | (i, b) <- zip [31, 30 .. 0] (sign ++ expt ++ mantissa), b]
        w32       = foldr (flip setBit) (0::Word32) positions

-- | Convert an (s, e, m) triple to a float value
getTripleDouble :: Integer -> Integer -> Integer -> Double
getTripleDouble s e m = wordToDouble w64
  where sign      = [s == 1]
        expt      = [e `testBit` i | i <- [10,  9 .. 0]]
        mantissa  = [m `testBit` i | i <- [51, 50 .. 0]]
        positions = [i | (i, b) <- zip [63, 62 .. 0] (sign ++ expt ++ mantissa), b]
        w64       = foldr (flip setBit) (0::Word64) positions

-- | Special constants of SMTLib2 and their internal translation. Mainly
-- rounding modes for now.
constantMap :: String -> String
constantMap n = fromMaybe n (listToMaybe [to | (from, to) <- special, n `elem` from])
 where special = [ (["RNE", "roundNearestTiesToEven"], show RoundNearestTiesToEven)
                 , (["RNA", "roundNearestTiesToAway"], show RoundNearestTiesToAway)
                 , (["RTP", "roundTowardPositive"],    show RoundTowardPositive)
                 , (["RTN", "roundTowardNegative"],    show RoundTowardNegative)
                 , (["RTZ", "roundTowardZero"],        show RoundTowardZero)
                 ]

-- | Parse a function like value. These come in two flavors: Either in the form of
-- a store-expression or a lambda-expression. So we handle both here.
parseSExprFunction :: SExpr -> Maybe (Either String ([([SExpr], SExpr)], SExpr))
parseSExprFunction e
  | Just r <- parseLambdaExpression  e = Just (Right r)
  | Just r <- parseSetLambda         e = Just (Right r)
  | Just r <- parseStoreAssociations e = Just r
  | True                               = Nothing         -- out-of luck. NB. This is where we would add support for other solvers!

-- | Parse a set-lambda expression, which is literally a lambda function, that might look like this:
--        (lambda ((x!1 String))
--          (or (not (or (= x!1 "o") (= x!1 "l") (= x!1 "e") (= x!1 "h")))
--              (= x!1 "o")
--              (= x!1 "l")
--              (= x!1 "e")
--              (= x!1 "h")))
--   For this, we do a little bit of an interpretative dance to see if we can "construct" the necesary expression.
--
--   In parsed form:
--      EApp [ECon "lambda",EApp [EApp [ECon "x!1",ECon "String"]],EApp [ECon "not",EApp [ECon "or",EApp [ECon "=",ECon "x!1",ECon "\"e\""],EApp [ECon "=",ECon "x!1",ECon "\"l\""]]]]
--
--   This is by no means comprehensive, and is quite crude, but hopefully covers the cases we see in practice.
parseSetLambda :: SExpr -> Maybe ([([SExpr], SExpr)], SExpr)
parseSetLambda funExpr = case funExpr of
                               EApp [l@(ECon "lambda"), bv@(EApp [EApp [ECon _, _]]), body] -> go (\bd -> EApp [l, bv, bd]) body
                               _                                                            -> Nothing
  where go mkLambda = build
         where build (EApp [ECon "not",  rest      ]) =         neg =<<      build rest
               build (EApp (ECon "or"  : rest@(_:_))) = foldM1 disj =<< mapM build rest
               build (EApp (ECon "and" : rest@(_:_))) = foldM1 conj =<< mapM build rest
               build other                            = parseLambdaExpression (mkLambda other)

        -- We're guaranteed by above construction that foldM1 will never take an empty list (due to rest@(_:_) pattern match.)
        foldM1 _ []     = error "Data.SBV.parseSetLambda: Impossible happened; empty arg to foldM1"
        foldM1 f (x:xs) = foldM f x xs

        checkBool (ENum (1, Nothing)) = True
        checkBool (ENum (0, Nothing)) = True
        checkBool _                   = False

        negBool (ENum (1, Nothing)) = ENum (0, Nothing)
        negBool _                   = ENum (1, Nothing)

        orBool t@(ENum (1, Nothing)) _                      = t
        orBool _                     t@(ENum (1, Nothing))  = t
        orBool _ _                                          = ENum (0, Nothing)

        andBool f@(ENum (0, Nothing)) _                     = f
        andBool _                     f@(ENum (0, Nothing)) = f
        andBool _ _                                         = ENum (1, Nothing)

        neg :: ([([SExpr], SExpr)], SExpr) -> Maybe ([([SExpr], SExpr)], SExpr)
        neg (rows, dflt)
         | all checkBool (dflt : map snd rows) = Just ([(e, negBool r) | (e, r) <- rows], negBool dflt)
         | True                                = Nothing

        disj, conj :: ([([SExpr], SExpr)], SExpr) -> ([([SExpr], SExpr)], SExpr) -> Maybe ([([SExpr], SExpr)], SExpr)
        disj = bin orBool
        conj = bin andBool

        bin f rd1@(rows1, dflt1) rd2@(rows2, dflt2)
          | all checkBool (dflt1 : dflt2 : map snd rows1 ++ map snd rows2) = Just (combine f rd1 rd2)
          | True                                                           = Nothing

        -- Since we don't have equality over SExprs (can of worms!), we use "show" equality here. The ice is thin, but it works!
        combine f (rows1, dflt1) (rows2, dflt2) = (rows, f dflt1 dflt2)
          where rows = map calc $ nubBy (\x y -> show x == show y) (map fst rows1 ++ map fst rows2)

                calc :: [SExpr] -> ([SExpr], SExpr)
                calc args = (args, f (find rows1 dflt1 args) (find rows2 dflt2 args))

                find rs d a = case [r | (v, r) <- rs, show v == show a] of
                               []  -> d
                               [x] -> x
                               x   -> error $ unlines [ "Data.SBV.parseSetLambda: Impossible happened while combining rows."
                                                      , "   First row  :"   ++ show rows1
                                                      , "   First dflt :"  ++ show dflt1
                                                      , "   Second row :"  ++ show rows2
                                                      , "   Second dflt:" ++ show dflt2
                                                      , "   Looking for: " ++ show a
                                                      , "Multiple matches found: " ++ show x
                                                      ]

-- | Parse a lambda expression, most likely z3 specific. There's some guess work
-- involved here regarding how z3 produces lambda-expressions; while we try to
-- be flexible, this is certainly not a full fledged parser. But hopefully it'll
-- cover everything z3 will throw at it.
parseLambdaExpression :: SExpr -> Maybe ([([SExpr], SExpr)], SExpr)
parseLambdaExpression funExpr = case funExpr of
                                  EApp [ECon "lambda", EApp params, body] -> mapM getParam params >>= flip lambda body >>= chainAssigns
                                  _                                       -> Nothing
  where getParam (EApp [ECon v, ECon ty]) = Just (v, ty == "Bool")
        getParam (EApp [ECon v, _      ]) = Just (v, False)
        getParam _                        = Nothing

        lambda :: [(String, Bool)]  -- Bool is True if this is a boolean variable. Otherwise we don't keep track of the type
               -> SExpr -> Maybe [Either ([SExpr], SExpr) SExpr]
        lambda params body = reverse <$> go [] body
          where true  = ENum (1, Nothing)
                false = ENum (0, Nothing)

                go :: [Either ([SExpr], SExpr) SExpr] -> SExpr -> Maybe [Either ([SExpr], SExpr) SExpr]
                go sofar (EApp [ECon "ite", selector, thenBranch, elseBranch])
                  = do s  <- select selector
                       tB <- go [] thenBranch
                       case cond s tB of
                          Just sv -> go (Left sv : sofar) elseBranch
                          _       -> Nothing

                -- Catch cases like: x = a)
                go sofar inner@(EApp [ECon "=", _, _])
                  = go sofar (EApp [ECon "ite", inner, true, false])

                -- Catch cases like: not x
                go sofar (EApp [ECon "not", inner])
                  = go sofar (EApp [ECon "ite", inner, false, true])

                -- Catch (or x y z..)
                go sofar (EApp (ECon "or" : elts))
                  = let xform []     = false
                        xform [x]    = x
                        xform (x:xs) = EApp [ECon "ite", x, true, xform xs]
                    in go sofar $ xform elts

                -- Catch (and x y z..)
                go sofar (EApp (ECon "and" : elts))
                  = let xform []     = true
                        xform [x]    = x
                        xform (x:xs) = EApp [ECon "ite", x, xform xs, false]
                    in go sofar $ xform elts

                -- z3 sometimes puts together a bunch of booleans as final expression,
                -- see if we can catch that.
                go sofar e
                 | Just s <- select e
                 = go (Left (s, true) : sofar) false

                -- Otherwise, just treat it as an "unknown" arbitrary expression
                -- as the default. It could be something arbitrary of course, but it's
                -- too complicated to parse; and hopefully this is good enough.
                go sofar e = Just $ Right e : sofar

                cond :: [SExpr] -> [Either ([SExpr], SExpr) SExpr] -> Maybe ([SExpr], SExpr)
                cond s [Right v] = Just (s, v)
                cond _ _         = Nothing

                -- select takes the condition of an ite, and returns precisely what match is done to the parameters
                select :: SExpr -> Maybe [SExpr]
                select e
                   | Just dict <- build e [] = mapM (`lookup` dict) paramNames
                   | True                    = Nothing
                  where paramNames = map fst params

                        -- build a dictionary of assignments from the scrutinee
                        build :: SExpr -> [(String, SExpr)] -> Maybe [(String, SExpr)]
                        build (EApp (ECon "and" : rest)) sofar = let next _ Nothing  = Nothing
                                                                     next c (Just x) = build c x
                                                                 in foldr next (Just sofar) rest

                        build expr sofar | Just (v, r) <- grok expr, v `elem` paramNames = Just $ (v, r) : sofar
                                         | True                                          = Nothing

                        -- See if we can figure out what z3 is telling us; hopefully this
                        -- mapping covers everything we can see:
                        grok (EApp [ECon "=", ECon v, r]) = Just (v, r)
                        grok (EApp [ECon "=", r, ECon v]) = Just (v, r)
                        grok (EApp [ECon "not", ECon v])  = Just (v, false) -- boolean negation, require it to be false
                        grok (ECon v)                     = case v `lookup` params of
                                                               Just True -> Just (v, true)  -- boolean identity, require it to be true
                                                               _         -> Nothing

                        -- Tough luck, we couldn't understand:
                        grok _ = Nothing

-- | Parse a series of associations in the array notation, things that look like:
--
--     (store (store ((as const Array) 12) 3 5 9) 5 6 75)
--
-- This is (most likely) entirely Z3 specific. So, we might have to tweak it for other
-- solvers; though it isn't entirely clear how to do that as we do not know what solver
-- we're using here. The trick is to handle all of possible SExpr's we see.
-- We'll cross that bridge when we get to it.
--
-- NB. In case there's no "constraint" on the UI, Z3 produces the self-referential model:
--
--    (x (_ as-array x))
--
-- So, we specifically handle that here, by returning a Left of that name.
parseStoreAssociations :: SExpr -> Maybe (Either String ([([SExpr], SExpr)], SExpr))
parseStoreAssociations (EApp [ECon "_", ECon "as-array", ECon nm]) = Just $ Left nm
parseStoreAssociations e                                           = Right <$> (chainAssigns =<< vals e)
    where vals :: SExpr -> Maybe [Either ([SExpr], SExpr) SExpr]
          vals (EApp [EApp [ECon "as", ECon "const", ECon "Array"],            defVal]) = return [Right defVal]
          vals (EApp [EApp [ECon "as", ECon "const", EApp (ECon "Array" : _)], defVal]) = return [Right defVal]
          vals (EApp (ECon "store" : prev : argsVal)) | length argsVal >= 2             = do rest <- vals prev
                                                                                             return $ Left (init argsVal, last argsVal) : rest
          vals _                                                                        = Nothing

-- | Turn a sequence of left-right chain assignments (condition + free) into a single chain
chainAssigns :: [Either ([SExpr], SExpr) SExpr] -> Maybe ([([SExpr], SExpr)], SExpr)
chainAssigns chain = regroup $ partitionEithers chain
  where regroup (vs, [d]) = Just (checkDup vs, d)
        regroup _         = Nothing

        -- If we get into a case like this:
        --
        --     (store (store a 1 2) 1 3)
        --
        -- then we need to drop the 1->2 assignment!
        --
        -- The way we parse these, the first assignment wins.
        checkDup :: [([SExpr], SExpr)] -> [([SExpr], SExpr)]
        checkDup []              = []
        checkDup (a@(key, _):as) = a : checkDup [r | r@(key', _) <- as, not (key `sameKey` key')]

        sameKey :: [SExpr] -> [SExpr] -> Bool
        sameKey as bs
          | length as == length bs = and $ zipWith same as bs
          | True                   = error $ "Data.SBV: Differing length of key received in chainAssigns: " ++ show (as, bs)

        -- We don't want to derive Eq; as this is more careful on floats and such
        same :: SExpr -> SExpr -> Bool
        same x y = case (x, y) of
                     (ECon a,      ECon b)       -> a == b
                     (ENum (i, _), ENum (j, _))  -> i == j
                     (EReal a,     EReal b)      -> algRealStructuralEqual a b
                     (EFloat  f1,  EFloat  f2)   -> fpIsEqualObjectH f1 f2
                     (EDouble d1,  EDouble d2)   -> fpIsEqualObjectH d1 d2
                     (EApp as,     EApp bs)      -> length as == length bs && and (zipWith same as bs)
                     (e1,          e2)           -> if eRank e1 == eRank e2
                                                    then error $ "Data.SBV: You've found a bug in SBV! Please report: SExpr(same): " ++ show (e1, e2)
                                                    else False
        -- Defensive programming: It's too long to list all pair up, so we use this function and
        -- GHC's pattern-match completion warning to catch cases we might've forgotten. If
        -- you ever get the error line above fire, because you must've disabled the pattern-match
        -- completion check warning! Shame on you.
        eRank :: SExpr -> Int
        eRank ECon{}           = 0
        eRank ENum{}           = 1
        eRank EReal{}          = 2
        eRank EFloat{}         = 3
        eRank EFloatingPoint{} = 4
        eRank EDouble{}        = 5
        eRank EApp{}           = 6

-- Turn
--  "((F (lambda ((x!1 Int)) (+ 3 (* 2 x!1)))))"
---  into
--  "F x = 3 + 2 * x"
-- if we can. We try but don't push too hard! This is only used for display purposes.
--
-- This isn't very fool-proof; can be confused if there are binding constructs etc.
-- Also, the generated text isn't necessarily fully Haskell acceptable.
-- But it seems to do an OK job for most common use cases.
makeHaskellFunction :: String -> String -> Maybe [String] -> Maybe String
makeHaskellFunction resp nm mbArgs
   = case parseSExpr resp of
       Right (EApp [EApp [ECon o, e]]) | o == nm -> do (args, bd) <- lambda e
                                                       return $ unwords (nm : args) ++ " = " ++ bd
       _                                         -> Nothing

  where -- infinite supply of names; starting with the ones we're given
        preSupply = fromMaybe [] mbArgs

        extras =  ["x", "y", "z"]
               ++ [[c] | c <- ['a' .. 'z'], c < 'x']
               ++ ['x' : show i | i <- [(1::Int) ..]]

        mkUnique x | x `elem` preSupply = mkUnique $ x ++ "'"
                   | True               = x

        supply = preSupply ++ map mkUnique extras

        lambda :: SExpr -> Maybe ([String], String)
        lambda (EApp [ECon "lambda", EApp args, bd]) = do as <- mapM getArg args
                                                          let env = zip as supply
                                                          pure (map snd env, body env bd)
        lambda _                                     = Nothing

        getArg (EApp [ECon argName, _]) = Just argName
        getArg _                        = Nothing

        body env = go
          where go :: SExpr -> String
                go (ECon n) | Just a <- lookup n env = a
                            | True                   = n

                go (ENum (i, _))      = show i
                go (EReal  a)         = show a
                go (EFloat f)         = show f
                go (EFloatingPoint f) = show f
                go (EDouble f)        = show f
                go (EApp xs)          = app (map (wrap . go) xs)

                parens x = '(' : x ++ ")"

                wrap x | "-" `isPrefixOf` x = parens x
                       | any isSpace x      = parens x
                       | True               = x

                mkBin o a b = wrap a ++ " " ++ o ++ " " ++ wrap b

                isPlus  = (`elem` ["+",  "bvadd"])
                isTimes = (`elem` ["*",  "bvmul"])
                isLT    = (`elem` ["<",  "bvult", "bvslt", "fp.lt" ])
                isLTE   = (`elem` ["<=", "bvule", "bvsle", "fp.leq"])
                isGT    = (`elem` [">",  "bvugt", "bvsgt", "fp.gt" ])
                isGTE   = (`elem` [">=", "bvuge", "bvsge", "fp.gte"])

                -- Make an application, with some simplifications
                app :: [String] -> String
                app (o : xs) | isPlus o = intercalate " + " xs

                -- multiplication of arbitrary elements, with proviso for multiplication by -1
                app [m, "(-1)", x] | isTimes m = '-' : x
                app (m  : xs)      | isTimes m = intercalate " * " xs

                -- binary arith ops
                app ["-",  a, b] = mkBin "-"  a b
                app ["/",  a, b] = mkBin "/"  a b

                app [o, a, b] | isLT  o = mkBin "<"  a b
                app [o, a, b] | isLTE o = mkBin "<=" a b
                app [o, a, b] | isGT  o = mkBin ">"  a b
                app [o, a, b] | isGTE o = mkBin ">=" a b

                -- give up, and just do prefix!
                app xs = unwords xs

{- HLint ignore chainAssigns "Redundant if" -}