packages feed

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

{-# LANGUAGE AllowAmbiguousTypes #-}

-- | Models returned by satisfiable queries.
module HSMT.API.Model
  ( Model (..)
  , eval
  , evalCore
  , field
  ) where

import Data.Proxy (Proxy (..))
import qualified Data.Text as T
import GHC.TypeLits (KnownSymbol, symbolVal)

import HSMT.API.Expr
import HSMT.API.Sort
import qualified HSMT.Core.Eval as C
import qualified HSMT.Core.Value as C

-- | A model of the assertions, valid for the solver instance @ctx@.
newtype Model ctx = Model {modelInterpretation :: C.Interpretation}
  deriving (Show)

-- | Evaluate any expression of the solver instance under a model.
eval :: forall s ctx. KnownSort s => Model ctx -> Expr ctx s -> Value s
eval m e = case decodeValue @s (evalCore m e) of
  Just v -> v
  Nothing -> error "hsmt: internal error, model value has the wrong sort"

-- | Evaluate to an untyped core value.
evalCore :: Model ctx -> Expr ctx s -> C.Value
evalCore (Model interp) (Expr e) = case C.evalExpr interp e of
  Right v -> v
  Left err -> error ("hsmt: internal error during evaluation: " <> show err)

-- | Read a field of a record value.
field
  :: forall l fs
   . (KnownSymbol l, KnownSort (FieldSort l fs))
  => Label l
  -> RecordValue fs
  -> Value (FieldSort l fs)
field _ (RecordValue fs) =
  case lookup (T.pack (symbolVal (Proxy @l))) fs >>= decodeValue @(FieldSort l fs) of
    Just v -> v
    Nothing -> error "hsmt: internal error, malformed record value"