packages feed

hsmt-0.1.0.0: src/HSMT/API/Expr.hs

{-# LANGUAGE AllowAmbiguousTypes #-}
-- Some constraints (e.g. @1 <= n@ or the bounds of 'bvExtract') are not
-- needed by the implementation: they exist only to reject ill-formed
-- expressions at compile time.
{-# OPTIONS_GHC -Wno-redundant-constraints #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE UndecidableInstances #-}

-- | Typed expressions.
--
-- @Expr ctx s@ is an expression of sort @s@ belonging to the solver instance
-- @ctx@ (see 'HSMT.API.Monad.runSMT'). Only well-sorted expressions can be
-- built: sort errors are Haskell type errors.
module HSMT.API.Expr
  ( Expr (..)
    -- * Booleans
  , true
  , false
  , bool
  , notB
  , (.&&)
  , (.||)
  , (.=>)
  , xorB
  , andB
  , orB
  , ite
  , (.==)
  , (./=)
  , distinct
    -- * Integers
  , int
  , (.<)
  , (.<=)
  , (.>)
  , (.>=)
  , idiv
  , imod
    -- * Bit-vectors
  , bv
  , bvNot
  , bvAnd
  , bvOr
  , bvXor
  , bvNeg
  , bvAdd
  , bvSub
  , bvMul
  , bvUDiv
  , bvURem
  , bvSDiv
  , bvSRem
  , bvSMod
  , bvShl
  , bvLShr
  , bvAShr
  , bvConcat
  , bvExtract
  , bvZeroExtend
  , bvSignExtend
  , bvULt
  , bvULe
  , bvUGt
  , bvUGe
  , bvSLt
  , bvSLe
  , bvSGt
  , bvSGe
    -- * Arrays
  , select
  , store
  , constArray
    -- * Strings
  , str
  , (<+>)
  , strLen
  , strAt
  , substr
  , contains
  , prefixOf
  , suffixOf
  , indexOf
  , replace
  , strToInt
  , strFromInt
  , strLt
  , strLe
    -- * Regular expressions
  , toRe
  , inRe
  , reNone
  , reAll
  , reAllChar
  , reRange
  , reConcat
  , reUnion
  , reInter
  , reStar
  , rePlus
  , reOpt
  , reComp
  , reDiff
  , reLoop
  , rePower
    -- * Floating point
  , rne
  , rna
  , rtp
  , rtn
  , rtz
  , roundingMode
  , fpValue
  , fpLit
  , fpNaN
  , fpInf
  , fpZero
  , fpFromFields
  , fpFromBV
  , fpAbs
  , fpNeg
  , fpAdd
  , fpSub
  , fpMul
  , fpDiv
  , fpFma
  , fpSqrt
  , fpRem
  , fpRoundToIntegral
  , fpMin
  , fpMax
  , fpLeq
  , fpLt
  , fpGeq
  , fpGt
  , fpEq
  , fpIsNormal
  , fpIsSubnormal
  , fpIsZero
  , fpIsInfinite
  , fpIsNaN
  , fpIsNegative
  , fpIsPositive
  , toFP
  , sbvToFP
  , ubvToFP
  , fpToUBV
  , fpToSBV
    -- * Records
  , Label (..)
  , Field (..)
  , Fields (..)
  , record
  , (!)
  , getField
  , setField
    -- * Uninterpreted functions
  , Fn
  , CurryFn (..)
  ) where

import Data.Kind (Type)
import Data.Proxy (Proxy (..))
import Data.String (IsString (..))
import Data.Text (Text)
import qualified Data.Text as T
import GHC.OverloadedLabels (IsLabel (..))
import GHC.TypeLits

import HSMT.API.Sort
import qualified HSMT.Core.Expr as C
import qualified HSMT.Core.Float as F
import HSMT.Core.Op (Op (..))
import qualified HSMT.Core.Value as C

-- | A typed expression. The constructor is internal; use the smart
-- constructors in this module.
--
-- t'Eq' and t'Ord' compare expressions structurally (for instance to look
-- for an assertion in an unsatisfiable core); use '.==' for the equality
-- of the logic.
newtype Expr (ctx :: Type) (s :: Sort) = Expr {unExpr :: C.Expr}
  deriving (Eq, Ord)

instance Show (Expr ctx s) where
  show (Expr e) = show e

op0 :: Op -> Expr ctx s
op0 o = Expr (C.App o [])

op1 :: Op -> Expr ctx a -> Expr ctx s
op1 o (Expr a) = Expr (C.App o [a])

op2 :: Op -> Expr ctx a -> Expr ctx b -> Expr ctx s
op2 o (Expr a) (Expr b) = Expr (C.App o [a, b])

op3 :: Op -> Expr ctx a -> Expr ctx b -> Expr ctx c -> Expr ctx s
op3 o (Expr a) (Expr b) (Expr c) = Expr (C.App o [a, b, c])

opN :: Op -> [Expr ctx a] -> Expr ctx s
opN o es = Expr (C.App o (map unExpr es))

-------------------------------------------------------------------------------
-- Booleans

infixr 3 .&&
infixr 2 .||
infixr 1 .=>
infix 4 .==, ./=, .<, .<=, .>, .>=

-- | The Boolean constant true.
true :: Expr ctx 'BoolS
true = bool True

-- | The Boolean constant false.
false :: Expr ctx 'BoolS
false = bool False

-- | A Boolean literal.
bool :: Bool -> Expr ctx 'BoolS
bool = op0 . BoolConst

-- | Negation.
notB :: Expr ctx 'BoolS -> Expr ctx 'BoolS
notB = op1 Not

-- | Conjunction.
(.&&) :: Expr ctx 'BoolS -> Expr ctx 'BoolS -> Expr ctx 'BoolS
(.&&) = op2 And

-- | Disjunction.
(.||) :: Expr ctx 'BoolS -> Expr ctx 'BoolS -> Expr ctx 'BoolS
(.||) = op2 Or

-- | Implication (right associative).
(.=>) :: Expr ctx 'BoolS -> Expr ctx 'BoolS -> Expr ctx 'BoolS
(.=>) = op2 Implies

-- | Exclusive or.
xorB :: Expr ctx 'BoolS -> Expr ctx 'BoolS -> Expr ctx 'BoolS
xorB = op2 Xor

-- | Conjunction of a list (true when empty).
andB :: [Expr ctx 'BoolS] -> Expr ctx 'BoolS
andB = opN And

-- | Disjunction of a list (false when empty).
orB :: [Expr ctx 'BoolS] -> Expr ctx 'BoolS
orB = opN Or

-- | @ite c t e@ is @t@ when @c@ holds and @e@ otherwise, for any sort.
ite :: Expr ctx 'BoolS -> Expr ctx s -> Expr ctx s -> Expr ctx s
ite = op3 Ite

-- | Equality, for any sort (extensional for arrays, field-wise for
-- records; for floating point it is the identity of values, see 'fpEq').
(.==) :: Expr ctx s -> Expr ctx s -> Expr ctx 'BoolS
(.==) = op2 Eq

-- | Disequality: @a ./= b = notB (a .== b)@.
(./=) :: Expr ctx s -> Expr ctx s -> Expr ctx 'BoolS
a ./= b = notB (a .== b)

-- | Pairwise distinctness. Lists with fewer than two elements are trivially
-- distinct.
distinct :: [Expr ctx s] -> Expr ctx 'BoolS
distinct es
  | length es < 2 = true
  | otherwise = opN Distinct es

-------------------------------------------------------------------------------
-- Integers

-- | An integer literal. Integer literals can also be written directly,
-- through the 'Num' instance.
int :: Integer -> Expr ctx 'IntS
int = op0 . IntConst

-- | Integer arithmetic. Multiplication is supported by the solver only when
-- one of the factors is a constant; other products make 'HSMT.checkSat'
-- answer unknown.
instance Num (Expr ctx 'IntS) where
  fromInteger = int
  (+) = op2 Add
  (-) = op2 Sub
  (*) = op2 Mul
  negate = op1 Neg
  abs = op1 Abs
  signum x = ite (x .> 0) 1 (ite (x .< 0) (-1) 0)

-- | Integer less than.
(.<) :: Expr ctx 'IntS -> Expr ctx 'IntS -> Expr ctx 'BoolS
(.<) = op2 Lt

-- | Integer less than or equal.
(.<=) :: Expr ctx 'IntS -> Expr ctx 'IntS -> Expr ctx 'BoolS
(.<=) = op2 Le

-- | Integer greater than.
(.>) :: Expr ctx 'IntS -> Expr ctx 'IntS -> Expr ctx 'BoolS
(.>) = op2 Gt

-- | Integer greater than or equal.
(.>=) :: Expr ctx 'IntS -> Expr ctx 'IntS -> Expr ctx 'BoolS
(.>=) = op2 Ge

-- | Euclidean division (SMT-LIB @div@): the remainder 'imod' is never
-- negative. The divisor must be a constant for the solver; division by
-- zero is unspecified (an uninterpreted function of the dividend).
idiv :: Expr ctx 'IntS -> Expr ctx 'IntS -> Expr ctx 'IntS
idiv = op2 IntDiv

-- | Euclidean remainder (SMT-LIB @mod@), between 0 and the absolute value
-- of the divisor minus one.
imod :: Expr ctx 'IntS -> Expr ctx 'IntS -> Expr ctx 'IntS
imod = op2 IntMod

-------------------------------------------------------------------------------
-- Bit-vectors

widthOf :: forall n. KnownNat n => Int
widthOf = fromIntegral (natVal (Proxy @n))

-- | A bit-vector literal; the integer is taken modulo @2^n@, so negative
-- numbers give their two's complement representation.
bv :: forall n ctx. (KnownNat n, 1 <= n) => Integer -> Expr ctx ('BVS n)
bv x = let w = widthOf @n in op0 (BVConst w (C.bvNormalize w x))

-- | Arithmetic is modulo @2^n@; 'abs' and 'signum' use the signed
-- interpretation.
instance (KnownNat n, 1 <= n) => Num (Expr ctx ('BVS n)) where
  fromInteger = bv
  (+) = bvAdd
  (-) = bvSub
  (*) = bvMul
  negate = bvNeg
  abs x = ite (bvSLt x 0) (bvNeg x) x
  signum x = ite (bvSGt x 0) 1 (ite (bvSLt x 0) (bv (-1)) 0)

type BVUn n = forall ctx. Expr ctx ('BVS n) -> Expr ctx ('BVS n)

type BVBin n = forall ctx. Expr ctx ('BVS n) -> Expr ctx ('BVS n) -> Expr ctx ('BVS n)

type BVCmp n = forall ctx. Expr ctx ('BVS n) -> Expr ctx ('BVS n) -> Expr ctx 'BoolS

-- | Bitwise complement.
bvNot :: BVUn n
bvNot = op1 BVNot

-- | Two's complement negation.
bvNeg :: BVUn n
bvNeg = op1 BVNeg

-- | Bitwise and.
bvAnd :: BVBin n
bvAnd = op2 BVAnd

-- | Bitwise or.
bvOr :: BVBin n
bvOr = op2 BVOr

-- | Bitwise exclusive or.
bvXor :: BVBin n
bvXor = op2 BVXor

-- | Addition modulo @2^n@.
bvAdd :: BVBin n
bvAdd = op2 BVAdd

-- | Subtraction modulo @2^n@.
bvSub :: BVBin n
bvSub = op2 BVSub

-- | Multiplication modulo @2^n@.
bvMul :: BVBin n
bvMul = op2 BVMul

-- | Unsigned division; division by zero gives all ones, as in SMT-LIB.
bvUDiv :: BVBin n
bvUDiv = op2 BVUDiv

-- | Unsigned remainder; the remainder of a division by zero is the dividend.
bvURem :: BVBin n
bvURem = op2 BVURem

-- | Signed division, rounding towards zero.
bvSDiv :: BVBin n
bvSDiv = op2 BVSDiv

-- | Signed remainder, with the sign of the dividend.
bvSRem :: BVBin n
bvSRem = op2 BVSRem

-- | Signed modulo, with the sign of the divisor.
bvSMod :: BVBin n
bvSMod = op2 BVSMod

-- | Shift left by the (unsigned) value of the second argument.
bvShl :: BVBin n
bvShl = op2 BVShl

-- | Logical shift right (filling with zeros).
bvLShr :: BVBin n
bvLShr = op2 BVLShr

-- | Arithmetic shift right (filling with the sign bit).
bvAShr :: BVBin n
bvAShr = op2 BVAShr

-- | Unsigned less than.
bvULt :: BVCmp n
bvULt = op2 BVULt

-- | Unsigned less than or equal.
bvULe :: BVCmp n
bvULe = op2 BVULe

-- | Unsigned greater than.
bvUGt :: BVCmp n
bvUGt = op2 BVUGt

-- | Unsigned greater than or equal.
bvUGe :: BVCmp n
bvUGe = op2 BVUGe

-- | Signed (two's complement) less than.
bvSLt :: BVCmp n
bvSLt = op2 BVSLt

-- | Signed less than or equal.
bvSLe :: BVCmp n
bvSLe = op2 BVSLe

-- | Signed greater than.
bvSGt :: BVCmp n
bvSGt = op2 BVSGt

-- | Signed greater than or equal.
bvSGe :: BVCmp n
bvSGe = op2 BVSGe

-- | Concatenation; the first argument gives the most significant bits.
bvConcat :: Expr ctx ('BVS n) -> Expr ctx ('BVS m) -> Expr ctx ('BVS (n + m))
bvConcat = op2 BVConcat

-- | @bvExtract \@hi \@lo x@ selects bits @hi@ down to @lo@ of @x@.
bvExtract
  :: forall hi lo n ctx
   . (KnownNat hi, KnownNat lo, lo <= hi, hi + 1 <= n)
  => Expr ctx ('BVS n)
  -> Expr ctx ('BVS (hi - lo + 1))
bvExtract = op1 (BVExtract (widthOf @hi) (widthOf @lo))

-- | Extend with @k@ zero bits.
bvZeroExtend :: forall k n ctx. KnownNat k => Expr ctx ('BVS n) -> Expr ctx ('BVS (n + k))
bvZeroExtend = op1 (BVZeroExtend (widthOf @k))

-- | Extend with @k@ copies of the sign bit.
bvSignExtend :: forall k n ctx. KnownNat k => Expr ctx ('BVS n) -> Expr ctx ('BVS (n + k))
bvSignExtend = op1 (BVSignExtend (widthOf @k))

-------------------------------------------------------------------------------
-- Arrays

-- | The element at an index.
select :: Expr ctx ('ArrayS i e) -> Expr ctx i -> Expr ctx e
select = op2 Select

-- | @store a i v@ is the array equal to @a@ except at @i@, where it is @v@.
store :: Expr ctx ('ArrayS i e) -> Expr ctx i -> Expr ctx e -> Expr ctx ('ArrayS i e)
store = op3 Store

-- | The array mapping every index to the given value.
constArray :: forall i e ctx. KnownSort i => Expr ctx e -> Expr ctx ('ArrayS i e)
constArray = op1 (ConstArray (sortRep @i))

-------------------------------------------------------------------------------
-- Strings

-- | A string literal. With @OverloadedStrings@, literals can be written
-- directly, through the 'IsString' instance.
str :: Text -> Expr ctx 'StringS
str = op0 . StrConst

instance IsString (Expr ctx 'StringS) where
  fromString = str . T.pack

infixr 5 <+>

-- | String concatenation.
(<+>) :: Expr ctx 'StringS -> Expr ctx 'StringS -> Expr ctx 'StringS
(<+>) = op2 StrConcat

-- | The length of a string, in characters (code points).
strLen :: Expr ctx 'StringS -> Expr ctx 'IntS
strLen = op1 StrLen

-- | The one-character string at a position (empty if out of range).
strAt :: Expr ctx 'StringS -> Expr ctx 'IntS -> Expr ctx 'StringS
strAt = op2 StrAt

-- | @substr s offset length@.
substr :: Expr ctx 'StringS -> Expr ctx 'IntS -> Expr ctx 'IntS -> Expr ctx 'StringS
substr = op3 StrSubstr

-- | @contains s t@ holds when @t@ occurs in @s@.
contains :: Expr ctx 'StringS -> Expr ctx 'StringS -> Expr ctx 'BoolS
contains = op2 StrContains

-- | @prefixOf s t@ holds when @s@ is a prefix of @t@.
prefixOf :: Expr ctx 'StringS -> Expr ctx 'StringS -> Expr ctx 'BoolS
prefixOf = op2 StrPrefixOf

-- | @suffixOf s t@ holds when @s@ is a suffix of @t@.
suffixOf :: Expr ctx 'StringS -> Expr ctx 'StringS -> Expr ctx 'BoolS
suffixOf = op2 StrSuffixOf

-- | @indexOf s t i@: first position of @t@ in @s@ at or after @i@, or -1.
indexOf :: Expr ctx 'StringS -> Expr ctx 'StringS -> Expr ctx 'IntS -> Expr ctx 'IntS
indexOf = op3 StrIndexOf

-- | @replace s t t'@ replaces the first occurrence of @t@ in @s@ by @t'@.
replace :: Expr ctx 'StringS -> Expr ctx 'StringS -> Expr ctx 'StringS -> Expr ctx 'StringS
replace = op3 StrReplace

-- | The natural number written by a string of decimal digits, or -1 when
-- the string is empty or has another character.
strToInt :: Expr ctx 'StringS -> Expr ctx 'IntS
strToInt = op1 StrToInt

-- | The decimal representation of a natural number, or the empty string
-- for negative numbers.
strFromInt :: Expr ctx 'IntS -> Expr ctx 'StringS
strFromInt = op1 StrFromInt

-- | Lexicographic order by code point, strict.
strLt :: Expr ctx 'StringS -> Expr ctx 'StringS -> Expr ctx 'BoolS
strLt = op2 StrLt

-- | Lexicographic order by code point, reflexive.
strLe :: Expr ctx 'StringS -> Expr ctx 'StringS -> Expr ctx 'BoolS
strLe = op2 StrLe

-------------------------------------------------------------------------------
-- Regular expressions

-- | @str.to_re@: the language of one string. The string must be a literal
-- (or a term built from literals): the solver answers unknown for
-- regular expressions that depend on variables. With @OverloadedStrings@,
-- string literals can be used directly as regular expressions.
toRe :: Expr ctx 'StringS -> Expr ctx 'RegLanS
toRe = op1 StrToRe

instance IsString (Expr ctx 'RegLanS) where
  fromString = toRe . str . T.pack

-- | @inRe s r@ holds when the string @s@ belongs to the language @r@.
inRe :: Expr ctx 'StringS -> Expr ctx 'RegLanS -> Expr ctx 'BoolS
inRe = op2 StrInRe

-- | The empty language.
reNone :: Expr ctx 'RegLanS
reNone = op0 ReNone

-- | The language of all strings.
reAll :: Expr ctx 'RegLanS
reAll = op0 ReAll

-- | The language of all one-character strings.
reAllChar :: Expr ctx 'RegLanS
reAllChar = op0 ReAllChar

-- | The one-character strings between two characters (by code point).
reRange :: Char -> Char -> Expr ctx 'RegLanS
reRange a b = op2 ReRange (str (T.singleton a)) (str (T.singleton b))

-- | Concatenation of a list of languages (the empty string when empty).
reConcat :: [Expr ctx 'RegLanS] -> Expr ctx 'RegLanS
reConcat = \case
  [] -> toRe (str "")
  [r] -> r
  rs -> opN ReConcat rs

-- | Union of a list of languages (the empty language when empty).
reUnion :: [Expr ctx 'RegLanS] -> Expr ctx 'RegLanS
reUnion = \case
  [] -> reNone
  [r] -> r
  rs -> opN ReUnion rs

-- | Intersection of a list of languages (all strings when empty).
reInter :: [Expr ctx 'RegLanS] -> Expr ctx 'RegLanS
reInter = \case
  [] -> reAll
  [r] -> r
  rs -> opN ReInter rs

-- | Kleene star: zero or more repetitions.
reStar :: Expr ctx 'RegLanS -> Expr ctx 'RegLanS
reStar = op1 ReStar

-- | One or more repetitions.
rePlus :: Expr ctx 'RegLanS -> Expr ctx 'RegLanS
rePlus = op1 RePlus

-- | Zero or one occurrence.
reOpt :: Expr ctx 'RegLanS -> Expr ctx 'RegLanS
reOpt = op1 ReOpt

-- | Complement: the strings not in the language.
reComp :: Expr ctx 'RegLanS -> Expr ctx 'RegLanS
reComp = op1 ReComp

-- | Difference: the strings of the first language not in the second.
reDiff :: Expr ctx 'RegLanS -> Expr ctx 'RegLanS -> Expr ctx 'RegLanS
reDiff = op2 ReDiff

-- | @reLoop i j r@: between @i@ and @j@ repetitions of @r@ (both
-- non-negative).
reLoop :: Int -> Int -> Expr ctx 'RegLanS -> Expr ctx 'RegLanS
reLoop i j = op1 (ReLoop (max 0 i) (max 0 j))

-- | @rePower n r@: exactly @n@ repetitions of @r@ (non-negative).
rePower :: Int -> Expr ctx 'RegLanS -> Expr ctx 'RegLanS
rePower n = op1 (RePower (max 0 n))

-------------------------------------------------------------------------------
-- Floating point

-- | Rounding modes: to nearest (ties to even, ties away from zero), towards
-- positive and negative infinity, and towards zero.
rne, rna, rtp, rtn, rtz :: Expr ctx 'RoundingModeS
rne = roundingMode RNE
rna = roundingMode RNA
rtp = roundingMode RTP
rtn = roundingMode RTN
rtz = roundingMode RTZ

-- | A rounding mode literal.
roundingMode :: RoundingMode -> Expr ctx 'RoundingModeS
roundingMode = op0 . RMConst

fpFormat :: forall eb sb. (KnownNat eb, KnownNat sb) => (Int, Int)
fpFormat = (widthOf @eb, widthOf @sb)

-- | A floating-point literal.
fpLit :: forall eb sb ctx. (KnownNat eb, KnownNat sb) => FloatingPoint eb sb -> Expr ctx ('FPS eb sb)
fpLit (FloatingPoint x) = let (eb, sb) = fpFormat @eb @sb in op0 (FPConst eb sb (F.canonicalize eb sb x))

-- | The literal nearest to a rational number (ties to even).
fpValue :: forall eb sb ctx. (KnownNat eb, KnownNat sb) => Rational -> Expr ctx ('FPS eb sb)
fpValue r = fpLit (floatFromValue @eb @sb (if r == 0 then F.Zero False else F.Finite (r < 0) (abs r)))

-- | Not a number. SMT-LIB has a single NaN.
fpNaN :: forall eb sb ctx. (KnownNat eb, KnownNat sb) => Expr ctx ('FPS eb sb)
fpNaN = fpLit (floatFromValue @eb @sb F.NaN)

-- | The infinity of the given sign ('True' for negative).
fpInf :: forall eb sb ctx. (KnownNat eb, KnownNat sb) => Bool -> Expr ctx ('FPS eb sb)
fpInf neg = fpLit (floatFromValue @eb @sb (F.Inf neg))

-- | The zero of the given sign ('True' for negative).
fpZero :: forall eb sb ctx. (KnownNat eb, KnownNat sb) => Bool -> Expr ctx ('FPS eb sb)
fpZero neg = fpLit (floatFromValue @eb @sb (F.Zero neg))

-- | The @fp@ constructor: sign bit, biased exponent and trailing
-- significand.
fpFromFields :: Expr ctx ('BVS 1) -> Expr ctx ('BVS eb) -> Expr ctx ('BVS m) -> Expr ctx ('FPS eb (m + 1))
fpFromFields = op3 FPFromFields

-- | A bit pattern read as a floating-point number.
fpFromBV
  :: forall eb sb ctx
   . (KnownNat eb, KnownNat sb)
  => Expr ctx ('BVS (eb + sb))
  -> Expr ctx ('FPS eb sb)
fpFromBV = let (eb, sb) = fpFormat @eb @sb in op1 (ToFP eb sb)

type FPUn eb sb = forall ctx. Expr ctx ('FPS eb sb) -> Expr ctx ('FPS eb sb)

type FPBin eb sb = forall ctx. Expr ctx ('FPS eb sb) -> Expr ctx ('FPS eb sb) -> Expr ctx ('FPS eb sb)

type FPRounded eb sb =
  forall ctx. Expr ctx 'RoundingModeS -> Expr ctx ('FPS eb sb) -> Expr ctx ('FPS eb sb) -> Expr ctx ('FPS eb sb)

type FPPred eb sb = forall ctx. Expr ctx ('FPS eb sb) -> Expr ctx 'BoolS

type FPCmp eb sb = forall ctx. Expr ctx ('FPS eb sb) -> Expr ctx ('FPS eb sb) -> Expr ctx 'BoolS

-- | Absolute value (clears the sign bit; exact, no rounding).
fpAbs :: FPUn eb sb
fpAbs = op1 FPAbs

-- | Negation (flips the sign bit; exact, no rounding).
fpNeg :: FPUn eb sb
fpNeg = op1 FPNeg

-- | Arithmetic, rounded with the given mode.
fpAdd, fpSub, fpMul, fpDiv :: FPRounded eb sb
fpAdd = op3 FPAdd
fpSub = op3 FPSub
fpMul = op3 FPMul
fpDiv = op3 FPDiv

-- | @fpFma rm x y z@ is @x * y + z@ with a single rounding.
fpFma
  :: Expr ctx 'RoundingModeS
  -> Expr ctx ('FPS eb sb)
  -> Expr ctx ('FPS eb sb)
  -> Expr ctx ('FPS eb sb)
  -> Expr ctx ('FPS eb sb)
fpFma rm x y z = Expr (C.App FPFma [unExpr rm, unExpr x, unExpr y, unExpr z])

-- | Square root, rounded with the given mode (NaN for negative numbers;
-- the square root of @-0@ is @-0@).
fpSqrt :: Expr ctx 'RoundingModeS -> Expr ctx ('FPS eb sb) -> Expr ctx ('FPS eb sb)
fpSqrt = op2 FPSqrt

-- | The integral value obtained by rounding with the given mode, in the
-- same format.
fpRoundToIntegral :: Expr ctx 'RoundingModeS -> Expr ctx ('FPS eb sb) -> Expr ctx ('FPS eb sb)
fpRoundToIntegral = op2 FPRoundToIntegral

-- | The IEEE remainder (@x - y * n@, with @n@ the nearest integer to
-- @x / y@), and the minimum and maximum. SMT-LIB leaves 'fpMin' and
-- 'fpMax' of two zeros of different signs unspecified: either zero.
fpRem, fpMin, fpMax :: FPBin eb sb
fpRem = op2 FPRem
fpMin = op2 FPMin
fpMax = op2 FPMax

-- | IEEE comparisons: false when an argument is NaN, and the two zeros
-- are equal. Unlike '.==', 'fpEq' is false on NaN and true on @+0, -0@.
fpLeq, fpLt, fpGeq, fpGt, fpEq :: FPCmp eb sb
fpLeq = op2 FPLeq
fpLt = op2 FPLt
fpGeq = op2 FPGeq
fpGt = op2 FPGt
fpEq = op2 FPEq

-- | Whether a number is normal (nonzero, finite and not subnormal).
fpIsNormal :: FPPred eb sb
fpIsNormal = op1 FPIsNormal

-- | Whether a number is subnormal (nonzero with the minimum exponent).
fpIsSubnormal :: FPPred eb sb
fpIsSubnormal = op1 FPIsSubnormal

-- | Whether a number is a zero of either sign.
fpIsZero :: FPPred eb sb
fpIsZero = op1 FPIsZero

-- | Whether a number is an infinity of either sign.
fpIsInfinite :: FPPred eb sb
fpIsInfinite = op1 FPIsInfinite

-- | Whether a value is NaN.
fpIsNaN :: FPPred eb sb
fpIsNaN = op1 FPIsNaN

-- | Whether a value is negative (including @-0@ and @-oo@, but not NaN).
fpIsNegative :: FPPred eb sb
fpIsNegative = op1 FPIsNegative

-- | Whether a value is positive (including @+0@ and @+oo@, but not NaN).
fpIsPositive :: FPPred eb sb
fpIsPositive = op1 FPIsPositive

-- | Conversion to another format.
toFP
  :: forall eb' sb' eb sb ctx
   . (KnownNat eb', KnownNat sb')
  => Expr ctx 'RoundingModeS
  -> Expr ctx ('FPS eb sb)
  -> Expr ctx ('FPS eb' sb')
toFP = let (eb, sb) = fpFormat @eb' @sb' in op2 (ToFP eb sb)

-- | Conversion from a signed or unsigned bit-vector.
sbvToFP, ubvToFP
  :: forall eb sb n ctx
   . (KnownNat eb, KnownNat sb)
  => Expr ctx 'RoundingModeS
  -> Expr ctx ('BVS n)
  -> Expr ctx ('FPS eb sb)
sbvToFP = let (eb, sb) = fpFormat @eb @sb in op2 (ToFP eb sb)
ubvToFP = let (eb, sb) = fpFormat @eb @sb in op2 (ToFPUnsigned eb sb)

-- | Conversion to an unsigned or signed bit-vector of width @w@ (after
-- rounding). Unspecified for NaN, infinities and values out of range.
fpToUBV, fpToSBV
  :: forall w eb sb ctx
   . (KnownNat w, 1 <= w)
  => Expr ctx 'RoundingModeS
  -> Expr ctx ('FPS eb sb)
  -> Expr ctx ('BVS w)
fpToUBV = op2 (FPToUBV (widthOf @w))
fpToSBV = op2 (FPToSBV (widthOf @w))

-------------------------------------------------------------------------------
-- Records

-- | Field labels, usually written with @OverloadedLabels@ as @#name@.
data Label (l :: Symbol) = Label

instance l ~ l' => IsLabel l (Label l') where
  fromLabel = Label

labelText :: forall l. KnownSymbol l => Text
labelText = T.pack (symbolVal (Proxy @l))

infix 6 :=

infixr 5 :&

-- | A field definition: @#name := expr@.
data Field ctx (f :: (Symbol, Sort)) where
  (:=) :: Label l -> Expr ctx s -> Field ctx '(l, s)

-- | A list of field definitions, terminated by 'FNil'.
data Fields ctx (fs :: [(Symbol, Sort)]) where
  FNil :: Fields ctx '[]
  (:&) :: KnownSymbol l => Field ctx '(l, s) -> Fields ctx fs -> Fields ctx ('(l, s) ': fs)

-- | Build a record:
--
-- > record (#name := "Ana" :& #age := 30 :& FNil)
record :: KnownSort ('RecordS fs) => Fields ctx fs -> Expr ctx ('RecordS fs)
record fs = Expr (C.App (RecordMk (names fs)) (exprs fs))
  where
    names :: Fields ctx gs -> [Text]
    names FNil = []
    names (((_ :: Label l) := _) :& rest) = labelText @l : names rest
    exprs :: Fields ctx gs -> [C.Expr]
    exprs FNil = []
    exprs ((_ := Expr e) :& rest) = e : exprs rest

infixl 9 !

-- | Field access: @p ! #age@.
(!) :: forall l fs ctx. KnownSymbol l => Expr ctx ('RecordS fs) -> Label l -> Expr ctx (FieldSort l fs)
r ! _ = op1 (RecordGet (labelText @l)) r

-- | Field access with the label first: @getField #age p = p ! #age@.
getField :: forall l fs ctx. KnownSymbol l => Label l -> Expr ctx ('RecordS fs) -> Expr ctx (FieldSort l fs)
getField l r = r ! l

-- | Functional update of a field.
setField
  :: forall l fs ctx
   . KnownSymbol l
  => Label l
  -> Expr ctx (FieldSort l fs)
  -> Expr ctx ('RecordS fs)
  -> Expr ctx ('RecordS fs)
setField _ v r = op2 (RecordSet (labelText @l)) r v

-------------------------------------------------------------------------------
-- Uninterpreted functions

-- | The curried Haskell type of an uninterpreted function with domain
-- @args@ and range @r@.
type family Fn ctx (args :: [Sort]) (r :: Sort) where
  Fn ctx '[] r = Expr ctx r
  Fn ctx (a ': as) r = Expr ctx a -> Fn ctx as r

-- | Turn an n-ary application builder into a curried function.
class CurryFn (args :: [Sort]) where
  curryFn :: Proxy ctx -> Proxy r -> ([C.Expr] -> C.Expr) -> Fn ctx args r

instance CurryFn '[] where
  curryFn _ _ k = Expr (k [])

instance CurryFn as => CurryFn (a ': as) where
  curryFn pc pr k = \(Expr e) -> curryFn @as pc pr (\es -> k (e : es))