packages feed

hsmt-0.1.0.0: src/HSMT/Core/Typing.hs

-- | Dynamic sort checking for the core language.
--
-- The typed API produces only well-sorted expressions, but front-ends such as
-- the SMT-LIB parser and the dynamic API rely on this module to reject
-- ill-sorted input.
module HSMT.Core.Typing
  ( SortError (..)
  , inferSort
  , sortOf
  ) where

import Control.Monad (unless, when)
import Data.List (nub)
import Data.Text (Text)
import qualified Data.Text as T

import HSMT.Core.Expr
import HSMT.Core.Op
import HSMT.Core.Sort

-- | A sort error, with the offending operator and argument sorts.
data SortError = SortError
  { seOp :: Op
  , seArgs :: [Sort]
  , seMessage :: Text
  }
  deriving (Eq, Show)

-- | Sort of an expression, checking every sub-expression.
sortOf :: Expr -> Either SortError Sort
sortOf (App op args) = traverse sortOf args >>= inferSort op

-- | Result sort of an operator applied to arguments of the given sorts.
inferSort :: Op -> [Sort] -> Either SortError Sort
inferSort op ss = case op of
  Uninterpreted sym -> do
    unless (ss == symArgs sym) $ bad "argument sorts do not match the declaration"
    pure (symResult sym)
  BoolConst _ -> nullary BoolSort
  Not -> exactly [BoolSort] BoolSort
  And -> allOf BoolSort 0 BoolSort
  Or -> allOf BoolSort 0 BoolSort
  Xor -> allOf BoolSort 2 BoolSort
  Implies -> allOf BoolSort 2 BoolSort
  Ite -> case ss of
    [BoolSort, a, b] | a == b -> pure a
    _ -> bad "expected (ite Bool s s)"
  Eq -> sameSorts 2 >> pure BoolSort
  Distinct -> sameSorts 2 >> pure BoolSort
  IntConst _ -> nullary IntSort
  Add -> allOf IntSort 2 IntSort
  Sub -> allOf IntSort 2 IntSort
  Neg -> exactly [IntSort] IntSort
  Mul -> allOf IntSort 2 IntSort
  IntDiv -> exactly [IntSort, IntSort] IntSort
  IntMod -> exactly [IntSort, IntSort] IntSort
  Abs -> exactly [IntSort] IntSort
  Le -> allOf IntSort 2 BoolSort
  Lt -> allOf IntSort 2 BoolSort
  Ge -> allOf IntSort 2 BoolSort
  Gt -> allOf IntSort 2 BoolSort
  BVConst w v -> do
    when (w <= 0) $ bad "bit-vector width must be positive"
    when (v < 0 || v >= 2 ^ w) $ bad "bit-vector literal out of range"
    nullary (BVSort w)
  BVNot -> bvUnary
  BVNeg -> bvUnary
  BVAnd -> bvNary
  BVOr -> bvNary
  BVXor -> bvNary
  BVAdd -> bvNary
  BVMul -> bvNary
  BVSub -> bvBinary
  BVUDiv -> bvBinary
  BVURem -> bvBinary
  BVSDiv -> bvBinary
  BVSRem -> bvBinary
  BVSMod -> bvBinary
  BVShl -> bvBinary
  BVLShr -> bvBinary
  BVAShr -> bvBinary
  BVConcat -> do
    ws <- traverse width ss
    when (length ws < 2) $ bad "concat expects at least two arguments"
    pure (BVSort (sum ws))
  BVExtract h l -> case ss of
    [BVSort w] | 0 <= l && l <= h && h < w -> pure (BVSort (h - l + 1))
    _ -> bad "invalid extract indices"
  BVZeroExtend k -> extendBy k
  BVSignExtend k -> extendBy k
  BVULt -> bvPred
  BVULe -> bvPred
  BVUGt -> bvPred
  BVUGe -> bvPred
  BVSLt -> bvPred
  BVSLe -> bvPred
  BVSGt -> bvPred
  BVSGe -> bvPred
  Select -> case ss of
    [ArraySort i e, i'] | i == i' -> pure e
    _ -> bad "expected (select (Array i e) i)"
  Store -> case ss of
    [ArraySort i e, i', e'] | i == i' && e == e' -> pure (ArraySort i e)
    _ -> bad "expected (store (Array i e) i e)"
  ConstArray i -> case ss of
    [e] -> pure (ArraySort i e)
    _ -> bad "const array expects one argument"
  StrConst _ -> nullary StringSort
  StrConcat -> allOf StringSort 2 StringSort
  StrLen -> exactly [StringSort] IntSort
  StrAt -> exactly [StringSort, IntSort] StringSort
  StrSubstr -> exactly [StringSort, IntSort, IntSort] StringSort
  StrContains -> exactly [StringSort, StringSort] BoolSort
  StrPrefixOf -> exactly [StringSort, StringSort] BoolSort
  StrSuffixOf -> exactly [StringSort, StringSort] BoolSort
  StrIndexOf -> exactly [StringSort, StringSort, IntSort] IntSort
  StrReplace -> exactly [StringSort, StringSort, StringSort] StringSort
  StrToInt -> exactly [StringSort] IntSort
  StrFromInt -> exactly [IntSort] StringSort
  StrLt -> exactly [StringSort, StringSort] BoolSort
  StrLe -> exactly [StringSort, StringSort] BoolSort
  StrToRe -> exactly [StringSort] RegLanSort
  StrInRe -> exactly [StringSort, RegLanSort] BoolSort
  ReNone -> nullary RegLanSort
  ReAll -> nullary RegLanSort
  ReAllChar -> nullary RegLanSort
  ReConcat -> allOf RegLanSort 2 RegLanSort
  ReUnion -> allOf RegLanSort 2 RegLanSort
  ReInter -> allOf RegLanSort 2 RegLanSort
  ReStar -> exactly [RegLanSort] RegLanSort
  RePlus -> exactly [RegLanSort] RegLanSort
  ReOpt -> exactly [RegLanSort] RegLanSort
  ReRange -> exactly [StringSort, StringSort] RegLanSort
  ReComp -> exactly [RegLanSort] RegLanSort
  ReDiff -> allOf RegLanSort 2 RegLanSort
  ReLoop i j -> do
    when (i < 0 || j < 0) $ bad "negative repetition count"
    exactly [RegLanSort] RegLanSort
  RePower n -> do
    when (n < 0) $ bad "negative repetition count"
    exactly [RegLanSort] RegLanSort
  RecordMk names -> do
    unless (length names == length ss) $ bad "wrong number of record fields"
    unless (length (nub names) == length names) $ bad "duplicated record field"
    pure (RecordSort (zip names ss))
  RecordGet f -> case ss of
    [RecordSort fs] | Just s <- lookup f fs -> pure s
    _ -> bad ("no field " <> f)
  RecordSet f -> case ss of
    [r@(RecordSort fs), s] | lookup f fs == Just s -> pure r
    _ -> bad ("cannot update field " <> f)
  FPConst eb sb x -> do
    format eb sb
    when (x < 0 || x >= 2 ^ (eb + sb)) $ bad "floating-point pattern out of range"
    nullary (FPSort eb sb)
  RMConst _ -> nullary RoundingModeSort
  FPFromFields -> case ss of
    [BVSort 1, BVSort eb, BVSort f] | eb >= 2 && f >= 1 -> pure (FPSort eb (f + 1))
    _ -> bad "expected (fp (_ BitVec 1) (_ BitVec eb) (_ BitVec sb-1))"
  FPAbs -> fpUnary
  FPNeg -> fpUnary
  FPAdd -> rmThen 2
  FPSub -> rmThen 2
  FPMul -> rmThen 2
  FPDiv -> rmThen 2
  FPFma -> rmThen 3
  FPSqrt -> rmThen 1
  FPRoundToIntegral -> rmThen 1
  FPRem -> fpSame 2 2
  FPMin -> fpSame 2 2
  FPMax -> fpSame 2 2
  FPLeq -> fpSame 2 maxBound >> pure BoolSort
  FPLt -> fpSame 2 maxBound >> pure BoolSort
  FPGeq -> fpSame 2 maxBound >> pure BoolSort
  FPGt -> fpSame 2 maxBound >> pure BoolSort
  FPEq -> fpSame 2 maxBound >> pure BoolSort
  FPIsNormal -> fpPred
  FPIsSubnormal -> fpPred
  FPIsZero -> fpPred
  FPIsInfinite -> fpPred
  FPIsNaN -> fpPred
  FPIsNegative -> fpPred
  FPIsPositive -> fpPred
  ToFP eb sb -> do
    format eb sb
    case ss of
      [BVSort w] | w == eb + sb -> pure (FPSort eb sb)
      [RoundingModeSort, FPSort _ _] -> pure (FPSort eb sb)
      [RoundingModeSort, BVSort _] -> pure (FPSort eb sb)
      _ -> bad "expected a bit-vector of the format's width, or a rounding mode and a floating-point number or bit-vector"
  ToFPUnsigned eb sb -> do
    format eb sb
    case ss of
      [RoundingModeSort, BVSort _] -> pure (FPSort eb sb)
      _ -> bad "expected a rounding mode and a bit-vector"
  FPToUBV w -> toBV w
  FPToSBV w -> toBV w
  where
    bad :: Text -> Either SortError a
    bad msg = Left (SortError op ss msg)

    nullary s = exactly [] s

    exactly expected result
      | ss == expected = pure result
      | otherwise =
          bad ("expected arguments " <> T.intercalate ", " (map prettySort expected))

    allOf s minArgs result = do
      when (length ss < minArgs) $ bad "too few arguments"
      unless (all (== s) ss) $ bad ("all arguments must have sort " <> prettySort s)
      pure result

    sameSorts minArgs = case ss of
      (s : rest) | length ss >= minArgs && all (== s) rest -> pure ()
      _ -> bad "arguments must have the same sort"

    width = \case
      BVSort w -> pure w
      _ -> bad "expected a bit-vector argument"

    bvUnary = case ss of
      [s@(BVSort _)] -> pure s
      _ -> bad "expected one bit-vector argument"

    bvBinary = case ss of
      [s@(BVSort _), s'] | s == s' -> pure s
      _ -> bad "expected two bit-vectors of the same width"

    bvNary = case ss of
      (s@(BVSort _) : rest) | not (null rest) && all (== s) rest -> pure s
      _ -> bad "expected bit-vectors of the same width"

    bvPred = bvBinary >> pure BoolSort

    format eb sb = unless (eb >= 2 && sb >= 2) $ bad "floating-point widths must be at least 2"

    fpUnary = case ss of
      [s@(FPSort _ _)] -> pure s
      _ -> bad "expected one floating-point argument"

    fpSame :: Int -> Int -> Either SortError Sort
    fpSame lo hi = case ss of
      (s@(FPSort _ _) : rest) | all (== s) rest && length ss >= lo && length ss <= hi -> pure s
      _ -> bad "expected floating-point arguments of the same format"

    rmThen n = case ss of
      (RoundingModeSort : s@(FPSort _ _) : rest) | length rest == n - 1 && all (== s) rest -> pure s
      _ -> bad "expected a rounding mode and floating-point arguments of the same format"

    fpPred = fpUnary >> pure BoolSort

    toBV w = case ss of
      [RoundingModeSort, FPSort _ _] | w >= 1 -> pure (BVSort w)
      _ -> bad "expected a rounding mode and a floating-point argument"

    extendBy k = case ss of
      [BVSort w] | k >= 0 -> pure (BVSort (w + k))
      _ -> bad "invalid extension"