packages feed

hsmt-0.1.0.0: src/HSMT/SMTLib/Printer.hs

-- | Rendering of core expressions, sorts, values and scripts in SMT-LIB 2.6
-- syntax.
--
-- Records have no native SMT-LIB counterpart; they are rendered as
-- single-constructor datatypes whose names are derived from the field list
-- (see 'recordName'), so structurally equal record sorts map to the same
-- datatype. Record updates are expanded into a constructor application.
--
-- The output is accepted by Z3 and by 'HSMT.SMTLib.Parser'.
module HSMT.SMTLib.Printer
  ( -- * Scripts
    renderScript
  , renderCommand
  , problemScript
  , declarationsFor
  , modelCommands
  , modelResponse
    -- * Terms
  , renderExpr
  , renderSort
  , renderSymbol
  , renderString
    -- * Records
  , recordName
  , recordConstructor
  , recordSelector
    -- * Values
  , valueExpr
  , valueSort
  ) where

import Data.Char (isAlphaNum, isDigit, ord)
import Data.List (sortOn)
import qualified Data.Map.Strict as Map
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Text (Text)
import qualified Data.Text as T
import Numeric (showHex)

import HSMT.Core.Eval
import HSMT.Core.Expr
import HSMT.Core.Op
import qualified HSMT.Core.Regex as R
import HSMT.Core.Sort
import HSMT.Core.Typing
import HSMT.Core.Value
import HSMT.SMTLib.Syntax

-------------------------------------------------------------------------------
-- Scripts

-- | Render a list of commands, one per line.
renderScript :: [Command] -> Text
renderScript = T.unlines . map renderCommand

-- | Render a single command.
renderCommand :: Command -> Text
renderCommand = \case
  SetLogic l -> parens ["set-logic", l]
  SetOption o v -> parens ["set-option", ":" <> o, v]
  SetInfo o v -> parens ["set-info", ":" <> o, v]
  DeclareSort n -> parens ["declare-sort", renderSymbol n, "0"]
  DeclareRecord fs ->
    let name = renderSymbol (recordName fs)
        fields = [parens [renderSymbol (recordSelector fs f), renderSort s] | (f, s) <- fs]
        ctor = parens (renderSymbol (recordConstructor fs) : fields)
     in parens ["declare-datatypes", parens [parens [name, "0"]], parens [parens [ctor]]]
  DeclareFun sym ->
    parens
      [ "declare-fun"
      , renderSymbol (symName sym)
      , parens (map renderSort (symArgs sym))
      , renderSort (symResult sym)
      ]
  DefineFun sym params body ->
    parens
      [ "define-fun"
      , renderSymbol (symName sym)
      , parens [parens [renderSymbol (symName p), renderSort (symResult p)] | p <- params]
      , renderSort (symResult sym)
      , renderExpr body
      ]
  Assert e -> parens ["assert", renderExpr e]
  AssertNamed n e -> parens ["assert", parens ["!", renderExpr e, ":named", renderSymbol n]]
  Push n -> parens ["push", tshow n]
  Pop n -> parens ["pop", tshow n]
  CheckSat -> "(check-sat)"
  CheckSatAssuming es -> parens ["check-sat-assuming", parens (map renderExpr es)]
  GetModel -> "(get-model)"
  GetValue es -> parens ["get-value", parens (map renderExpr es)]
  GetAssertions -> "(get-assertions)"
  GetUnsatCore -> "(get-unsat-core)"
  GetInfo k -> parens ["get-info", ":" <> k]
  GetOption k -> parens ["get-option", ":" <> k]
  Echo t -> parens ["echo", renderString t]
  Reset -> "(reset)"
  ResetAssertions -> "(reset-assertions)"
  Exit -> "(exit)"

-- | A complete script checking the conjunction of the assertions.
problemScript :: [Expr] -> [Command]
problemScript as =
  [SetLogic "ALL"] <> declarationsFor as <> map Assert as <> [CheckSat]

-- | Declarations for every sort and symbol used by the expressions:
-- uninterpreted sorts, record datatypes (dependencies first) and symbols.
declarationsFor :: [Expr] -> [Command]
declarationsFor as =
  sortDeclarations (concatMap symbolSorts syms <> Set.toList (foldMap subtermSorts as))
    <> map DeclareFun syms
  where
    syms = Set.toList (foldMap symbols as)

-- | Sorts of all subterms of a well-sorted expression.
subtermSorts :: Expr -> Set Sort
subtermSorts = snd . go
  where
    go (App op args) =
      let (ss, sets) = unzip (map go args)
          s = either (const BoolSort) id (inferSort op ss)
       in (s, Set.insert s (Set.unions sets))

symbolSorts :: Symbol -> [Sort]
symbolSorts sym = symResult sym : symArgs sym

-- | Declarations of the uninterpreted and record sorts occurring in the
-- given sorts, in dependency order and without repetitions.
sortDeclarations :: [Sort] -> [Command]
sortDeclarations = reverse . snd . foldl visit (Set.empty, [])
  where
    visit (seen, acc) s
      | Set.member s seen = (seen, acc)
      | otherwise =
          let (seen', acc') = foldl visit (Set.insert s seen, acc) (children s)
           in case s of
                UninterpretedSort n -> (seen', DeclareSort n : acc')
                RecordSort fs -> (seen', DeclareRecord fs : acc')
                _ -> (seen', acc')
    children = \case
      ArraySort i e -> [i, e]
      RecordSort fs -> map snd fs
      _ -> []

-------------------------------------------------------------------------------
-- Models

-- | Commands declaring the sorts of the given expressions and defining
-- every symbol they use according to the interpretation, for checking a
-- model with another solver.
--
-- Elements of uninterpreted sorts become fresh constants that are asserted
-- pairwise distinct. Symbols the interpretation does not mention take the
-- default value of their sort. The interpretation of integer division by
-- zero cannot be expressed in SMT-LIB and is left to the other solver.
modelCommands :: Interpretation -> [Expr] -> [Command]
modelCommands interp as =
  sortDeclarations (concatMap symbolSorts syms <> Set.toList (foldMap subtermSorts as) <> elemSorts)
    <> map DeclareFun elemSyms
    <> [Assert (App Distinct es) | es <- elemGroups, length es >= 2]
    <> map (definition interp) syms
  where
    syms = Set.toList (foldMap symbols as)
    elems = modelElements interp syms
    elemSyms = map elemSymbol elems
    elemSorts = [s | VUninterp s _ <- elems]
    elemGroups =
      Map.elems $
        Map.fromListWith (flip (<>)) [(s, [constant (Uninterpreted (elemSymbol v))]) | v@(VUninterp s _) <- elems]

-- | The answer to @get-model@ for the given symbols: a declaration for each
-- element of an uninterpreted sort that the model uses (as Z3 does), then
-- a definition of each symbol.
modelResponse :: Interpretation -> [Symbol] -> [Command]
modelResponse interp syms =
  map (DeclareFun . elemSymbol) (modelElements interp syms) <> map (definition interp) syms

-- | The interpretation of a symbol; symbols the interpretation does not
-- mention take the default value of their sort.
funOf :: Interpretation -> Symbol -> FunInterp
funOf interp sym =
  Map.findWithDefault (constInterp (defaultValue (symResult sym))) sym (interpSymbols interp)

-- | Elements of uninterpreted sorts in the interpretations of the symbols.
modelElements :: Interpretation -> [Symbol] -> [Value]
modelElements interp syms =
  Set.toList . foldMap uninterpElems $
    concat
      [ fiDefault fi : concat [r : args | (args, r) <- Map.toList (fiTable fi)]
      | sym <- syms
      , let fi = funOf interp sym
      ]

-- | A @define-fun@ giving the interpretation of a symbol, as a chain of
-- @ite@ over its table.
definition :: Interpretation -> Symbol -> Command
definition interp sym =
  let fi = funOf interp sym
      params = [Symbol ("x!" <> tshow i) [] s | (i, s) <- zip [0 :: Int ..] (symArgs sym)]
      paramExprs = map (constant . Uninterpreted) params
      entry (args, r) rest =
        App Ite [conj (zipWith (\p v -> App Eq [p, valueExpr v]) paramExprs args), valueExpr r, rest]
      body
        | null params = valueExpr (Map.findWithDefault (fiDefault fi) [] (fiTable fi))
        | otherwise = foldr entry (valueExpr (fiDefault fi)) (Map.toList (fiTable fi))
   in DefineFun sym params body
  where
    conj [c] = c
    conj cs = App And cs

-- | Every abstract element occurring in a value.
uninterpElems :: Value -> Set Value
uninterpElems = \case
  v@(VUninterp _ _) -> Set.singleton v
  VArray _ entries def ->
    foldMap uninterpElems (def : Map.keys entries <> Map.elems entries)
  VRecord fs -> foldMap (uninterpElems . snd) fs
  _ -> Set.empty

elemSymbol :: Value -> Symbol
elemSymbol = \case
  VUninterp s n -> Symbol (sortTag s <> "!elem!" <> tshow n) [] s
  v -> error ("elemSymbol: not an abstract element: " <> show v)
  where
    sortTag = \case
      UninterpretedSort n -> n
      s -> renderSort s

-- | A term denoting a value. Abstract elements of uninterpreted sorts are
-- denoted by the constants introduced by 'modelCommands'.
valueExpr :: Value -> Expr
valueExpr = \case
  VBool b -> constant (BoolConst b)
  VInt n -> constant (IntConst n)
  VString s -> constant (StrConst s)
  VBV w x -> constant (BVConst w x)
  VArray idx entries def ->
    foldl
      (\acc (k, e) -> App Store [acc, valueExpr k, valueExpr e])
      (App (ConstArray idx) [valueExpr def])
      (sortOn fst (Map.toList entries))
  VRecord fs -> App (RecordMk (map fst fs)) (map (valueExpr . snd) fs)
  v@(VUninterp _ _) -> constant (Uninterpreted (elemSymbol v))
  VFP eb sb x -> constant (FPConst eb sb x)
  VRM rm -> constant (RMConst rm)
  VRegLan r -> regexExpr r

-- | A term denoting a regular expression.
regexExpr :: R.Regex -> Expr
regexExpr = \case
  R.RSet [] -> constant ReNone
  R.RSet cs
    | cs == R.fullSet -> constant ReAllChar
    | otherwise -> case map rangeExpr cs of
        [e] -> e
        es -> App ReUnion es
  R.REps -> App StrToRe [constant (StrConst "")]
  R.RCat a b -> App ReConcat [regexExpr a, regexExpr b]
  R.RAlt xs -> App ReUnion (map regexExpr (Set.toList xs))
  R.RAnd xs -> App ReInter (map regexExpr (Set.toList xs))
  R.RStar r -> App ReStar [regexExpr r]
  R.RNot (R.RSet []) -> constant ReAll
  R.RNot r -> App ReComp [regexExpr r]
  where
    char c = constant (StrConst (T.singleton (toEnum c)))
    rangeExpr (lo, hi)
      | lo == hi = App StrToRe [char lo]
      | otherwise = App ReRange [char lo, char hi]

-- | Sort of a value.
valueSort :: Value -> Sort
valueSort = \case
  VBool _ -> BoolSort
  VInt _ -> IntSort
  VString _ -> StringSort
  VBV w _ -> BVSort w
  VArray idx _ def -> ArraySort idx (valueSort def)
  VRecord fs -> RecordSort [(f, valueSort v) | (f, v) <- fs]
  VUninterp s _ -> s
  VFP eb sb _ -> FPSort eb sb
  VRM _ -> RoundingModeSort
  VRegLan _ -> RegLanSort

-------------------------------------------------------------------------------
-- Terms

-- | Render a well-sorted expression as an SMT-LIB term.
renderExpr :: Expr -> Text
renderExpr (App op args) = case (op, args) of
  (IntConst n, [])
    | n < 0 -> parens ["-", tshow (negate n)]
    | otherwise -> tshow n
  (BVConst w v, []) -> parens ["_", "bv" <> tshow v, tshow w]
  (StrConst s, []) -> renderString s
  (FPConst eb sb x, []) -> prettyValue (VFP eb sb x)
  (Uninterpreted sym, _) -> apply (renderSymbol (symName sym))
  -- Degenerate Boolean connectives.
  (And, []) -> "true"
  (And, [a]) -> renderExpr a
  (Or, []) -> "false"
  (Or, [a]) -> renderExpr a
  (ConstArray idx, [e]) ->
    parens
      [ parens ["as", "const", renderSort (ArraySort idx (exprSort e))]
      , renderExpr e
      ]
  (RecordMk names, _) -> apply (renderSymbol (recordConstructor (fieldsOf names args)))
  (RecordGet f, [r]) -> case exprSort r of
    RecordSort fs -> parens [renderSymbol (recordSelector fs f), renderExpr r]
    s -> illSorted s
  (RecordSet f, [r, v]) -> case exprSort r of
    RecordSort fs ->
      renderExpr $
        App
          (RecordMk (map fst fs))
          [if g == f then v else App (RecordGet g) [r] | (g, _) <- fs]
    s -> illSorted s
  _ -> apply (opName op)
  where
    apply f
      | null args = f
      | otherwise = parens (f : map renderExpr args)
    fieldsOf names es = zip names (map exprSort es)
    illSorted s = "|ill-sorted:" <> renderSort s <> "|"

-- | Sort of a well-sorted expression. Rendering ill-sorted expressions is a
-- bug in the caller.
exprSort :: Expr -> Sort
exprSort e = case sortOf e of
  Right s -> s
  Left err -> error ("hsmt: rendering an ill-sorted expression: " <> show err)

-- | Render a sort; record sorts are rendered as the name of their datatype.
renderSort :: Sort -> Text
renderSort = \case
  BoolSort -> "Bool"
  IntSort -> "Int"
  StringSort -> "String"
  BVSort n -> parens ["_", "BitVec", tshow n]
  ArraySort i e -> parens ["Array", renderSort i, renderSort e]
  RecordSort fs -> renderSymbol (recordName fs)
  UninterpretedSort n -> renderSymbol n
  FPSort eb sb -> parens ["_", "FloatingPoint", tshow eb, tshow sb]
  RoundingModeSort -> "RoundingMode"
  RegLanSort -> "RegLan"

-- | Name of the datatype standing for a record sort. It is a function of the
-- field list, so equal record sorts get equal names.
recordName :: [(Text, Sort)] -> Text
recordName fs = "Record{" <> T.intercalate "," [f <> ":" <> plain s | (f, s) <- fs] <> "}"
  where
    plain = \case
      RecordSort gs -> recordName gs
      UninterpretedSort n -> n
      s -> renderSort s

-- | Name of the constructor of the datatype standing for a record sort.
recordConstructor :: [(Text, Sort)] -> Text
recordConstructor fs = "mk-" <> recordName fs

-- | Name of the selector of the given field of a record sort.
recordSelector :: [(Text, Sort)] -> Text -> Text
recordSelector fs f = recordName fs <> "." <> f

-- | Render a symbol, quoting it when it is not a simple symbol.
renderSymbol :: Text -> Text
renderSymbol s
  | isSimple = s
  | otherwise = "|" <> s <> "|"
  where
    isSimple =
      not (T.null s)
        && T.all (\c -> isAsciiAlphaNum c || c `elem` ("~!@$%^&*_-+=<>.?/" :: String)) s
        && not (isDigit (T.head s))
        && s `notElem` reserved
    isAsciiAlphaNum c = isAlphaNum c && ord c < 128
    reserved =
      ["par", "NUMERAL", "DECIMAL", "STRING", "_", "!", "as", "let", "exists", "forall", "match"]

-- | Render a string literal. Quotes are doubled; backslashes and characters
-- outside printable ASCII use the @\\u{...}@ escape of SMT-LIB 2.6.
renderString :: Text -> Text
renderString s = "\"" <> T.concatMap escape s <> "\""
  where
    escape c
      | c == '"' = "\"\""
      | c == '\\' || ord c < 32 || ord c > 126 = "\\u{" <> T.pack (showHex (ord c) "") <> "}"
      | otherwise = T.singleton c

parens :: [Text] -> Text
parens ts = "(" <> T.unwords ts <> ")"

tshow :: Show a => a -> Text
tshow = T.pack . show