hsmt-0.1.0.0: src/HSMT/Tutorial.hs
-- | A tutorial on hsmt. This module exports nothing; its documentation is
-- the tutorial. Every example below is also part of the test suite
-- (@test/HSMT/TutorialSpec.hs@).
--
-- = Getting started
--
-- An SMT solver decides whether a formula over some theories (integers,
-- bit-vectors, arrays...) has a solution, and gives one when it does. With
-- hsmt, formulas are Haskell values built inside the 'HSMT.SMT' monad:
--
-- > {-# LANGUAGE DataKinds, LambdaCase, OverloadedLabels, OverloadedStrings, TypeApplications #-}
-- > import Data.Text (Text)
-- > import qualified Data.Text as T
-- > import HSMT
-- >
-- > example :: IO (Maybe (Integer, Integer))
-- > example = runSMT defaultConfig $ do
-- > x <- declare @IntS "x"
-- > y <- declare @IntS "y"
-- > assert (x + y .== 10)
-- > assert (x - y .== 4)
-- > checkSat >>= \case
-- > Sat m -> pure (Just (eval m x, eval m y))
-- > _ -> pure Nothing
--
-- @example@ gives @Just (7, 3)@. (The extensions and imports above are the
-- ones all the examples of this tutorial need.) The steps are always the
-- same:
--
-- 1. 'HSMT.runSMT' starts a solver instance with a 'HSMT.Config'
-- ('HSMT.defaultConfig' is fine to begin with).
-- 2. 'HSMT.declare' introduces a constant of a sort, chosen with a type
-- application. Constants are expressions, 'HSMT.Expr' @ctx s@.
-- 3. 'HSMT.assert' adds a Boolean expression to the assertions.
-- 4. 'HSMT.checkSat' decides the conjunction of the assertions. It answers
-- 'HSMT.Sat' with a model, 'HSMT.Unsat' with an unsatisfiable core, or
-- 'HSMT.Unknown' with the reason the solver gave up.
-- 5. 'HSMT.eval' evaluates any expression under a model, giving a Haskell
-- value: 'Integer' for integers, 'Bool' for Booleans, and so on (the
-- type family 'HSMT.Value').
--
-- = Sorts and type safety
--
-- Sorts are types of the kind 'HSMT.Sort': 'HSMT.BoolS', 'HSMT.IntS',
-- 'HSMT.StringS', 'HSMT.BVS' @n@, 'HSMT.ArrayS' @i e@, 'HSMT.RecordS'
-- @fields@, 'HSMT.UninterpS' @name@, 'HSMT.FPS' @eb sb@ and
-- 'HSMT.RoundingModeS'. An expression carries its sort in its type, so
-- ill-sorted formulas do not compile:
--
-- > assert (x .== "hello") -- rejected: x is an integer, "hello" a string
-- > bvAdd (bv @8 1) (bv @16 1) -- rejected: widths differ
-- > p ! #weight -- rejected: "Record has no field weight"
--
-- The parameter @ctx@ of 'HSMT.Expr' and 'HSMT.Model' identifies the solver
-- instance: like 'Control.Monad.ST.ST', 'HSMT.runSMT' is rank 2, so
-- expressions and models cannot escape it or be mixed between instances.
--
-- = Theories
--
-- == Booleans and integers
--
-- Booleans have 'HSMT.notB', '(HSMT..&&)', '(HSMT..||)', '(HSMT..=>)',
-- 'HSMT.xorB', 'HSMT.andB', 'HSMT.orB' and 'HSMT.ite'; equality '(HSMT..==)'
-- and 'HSMT.distinct' work at every sort. Integers have a 'Num' instance,
-- the comparisons '(HSMT..<)', '(HSMT..<=)', '(HSMT..>)', '(HSMT..>=)' and
-- Euclidean 'HSMT.idiv' and 'HSMT.imod'. Arithmetic must be linear: one
-- factor of each product, and each divisor, must be a constant.
--
-- > -- Is there an even number between 7 and 9 that is also a multiple of 3?
-- > multipleOfSix :: IO Bool
-- > multipleOfSix = runSMT defaultConfig $ do
-- > n <- declare @IntS "n"
-- > assert (n .> 7 .&& n .< 9)
-- > assert (n `imod` 2 .== 0 .&& n `imod` 3 .== 0)
-- > checkSat >>= \case
-- > Unsat _ -> pure False
-- > _ -> pure True
--
-- @multipleOfSix@ is @False@.
--
-- == Bit-vectors
--
-- @'HSMT.BVS' n@ is the sort of bit-vectors of width @n@, with arithmetic
-- modulo @2^n@ ('Num' instance), bitwise operations, shifts, signed and
-- unsigned division and comparisons, and 'HSMT.bvConcat', 'HSMT.bvExtract',
-- 'HSMT.bvZeroExtend' and 'HSMT.bvSignExtend', whose widths are checked by
-- the type checker. Models give 'HSMT.BitVector' values.
--
-- > -- x & (x - 1) clears the lowest set bit: it is zero only for powers of
-- > -- two (and zero). Find a power of two above 1000.
-- > powerOfTwo :: IO (Maybe (BitVector 16))
-- > powerOfTwo = runSMT defaultConfig $ do
-- > x <- declare @(BVS 16) "x"
-- > assert (bvAnd x (x - 1) .== 0)
-- > assert (bvUGt x 1000)
-- > assert (bvULt x 2000)
-- > checkSat >>= \case
-- > Sat m -> pure (Just (eval m x))
-- > _ -> pure Nothing
--
-- @powerOfTwo@ gives @Just (BitVector 1024)@.
--
-- == Arrays
--
-- @'HSMT.ArrayS' i e@ maps indices of sort @i@ to elements of sort @e@,
-- with 'HSMT.select', 'HSMT.store' and 'HSMT.constArray'. Array equality is
-- extensional.
--
-- > swapTwice :: IO Bool
-- > swapTwice = runSMT defaultConfig $ do
-- > a <- declare @(ArrayS IntS IntS) "a"
-- > i <- declare @IntS "i"
-- > j <- declare @IntS "j"
-- > let swap b = store (store b i (select b j)) j (select b i)
-- > assert (swap (swap a) ./= a)
-- > checkSat >>= \case
-- > Unsat _ -> pure True
-- > _ -> pure False
--
-- @swapTwice@ is @True@: swapping twice gives the array back.
--
-- == Strings
--
-- Strings are sequences of Unicode code points, with literals (through
-- @OverloadedStrings@), concatenation '(HSMT.<+>)', 'HSMT.strLen',
-- 'HSMT.substr', 'HSMT.strAt', 'HSMT.contains', 'HSMT.prefixOf',
-- 'HSMT.suffixOf', 'HSMT.indexOf', 'HSMT.replace', conversions to and from
-- integers, and the lexicographic order.
--
-- > greeting :: IO (Maybe Text)
-- > greeting = runSMT defaultConfig $ do
-- > name <- declare @StringS "name"
-- > let s = "hello, " <+> name
-- > assert (strLen s .== 10)
-- > assert (suffixOf "!" name .&& contains name "b")
-- > checkSat >>= \case
-- > Sat m -> pure (Just (eval m s))
-- > _ -> pure Nothing
--
-- The answer is a string such as @\"hello, b!\"@ preceded by an extra
-- character before the @b@. The procedure for strings considers strings up
-- to some length (growing from 8 to 32 characters); problems that are
-- unsatisfiable only because of longer strings are answered with
-- 'HSMT.Unknown'.
--
-- == Regular expressions
--
-- @'HSMT.RegLanS'@ is the sort of regular languages, built from string
-- literals ('HSMT.toRe', or a literal directly with @OverloadedStrings@),
-- 'HSMT.reRange', 'HSMT.reAllChar', 'HSMT.reAll', 'HSMT.reNone', and the
-- operators 'HSMT.reConcat', 'HSMT.reUnion', 'HSMT.reInter', 'HSMT.reStar',
-- 'HSMT.rePlus', 'HSMT.reOpt', 'HSMT.reComp', 'HSMT.reDiff',
-- 'HSMT.reLoop' and 'HSMT.rePower'. 'HSMT.inRe' tests membership.
-- Regular expressions must be ground: one that depends on a variable (such
-- as @toRe s@ for a declared @s@) makes the check answer 'HSMT.Unknown'.
--
-- > -- An identifier of 3 to 5 characters that contains a 9 and is not a
-- > -- keyword.
-- > identifier :: IO (Maybe Text)
-- > identifier = runSMT defaultConfig $ do
-- > s <- declare @StringS "s"
-- > let letter = reUnion [reRange 'a' 'z', reRange 'A' 'Z']
-- > ident = reConcat [letter, reStar (reUnion [letter, reRange '0' '9'])]
-- > assert (inRe s (reInter [ident, reLoop 3 5 reAllChar]))
-- > assert (notB (inRe s (reUnion ["else", "then"])))
-- > assert (contains s "9")
-- > checkSat >>= \case
-- > Sat m -> pure (Just (eval m s))
-- > _ -> pure Nothing
--
-- The answer is a string such as @\"a9\"@ followed by up to three more
-- letters or digits. Membership is decided by running the automaton of the
-- expression over the bounded encoding of the string, so the remark about
-- long strings above applies to regular expressions too.
--
-- == Uninterpreted sorts and functions
--
-- 'HSMT.declareFun' declares a function about which nothing is known
-- except that equal arguments give equal results. Its domain is a list of
-- sorts, and the result is a curried Haskell function on expressions.
-- @'HSMT.UninterpS' name@ is a sort with no structure at all.
--
-- > congruence :: IO Bool
-- > congruence = runSMT defaultConfig $ do
-- > f <- declareFun @'[UninterpS "U"] @(UninterpS "U") "f"
-- > a <- declare @(UninterpS "U") "a"
-- > assert (f (f (f a)) .== a)
-- > assert (f (f (f (f (f a)))) .== a)
-- > assert (f a ./= a)
-- > checkSat >>= \case
-- > Unsat _ -> pure True
-- > _ -> pure False
--
-- @congruence@ is @True@: the first two assertions imply @f a = a@.
--
-- == Records
--
-- @'HSMT.RecordS' fields@ is a record sort with named fields, written with
-- @OverloadedLabels@. Records are built with 'HSMT.record', read with
-- '(HSMT.!)' and updated with 'HSMT.setField'; in a model, 'HSMT.field'
-- reads the fields of a value.
--
-- > type Point = RecordS '[ '("x", IntS), '("y", IntS)]
-- >
-- > reflection :: IO (Maybe (Integer, Integer))
-- > reflection = runSMT defaultConfig $ do
-- > p <- declare @Point "p"
-- > let q = record (#x := p ! #y :& #y := p ! #x :& FNil)
-- > assert (q .== setField #x 3 p)
-- > assert (p ! #x .> 0)
-- > checkSat >>= \case
-- > Sat m -> pure (Just (field #x (eval m p), field #y (eval m p)))
-- > _ -> pure Nothing
--
-- @reflection@ gives @Just (3, 3)@.
--
-- == Floating point
--
-- @'HSMT.FPS' eb sb@ is the IEEE 754 format with @eb@ exponent bits and
-- @sb@ significand bits (counting the hidden bit), with the abbreviations
-- 'HSMT.Float16S', 'HSMT.Float32S' and 'HSMT.Float64S'. Arithmetic takes a
-- rounding mode ('HSMT.rne', 'HSMT.rna', 'HSMT.rtp', 'HSMT.rtn',
-- 'HSMT.rtz'). The IEEE comparisons ('HSMT.fpEq', 'HSMT.fpLt'...) are false
-- on NaN and identify the two zeros, while '(HSMT..==)' is the identity of
-- values. 'HSMT.toFloat' and 'HSMT.toDouble' convert model values.
--
-- > -- A float that is not equal to itself.
-- > notReflexive :: IO (Maybe Bool)
-- > notReflexive = runSMT defaultConfig $ do
-- > x <- declare @Float32S "x"
-- > assert (notB (fpEq x x))
-- > checkSat >>= \case
-- > Sat m -> pure (Just (isNaN (toFloat (eval m x))))
-- > _ -> pure Nothing
--
-- @notReflexive@ gives @Just True@: only NaN differs from itself.
--
-- = Incremental solving
--
-- One solver instance can answer many queries, reusing what it learned.
-- 'HSMT.push' opens a scope of assertions and 'HSMT.pop' discards it
-- ('HSMT.scoped' does both around an action). 'HSMT.checkSatAssuming'
-- checks the assertions together with formulas that hold for that check
-- only.
--
-- When the answer is 'HSMT.Unsat', the 'HSMT.Core' lists assertions and
-- assumptions that are already unsatisfiable together
-- ('HSMT.coreAssertions', 'HSMT.coreAssumptions'). With
-- 'HSMT.cfgMinimizeCores' the core is minimal: removing any element makes
-- it satisfiable. A classic use is to name constraints with Boolean
-- constants and assume them:
--
-- > conflicting :: IO [Int]
-- > conflicting = runSMT defaultConfig {cfgMinimizeCores = True} $ do
-- > x <- declare @IntS "x"
-- > labels <- mapM (\i -> declare @BoolS ("c" <> T.pack (show i))) [0 .. 3 :: Int]
-- > let constraints = [x .> 10, x .< 20, x .== 5, x .> 0]
-- > sequence_ [assert (l .=> c) | (l, c) <- zip labels constraints]
-- > checkSatAssuming labels >>= \case
-- > Unsat core -> pure [i | (i, l) <- zip [0 ..] labels, l `elem` coreAssumptions core]
-- > _ -> pure []
--
-- @conflicting@ gives @[0, 2]@: @x > 10@ and @x = 5@ conflict.
--
-- Hard problems can be bounded with 'HSMT.cfgTimeout' (milliseconds per
-- check) and 'HSMT.cfgConflictLimit'; a check that reaches a limit answers
-- 'HSMT.Unknown', and the instance stays usable.
--
-- = Models
--
-- By default ('HSMT.cfgValidateModels') every model is checked against the
-- assertions by an independent evaluator before 'HSMT.checkSat' returns
-- it. A model gives a value to every expression of the instance, not only
-- to the declared constants: @eval m (f 3)@ or @eval m (x * 2 + y)@ work as
-- well.
--
-- = External solvers
--
-- The same programs can run on an external SMT solver instead of the
-- Haskell engine: 'HSMT.cfgBackend' selects it. With
-- @'HSMT.External' 'HSMT.z3Backend'@, hsmt starts Z3 (found through the
-- environment variable @HSMT_Z3@ or the @PATH@), sends it the formulas in
-- SMT-LIB, and reads its answers, cores and models back, so 'HSMT.eval'
-- works as usual:
--
-- > viaZ3 :: IO (Maybe (Integer, Integer))
-- > viaZ3 = runSMT defaultConfig {cfgBackend = External z3Backend} $ do
-- > x <- declare @IntS "x"
-- > y <- declare @IntS "y"
-- > assert (x * y .== 12 .&& x .> y .&& y .> 1)
-- > checkSat >>= \case
-- > Sat m -> pure (Just (eval m x, eval m y))
-- > _ -> pure Nothing
--
-- @viaZ3@ gives @Just (6, 2)@ or @Just (4, 3)@: Z3 decides nonlinear
-- arithmetic, which the engine does not. Other solvers are described by an
-- 'HSMT.ExternalSolver' (executable, arguments, 'HSMT.Dialect' and
-- logic). Models are validated by hsmt's own evaluator, as with the
-- engine; results that SMT-LIB leaves unspecified (such as division by
-- zero) follow the solver on the terms of the formulas and the evaluator's
-- defaults elsewhere. Unsatisfiable answers cost a second, tracked check
-- that computes the core (bounded in time; if it gives up, the core is
-- every formula).
--
-- = The SMT-LIB front end
--
-- The @hsmt@ executable reads SMT-LIB 2.6 scripts:
--
-- > $ hsmt problem.smt2
-- > $ hsmt --timeout=5000 < problem.smt2
-- > $ hsmt --solver=z3 problem.smt2
--
-- It supports the commands for declarations and definitions (including
-- @define-sort@, @define-const@ and single-constructor datatypes, read as
-- records), @assert@ (with @:named@), @push@, @pop@, @reset@,
-- @reset-assertions@, @check-sat@, @check-sat-assuming@, @get-model@,
-- @get-value@, @get-assertions@, @get-unsat-core@, @get-info@,
-- @get-option@, @set-option@ (@:print-success@, @:timeout@,
-- @:smt.core.minimize@, @:produce-unsat-cores@), @echo@ and @exit@, and
-- terms with @let@. Errors answer @(error ...)@ and the script goes on.
-- With @--solver@, the checks are decided by an external solver and the
-- other commands are still answered by hsmt. From Haskell,
-- 'HSMT.SMTLib.Run.runScriptWith' runs a script and passes each response
-- to a callback.
--
-- = Limitations
--
-- * Integer arithmetic is linear; other products and divisions answer
-- 'HSMT.Unknown'.
-- * Strings are decided for bounded lengths, so some unsatisfiable
-- problems answer 'HSMT.Unknown'. Regular expressions must be ground.
-- * There are no quantifiers, real numbers or general algebraic
-- datatypes.
-- * Bit-vectors and floating point are bit-blasted, so wide
-- multiplications and divisions can be slow.
module HSMT.Tutorial () where