! X[ G      !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~      !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~      !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~      !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~                                                                                                              ! " # $ % & ' ( ) * + , - . / 0 1 2 3 4 5 6 7 8 9 : ; < = > ? @ A B C D E F G HIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~      !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~      !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~  !!!!!!"""""###$$$$$%%%&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&'''''''''''''(((((((((((((((((((((( ( ( ( ( (((((((((((()))))** *!*"*#*$*%*&+'+(+)+*+++,+-+.+/+0+1+2+3+4+5+6+7+8+9+:+;,<,=->.?.@.A/B/C/D/E/F/G/H/I/J/K/L/M/N/O/P/Q/R0S0T0U0V0W1X1Y2Z2[2\2]2^2_2`2a2b2c2d2e2f2g2h2i2j2k2l2m2n2o2p2q2r3s3t3u4v4w4x4y4z4{4|5}6~7788888888888888888888889:;<=============>>>>>>>>>>>>>>??????????????????@@@@@@@@@@@@@AAAAAAAAAAAAABBBBBBBBBBCCCCDEEEFFFFFFFFFFFFFFFFFFFFFF F F F F FFFFFFFFFFFFFFFFFFF F!F"F#F$F%F&F'F(F)F*F+F,F-F.F/F0F1F2F3F4F5F6F7F8F9F:G;G<G=G>G?G@GAGBGCGDGEGFGGGHGIGJGKGLHMHNHOHPHQHRHSHTHUHVHWHXHYHZH[H\H]H^H_H`IaJbJcJdJeJfJgJhJiKjKkKlLmMnMoMpMqMrMsMtMuMvMwMxMyMzM{M|M}N~NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNOOPPQQQQQQQQRRRRRRRRRRRRRRRRRRSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS S S T T U U V V W W W W X X X X X X X X X X X X X X X X Y Y Y Y Y !Y "Y #Y $Y %Y &Y 'Y (Y )Y *Y +Y ,Y -Y .Y /Y 0Y 1Y 2Y 3Y 4Y 5Y 6Y 7Y 8Y 9Y :Y ;Y <Y =Y >Y ?Y @Y AY BY CY DY EY FY GY HY IY JY KY LY MY NY OY PY QY RY SY TY UY VY WY XY YY ZY [Y \Y ]Y ^Y _Y `Y aZ bZ cZ dZ e[ f[ g[ h[ i[ j[ k[ l[ m[ n[ o[ p[ q[ r[ s[ t[ u[ v\ w\ x] y] z^ {^ |^ }^ ~^ ^ ^ ^ ^ ^ ^ ^ _ _ _ _ _ _ _ _ _ _ _ _ ` ` ` ` ` ` ` ` ` ` ` ` a a a a a a a a a a a a a a a a a b b b b b b b b b b b b b b b b b b b c c c c c c c c c c c c c c c c c c c c c c c d d d d d d d d d d d d d d d d d d d d d d d e e e e e e e e e e e e e e e e e e e e e e e f f f f f f f f f f f f f f f f f f f f f f f g g g !g "g #g $g %g &g 'g (g )g *g +g ,g -g .g /g 0g 1g 2g 3h 4h 5h 6h 7h 8h 9h :h ;h <h =h >h ?h @h Ah Bh Ch Dh Eh Fhi(c) Levent ErkokBSD3erkokl@gmail.com experimentalSafe79ѱ,sbvSMT-Lib logics. If left unspecified SBV will pick the logic based on what it determines is needed. However, the user can override this choice using a call to jr This is especially handy if one is experimenting with custom logics that might be supported on new solvers. See  'http://smtlib.cs.uiowa.edu/logics.shtml for the official list.sbvFormulas over the theory of linear integer arithmetic and arrays extended with free sort and function symbols but restricted to arrays with integer indices and values.sbvyLinear formulas with free sort and function symbols over one- and two-dimentional arrays of integer index and real value.sbvtFormulas with free function and predicate symbols over a theory of arrays of arrays of integer index and real value.sbv*Linear formulas in linear real arithmetic.sbvLQuantifier-free formulas over the theory of bitvectors and bitvector arrays.sbvyQuantifier-free formulas over the theory of bitvectors and bitvector arrays extended with free sort and function symbols.sbvoQuantifier-free linear formulas over the theory of integer arrays extended with free sort and function symbols.sbvGQuantifier-free formulas over the theory of arrays with extensionality. sbvBQuantifier-free formulas over the theory of fixed-size bitvectors. sbvDifference Logic over the integers. Boolean combinations of inequations of the form x - y < b where x and y are integer variables and b is an integer constant. sbvUnquantified linear integer arithmetic. In essence, Boolean combinations of inequations between linear polynomials over integer variables. sbvUnquantified linear real arithmetic. In essence, Boolean combinations of inequations between linear polynomials over real variables. sbv#Quantifier-free integer arithmetic.sbv Quantifier-free real arithmetic.sbvDifference Logic over the reals. In essence, Boolean combinations of inequations of the form x - y < b where x and y are real variables and b is a rational constant.sbveUnquantified formulas built over a signature of uninterpreted (i.e., free) sort and function symbols.sbvSUnquantified formulas over bitvectors with uninterpreted sort function and symbols.sbvaDifference Logic over the integers (in essence) but with uninterpreted sort and function symbols.sbvTUnquantified linear integer arithmetic with uninterpreted sort and function symbols.sbvQUnquantified linear real arithmetic with uninterpreted sort and function symbols.sbvUUnquantified non-linear real arithmetic with uninterpreted sort and function symbols.sbv]Unquantified non-linear real integer arithmetic with uninterpreted sort and function symbols.sbvDLinear real arithmetic with uninterpreted sort and function symbols.sbvKNon-linear integer arithmetic with uninterpreted sort and function symbols.sbv\Quantifier-free formulas over the theory of floating point numbers, arrays, and bit-vectors.sbvCQuantifier-free formulas over the theory of floating point numbers.sbvQuantifier-free finite domains.sbv4Quantifier-free formulas over the theory of strings.sbvThe catch-all value.sbv=Use this value when you want SBV to simply not set the logic.sbv(In case you need a really custom string! sbvPOption values that can be set in the solver, following the SMTLib specification  )http://smtlib.cs.uiowa.edu/language.shtml.3Note that not all solvers may support all of these!IFurthermore, SBV doesn't support the following options allowed by SMTLib.:interactive-mode+ (Deprecated in SMTLib, use " instead.):print-successH (SBV critically needs this to be True in query mode.):produce-modelsI (SBV always sets this option so it can extract models.):regular-output-channelT (SBV always requires regular output to come on stdout for query purposes.):global-declarationsV (SBV always uses global declarations since definitions are accumulative.) Note that , and - are, strictly speaking, not SMTLib options. However, we treat it as such here uniformly, as it fits better with how options work..sbv(Collectable information from the solver.8sbvReason for reporting unknown.=sbv"Behavior of the solver for errors.@sbv(Collectable information from the solver.Isbv Result of a k or l call.Jsbv=Satisfiable: A model is available, which can be queried with m.KsbvHUnsatisfiable: No model is available. Unsat cores might be obtained via n.Lsbv Unknown: Use o5 to obtain an explanation why this might be the case. Gsbv7Can this command only be run at the very beginning? If  Hz then we will reject setting these options in the query mode. Note that this classification follows the SMTLib document. IsbvMTranslate an option setting to SMTLib. Note the SetLogic/SetInfo discrepancy. JsbvShow instance for unknownO  !"#$%&'()*+,-./0123456789:;<=>?@EGABCDFHIJKL G Ip(c) Levent ErkokBSD3erkokl@gmail.com experimentalNone=?! MsbvA univariate polynomial, represented simply as a coefficient list. For instance, "5x^3 + 2x - 5" is represented as [(5, 3), (2, 1), (-5, 0)]OsbvAlgebraic reals. Note that the representation is left abstract. We represent rational results explicitly, while the roots-of-polynomials are represented implicitly by their defining equationPsbvLbool says it's exact (i.e., SMT-solver did not return it with ? at the end.)Qsbvjwhich root of this polynomial and an approximate decimal representation with given precision, if available Ksbv2Check wheter a given argument is an exact rational LsbvcConstruct a poly-root real with a given approximate value (either as a decimal, or polynomial-root) MsbvAStructural equality for AlgReal; used when constants are Map keys NsbvDStructural comparisons for AlgReal; used when constants are Map keys Osbv Render an OA as an SMTLib2 value. Only supports rationals for the time being. Psbv Render an O as a Haskell value. Only supports rationals, since there is no corresponding standard Haskell type that can represent root-of-polynomial variety.Rsbv Convert an O to a  Q . If the O is exact, then you get a  R value. Otherwise, you get a  S( value which is simply an approximation. TsbvcMerge the representation of two algebraic reals, one assumed to be in polynomial form, the other in decimal. Arguments can be the same kind, so long as they are both rationals and equivalent; if not there must be one that is precise. It's an error to pass anything else to this function! (Used in reconstructing SMT counter-example values with reals). Usbv2NB: Following the other types we have, we require `a/0` to be `0` for all a. MNOPQ K L M N O PR Tq(c) Levent ErkokBSD3erkokl@gmail.com experimentalSafeJSsbvyNames reserved by SMTLib. This list is current as of Dec 6 2015; but of course there's no guarantee it'll stay that way.Sr(c) Brian SchroederBSD3erkokl@gmail.com experimentalSafeTsbvMonads which support  V operations and can extract all  V2 behavior for interoperation with functions like st, which takes an  VZ action in negative position. This function can not be implemented for transformers like  ReaderT r or StateT s, whose resultant  V6 actions are a function of some environment or state.Usbv Law: the m a yielded by  V is pure with respect to  V. WsbvIO extraction for strict  X. YsbvIO extraction for lazy  Z. [sbvIO extraction for  \. ]sbvIO extraction for  ^. _sbvTrivial IO extraction for  V.TUu(c) Levent ErkokBSD3erkokl@gmail.com experimentalSafeSX  `sbvWe have a nasty issue with the usual String/List confusion in Haskell. However, we can do a simple dynamic trick to determine where we are. The ice is thin here, but it seems to work. asbvMonadic lift over 2-tuples bsbvMonadic lift over 3-tuples csbvMonadic lift over 4-tuples dsbvMonadic lift over 5-tuples esbvMonadic lift over 6-tuples fsbvMonadic lift over 7-tuples gsbvMonadic lift over 8-tuples hsbvGiven a sequence of arguments, join them together in a manner that could be used on the command line, giving preference to the Windows cmd shell quoting conventions.vFor an alternative version, intended for actual running the result in a shell, see "System.Process.showCommandForUser" isbvCGiven a string, split into the available arguments. The inverse of  h#. Courtesy of the cmdargs package. jsbvcGiven a QF_S string (i.e., one that works in the string theory), convert it to a Haskell equivalent ksbvGiven a Haskell, convert it to one that's understood by the QF_S logic TODO: This function will require mods with the new String logic; as escapes will completely be different! ` a b c d e f g h i j kv(c) Levent ErkokBSD3erkokl@gmail.com experimentalNone%8=?X_k&L VsbvA class for capturing values that have a sign and a size (finite or infinite) minimal complete definition: kindOf, unless you can take advantage of the default signature: This class can be automatically derived for data-types that have a  l instance; this is useful for creating uninterpreted sorts. So, in reality, end users should almost never need to define any methods.isbvKind of symbolic value msbv;A version of show for kinds that says Bool instead of SBool nsbvIPut parens if necessary. This test is rather crummy, but seems to work ok osbvHow the type maps to SMT land psbv+Does this kind represent a signed quantity? qsbvConstruct an uninterpreted/enumerated kind from a piece of data; we distinguish simple enumerations as those are mapped to proper SMT-Lib2 data-types; while others go completely uninterpreted rsbvADo we have a completely uninterpreted sort lying around anywhere? ssbvShould we ask the solver to flatten the output? This comes in handy so output is parseable Essentially, we're being conservative here and simply requesting flattening anything that has some structure to it. tsbvThe interesting about the show instance is that it can tell apart two kinds nicely; since it conveniently ignores the enumeration constructors. Also, when we construct a n<, we make sure we don't use any of the reserved names; see  q for details. usbvThis instance allows us to use the `kindOf (Proxy @a)` idiom instead of the `kindOf (undefined :: a)`, which is safer and looks more idiomatic.'VWXYZ[\]^_`abcdefghijklmnopqrstuvw m o q r sw(c) Levent ErkokBSD3erkokl@gmail.com experimentalSafe@xsbvThe SMT-Lib (in particular Z3) implementation for min/max for floats does not agree with Haskell's; and also it does not agree with what the hardware does. Sigh.. See:  ,http://ghc.haskell.org/trac/ghc/ticket/10378  'http://github.com/Z3Prover/z3/issues/68 So, we codify here what the Z3 (SMTLib) is implementing for fpMax. The discrepancy with Haskell is that the NaN propagation doesn't work in Haskell The discrepancy with x86 is that given +0/-0, x86 returns the second argument; SMTLib is non-deterministicysbv SMTLib compliant definition for x. See the comments for y.zsbv.Convert double to float and back. Essentially fromRational . toRational, except careful on NaN, Infinities, and -0.{sbvkCompute the "floating-point" remainder function, the float/double value that remains from the division of x and yP. There are strict rules around 0's, Infinities, and NaN's as coded below, See  $http://smt-lib.org/papers/BTRW14.pdf", towards the end of section 4.c.|sbvBConvert a float to the nearest integral representable in that type}sbv|Check that two floats are the exact same values, i.e., +0/-0 does not compare equal, and NaN's compare equal to themselves.~sbv$Ordering for floats, avoiding the +0-0NaN issues. Note that this is essentially used for indexing into a map, so we need to be total. Thus, the order we pick is: NaN -oo -0 +0 +oo The placement of NaN here is questionable, but immaterial.sbvCheck if a number is "normal." Note that +0/-0 is not considered a normal-number and also this is not simply the negation of isDenormalized!xyz{|}~z(c) Levent ErkokBSD3erkokl@gmail.com experimentalNoneXkq,sbvYA simple expression type over extendent values, covering infinity, epsilon and intervals.sbvvA generalized CV allows for expressions involving infinite and epsilon values/intervals Used in optimization problems.sbvx represents a concrete word of a fixed size: For signed words, the most significant digit is considered to be the sign.sbvA constant valuesbvAlgebraic realsbvBit-vector/unbounded integersbvFloatsbvDoublesbv CharactersbvStringsbvListsbv$Set. Can be regular or complemented.sbvXValue of an uninterpreted/user kind. The Maybe Int shows index position for enumerationssbvTuplesbvMaybesbvDisjoint unionsbvA _ is either a regular set or a set given by its complement from the corresponding universal set. vsbvStructural equality for  . We need EqOrd instances for $ because we want to put them in mapstables. But we don't want to derive these, nor make it an instance! Why? Because the same set can have multiple representations if the underlying type is finite. For instance, {True} = U - {False} for boolean sets! Instead, we use the following two functions, which are equivalent to Eq/Ord instances and work for our purposes, but we do not export these to the user. wsbv Comparing  values. See comments for  v on why we don't define the  x instance. ysbvLAssing a rank to constant values, this is structural and helps with ordering zsbv*Show an extended CV, with kind if requiredsbvIs this a regular CV?sbvAre two CV's of the same type?sbvDConvert a CV to a Haskell boolean (NB. Assumes input is well-kinded)sbv5Normalize a CV. Essentially performs modular arithmetic to make sure the value can fit in the given bit-size. Note that this is rather tricky for negative values, due to asymmetry. (i.e., an 8-bit negative number represents values in the range -128 to 127; thus we have to be careful on the negative side.)sbvConstant False as a ,. We represent it using the integer value 0.sbvConstant True as a ,. We represent it using the integer value 1. {sbv Lift a unary function through a .sbv!Lift a binary function through a .sbvMap a unary function through a .sbv Map a binary function through a . |sbv)Show a CV, with kind info if bool is Truesbv(Create a constant word from an integral. }sbv"Generate a random constant value () of the correct kind. ~sbv"Generate a random constant value () of the correct kind. sbvVShow instance. Regular sets are shown as usual. Complements are shown "U -" notation. sbv-Ord instance for VWVal. Same comments as the  % instance why this cannot be derived. sbvEq instance for CVVal. Note that we cannot simply derive Eq/Ord, since CVAlgReal doesn't have proper instances for these when values are infinitely precise reals. However, we do need a structural eq/ord for Map indexes; so define custom ones here: sbvShow instance for . sbvi instance for CV sbv"Show instance, shows with the kind sbvKind instance for Extended CV sbvShow instance for Generalized  sbvi instance for generalized CV0 v w y z { | } ~{(c) Levent ErkokBSD3erkokl@gmail.com experimentalSafewsbv2Specify how to save timing information, if at all.sbvShow   in human readable form.   is essentially picoseconds (10^-12 seconds). We show it so that it's represented at the day:hour:minute:second.XXX granularity.|(c) Levent ErkokBSD3erkokl@gmail.com experimentalNone$&'248=?@ACMPSUVXFsbvQuery execution contextsbvTriggered from inside SBVsbvTriggered from user codesbv An SMT solversbvThe solver in usesbvThe path to its executablesbvPEach line sent to the solver will be passed through this function (typically id)sbv Options to provide to the solversbv=The solver engine, responsible for interpreting solver outputsbv"Various capabilities of the solversbvSolvers that SBV is aware of sbv An SMT enginesbv%A script, to be passed to the solver.sbv Initial feedsbv'Continuation script, to extract resultssbvGThe result of an SMT solver call. Each constructor is tagged with the  that created it so that further tools can inspect it and build layers of results, if needed. For ordinary uses of the library, this type should not be needed, instead use the accessor functions on it. (Custom Show instances and model extractors.)sbvYUnsatisfiable. If unsat-cores are enabled, they will be returned in the second parameter.sbvSatisfiable with modelsbvNProver returned a model, but in an extension field containing Infinite/epsilonsbv.Prover returned unknown, with the given reasonsbv0Prover errored out, with possibly a bogus resultsbv A model, as returned by a solversbv/Mapping of symbolic values to objective values.sbvfMapping of input variables as reported by the solver. Only collected if model validation is requested.sbv(Mapping of symbolic values to constants.sbvMapping of uninterpreted functions to association lists in the model. Note that an uninterpreted constant (function of arity 0) will be stored in the  field.sbvSolver configuration. See also }, ~, , , , etc. which are instantiations of this type for those solvers, with reasonable defaults. In particular, custom configuration can be created by varying those values. (Such as z3{verbose=True}.)Most fields are self explanatory. The notion of precision for printing algebraic reals stems from the fact that such values does not necessarily have finite decimal representations, and hence we have to stop printing at some depth. It is important to emphasize that such values always have infinite precision internally. The issue is merely with how we print such an infinite precision value on the screen. The field  controls the printing precision, by specifying the number of digits after the decimal point. The default value is 16, but it can be set to any positive integer.'When printing, SBV will add the suffix ... at the and of a real-value, if the given bound is not sufficient to represent the real-value exactly. Otherwise, the number will be written out in standard decimal notation. Note that SBV will always print the whole value if it is precise (i.e., if it fits in a finite number of digits), regardless of the precision limit. The limit only applies if the representation of the real value is not finite, i.e., if it is not rational.The  field can be used to print numbers in base 2, 10, or 16. If base 2 or 16 is used, then floating-point values will be printed in their internal memory-layout format as well, which can come in handy for bit-precise analysis.sbv Debug modesbvXPrint timing information on how long different phases took (construction, solving, etc.)sbvCPrint integral literals in this base (2, 10, and 16 are supported.)sbvEPrint algebraic real values with this precision. (SReal, default: 16)sbvUUsually "(check-sat)". However, users might tweak it based on solver characteristics.sbvIn a ? call, return at most this many models. If nothing, return all.sbvIn a & call, print models as they are found.sbvIn a B call, should we try to extract values of uninterpreted functions?sbvWhen constructing a model, ignore variables whose name satisfy this predicate. (Default: (const False), i.e., don't ignore anything)sbvLIf set, SBV will attempt to validate the model it gets back from the solver.sbvuValidate optimization results. NB: Does NOT make sure the model is optimal, just checks they satisfy the constraints.sbvcIf Just, the entire interaction will be recorded as a playable file (for debugging purposes mostly)sbv+What version of SMT-lib we use for the toolsbvThe actual SMT solver.sbvLShould we permit use of quantifiers in the query mode? (Default: False. See  ,http://github.com/LeventErkok/sbv/issues/459 for why.)sbv3Rounding mode to use for floating-point conversionssbv%Options to set as we start the solversbvSIf true, we shall ignore the exit code upon exit. Otherwise we require ExitSuccess.sbvQRedirect the verbose output to this file if given. If Nothing, stdout is implied.sbvaRounding mode to be used for the IEEE floating-point operations. Note that Haskell's default is v. If you use a different rounding mode, then the counter-examples you get may not match what you observe in Haskell.sbvyRound to nearest representable floating point value. If precisely at half-way, pick the even number. (In this context, even% means the lowest-order bit is zero.)sbvRound to nearest representable floating point value. If precisely at half-way, pick the number further away from 0. (That is, for positive values, pick the greater; for negative values, pick the smaller.)sbvHRound towards positive infinity. (Also known as rounding-up or ceiling.)sbvHRound towards negative infinity. (Also known as rounding-down or floor.)sbv/Round towards zero. (Also known as truncation.)sbvKTranslation tricks needed for specific capabilities afforded by each solversbv$Supports SMT-Lib2 style quantifiers?sbv+Supports SMT-Lib2 style uninterpreted-sortssbvSupports unbounded integers?sbvSupports reals?sbv-Supports printing of approximations of reals?sbv Supports floating point numbers?sbvSupports set operations?sbvSupports optimization routines?sbv#Supports pseudo-boolean operations?sbv)Supports interactive queries per SMT-Lib?sbv4Supports global declarations? (Needed for push-pop.)sbvSupports datatypes?sbv;Supports flattened model output? (With given config lines.)sbvURepresentation of an SMT-Lib program. In between pre and post goes the refuted modelssbvRepresentation of SMTLib Program versions. As of June 2015, we're dropping support for SMTLib1, and supporting SMTLib2 only. We keep this data-type around in case SMTLib3 comes along and we want to support 2 and 3 simultaneously. sbv/A functional array index is simply an int value sbv)An SMT array index is simply an int valuesbvWe implement a peculiar caching mechanism, applicable to the use case in implementation of SBV's. Whenever we do a state based computation, we do not want to keep on evaluating it in the then-current state. That will produce essentially a semantically equivalent value. Thus, we want to run it only once, and reuse that result, capturing the sharing at the Haskell level. This is similar to the "type-safe observable sharing" work, but also takes into the account of how symbolic simulation executes.^See Andy Gill's type-safe obervable sharing trick for the inspiration behind this technique: =http://ku-fpg.github.io/files/Gill-09-TypeSafeReification.pdf/Note that this is *not* a general memo utility!sbv is specialization of  to the  VZ monad. Unless you are using transformers explicitly, this is the type you should prefer.sbvA generalization of .sbvA Symbolic computation. Represented by a reader monad carrying the state of the computation, layered on top of IO for creating unique references to hold onto intermediate results..Computations which support symbolic operationssbvThe Symbolic value. Either a constant (Left) or a symbolic value ( Right CachedH). Note that caching is essential for making sure sharing is preserved.sbv%The state of the symbolic interpreter sbv kind KBool sbv1The state in query mode, i.e., additional contextsbv3Different means of running a symbolic piece of codesbv;In regular mode, with a stage. Bool is True if this is SAT.sbvCode generation mode.sbvLConcrete simulation mode, with given environment if any. If Nothing: Random. sbvStage of an interactive run sbv#Cached values, implementing sharing sbv?Code-segments for Uninterpreted-constants, as given by the user sbv7Uninterpreted-constants generated during a symbolic run sbv1Functional Arrays generated during a symbolic run sbv*SMT Arrays generated during a symbolic run sbv"Representation for symbolic arrays sbv&Tables generated during a symbolic run sbvOKinds used in the program; used for determining the final SMT-Lib logic to pick sbv0Constants are stored in a map, for hash-consing. sbv%Expression map, used for hash-consingsbv*The context of a symbolic array as createdsbvFA new array, the contents are initialized with the given value, if anysbv:An array created by mutating another array at a given cellsbv9An array created by symbolically merging two other arrayssbv(Result of running a symbolic computationsbvkinds used in the programsbv0quick-check counter-example information (if any)sbv*observable expressions (part of the model)sbvuninterpeted code segmentssbv,inputs (possibly existential) + tracker varssbv constantssbvJtables (automatically constructed) (tableno, index-type, result-type) eltssbvarrays (user specified)sbvuninterpreted constantssbvaxiomssbv assignmentssbv additional constraints (boolean) sbv assertions!sbvoutputs"sbv`A query is a user-guided mechanism to directly communicate and extract results from the solver.#sbv4An queriable value. This is a generalization of the 'Y class, in case one needs to be more specific about how projections/embeddings are done.$sbv&^ Create a new symbolic value of type a%sbv,^ Extract the current value in a SAT context&sbv#^ Create a literal value. Morally, & and %% are inverses of each other via the ) monad transformer.'sbvCreate a fresh variable of some type in the underlying query monad transformer. For further control on how these variables are projected and embedded, see the # class.)sbvuA query is a user-guided mechanism to directly communicate and extract results from the solver. A generalization of .,sbv,Computations which support query operations..sbv9The state we keep track of as we interact with the solver7sbvuObjective of optimization. We can minimize, maximize, or give a soft assertion with a penalty for not satisfying it.8sbvMinimize this metric9sbvMaximize this metric:sbv,A soft assertion, with an associated penalty;sbv5Penalty for a soft-assertion. The default penalty is 1, with all soft-assertions belonging to the same objective goal. A positive weight and an optional group can be provided by using the ; constructor.<sbvDefault: Penalty of 1 and no group attached=sbv+Penalty with a weight and an optional group>sbvStyle of optimization. Note that in the pareto case the user is allowed to specify a max number of fronts to query the solver for, since there might potentially be an infinite number of them and there is no way to know exactly how many ahead of time. If  L is given, SBV will possibly loop forever if the number is really infinite.?sbvUObjectives are optimized in the order given, earlier objectives have higher priority.@sbv*Each objective is optimized independently.Asbv}Objectives are optimized according to pareto front: That is, no objective can be made better without making some other worse.BsbvBC pairs symbolic values and user given/automatically generated namesCsbv&A program is a sequence of assignmentsFsbvA symbolic expressionHsbvA simple type for SBV computations, used mainly for uninterpreted constants. We keep track of the signedness/size of the arguments. A non-function will have just one entry in the list.JsbvFQuantifiers: forall or exists. Note that we allow arbitrary nestings. sbvSet operations.MsbvSequence operations.Nsbv See StrConcatOsbv See StrLenPsbv See StrUnitQsbv See StrNthRsbv See StrSubseqSsbvSee StrIndexOfTsbvSee StrContainsUsbvSee StrPrefixOfVsbvSee StrSuffixOfWsbvSee StrReplaceXsbvURegular expressions. Note that regular expressions themselves are concrete, but the  function from the Z class can check membership against a symbolic string/character. Also, we are preferring a datatype approach here, as opposed to coming up with some string-representation; there are way too many alternatives already so inventing one isn't a priority. Please get in touch if you would like a parser for this type as it might be easier to use.Ysbv Precisely match the given stringZsbvAccept every string[sbvAccept no strings\sbvAccept range of characters]sbv Concatenation^sbvKleene Star: Zero or more_sbvKleene Plus: One or more`sbv Zero or oneasbvFrom n repetitions to m repetitionsbsbvUnion of regular expressionscsbv#Intersection of regular expressionsdsbv.String operations. Note that we do not define StrAt as it translates to i trivially.esbv$Concatenation of one or more stringsfsbv String lengthgsbv Unit stringhsbv Nth elementisbvRetrieves substring of s at offsetjsbvRetrieves first position of sub in s, -1 if there are no occurrencesksbvDoes s contain the substring sub?lsbvIs pre a prefix of s?msbvIs suf a suffix of s?nsbv Replace the first occurrence of src by dst in sosbv#Retrieve integer encoded by string s (ground rewriting only)psbv#Retrieve string encoded by integer i (ground rewriting only)qsbv,Check if string is in the regular expression sbvOverflow operations sbvSigned multiplication overflow sbvSigned multiplication underflow sbv Unsigned multiplication overflowrsbvPseudo-boolean operationsssbv At most ktsbv At least kusbv Exactly kvsbv:At most k, with coefficients given. Generalizes PB_AtMostwsbv;At least k, with coefficients given. Generalizes PB_AtLeastxsbv;Exactly k, with coefficients given. Generalized PB_ExactlyysbvFloating point operationssbvSymbolic operationssbv3A symbolic word, tracking it's signedness and size.sbvA symbolic node id sbvKind of a symbolic word.sbvForcing an argument; this is a necessary evil to make sure all the arguments to an uninterpreted function are evaluated before called; the semantics of uinterpreted functions is necessarily strict; deviating from Haskell'ssbvConstant False as an /. Note that this value always occupies slot -2.sbvConstant True as an /. Note that this value always occupies slot -1.sbv&Are there any existential quantifiers? sbv`To improve hash-consing, take advantage of commutative operators by reordering their arguments. sbvThe name of the objective sbvAre we cecking safety sbvAre we in setup? sbvAre we in a run?sbv.Is this a CodeGen run? (i.e., generating code) sbvGet a new IncState sbvGet a new IncState sbvGet the current path condition sbv4Extend the path condition with the given test value.sbvAre we running in proof mode? sbv?Things we do not support in interactive mode, at least for now! sbv Modification of the state, but carefully handling the interactive tasks. Note that the state is always updated regardless of the mode, but we get to also perform extra operation in interactive mode. (Typically error out, but also simply ignore if it has no impact.) sbvModify the incremental state sbvAdd an observable sbvIncrement the variable countersbvUninterpreted constants and functions. An uninterpreted constant is a value that is indexed by its name. The only property the prover assumes about these values are that they are equivalent to themselves; i.e., (for functions) they return the same results when applied to same arguments. We support uninterpreted-functions as a general means of black-box'ing operations that are  irrelevantx for the purposes of the proof; i.e., when the proofs can be performed without any knowledge about the function itself.sbv@Create a new uninterpreted symbol, possibly with user given code sbv"Add a new sAssert based constraintsbvCreate an internal variable, which acts as an input but isn't visible to the user. Such variables are existentially quantified in a SAT context, and universally quantified in a proof context. sbvCreate a new SVsbvRegister a new kind with the system, used for uninterpreted sorts. NB: Is it safe to have new kinds in query mode? It could be that the new kind might introduce a constraint that effects the logic. For instance, if we're seeing   for the first time and using a BV logic, then things would fall apart. But this should be rare, and hopefully the success-response checking mechanism will catch the rare cases where this is an issue. In either case, the user can always arrange for the right logic by calling j9 appropriately, so it seems safe to just allow for this. sbvNRegister a new label with the system, making sure they are unique and have no '|' s in them sbv-Create a new constant; hash-cons as necessarysbv*Create a new table; hash-cons as necessarysbv/Create a new expression; hash-cons as necessary sbv*Convert a symbolic value to an internal SV sbvGeneralization of  sbv0Map a computation over the symbolic transformer.sbvCreate a symbolic value, based on the quantifier we have. If an explicit quantifier is given, we just use that. If not, then we pick the quantifier appropriately based on the run-mode. randomCVG is used for generating random values for this variable when used for  quickCheck or  purposes. sbv3Create an existentially quantified tracker variablesbvGeneralization of sbvGeneralization of sbvGeneralization of sbvGeneralization of  sbvCreate a symbolic value, based on the quantifier we have. If an explicit quantifier is given, we just use that. If not, then we pick the quantifier appropriately based on the run-mode. randomCVG is used for generating random values for this variable when used for  quickCheck or  purposes. sbvZIntroduce a new user name. We simply append a suffix if we have seen this variable before.sbvGeneralization of sbv:Grab the program from a running symbolic simulation state. sbvGeneralization of  sbvGeneralization of sbvURequire a boolean condition to be true in the state. Only used for internal purposes.sbvGeneralization of sbvGeneralization of sbvCache a state-based computationsbv'Uncache a previously cached computationsbv%Uncache, retrieving SMT array indexes sbv,Uncache, retrieving Functional array indexes sbvSGeneric uncaching. Note that this is entirely safe, since we do it in the IO monad.sbv)The extension associated with the version sbv-Returns true if we have to perform validation sbv*Again, simply use the node-id for ordering sbv'For equality, we merely use the node-id sbvEShow instance. It's important that these follow the internal z3 names sbvShow instance for XR. The mapping is done so the outcome matches the SMTLib string reg-exp operations sbvRegular expressions as a   instance. Note that only   (union) and   (concatenation) make sense. sbvHWith overloaded strings, we can have direct literal regular expressions. sbvShow instance for StrOpV. Note that the mapping here is important to match the SMTLib equivalents, see here: 0http://rise4fun.com/z3/tutorialcontent/sequences sbv5Show instance for SeqOp. Again, mapping is important. sbvShow instance for J sbv0We simply show indexes as the underlying integer sbv0We simply show indexes as the underlying integer sbv kind sbvShow instance for , for debugging purposes sbvEThis instance is only defined so that we can define an instance for .   and   simply throw an error. sbv instance for `SymbolicT m` sbvcurrent configurationsbv$the state in which to run the enginesbvprogramsbv continuation        !"#$%&'()*+,-./0123456789:;=<>?@ABCDEFGHIJKL   MNOPQRSTUVWXYZb\[]^_`acdefghijklmnopq rstuvwxyz{|}~          (c) Levent ErkokBSD3erkokl@gmail.com experimentalNoneJdsbvArrays managed internallysbv!Arrays in terms of SMT-Lib arrayssbv Boolean True.sbvBoolean False.sbvConvert from a Boolean.sbvConvert from an Integer.sbvConvert from a FloatsbvConvert from a Float sbvConvert from a String sbvConvert from a CharsbvConvert from a Rationalsbv<Extract a bool, by properly interpreting the integer stored.sbv)Extract an integer from a concrete value.sbv,Grab the numerator of an SReal, if availablesbv.Grab the denominator of an SReal, if availablesbvConstructing [x, y, .. z] and [x .. y]. Only works when all arguments are concrete and integral and the result is guaranteed finite Note that the it isn't "obviously" clear why the following works; after all we're doing the construction over Integer's and mapping it back to other types such as SIntN/SWordN. The reason is that the values we receive are guaranteed to be in their domains; and thus the lifting to Integers preserves the bounds; and then going back is just fine. So, things like [1, 5 .. 200] :: [SInt8]< work just fine (end evaluate to empty list), since we see  [1, 5 .. -56] in the Integer* domain. Also note the explicit check for s /= fC below to make sure we don't stutter and produce an infinite list.sbv Addition.sbvMultiplication.sbv Subtraction.sbv Unary minus.sbvAbsolute value.sbv Division.sbvExponentiation.sbv<Bit-blast: Little-endian. Assumes the input is a bit-vector.sbvSet a given bit at indexsbv9Bit-blast: Big-endian. Assumes the input is a bit-vector.sbvnUn-bit-blast from big-endian representation to a word of the right size. The input is assumed to be unsigned.sbvqUn-bit-blast from little-endian representation to a word of the right size. The input is assumed to be unsigned.sbvAdd a constant value:sbv Increment:sbv Decrement:sbvQuotient: Overloaded operation whose meaning depends on the kind at which it is used: For unbounded integers, it corresponds to the SMT-Lib "div" operator ( Euclidean division, which always has a non-negative remainder). For unsigned bitvectors, it is "bvudiv"; and for signed bitvectors it is "bvsdiv", which rounds toward zero. Division by 0 is defined s.t. x/0 = 0, which holds even when x itself is 0.sbvFRemainder: Overloaded operation whose meaning depends on the kind at which it is used: For unbounded integers, it corresponds to the SMT-Lib "mod" operator (always non-negative). For unsigned bitvectors, it is "bvurem"; and for signed bitvectors it is "bvsrem", which rounds toward zero (sign of remainder matches that of x"). Division by 0 is defined s.t. x/0 = 0, which holds even when x itself is 0.sbvCombination of quot and rem sbvDOptimize away x == true and x /= false to x; otherwise just do eqOptsbv Equality.sbv Inequality. sbvSet equality. Note that we only do constant folding if we get both a regular or both a complement set. Otherwise we get a symbolic value even if they might be completely concrete. sbv7Strong equality. Only matters on floats, where it says NaN equals NaN and +0 and -0) are different. Otherwise equivalent to .sbv Less than.sbv Greater than.sbvLess than or equal to.sbvGreater than or equal to.sbv Bitwise and.sbv Bitwise or.sbv Bitwise xor.sbvBitwise complement.sbvQShift left by a constant amount. Translates to the "bvshl" operation in SMT-Lib.NB. Haskell spec says the behavior is undefined if the shift amount is negative. We arbitrarily return the value unchanged if this is the case.sbvShift right by a constant amount. Translates to either "bvlshr" (logical shift right) or "bvashr" (arithmetic shift right) in SMT-Lib, depending on whether x is a signed bitvector.NB. Haskell spec says the behavior is undefined if the shift amount is negative. We arbitrarily return the value unchanged if this is the case.sbvRotate-left, by a constant.NB. Haskell spec says the behavior is undefined if the shift amount is negative. We arbitrarily return the value unchanged if this is the case.sbvRotate-right, by a constant.NB. Haskell spec says the behavior is undefined if the shift amount is negative. We arbitrarily return the value unchanged if this is the case. sbvuGeneric rotation. Since the underlying representation is just Integers, rotations has to be careful on the bit-size. sbvExtract bit-sequences. sbv Join two words, by concataneting sbv+If-then-else. This one will force branches. sbvYLazy If-then-else. This one will delay forcing the branches unless it's really necessary. sbv#Merge two symbolic values, at kind k , possibly forceH'ing the branches to make sure they do not evaluate to the same result.sbvTotal indexing operation. svSelect xs default index is intuitively the same as  xs !! index, except it evaluates to default if index) overflows. Translates to SMT-Lib tables.sbv5Convert a symbolic bitvector from unsigned to signed.sbv5Convert a symbolic bitvector from signed to unsigned.sbv?Convert a symbolic bitvector from one integral kind to another.sbvBConvert an SVal from kind Bool to an unsigned bitvector of size 1.sbvMConvert an SVal from a bitvector of size 1 (signed or unsigned) to kind Bool.sbvTest the value of a bit. Note that we do an extract here as opposed to masking and checking against zero, as we found extraction to be much faster with large bit-vectors.sbvGeneralization of %, where the shift-amount is symbolic.sbvGeneralization of %, where the shift-amount is symbolic.XNB. If the shiftee is signed, then this is an arithmetic shift; otherwise it's logical. sbv.Generic shifting of bounded quantities. The shift amount must be non-negative and within the bounds of the argument for bit vectors. For negative shift amounts, the result is returned unchanged. For overshifts, left-shift produces 0, right shift produces 0 or -1 depending on the result being signed.sbvGeneralization of s, where the rotation amount is symbolic. If the first argument is not bounded, then the this is the same as shift.sbv A variant of  that uses a barrel-rotate design, which can lead to better verification code. Only works when both arguments are finite and the second argument is unsigned.sbv A variant of  that uses a barrel-rotate design, which can lead to better verification code. Only works when both arguments are finite and the second argument is unsigned.sbvGeneralization of s, where the rotation amount is symbolic. If the first argument is not bounded, then the this is the same as shift. sbvOverflow detection.sbvRead the array element at asbvUpdate the element at a to be bsbv?Merge two given arrays on the symbolic condition Intuitively: ,mergeArrays cond a b = if cond then a else b=. Merging pushes the if-then-else choice down on to elementssbvCreate a named new arraysbvCompare two arrays for equality sbvConvert a node-id to an SVal sbv Convert an  to an  sbvA variant of SVal equality, but taking into account of constants NB. The rationalCheck is paranid perhaps, but is necessary in case we have some funky polynomial roots in there. We do allow for floating-points here though. Why? Because the Eq instance of X does the right thing by using object equality. (i.e., it does the right thing for NaN+0D-0 etc.) A straightforward equality here would be wrong for floats! sbvRead the array element at a. For efficiency purposes, we create a memo-table as we go along, as otherwise we suffer significant performance penalties. See:  ,http://github.com/LeventErkok/sbv/issues/402 and  ,http://github.com/LeventErkok/sbv/issues/396.!sbvUpdate the element at address to be b"sbv?Merge two given arrays on the symbolic condition Intuitively: ,mergeArrays cond a b = if cond then a else b=. Merging pushes the if-then-else choice down on to elements#sbvCreate a named new array sbvECreate a symbolic two argument operation; with shortcut optimizations sbvCCreate a symbolic two argument operation; no shortcut optimizations sbv-eqOpt says the references are to the same SV, thus we can optimize. Note that we explicitly disallow KFloat/KDouble here. Why? Because it's *NOT* true that NaN == NaN, NaN >= NaN, and so-forth. So, we have to make sure we don't optimize floats and doubles, in case the argument turns out to be NaN. sbv)Predicate to check if a value is concrete sbv2Predicate for optimizing word operations like (+) and (*). NB. We specifically do *not* match for Double/Float; because FP-arithmetic doesn't obey traditional rules. For instance, 0 * x = 0 fails if x happens to be NaN or +/- Infinity. So, we merely return False when given a floating-point value here. sbvOPredicate for optimizing word operations like (+) and (*). NB. See comment on  6 for why we don't match for Float/Double values here. sbvPredicate for optimizing bitwise operations. The unbounded integer case of checking against -1 might look dubious, but that's how Haskell treats  % as a member of the Bits class, try (-1 :: Integer)   i for any i and you'll get  H. sbv%Predicate for optimizing comparisons. sbv%Predicate for optimizing comparisons. sbvjMost operations on concrete rationals require a compatibility check to avoid faulting on algebraic reals. sbv;Quot/Rem operations require a nonzero check on the divisor. sbv'Same as rationalCheck, except for SBV's$sbvDGiven a composite structure, figure out how to compare for less than sbvStructural less-than for tuples sbvStructural less-than for maybes sbvStructural less-than for eitherQ            !"# $(c) Levent ErkokBSD3erkokl@gmail.com experimentalNone/789=>?@AHVXkn%sbvHArrays implemented internally, without translating to SMT-Lib functions:Internally handled by the library and not mapped to SMT-Lib, hence can be used with solvers that don't support arrays. (Such as abc.)KReading from an unintialized value is OK. If the default value is given in -S, it will be the result. Otherwise, the read yields an uninterpreted constant.$Cannot check for equality of arrays.8Can be used in code-generation (i.e., compilation to C).#Can not quick-check theorems using  SFunArray values=Typically faster as it gets compiled away during translation.(sbv+Arrays implemented in terms of SMT-arrays: 2http://smtlib.cs.uiowa.edu/theories-ArraysEx.shtmlMaps directly to SMT-lib arraysKReading from an unintialized value is OK. If the default value is given in -S, it will be the result. Otherwise, the read yields an uninterpreted constant.&Can check for equality of these arrays:Cannot be used in code-generation (i.e., compilation to C)"Cannot quick-check theorems using SArray valuesITypically slower as it heavily relies on SMT-solving for the array theory+sbv#Flat arrays of symbolic values An  array a b! is an array indexed by the type q a, with elements of type q b.If a default value is supplied, then all the array elements will be initialized to this value. Otherwise, they will be left unspecified, i.e., a read from an unwritten location will produce an uninterpreted constant.>While it's certainly possible for user to create instances of +, the ( and % instances already provided should cover most use cases in practice. Note that there are a few differences between these two models in terms of use models:(X produces SMTLib arrays, and requires a solver that understands the array theory. %b is internally handled, and thus can be used with any solver. (Note that all solvers except < support arrays, so this isn't a big decision factor.)For both arrays, if a default value is supplied, then reading from uninitialized cell will return that value. If the default is not given, then reading from uninitialized cells is still OK for both arrays, and will produce an uninterpreted constant in both cases.Only (n supports checking equality of arrays. (That is, checking if an entire array is equivalent to another.) %s cannot be checked for equality. In general, checking wholesale equality of arrays is a difficult decision problem and should be avoided if possible.Only %+ supports compilation to C. Programs using (4 will not be accepted by the C-code generator.JYou cannot use quickcheck on programs that contain these arrays. (Neither ( nor %.)With (, SBV transfers all array-processing to the SMT-solver. So, it can generate programs more quickly, but they might end up being too hard for the solver to handle. With %#, SBV only generates code for individual elements and the array itself never shows up in the resulting SMTLib program. This puts more onus on the SBV side and might have some performance impacts, but it might generate problems that are easier for the SMT solvers to handle.As a rule of thumb, try ( first. These should generate compact code. However, if the backend solver has hard time solving the generated problems, switch to %R. If you still have issues, please report so we can see what the problem might be!,sbvGeneralization of -sbvGeneralization of .sbvRead the array element at a/sbvUpdate the element at a to be b0sbv?Merge two given arrays on the symbolic condition Intuitively: ,mergeArrays cond a b = if cond then a else b=. Merging pushes the if-then-else choice down on to elements1sbv+Internal function, not exported to the user2sbvA 2` is a potential symbolic value that can be created instances of to be fed to a symbolic program.3sbvGeneralization of 4sbv#Turn a literal constant to symbolic5sbv+Extract a literal, from a CV representation6sbv/Does it concretely satisfy the given predicate?7sbvGeneralization of 8sbvGeneralization of 9sbvGeneralization of :sbvGeneralization of ;sbvGeneralization of <sbvGeneralization of =sbvGeneralization of >sbvGeneralization of ?sbvGeneralization of @sbvGeneralization of AsbvGeneralization of Bsbv+Extract a literal, if the value is concreteCsbvIs the symbolic word concrete?Dsbv%Is the symbolic word really symbolic?EsbvFA class representing what can be returned from a symbolic computation.FsbvGeneralization of GsbvjActions we can do in a context: Either at problem description time or while we are dynamically querying.  and "m are two instances of this class. Note that we use this mechanism internally and do not export it from SBV.HsbvFAdd a constraint, any satisfying instance must satisfy this condition.IsbviAdd a soft constraint. The solver will try to satisfy this condition if possible, but won't if it cannot.JsbvBAdd a named constraint. The name is used in unsat-core extraction.Ksbv,Add a constraint, with arbitrary attributes.LsbvSet info. Example: setInfo ":status" ["unsat"].MsbvSet an option.NsbvSet the logic.OsbvAdd a user specified axiom to the generated SMT-Lib file. The first argument is a mere string, use for commenting purposes. The second argument is intended to hold the multiple-lines of the axiom text as expressed in SMT-Lib notation. Note that we perform no checks on the axiom itself, to see whether it's actually well-formed or is sensical by any means. A separate formalization of SMT-Lib would be very useful here.PsbvhSet a solver time-out value, in milli-seconds. This function essentially translates to the SMTLib call (set-info :timeout val)r, and your backend solver may or may not support it! The amount given is in milliseconds. Also see the function : for finer level control of time-outs, directly from SBV.Qsbv*Get the state associated with this contextRsbvThe symbolic variant of Ssbv7Internal representation of a symbolic simulation resultTsbv'SMTLib representation, given the configVsbvSymbolic 8-tuple.WsbvSymbolic 7-tuple.XsbvSymbolic 6-tuple.YsbvSymbolic 5-tuple.ZsbvSymbolic 4-tuple.[sbvSymbolic 3-tuple.\sbvSymbolic 2-tuple. NB. ] and \ are equivalent.]sbvSymbolic 2-tuple. NB. ] and \ are equivalent.^sbv Symbolic . Note that we use , which supports both regular sets and complements, i.e., those obtained from the universal set (of the right type) by removing elements._sbv Symbolic  !`sbv Symbolic  "asbv7A symbolic list of items. Note that a symbolic list is not= a list of symbolic items, that is, it is not the case that  SList a = [a]F, unlike what one might expect following haskell lists/sequences. An a is a symbolic value of its own, of possibly arbitrary but finite length, and internally processed as one unit as opposed to a fixed-length list of items. Note that lists can be nested, i.e., we do allow lists of lists of ... items.bsbv2A symbolic string. Note that a symbolic string is notB a list of symbolic characters, that is, it is not the case that SString = [SChar]>, unlike what one might expect following Haskell strings. An b is a symbolic value of its own, of possibly arbitrary but finite length, and internally processed as one unit as opposed to a fixed-length list of characters.csbvA symbolic character. Note that, as far as SBV's symbolic strings are concerned, a character is currently an 8-bit unsigned value, corresponding to the ISO-8859-1 (Latin-1) character set:  +http://en.wikipedia.org/wiki/ISO/IEC_8859-1 . A Haskell  #, on the other hand, is based on unicode. Therefore, there isn't a 1-1 correspondence between a Haskell character and an SBV character for the time being. This limitation is due to the SMT-solvers only supporting this particular subset. However, there is a pending proposal to add support for unicode, and SBV will track these changes to have full unicode support as solvers become available. For details, see: 8http://smtlib.cs.uiowa.edu/theories-UnicodeStrings.shtmldsbv0IEEE-754 double-precision floating point numbersesbv0IEEE-754 single-precision floating point numbersfsbv0Infinite precision symbolic algebraic real valuegsbv(Infinite precision signed symbolic valuehsbv;64-bit signed symbolic value, 2's complement representationisbv;32-bit signed symbolic value, 2's complement representationjsbv;16-bit signed symbolic value, 2's complement representationksbv:8-bit signed symbolic value, 2's complement representationlsbv64-bit unsigned symbolic valuemsbv32-bit unsigned symbolic valuensbv16-bit unsigned symbolic valueosbv8-bit unsigned symbolic valuepsbvA symbolic boolean/bitqsbvThe Symbolic value. The parameter aV is phantom, but is extremely important in keeping the user interface strongly typed.tsbvGet the current path conditionusbv4Extend the path condition with the given test value.vsbvNot-A-Number for   and  $X. Surprisingly, Haskell Prelude doesn't have this value defined, so we provide it here.wsbv Infinity for   and  $X. Surprisingly, Haskell Prelude doesn't have this value defined, so we provide it here.xsbv@Symbolic variant of Not-A-Number. This value will inhabit both d and e.ysbv<Symbolic variant of infinity. This value will inhabit both d and e.zsbv Symbolic  H{sbv Symbolic  %|sbvSymbolic boolean negation}sbvSymbolic conjunction~sbvSymbolic disjunctionsbvSymbolic logical xorsbv Symbolic nandsbv Symbolic norsbvSymbolic implicationsbvSymbolic boolean equivalencesbvConversion from  & to psbvGeneralization of  'sbvGeneralization of  (sbvGeneralization of  )sbvGeneralization of  *sbvSymbolic variant of sbvSymbolic variant of sbvSymbolic variant of sbvSymbolic variant of sbvSymbolic variant of sbv Alias for sbv Alias for sbv Alias for sbv Alias for sbv Alias for sbv+Convert a symbolic value to a symbolic-wordsbvGeneralization of sbvGeneralization of  +sbvEThis instance is only defined so that we can define an instance for .   and   simply throw an error. Use  instead. ,sbvA  - instance is not particularly "desirable," when the value is symbolic, but we do need this instance as otherwise we cannot simply evaluate Haskell functions that return symbolic values and have their constant values printed easily! .sbv can be used symbolically /sbv=IsList instance allows list literals to be written compactly.MNOPQSVWXYZ[\]^_`abcdefghijklmnopqrstuvw  !)*+./0123456789:;=<>?@ABCDEFGHIJKLMNOPQRSTUVWXYZb\[]^_`acdefghijklmnopqrstuvwxyz{|}~%&'()*+-,./012=789:;<>?@A4B5CD63EFGOHIJKNMLPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~}3~263211(c) Levent ErkokBSD3erkokl@gmail.com experimentalNone? 0sbvNADT S-Expression format, suitable for representing get-model output of SMT-Lib 1sbv:Extremely simple minded tokenizer, good for our use model. 2sbvIThe balance of parens in this string. If 0, this means it's a legit line! 3sbvGParse a string into an SExpr, potentially failing with an error message 4sbvMParses the Z3 floating point formatted numbers like so: 1.321p5/1.2123e9 etc. 5sbv,Convert an (s, e, m) triple to a float value 6sbv,Convert an (s, e, m) triple to a float value 7sbv\Special constants of SMTLib2 and their internal translation. Mainly rounding modes for now. 8sbvParse a function like value. These come in two flavors: Either in the form of a store-expression or a lambda-expression. So we handle both here. 9sbvParse a lambda expression, most likely z3 specific. There's some guess work involved here regarding how z3 produces lambda-expressions; while we try to be flexible, this is certainly not a full fledged parser. But hopefully it'll cover everything z3 will throw at it. :sbvLParse a series of associations in the array notation, things that look like:2(store (store ((as const Array) 12) 3 5 9) 5 6 75)This is (most likely) entirely Z3 specific. So, we might have to tweak it for other solvers; though it isn't entirely clear how to do that as we do not know what solver we're using here. The trick is to handle all of possible SExpr's we see. We'll cross that bridge when we get to it.VNB. In case there's no "constraint" on the UI, Z3 produces the self-referential model:(x (_ as-array x))GSo, we specifically handle that here, by returning a Left of that name. ;sbvVTurn a sequence of left-right chain assignments (condition + free) into a single chain 0 < = > ? @ A 2 3 8(c) Levent ErkokBSD3erkokl@gmail.com experimentalNone=?X:sbviPrettyNum class captures printing of numbers in hex and binary formats; also supporting negative numbers.sbv,Show a number in hexadecimal, starting with 0x and type.sbv'Show a number in binary, starting with 0b and type.sbv,Show a number in hexadecimal, starting with 0x but no type.sbv'Show a number in binary, starting with 0b but no type.sbv/Show a number in hex, without prefix, or types.sbv/Show a number in bin, without prefix, or types.sbvShow as a hexadecimal value. First bool controls whether type info is printed while the second boolean controls wether 0x prefix is printed. The tuple is the signedness and the bit-length of the input. The length of the string will not0 depend on the value, but rather the bit-length.sbvShow as hexadecimal, but for C programs. We have to be careful about printing min-bounds, since C does some funky casting, possibly losing the sign bit. In those cases, we use the defined constants in  stdint.h<. We also properly append the necessary suffixes as needed.sbvShow as a hexadecimal value, integer version. Almost the same as shex above except we don't have a bit-length so the length of the string will depend on the actual value.sbv Similar to ; except in binary.sbv Similar to ; except in binary. BsbvUPad a string to a given length. If the string is longer, then we don't drop anything. CsbvBinary printer Dsbv Hex printersbvVA more convenient interface for reading binary numbers, also supports negative numberssbvvA version of show for floats that generates correct C literals for nan/infinite. NB. Requires "math.h" to be included.sbvwA version of show for doubles that generates correct C literals for nan/infinite. NB. Requires "math.h" to be included.sbvUA version of show for floats that generates correct Haskell literals for nan/infinitesbvVA version of show for doubles that generates correct Haskell literals for nan/infinitesbv[A version of show for floats that generates correct SMTLib literals using the rounding modesbv\A version of show for doubles that generates correct SMTLib literals using the rounding mode Esbv Show a rational in SMTLib formatsbv;Convert a rounding mode to the format SMT-Lib2 understands.sbv*Convert a CV to an SMTLib2 compliant valuesbvCreate a skolem 0 for the kind(c) Levent ErkokBSD3erkokl@gmail.com experimentalNoneIsbvTest output stylesbv"As a Haskell value with given namesbv'As a C array of structs with given namesbvAs a Forte/Verilog value with given name. If the boolean is True then vectors are blasted big-endian, otherwise little-endian The indices are the split points on bit-vectors for input and output valuessbvType of test vectors (abstract)sbvZRetrieve the test vectors for further processing. This function is useful in cases where K is not sufficient and custom output (or further preprocessing) is needed.sbvGenerate a set of concrete test values from a symbolic program. The output can be rendered as test vectors in different languages as necessary. Use the function FG call to indicate what fields should be in the test result. (Also see H' for filtering acceptable test values.)sbv7Render the test as a Haskell value with the given name n.(c) Levent ErkokBSD3erkokl@gmail.com experimentalNone$i sbvuAn exception thrown from SBV. If the solver ever responds with a non-success value for a command, SBV will throw an :, it so the user can process it as required. The provided  - instance will render the failure nicely. Note that if you ever catch this exception, the solver is no longer alive: You should either -- throw the exception up, or do other proper clean-up before continuing. FsbvyAn instance of SMT-Lib converter; instantiated for SMT-Lib v1 and v2. (And potentially for newer versions in the future.) GsbvyAn instance of SMT-Lib converter; instantiated for SMT-Lib v1 and v2. (And potentially for newer versions in the future.) HsbvCreate an annotated term Isbv1Show a millisecond time-out value somewhat nicely JsbvXNicely align a potentially multi-line message with some tag, but prefix with three stars KsbvGNicely align a potentially multi-line message with some tag, no prefix. LsbvAlign with some given prefix MsbvDiagnostic message when verbose NsbvIn case the SMT-Lib solver returns a response over multiple lines, compress them so we have each S-Expression spanning only a single line. Osbv?A fairly nice rendering of the exception, for display purposes. PsbvSBVExceptions are throwable. A simple "show" will render this exception nicely though of course you can inspect the individual fields as necessary. F sbvinputssbv new kindssbv constantssbvnewly created arrayssbvnewly created tablessbv/newly created uninterpreted functions/constantssbv assignmentssbvextra constraintssbv configuration GsbvInternal or external query?sbvKinds used in the problemsbvis this a sat problem?sbvextra comments to place on topsbv&inputs and aliasing names and trackerssbvskolemized inputssbv constantssbvauto-generated tablessbvuser specified arrays sbv!uninterpreted functions/constants sbvuser given axioms sbv assignments sbvextra constraints sbvoutput variablesbv configuration F G H I J K M N(c) Levent ErkokBSD3erkokl@gmail.com experimentalNonex Qsbv*Translate a problem into an SMTLib2 script RsbvDeclare new sorts SsbvDeclare tuple datatypeseg: (declare-datatypes ((SBVTuple2 2)) ((par (T1 T2) ((mkSBVTuple2 (proj_1_SBVTuple2 T1) (proj_2_SBVTuple2 T2)))))) Tsbv Find the set of tuple sizes to declare, eg (2-tuple, 5-tuple). NB. We do *not* need to recursively go into list/tuple kinds here, because register-kind function automatically registers all subcomponent kinds, thus everything we need is available at the top-level. UsbvIs Either being used? VsbvIs Maybe being used? Wsbv?Convert in a query context. NB. We do not store everything in newKsQ below, but only what we need to do as an extra in the incremental context. See |T for a list of what we include, in case something doesn't show up and you need it! Q W(c) Levent ErkokBSD3erkokl@gmail.com experimentalNone$|D Xsbv.Convert to SMT-Lib, in a full program context. Ysbv4Convert to SMT-Lib, in an incremental query context. ZsbvConvert to SMTLib-2 format [sbvConvert to SMTLib-2 format X Y(c) Levent ErkokBSD3erkokl@gmail.com experimentalNone$8MSXAE \sbv0An internal type to track of solver interactions ]sbv All is well ^sbvTimeout expired _sbvSomething else went wrongsbv6Various SMT results that we can extract models out of.sbvIs there a model?sbvExtract assignments of a model, the result is a tuple where the first argument (if True) indicates whether the model was "probable". (i.e., if the solver returned unknown.)sbvExtract a model dictionary. Extract a dictionary mapping the variables to their respective values as returned by the SMT solver. Also see .sbv4Extract a model value for a given element. Also see .sbvExtract a representative name for the model value of an uninterpreted kind. This is supposed to correspond to the value as computed internally by the SMT solver; and is unportable from solver to solver. Also see .sbvA simpler variant of % to get a model out without the fuss.sbv;Extract model objective values, for all optimization goals.sbv!Extract the value of an objectivesbv%Extract model uninterpreted-functionssbvEExtract the value of an uninterpreted-function as an association listsbv Instances of  can be automatically extracted from models returned by the solvers. The idea is that the sbv infrastructure provides a stream of CV's (constant values) coming from the solver, and the type a is interpreted based on these constants. Many typical instances are already provided, so new instances can be declared with relative ease.Minimum complete definition: sbvEGiven a sequence of constant-words, extract one instance of the type a{, returning the remaining elements untouched. If the next element is not what's expected for this type you should return  sbv2Given a parsed model instance, transform it using fh, and return the result. The default definition for this method should be sufficient in most use cases.sbvAn  call results in a  . In the  case, the boolean is  H^ if we reached pareto-query limit and so there might be more unqueried results remaining. If  %A, it means that we have all the pareto fronts returned. See the A > for details.sbvA  call results in a sbvAn  call results in a . The first boolean says whether we hit the max-model limit as we searched. The second boolean says whether there were prefix-existentials. The third boolean says whether we stopped because the solver returned .sbvA  call results in a # The reason for having a separate  is to have a more meaningful  - instance.sbvA  call results in a  `sbv-Extract the final configuration from a resultsbv1Parse a signed/sized value from a sequence of CVssbvReturn all the models from an  call, similar to 3 but is suitable for the case of multiple results.sbv2Get dictionaries from an all-sat call. Similar to .sbv=Extract value of a variable from an all-sat call. Similar to .sbvLExtract value of an uninterpreted variable from an all-sat call. Similar to . asbv@Extract a model out, will throw error if parsing is unsuccessfulsbv Given an T call, we typically want to iterate over it and print the results in sequence. The ) function automates this task by calling disp+ on each result, consecutively. The first  b argument to disp 'is the current model number. The second argument is a tuple, where the first element indicates whether the model is alleged (i.e., if the solver is not sure, returing Unknown). The arrange argument can sort the results in any way you like, if necessary. csbv"Show an SMTResult; generic versionsbvShow a model in human readable form. Ignore bindings to those variables that start with "__internal_sbv_" and also those marked as "nonModelVar" in the config; as these are only for internal purposes dsbv:Show bindings in a generalized model dictionary, tabulated esbvShow an uninterpreted function fsbv1Show a constant value, in the user-specified base gsbv-Helper function to spin off to an SMT solver. hsbvUA standard engine interface. Most solvers follow-suit here in how we "chat" to them.. isbv}A standard solver interface. If the solver is SMT-Lib compliant, then this function should suffice in communicating with it. jsbv A variant of readProcessWithExitCode(; except it deals with SBV continuations ksbvCompute and report the end time lsbv&Start a transcript file, if requested. msbvFinish up the transcript file. nsbv7-Tuples extracted from a model osbv6-Tuples extracted from a model psbv5-Tuples extracted from a model qsbv4-Tuples extracted from a model rsbv3-Tuples extracted from a model ssbvTuples extracted from a model tsbvA list of values as extracted from a model. When reading a list, we go as long as we can (maximal-munch). Note that this never fails, as we can always return the empty list! usbvFA rounding mode, extracted from a model. (Default definition suffices) vsbvCV. as extracted from a model; trivial definition wsbv  as extracted from a model xsbv $ as extracted from a model ysbvO as extracted from a model zsbv  as extracted from a model {sbv | as extracted from a model }sbv ~ as extracted from a model sbv  as extracted from a model sbv  as extracted from a model sbv  as extracted from a model sbv  as extracted from a model sbv  as extracted from a model sbv  as extracted from a model sbv & as extracted from a model sbvBase case for = at unit type. Comes in handy if there are no real variables. sbv as a generic model provider sbv as a generic model provider sbv as a generic model provider isbvThe currrent configurationsbvContext in which we are runningsbv The programsbvThe continuation$ d f h(c) Levent ErkokBSD3erkokl@gmail.com experimentalNoneX sbvAThe description of the Z3 SMT solver. The default executable is "z3"., which must be in your path. You can use the SBV_Z3Z environment variable to point to the executable on your system. The default options are "-nw -in -smt2". You can use the SBV_Z3_OPTIONS. environment variable to override the options. (c) Levent ErkokBSD3erkokl@gmail.com experimentalNoneX  sbvCThe description of the Yices SMT solver The default executable is  "yices-smt2"., which must be in your path. You can use the  SBV_YICES| environment variable to point to the executable on your system. SBV does not pass any arguments to yices. You can use the SBV_YICES_OPTIONS. environment variable to override the options. (c) Levent ErkokBSD3erkokl@gmail.com experimentalNoneXQ sbvEThe description of the MathSAT SMT solver The default executable is  "mathsat"., which must be in your path. You can use the  SBV_MATHSATZ environment variable to point to the executable on your system. The default options are  "-input=smt2". You can use the SBV_MATHSAT_OPTIONS. environment variable to override the options. (c) Levent ErkokBSD3erkokl@gmail.com experimentalNoneXb sbvBThe description of the CVC4 SMT solver The default executable is "cvc4"., which must be in your path. You can use the SBV_CVC4Z environment variable to point to the executable on your system. The default options are  "--lang smt". You can use the SBV_CVC4_OPTIONS. environment variable to override the options. (c) Levent ErkokBSD3erkokl@gmail.com experimentalNone sbvGThe description of the Boolector SMT solver The default executable is  "boolector"., which must be in your path. You can use the  SBV_BOOLECTORZ environment variable to point to the executable on your system. The default options are  "-m --smt2". You can use the SBV_BOOLECTOR_OPTIONS. environment variable to override the options. (c) Adam FoltzerBSD3erkokl@gmail.com experimentalNone sbv2The description of abc. The default executable is "abc"/, which must be in your path. You can use the SBV_ABC\ environment variable to point to the executable on your system. The default options are 6-S "%blast; &sweep -C 5000; &syn4; &cec -s -m -C 2000". You can use the SBV_ABC_OPTIONS. environment variable to override the options. (c) Levent ErkokBSD3erkokl@gmail.com experimentalNone $=>?@ACPX_k,8 sbv6A class which allows for sexpr-conversion to functions sbv\Adding a constraint, possibly with attributes and possibly soft. Only used internally. Use H and J from user programs. sbvGet the current configuration sbvGet the objectives sbvGet the program sbvGet the assertions put in via sbvGeneralization of  sbv>Sync-up the external solver with new context we have generated sbvRetrieve the query context sbvGeneralization of  sbvGeneralization of sbvGeneralization of sbvGeneralization of sbvGeneralization of sbvGeneralization of  sbv#Creating arrays, internal use only.sbvGeneralization of  sbvGeneralization of  sbvzSend a string to the solver, and return the response. Except, if the response is one of the "ignore" ones, keep querying. sbvGeneralization of  sbvGeneralization of sbvGeneralization of msbvRegistering an uninterpreted SMT function. This is typically not necessary as uses of the UI function itself will register it automatically. But there are cases where doing this explicitly can come in handy. sbvPointwise function value extraction. If we get unlucky and can't parse z3's output (happens when we have all booleans and z3 decides to spit out an expression), just brute force our way out of it. Note that we only do this if we have a pure boolean type, as otherwise we'd blow up. And I think it'll only be necessary then, I haven't seen z3 try anything smarter in other scenarios. sbvFor saturation purposes, get a proper argument. The forall quantification is safe here since we only use in smtFunSaturate calls, which looks at the kind stored inside only.sbvGeneralization of sbvGeneralization of  sbvrGet the value of a term, but in CV form. Used internally. The model-index, in particular is extremely Z3 specific! sbv5"Make up" a CV for this type. Like zero, but smarter. sbv$Go from an SExpr directly to a value sbvCRecover a given solver-printed value with a possible interpretation sbvGeneralization of  sbvGeneralization of sbvGeneralization of ksbvGeneralization of  sbvNWhat are the top level inputs? Trackers are returned as top level existentialssbvKGet observables, i.e., those explicitly labeled by the user with a call to . sbvtGet UIs, both constants and functions. This call returns both the before and after query ones. | Generalization of . sbvRepeatedly issue check-sat, after refuting the previous model. The bool is true if the model is unique upto prefix existentials. sbvGeneralization of sbvGeneralization of  sbvBail out if a parse goes bad sbvGeneralization of  sbv(Convert a query result to an SMT Problem sbvGeneralization of  sbvGeneric # instance for things that are ' and look like containers: sbvGeneric # instance for 'SymVal'/'SMTValue' values sbv as a G. sbvFunctions of arity 8 sbvFunctions of arity 7 sbvFunctions of arity 6 sbvFunctions of arity 5 sbvFunctions of arity 4 sbvFunctions of arity 3 sbvFunctions of arity 2 sbvFunctions of arity 1*       (c) Levent ErkokBSD3erkokl@gmail.com experimentalNone$SX_L" sbv An Assignment of a model bindingsbvGeneralization of sbvGeneralization of sbvGeneralization of osbvGeneralization of sbvGeneralization of  sbvCClassify a model based on whether it has unbound objectives or not. sbvGeneralization of  sbvGeneralization of  sbvGeneralization of sbvGeneralization of  sbv@Get a model stored at an index. This is likely very Z3 specific! sbvkJust after a check-sat is issued, collect objective values. Used internally only, not exposed to the user.sbvGeneralization of lsbvGeneralization of  sbvGHelper for the two variants of checkSatAssuming we have. Internal only.sbvGeneralization of  sbv;Upon a pop, we need to restore all arrays and tables. See: ,http://github.com/LeventErkok/sbv/issues/374sbvGeneralization of sbvGeneralization of sbvGeneralization of sbvGeneralization of sbvGeneralization of sbvGeneralization of sbvGeneralization of sbvGeneralization of n sbv@Retrieve the unsat core if it was asked for in the configurationsbvGeneralization of sbvGeneralization of  . Use this version with MathSAT.sbvGeneralization of . Use this version with Z3.sbvGeneralization of sbvGeneralization of sbvMake an assignment. The type  1 is abstract, the result is typically passed to : [ mkSMTResult [ a |-> 332 , b |-> 2.3 , c |-> True ] End users should use \ for automatically constructing models from the current solver state. However, an explicit  Q might be handy in complex scenarios where a model needs to be created manually.sbvGeneralization of  NB. This function does not allow users to create interpretations for UI-Funs. But that's probably not a good idea anyhow. Also, if you use the  or ? features, SBV will fail on models returned via this function.z  !"#$%&'()*+,-./0123456789:;<=>?@EGABCDFHIJKL    11(c) Brian Schroeder Levent ErkokBSD3erkokl@gmail.com experimentalNoneOsbvRun a custom query.U !"#$%&'()*+,-./01234567=>?@EGABCDFHIJKLTU"),-UTU,-)"IJKL@EGABCDFH=>?./01234567 !"#$%&'()*+,-(c) Levent ErkokBSD3erkokl@gmail.com experimentalNone $,=>?@APX4sbvISymbolically executable program fragments. This class is mainly used for  t calls, and is sufficently populated internally to cover most use cases. Users can extend it as they wish to allow  F checks for SBV programs that return/take types that are user-defined. sbvGeneralization of  sbvGeneralization of  sbvGeneralization of  sbvGeneralization of  sbv  is specialization of  to the  VZ monad. Unless you are using transformers explicitly, this is the type you should prefer.sbvA type aa is provable if we can turn it into a predicate. Note that a predicate can be made from a curried function of arbitrary arity, where each element is either a symbolic type or up-to a 7-tuple of symbolic-types. So predicates can be constructed from almost arbitrary Haskell functions that have arbitrary shapes. (See the instance declarations below.)sbvGeneralization of sbvGeneralization of sbvGeneralization of sbvGeneralization of sbvGeneralization of sbvGeneralization of sbvGeneralization of sbvGeneralization of sbvGeneralization of sbvGeneralization of sbvGeneralization of sbvGeneralization of sbvGeneralization of sbvGeneralization of sbvGeneralization of sbvGeneralization of sbvGeneralization of  sbvGeneralization of !sbv)Validate a model obtained from the solver"sbvA goal is a symbolic program that returns no values. The idea is that the constraints/min-max goals will serve as appropriate directives for sat/prove calls.#sbvA predicate is a symbolic program that returns a (symbolic) boolean value. For all intents and purposes, it can be treated as an n-ary function from symbolic-values to a boolean. The  monad captures the underlying representation, and can/should be ignored by the users of the library, unless you are building further utilities on top of SBV itself. Instead, simply use the # type when necessary. sbvqIf supported, this makes all output go to stdout, which works better with SBV Alas, not all solvers support it..$sbv2Default configuration for the Boolector SMT solver%sbv.Default configuration for the CVC4 SMT Solver.&sbv/Default configuration for the Yices SMT Solver.'sbv+Default configuration for the Z3 SMT solver(sbv0Default configuration for the MathSAT SMT solver)sbvBDefault configuration for the ABC synthesis and verification tool.*sbv<The default solver used by SBV. This is currently set to z3.+sbv~Prove a property with multiple solvers, running them in separate threads. The results will be returned in the order produced.,sbvProve a property with multiple solvers, running them in separate threads. Only the result of the first one to finish will be returned, remaining threads will be killed. Note that we send an exception to the losing processes, but we do *not* actually wait for them to finish. In rare cases this can lead to zombie processes. In previous experiments, we found that some processes take their time to terminate. So, this solution favors quick turnaround.-sbvFind a satisfying assignment to a property with multiple solvers, running them in separate threads. The results will be returned in the order produced..sbvFind a satisfying assignment to a property with multiple solvers, running them in separate threads. Only the result of the first one to finish will be returned, remaining threads will be killed. Note that we send an exception to the losing processes, but we do *not* actually wait for them to finish. In rare cases this can lead to zombie processes. In previous experiments, we found that some processes take their time to terminate. So, this solution favors quick turnaround./sbvFind a satisfying assignment to a property using a single solver, but providing several query problems of interest, with each query running in a separate thread and return the first one that returns. This can be useful to use symbolic mode to drive to a location in the search space of the solver and then refine the problem in query mode. If the computation is very hard to solve for the solver than running in concurrent mode may provide a large performance benefit.0sbvProve a property by running many queries each isolated to their own thread concurrently and return the first that finishes, killing the others1sbvFind a satisfying assignment to a property using a single solver, but run each query problem in a separate isolated thread and wait for each thread to finish. See / for more details.2sbvProve a property by running many queries each isolated to their own thread concurrently and wait for each to finish returning all results3sbv"Create an SMT-Lib2 benchmark. The  & argument controls whether this is a SAT instance, i.e., translate the query directly, or a PROVE instance, i.e., translate the negated query.4sbvGeneralization of 5sbvGeneralization of  sbvRuns with a query.6sbv0Check if a safe-call was safe or not, turning a  to a Bool. sbvLPerform an action asynchronously, returning results together with diff-time. sbvPerform action for all given configs, return the first one that wins. Note that we do not wait for the other asyncs to terminate; hopefully they'll do so quickly. sbv=Perform action for all given configs, return all the results.q     ! "#$%&'()*+,-./0123456(c) Levent ErkokBSD3erkokl@gmail.com experimentalNone8=>?HSUVXkծ7sbvEquality as a proof method. Allows for very concise construction of equivalence proofs, which is very typical in bit-precise proofs.9sbvClass of metrics we can optimize for. Currently, booleans, bounded signed/unsigned bit-vectors, unbounded integers, algebraic reals and floats can be optimized. You can add your instances, but bewared that the : should map your type to something the backend solver understands, which are limited to unsigned bit-vectors, reals, and unbounded integers for z3.EA good reference on these features is given in the following paper:  Xhttp://www.microsoft.com/en-us/research/wp-content/uploads/2016/02/nbjorner-scss2014.pdf.&Minimal completion: None. However, if  MetricSpace3 is not identical to the type, you want to define ; and possibly 'minimize'/'maximize'' to add extra constraints as necessary.:sbvThe metric space we optimize the goal over. Usually the same as the type itself, but not always! For instance, signed bit-vectors are optimized over their unsigned counterparts, floats are optimized over their   comparable counterparts, etc.;sbv%Compute the metric value to optimize.<sbv=Compute the value itself from the metric corresponding to it.=sbvMinimizing a metric space>sbvMaximizing a metric space?sbvUninterpreted constants and functions. An uninterpreted constant is a value that is indexed by its name. The only property the prover assumes about these values are that they are equivalent to themselves; i.e., (for functions) they return the same results when applied to same arguments. We support uninterpreted-functions as a general means of black-box'ing operations that are  irrelevantx for the purposes of the proof; i.e., when the proofs can be performed without any knowledge about the function itself.Minimal complete definition: B. However, most instances in practice are already provided by SBV, so end-users should not need to define their own instances.@sbvUninterpret a value, receiving an object that can be used instead. Use this version when you do not need to add an axiom about this value.Asbv Uninterpret a value, only for the purposes of code-generation. For execution and verification the value is used as is. For code-generation, the alternate definition is used. This is useful when we want to take advantage of native libraries on the target languages.BsbvMost generalized form of uninterpretation, this function should not be needed by end-user-code, but is rather useful for the library development. sbvNot exported. Used only in  k. Instances are provided for the generic representations of product types where each element is Mergeable.Csbv)Symbolic conditionals are modeled by the C class, describing how to merge the results of an if-then-else call with a symbolic test. SBV provides all basic types as instances of this class, so users only need to declare instances for custom data-types of their programs as needed.A C instance may be automatically derived for a custom data-type with a single constructor where the type of each field is an instance of C?, such as a record of symbolic values. Users only need to add   and C to the deriving clause for the data-type. See N] for an example and an illustration of what the instance would look like if written by hand. The function E is a total-indexing function out of a list of choices with a default value, simulating array/list indexing. It's an n-way generalization of the  function.>Minimal complete definition: None, if the type is instance of Generic . Otherwise DQ. Note that most types subject to merging are likely to be trivial instances of Generic.Dsbv'Merge two values based on the condition. The first argument states whether we force the then-and-else branches before the merging, at the word level. This is an efficiency concern; one that we'd rather not make but unfortunately necessary for getting symbolic simulation working efficiently.EsbvTotal indexing operation. select xs default index is intuitively the same as  xs !! index, except it evaluates to default if index underflows/overflows.FsbvThe FP class captures the essence of division. Unfortunately we cannot use Haskell's   class since the   and  H superclasses are not implementable for symbolic bit-vectors. However,   and  " both make perfect sense, and the F) class captures this operation. One issue is how division by 0 behaves. The verification technology requires total functions, and there are several design choices here. We follow Isabelle/HOL approach of assigning the value 0 for division by 0. Therefore, we impose the following pair of laws:  x G 0 = (0, x) x H 0 = (0, x) 5Note that our instances implement this law even when x is 0 itself.NB.   truncates toward zero, while  $ truncates toward negative infinity.(C code generation of division operationsBIn the case of division or modulo of a minimal signed value (e.g. -128 for k) by -1 , SMTLIB and Haskell agree on what the result should be. Unfortunately the result in C code depends on CPU architecture and compiler settings, as this is undefined behaviour in C. **SBV does not guarantee** what will happen in generated C code in this corner case.Msbv;Finite bit-length symbolic values. Essentially the same as ], but further leaves out  . Loosely based on Haskell's  FiniteBits class, but with more methods defined and structured differently to fit into the symbolic world view. Minimal complete definition: N.Nsbv Bit size.Osbv:Least significant bit of a word, always stored at index 0.PsbvCMost significant bit of a word, always stored at the last position.Qsbv,Big-endian blasting of a word into its bits.Rsbv/Little-endian blasting of a word into its bits.Ssbv4Reconstruct from given bits, given in little-endian.Tsbv4Reconstruct from given bits, given in little-endian.UsbvReplacement for   , returning p instead of  &.Vsbv Variant of U2, where we want to extract multiple bit positions.Wsbv Variant of  , returning a symbolic value.Xsbv A combo of   and  %, when the bit to be set is symbolic.YsbvNFull adder, returns carry-out from the addition. Only for unsigned quantities.ZsbvSFull multipler, returns both high and low-order bits. Only for unsigned quantities.[sbv9Count leading zeros in a word, big-endian interpretation.\sbv:Count trailing zeros in a word, big-endian interpretation.]sbvSymbolic Numbers. This is a simple class that simply incorporates all number like base types together, simplifying writing polymorphic type-signatures that work for all symbolic numbers, such as o, kM etc. For instance, we can write a generic list-minimum function as follows: S mm :: SIntegral a => [SBV a] -> SBV a mm = foldr1 (a b -> ite (a .<= b) a b) It is similar to the standard  / class, except ranging over symbolic instances.^sbv!Symbolic Comparisons. Similar to   , we cannot implement Haskell's  x+ class since there is no way to return an  1 value from a symbolic comparison. Furthermore, ^ requires CR to implement if-then-else, for the benefit of implementing symbolic versions of   and   functions._sbvSymbolic less than.`sbvSymbolic less than or equal to.asbvSymbolic greater than.bsbv"Symbolic greater than or equal to.csbvSymbolic minimum.dsbvSymbolic maximum.esbv!Is the value withing the allowed  inclusive range?fsbv4Symbolic Equality. Note that we can't use Haskell's  s class since Haskell insists on returning Bool Comparing symbolic values will necessarily return a symbolic value.gsbvSymbolic equality.hsbvSymbolic inequality.isbvStrong equality. On floats ('SFloat'/'SDouble'0), strong equality is object equality; that is  NaN == NaN holds, but +0 == -0J doesn't. On other types, (.===) is simply (.==). Note that (.==) is the rightG notion of equality for floats per IEEE754 specs, since by definition +0 == -0 and NaN\ equals no other value including itself. But occasionally we want to be stronger and state NaN equals NaN and +0 and -0V are different from each other. In a context where your type is concrete, simply use A. But in a polymorphic context, use the strong equality instead.MNB. If you do not care about or work with floats, simply use (.==) and (./=).jsbvLNegation of strong equality. Equaivalent to negation of (.===) on all types.ksbvReturns (symbolic) z5 if all the elements of the given list are different.lsbvReturns (symbolic) z if all the elements of the given list are different. The second list contains exceptions, i.e., if an element belongs to that set, it will be considered distinct regardless of repetition.>prove $ \a -> distinctExcept [a, a] [0::SInteger] .<=> a .== 0Q.E.D.Lprove $ \a b -> distinctExcept [a, b] [0::SWord8] .<=> (a .== b .=> a .== 0)Q.E.D.Xprove $ \a b c d -> distinctExcept [a, b, c, d] [] .== distinct [a, b, c, (d::SInteger)]Q.E.D.msbvReturns (symbolic) z4 if all the elements of the given list are the same.nsbvSymbolic membership test.osbv!Symbolic negated membership test.psbvdIdentify tuple like things. Note that there are no methods, just instances to control type inference sbv+Generate a finite symbolic bitvector, named sbv-Generate a finite symbolic bitvector, unnamedqsbv$Generate a finite constant bitvectorrsbv'Convert a constant to an integral valuessbvGeneralization of tsbvGeneralization of  sbvGeneralization of usbvGeneralization of vsbvGeneralization of  sbvGeneralization of  wsbvGeneralization of  xsbvGeneralization of  sbvGeneralization of  ysbvGeneralization of  zsbvGeneralization of  sbvGeneralization of {sbvGeneralization of |sbvGeneralization of  sbvGeneralization of }sbvGeneralization of ~sbvGeneralization of  sbvGeneralization of sbvGeneralization of sbvGeneralization of  sbvGeneralization of sbvGeneralization of sbvGeneralization of  sbvGeneralization of sbvGeneralization of sbvGeneralization of  sbvGeneralization of sbvGeneralization of sbvGeneralization of  sbvGeneralization of !sbvGeneralization of "sbvGeneralization of # sbvGeneralization of $sbvGeneralization of %sbvGeneralization of & sbvGeneralization of 'sbvGeneralization of (sbvGeneralization of ) sbvGeneralization of *sbvGeneralization of +sbvGeneralization of , sbvGeneralization of -sbvGeneralization of .sbvGeneralization of / sbvGeneralization of 0sbvGeneralization of 1sbvGeneralization of 2 sbvGeneralization of 3sbvGeneralization of 4 sbvGeneralization of 5 sbvGeneralization of 6 sbvGeneralization of 7 sbvGeneralization of 8 sbvGeneralization of 9 sbvGeneralization of : sbvGeneralization of ; sbvGeneralization of < sbvGeneralization of = sbvGeneralization of > sbvGeneralization of < sbvGeneralization of =sbvGeneralization of ?sbvKConvert an SReal to an SInteger. That is, it computes the largest integer n that satisfies sIntegerToSReal n <= r essentially giving us the floor.For instance, 1.3 will be 1, but -1.3 will be -2.sbvlabel: Label the result of an expression. This is essentially a no-op, but useful as it generates a comment in the generated C/SMT-Lib code. Note that if the argument is a constant, then the label is dropped completely, per the usual constant folding strategy. Compare this to . which is good for printing counter-examples. sbv$Check if an observable name is good.sbvObserve the value of an expression, if the given condition holds. Such values are useful in model construction, as they are printed part of a satisfying model, or a counter-example. The same works for quick-check as well. Useful when we want to see intermediate values, or expected/obtained pairs in a particular run. Note that an observed expression is always symbolic, i.e., it won't be constant folded. Compare this to C which is used for putting a label in the generated SMTLib-C code.sbv8Observe the value of an expression, uncoditionally. See  for a generalized version.sbvfA variant of observe that you can use at the top-level. This is useful with quick-check, for instance.sbvReturns 1 if the boolean is z, otherwise 0. sbv+Lift a pseudo-boolean op, performing checkssbvz if at most k of the input arguments are zsbvz if at least k of the input arguments are zsbvz if exactly k of the input arguments are zsbvz if the sum of coefficients for z elements is at most k. Generalizes .sbvz if the sum of coefficients for z elements is at least k. Generalizes .sbvz if the sum of coefficients for z elements is exactly least k. Useful for coding exactly K-of-N2 constraints, and in particular mutex constraints.sbvz if there is at most one set bitsbvz if there is exactly one set bit sbvEConvert a concrete pseudo-boolean to given int; converting to integer sbv:Predicate for optimizing word operations like (+) and (*). sbv:Predicate for optimizing word operations like (+) and (*).sbvASymbolic exponentiation using bit blasting and repeated squaring.ZN.B. The exponent must be unsigned/bounded if symbolic. Signed exponents will be rejected. sbv&Lift a 1 arg FP-op, using sRNE default sbv7Lift a float/double unary function, only over constants sbv8Lift a float/double binary function, only over constantssbv?Conversion between integral-symbolic values, akin to Haskell's  sbvLift a binary operation thru it's dynamic counterpart. Note that we still want the actual functions here as differ in their type compared to their dynamic counterparts, but the implementations are the same.sbvGeneralization of  6, when the shift-amount is symbolic. Since Haskell's   only takes an  bV as the shift amount, it cannot be used when we have a symbolic amount to shift with.sbvGeneralization of  6, when the shift-amount is symbolic. Since Haskell's   only takes an  bV as the shift amount, it cannot be used when we have a symbolic amount to shift with.NB. If the shiftee is signed, then this is an arithmetic shift; otherwise it's logical, following the usual Haskell convention. See a for a variant that explicitly uses the msb as the sign bit, even for unsigned underlying types.sbvUArithmetic shift-right with a symbolic unsigned shift amount. This is equivalent to H when the argument is signed. However, if the argument is unsigned, then it explicitly treats its msb as a sign-bit, and uses it as the bit that gets shifted in. Useful when using the underlying unsigned bit representation to implement custom signed operations. Note that there is no direct Haskell analogue of this function.sbvGeneralization of  6, when the shift-amount is symbolic. Since Haskell's   only takes an  b as the shift amount, it cannot be used when we have a symbolic amount to shift with. The first argument should be a bounded quantity.sbv=An implementation of rotate-left, using a barrel shifter like design. Only works when both arguments are finite bitvectors, and furthermore when the second argument is unsigned. The first condition is enforced by the type, but the second is dynamically checked. We provide this implementation as an alternative to  since SMTLib logic does not support variable argument rotates (as opposed to shifts), and thus this implementation can produce better code for verification compared to .aprove $ \x y -> (x `sBarrelRotateLeft` y) `sBarrelRotateRight` (y :: SWord32) .== (x :: SWord64)Q.E.D.sbvGeneralization of  6, when the shift-amount is symbolic. Since Haskell's   only takes an  b as the shift amount, it cannot be used when we have a symbolic amount to shift with. The first argument should be a bounded quantity.sbvYAn implementation of rotate-right, using a barrel shifter like design. See comments for  for details.aprove $ \x y -> (x `sBarrelRotateRight` y) `sBarrelRotateLeft` (y :: SWord32) .== (x :: SWord64)Q.E.D. sbv*Helper function for use in enum operationssbvLift  2 to symbolic words. Division by 0 is defined s.t. x/0 = 0; which holds even when x is 0 itself.sbvLift  2 to symbolic words. Division by 0 is defined s.t. x/0 = 0; which holds even when x is 0u itself. Essentially, this is conversion from quotRem (truncate to 0) to divMod (truncate towards negative infinity)sbv$If-then-else. This is by definition DS with both branches forced. This is typically the desired behavior, but also see  should you need more laziness.sbvA Lazy version of ite, which does not force its arguments. This might cause issues for symbolic simulation with large thunks around, so use with care.sbvBSymbolic assert. Check that the given boolean condition is always zv in the given path. The optional first argument can be used to provide call-stack info via GHC's location facilities. sbv#Merge two symbolic values, at kind k , possibly force'ing the branches to make sure they do not evaluate to the same result. This should only be used for internal purposes; as default definitions provided should suffice in many cases. (i.e., End users should only need to define D2 when needed; which should be rare to start with.) sbv?Construct a useful error message if we hit an unmergeable case. sbvKNot exported. Symbolic merge using the generic representation provided by @A. sbv(Add an axiom. Only used internally, use OL from user programs which works over both regular and query modes of usage.sbvGeneralization of B sbvGeneralization of C sbvGeneralization of Dsbv1Quick check an SBV property. Note that a regular  quickCheckZ call will work just as well. Use this variant if you want to receive the boolean result. sbvExplicit sharing combinator. The SBV library has internal caching/hash-consing mechanisms built in, based on Andy Gill's type-safe obervable sharing technique (see:  =http://ku-fpg.github.io/files/Gill-09-TypeSafeReification.pdfu). However, there might be times where being explicit on the sharing can help, especially in experimental code. The   combinator ensures that its first argument is computed once and passed on to its continuation, explicitly indicating the intent of sharing. Most use cases of the SBV library should simply use Haskell's let construct for this purpose. sbvFSymbolic computations provide a context for writing symbolic programs. sbvUsing   or  6 on non-concrete values will result in an error. Use W or U instead. sbv'Define Floating instance on SBV's; only for base types that are already floating; i.e., SFloat and SDouble Note that most of the fields are "undefined" for symbolic values, we add methods as they are supported by SMTLib. Currently, the only symbolicly available function in this class is sqrt. sbvSymVal for 8-tuples sbvSymVal for 7-tuples sbvSymVal for 6-tuples sbvSymVal for 5-tuples sbvSymVal for 4-tuples !sbvSymVal for 3-tuples "sbvSymVal for 2-tuples #sbvSymVal for 0-tuple (i.e., unit) $sbvXIf comparison is over something SMTLib can handle, just translate it. Otherwise desugar.;:87789:;<=>?@ABCEDFGHIJKLMPNOQRSTUVWXYZ[\]^e_`abcdfghkijlmnop qrst uv wx yz {| }~                   84_4`4a4b4g4h4i4j4 -(c) Joel Burget Levent ErkokBSD3erkokl@gmail.com experimentalNone .=>?@ACHSXk  %sbv<Constructing a tuple from its parts and deconstructing back.sbvZDeconstruct a tuple, getting its constituent parts apart. Forms an isomorphism pair with :Fprove $ \p -> tuple @(Integer, Bool, (String, Char)) (untuple p) .== pQ.E.D.sbvDConstructing a tuple from its parts. Forms an isomorphism pair with :Fprove $ \p -> untuple @(Integer, Bool, (String, Char)) (tuple p) .== pQ.E.D. &sbv The class  &4 captures the notion that a type has a certain field 'sbv Field labelssbvtField access, inspired by the lens library. This is merely reverse application, but allows us to write things like  (1, 2)^._1s which is likely to be familiar to most Haskell programmers out there. Note that this is precisely equivalent to  _1 (1, 2)', but perhaps it reads a little nicer. (sbvvDynamic interface to exporting tuples, this function is not exported on purpose; use it only via the field functions , , etc.sbvAccess the 1st element of an STupleN,  2 <= N <= 8 . Also see .sbvAccess the 2nd element of an STupleN,  2 <= N <= 8 . Also see .sbvAccess the 3nd element of an STupleN,  3 <= N <= 8 . Also see .sbvAccess the 4th element of an STupleN,  4 <= N <= 8 . Also see .sbvAccess the 5th element of an STupleN,  5 <= N <= 8 . Also see .sbvAccess the 6th element of an STupleN,  6 <= N <= 8 . Also see .sbvAccess the 7th element of an STupleN,  7 <= N <= 8 . Also see .sbvAccess the 8th element of an STupleN,  8 <= N <= 8 . Also see .  8 (c) Levent ErkokBSD3erkokl@gmail.com experimentalNone=>?Xksbv]A symbolic tree containing values of type e, indexed by elements of type i. Note that these are full-trees, and their their shapes remain constant. There is no API provided that can change the shape of the tree. These structures are useful when dealing with data-structures that are indexed with symbolic values where access time is important. 7 structures provide logarithmic time reads and writes.sbv`Reading a value. We bit-blast the index and descend down the full tree according to bit-values.sbvWriting a value, similar to how reads are done. The important thing is that the tree representation keeps updates to a minimum.sbvAConstruct the fully balanced initial tree using the given values. (c) Levent ErkokBSD3erkokl@gmail.com experimentalNone=>?SXk7L!sbvcA class of checked-arithmetic operations. These follow the usual arithmetic, except make calls to J to ensure no overflow/underflow can occur. Use them in conjunction with " to ensure no overflow can happen.sbvDetecting underflow/overflow conditions. For each function, the first result is the condition under which the computation underflows, and the second is the condition under which it overflows.sbveBit-vector addition. Unsigned addition can only overflow. Signed addition can underflow and overflow.eA tell tale sign of unsigned addition overflow is when the sum is less than minumum of the arguments.Dprove $ \x y -> snd (bvAddO x (y::SWord16)) .<=> x + y .< x `smin` yQ.E.D.sbvoBit-vector subtraction. Unsigned subtraction can only underflow. Signed subtraction can underflow and overflow.sbvwBit-vector multiplication. Unsigned multiplication can only overflow. Signed multiplication can underflow and overflow.sbvSame as , except instead of doing the computation internally, it simply sends it off to z3 as a primitive. Obviously, only use if you have the z3 backend! Note that z3 provides this operation only when no logic is set, so make sure to call setLogic Logic_NONE in your program!sbvBit-vector division. Unsigned division neither underflows nor overflows. Signed division can only overflow. In fact, for each signed bitvector type, there's precisely one pair that overflows, when x is minBound and y is -1:,allSat $ \x y -> snd (x `bvDivO` (y::SInt8)) Solution #1: s0 = -128 :: Int8 s1 = -1 :: Int8This is the only solution.sbvBit-vector negation. Unsigned negation neither underflows nor overflows. Signed negation can only overflow, when the argument is minBound::prove $ \x -> x .== minBound .<=> snd (bvNegO (x::SInt16))Q.E.D. )sbvZero-extend to given bits *sbvLSign-extend to given bits. Note that we keep the signedness of the argument. +sbvGet the sign-bit ,sbvIs the sign-bit high? -sbvIs the sign-bit low? .sbvDo these have the same sign? /sbvDo these have opposing signs? 0sbvCheck all true 1sbv.Are all the bits between a b (inclusive) zero? 2sbv-Are all the bits between a b (inclusive) one? 3sbv%Unsigned addition. Can only overflow. 4sbvSigned addition. 5sbv)Unsigned subtraction. Can only underflow. 6sbvSigned subtraction. 7sbv+Unsigned multiplication. Can only overflow. 8sbvSigned multiplication. 9sbvIs this a concrete value? :sbv:Unsigned multiplication, fast version using z3 primitives. ;sbv8Signed multiplication, fast version using z3 primitives. <sbv5Unsigned division. Neither underflows, nor overflows. =sbv#Signed division. Can only overflow. >sbv5Unsigned negation. Neither underflows, nor overflows. ?sbv#Signed negation. Can only overflow.sbvDetecting underflow/overflow conditions for casting between bit-vectors. The first output is the result, the second component itself is a pair with the first boolean indicating underflow and the second indicating overflow.:sFromIntegralO (256 :: SInt16) :: (SWord8, (SBool, SBool))(0 :: SWord8,(False,True))9sFromIntegralO (-2 :: SInt16) :: (SWord8, (SBool, SBool))(254 :: SWord8,(True,False))8sFromIntegralO (2 :: SInt16) :: (SWord8, (SBool, SBool))(2 :: SWord8,(False,False))\prove $ \x -> sFromIntegralO (x::SInt32) .== (sFromIntegral x :: SInteger, (sFalse, sFalse))Q.E.D.)As the last example shows, converting to - never underflows or overflows for any value.sbv Version of  that has calls to > for checking no overflow/underflow can happen. Use it with a  call.6677 -(c) Joel Burget Levent ErkokBSD3erkokl@gmail.com experimentalNoneSXk}"sbvLength of a string.sat $ \s -> length s .== 2Satisfiable. Model: s0 = "\NUL\NUL" :: Stringsat $ \s -> length s .< 0 Unsatisfiable>prove $ \s1 s2 -> length s1 + length s2 .== length (s1 .++ s2)Q.E.D.sbv s is True iff the string is empty(prove $ \s -> null s .<=> length s .== 0Q.E.D."prove $ \s -> null s .<=> s .== ""Q.E.D.sbvB returns the head of a string. Unspecified if the string is empty.&prove $ \c -> head (singleton c) .== cQ.E.D.sbvB returns the tail of a string. Unspecified if the string is empty..prove $ \h s -> tail (singleton h .++ s) .== sQ.E.D.@prove $ \s -> length s .> 0 .=> length (tail s) .== length s - 1Q.E.D.Cprove $ \s -> sNot (null s) .=> singleton (head s) .++ tail s .== sQ.E.D.sbv@V returns the pair of the first character and tail. Unspecified if the string is empty.sbvR returns all but the last element of the list. Unspecified if the string is empty..prove $ \c t -> init (t .++ singleton c) .== tQ.E.D.sbv c\ is the string of length 1 that contains the only character whose value is the 8-bit value c.7prove $ \c -> c .== literal 'A' .=> singleton c .== "A"Q.E.D.(prove $ \c -> length (singleton c) .== 1Q.E.D.sbv s offset. Substring of length 1 at offset in s*. Unspecified if offset is out of bounds.Hprove $ \s1 s2 -> strToStrAt (s1 .++ s2) (length s1) .== strToStrAt s2 0Q.E.D.Msat $ \s -> length s .>= 2 .&& strToStrAt s 0 ./= strToStrAt s (length s - 1)Satisfiable. Model: s0 = "\NUL\NUL\EOT" :: Stringsbv s i' is the 8-bit value stored at location i). Unspecified if index is out of bounds.Mprove $ \i -> i .>= 0 .&& i .<= 4 .=> "AAAAA" `strToCharAt` i .== literal 'A'Q.E.D.>>> prove $ s i c -> i e (0, length s - 1) .&& s 2 i .== c .=> indexOf s (singleton c) .<= i Q.E.D.sbvShort cut for sbv cs is the string of length |cs|V containing precisely those characters. Note that there is no corresponding function explode:, since we wouldn't know the length of a symbolic string.8prove $ \c1 c2 c3 -> length (implode [c1, c2, c3]) .== 3Q.E.D.eprove $ \c1 c2 c3 -> map (strToCharAt (implode [c1, c2, c3])) (map literal [0 .. 2]) .== [c1, c2, c3]Q.E.D. sbv$Prepend an element, the traditional cons.!sbvAppend an element"sbvREmpty string. This value has the property that it's the only string with length 0:+prove $ \l -> length l .== 0 .<=> l .== nilQ.E.D.#sbv"Concatenate two strings. See also $.$sbvShort cut for #.Vsat $ \x y z -> length x .== 5 .&& length y .== 1 .&& x .++ y .++ z .== "Hello world!"Satisfiable. Model: s0 = "Hello" :: String s1 = " " :: String s2 = "world!" :: String%sbv% sub s. Does s contain the substring sub?6prove $ \s1 s2 s3 -> s2 `isInfixOf` (s1 .++ s2 .++ s3)Q.E.D.Hprove $ \s1 s2 -> s1 `isInfixOf` s2 .&& s2 `isInfixOf` s1 .<=> s1 .== s2Q.E.D.&sbv& pre s. Is pre a prefix of s?-prove $ \s1 s2 -> s1 `isPrefixOf` (s1 .++ s2)Q.E.D.Gprove $ \s1 s2 -> s1 `isPrefixOf` s2 .=> subStr s2 0 (length s1) .== s1Q.E.D.'sbv' suf s. Is suf a suffix of s?-prove $ \s1 s2 -> s2 `isSuffixOf` (s1 .++ s2)Q.E.D.]prove $ \s1 s2 -> s1 `isSuffixOf` s2 .=> subStr s2 (length s2 - length s1) (length s1) .== s1Q.E.D.(sbv( len s. Corresponds to Haskell's ( on symbolic-strings.3prove $ \s i -> i .>= 0 .=> length (take i s) .<= iQ.E.D.)sbv) len s. Corresponds to Haskell's ) on symbolic-strings..prove $ \s i -> length (drop i s) .<= length sQ.E.D.+prove $ \s i -> take i s .++ drop i s .== sQ.E.D.*sbv* s offset len is the substring of s at offset offset with length lenY. This function is under-specified when the offset is outside the range of positions in s or len is negative or  offset+len exceeds the length of s.^prove $ \s i -> i .>= 0 .&& i .< length s .=> subStr s 0 i .++ subStr s i (length s - i) .== sQ.E.D.+sat $ \i j -> subStr "hello" i j .== "ell"Satisfiable. Model: s0 = 1 :: Integer s1 = 3 :: Integer)sat $ \i j -> subStr "hell" i j .== "no" Unsatisfiable+sbv+ s src dst". Replace the first occurrence of src by dst in sEprove $ \s -> replace "hello" s "world" .== "world" .=> s .== "hello"Q.E.D.Gprove $ \s1 s2 s3 -> length s2 .> length s1 .=> replace s1 s2 s3 .== s1Q.E.D.,sbv, s sub. Retrieves first position of sub in s, -1- if there are no occurrences. Equivalent to - s sub 0.!>>> prove $ s i -> i .> 0 .&& i . lengths .=' indexOf s (subStr s i 1) .<= i Q.E.D.Aprove $ \s1 s2 -> length s2 .> length s1 .=> indexOf s1 s2 .== -1Q.E.D.-sbv- s sub offset. Retrieves first position of sub at or after offset in s, -1 if there are no occurrences.9prove $ \s sub -> offsetIndexOf s sub 0 .== indexOf s subQ.E.D.Wprove $ \s sub i -> i .>= length s .&& length sub .> 0 .=> offsetIndexOf s sub i .== -1Q.E.D.Bprove $ \s sub i -> i .> length s .=> offsetIndexOf s sub i .== -1Q.E.D..sbv. s%. Retrieve integer encoded by string sQ (ground rewriting only). Note that by definition this function only works when sW only contains digits, that is, if it encodes a natural number. Otherwise, it returns '-1'.Mprove $ \s -> let n = strToNat s in length s .== 1 .=> (-1) .<= n .&& n .<= 9Q.E.D./sbv/ i%. Retrieve string encoded by integer i (ground rewriting only). Again, only naturals are supported, any input that is not a natural number produces empty string, even though we take an integer as an argument.5prove $ \i -> length (natToStr i) .== 3 .=> i .<= 999Q.E.D. @sbv#Lift a unary operator over strings. Asbv$Lift a binary operator over strings. Bsbv%Lift a ternary operator over strings. Csbv!Concrete evaluation for unary ops Dsbv"Concrete evaluation for binary ops Esbv#Concrete evaluation for ternary ops Fsbv%Is the string concretely known empty? !"#$%&'()*+,-./# !"$%'&()*+,-./ 5$5 (c) Levent ErkokBSD3erkokl@gmail.com experimentalNoneSXk0sbv Empty set.empty :: SSet Integer{} :: {SInteger}1sbv Full set.full :: SSet IntegerU :: {SInteger}ENote that the universal set over a type is represented by the letter U.2sbv Synonym for 1.3sbvSingleton list.singleton 2 :: SSet Integer{2} :: {SInteger}4sbvConversion from a list.fromList ([] :: [Integer]){} :: {SInteger}fromList [1,2,3]{1,2,3} :: {SInteger}fromList [5,5,5,12,12,3]{3,5,12} :: {SInteger}5sbv Complement.+empty .== complement (full :: SSet Integer)True2Complementing twice gets us back the original set:?prove $ \(s :: SSet Integer) -> complement (complement s) .== sQ.E.D.6sbvInsert an element into a set.Insertion is order independent:[prove $ \x y (s :: SSet Integer) -> x `insert` (y `insert` s) .== y `insert` (x `insert` s)Q.E.D.5Deletion after insertion is not necessarily identity:Aprove $ \x (s :: SSet Integer) -> x `delete` (x `insert` s) .== sFalsifiable. Counter-example: s0 = 0 :: Integer s1 = {0} :: {Integer}DBut the above is true if the element isn't in the set to start with:Uprove $ \x (s :: SSet Integer) -> x `notMember` s .=> x `delete` (x `insert` s) .== sQ.E.D.'Insertion into a full set does nothing:6prove $ \x -> insert x full .== (full :: SSet Integer)Q.E.D.7sbvDelete an element from a set.Deletion is order independent:[prove $ \x y (s :: SSet Integer) -> x `delete` (y `delete` s) .== y `delete` (x `delete` s)Q.E.D.5Insertion after deletion is not necessarily identity:Aprove $ \x (s :: SSet Integer) -> x `insert` (x `delete` s) .== sFalsifiable. Counter-example: s0 = 0 :: Integer s1 = {} :: {Integer}ABut the above is true if the element is in the set to start with:Rprove $ \x (s :: SSet Integer) -> x `member` s .=> x `insert` (x `delete` s) .== sQ.E.D.(Deletion from an empty set does nothing:8prove $ \x -> delete x empty .== (empty :: SSet Integer)Q.E.D.8sbvTest for membership.2prove $ \x -> x `member` singleton (x :: SInteger)Q.E.D.;prove $ \x (s :: SSet Integer) -> x `member` (x `insert` s)Q.E.D./prove $ \x -> x `member` (full :: SSet Integer)Q.E.D.9sbvTest for non-membership.Eprove $ \x -> x `notMember` observe "set" (singleton (x :: SInteger))Falsifiable. Counter-example: set = {0} :: {Integer} s0 = 0 :: Integer>prove $ \x (s :: SSet Integer) -> x `notMember` (x `delete` s)Q.E.D.3prove $ \x -> x `notMember` (empty :: SSet Integer)Q.E.D.:sbvIs this the empty set?null (empty :: SSet Integer)True9prove $ \x -> null (x `delete` singleton (x :: SInteger))Q.E.D.#prove $ null (full :: SSet Integer) FalsifiableNote how we have to call q in the last case since dealing with infinite sets requires a call to the solver and cannot be constant folded.;sbv Synonym for :.<sbvIs this the full set?&prove $ isFull (empty :: SSet Integer) FalsifiableHprove $ \x -> isFull (observe "set" (x `delete` (full :: SSet Integer)))Falsifiable. Counter-example: set = U - {0} :: {Integer} s0 = 0 :: IntegerisFull (full :: SSet Integer)TrueNote how we have to call r in the first case since dealing with infinite sets requires a call to the solver and cannot be constant folded.=sbv Synonym for <.>sbvmDoes the set have the given size? It implicitly asserts that the set it is operating on is finite. Also see  E.=prove $ \i -> hasSize (empty :: SSet Integer) i .== (i .== 0)Q.E.D.,sat $ \i -> hasSize (full :: SSet Integer) i Unsatisfiableh>>> prove $ a b i j k -> hasSize (a :: SSet Integer) i .&& hasSize (b :: SSet Integer) j .&& hasSize (a B b) k .=> k .>= i smax j Q.E.D.h>>> prove $ a b i j k -> hasSize (a :: SSet Integer) i .&& hasSize (b :: SSet Integer) j .&& hasSize (a D b) k .=> k .<= i smin j Q.E.D.D>>> prove $ a k -> hasSize (a :: SSet Integer) k .=> k .>= 0 Q.E.D.?sbv Subset test.1prove $ empty `isSubsetOf` (full :: SSet Integer)Q.E.D.?prove $ \x (s :: SSet Integer) -> s `isSubsetOf` (x `insert` s)Q.E.D.?prove $ \x (s :: SSet Integer) -> (x `delete` s) `isSubsetOf` sQ.E.D.@sbvProper subset test.7prove $ empty `isProperSubsetOf` (full :: SSet Integer)Q.E.D.Eprove $ \x (s :: SSet Integer) -> s `isProperSubsetOf` (x `insert` s)Falsifiable. Counter-example: s0 = 0 :: Integer s1 = U :: {Integer}Yprove $ \x (s :: SSet Integer) -> x `notMember` s .=> s `isProperSubsetOf` (x `insert` s)Q.E.D.Eprove $ \x (s :: SSet Integer) -> (x `delete` s) `isProperSubsetOf` sFalsifiable. Counter-example: s0 = 0 :: Integer s1 = U - {0,1} :: {Integer}Vprove $ \x (s :: SSet Integer) -> x `member` s .=> (x `delete` s) `isProperSubsetOf` sQ.E.D.AsbvDisjoint test..disjoint (fromList [2,4,6]) (fromList [1,3])True2disjoint (fromList [2,4,6,8]) (fromList [2,3,5,7])False2disjoint (fromList [1,2]) (fromList [1,2,3,4])False9prove $ \(s :: SSet Integer) -> s `disjoint` complement sQ.E.D./allSat $ \(s :: SSet Integer) -> s `disjoint` s Solution #1: s0 = {} :: {Integer}This is the only solution.SThe last example is particularly interesting: The empty set is the only set where A is not reflexive!Note that disjointness of a set from its complement is guaranteed by the fact that all types are inhabited; an implicit assumption we have in classic logic which is also enjoyed by Haskell due to the presence of bottom!BsbvUnion.Runion (fromList [1..10]) (fromList [5..15]) .== (fromList [1..15] :: SSet Integer)True=prove $ \(a :: SSet Integer) b -> a `union` b .== b `union` aQ.E.D.Wprove $ \(a :: SSet Integer) b c -> a `union` (b `union` c) .== (a `union` b) `union` cQ.E.D.7prove $ \(a :: SSet Integer) -> a `union` full .== fullQ.E.D.5prove $ \(a :: SSet Integer) -> a `union` empty .== aQ.E.D.?prove $ \(a :: SSet Integer) -> a `union` complement a .== fullQ.E.D.CsbvUnions. Equivalent to  G B 0.-prove $ unions [] .== (empty :: SSet Integer)Q.E.D.Dsbv Intersection.Yintersection (fromList [1..10]) (fromList [5..15]) .== (fromList [5..10] :: SSet Integer)TrueKprove $ \(a :: SSet Integer) b -> a `intersection` b .== b `intersection` aQ.E.D.sprove $ \(a :: SSet Integer) b c -> a `intersection` (b `intersection` c) .== (a `intersection` b) `intersection` cQ.E.D.;prove $ \(a :: SSet Integer) -> a `intersection` full .== aQ.E.D.@prove $ \(a :: SSet Integer) -> a `intersection` empty .== emptyQ.E.D.Gprove $ \(a :: SSet Integer) -> a `intersection` complement a .== emptyQ.E.D.Qprove $ \(a :: SSet Integer) b -> a `disjoint` b .=> a `intersection` b .== emptyQ.E.D.EsbvIntersections. Equivalent to  G D 1. Note that Haskell's [ does not support this operation as it does not have a way of representing universal sets.3prove $ intersections [] .== (full :: SSet Integer)Q.E.D.Fsbv Difference.>prove $ \(a :: SSet Integer) -> empty `difference` a .== emptyQ.E.D.:prove $ \(a :: SSet Integer) -> a `difference` empty .== aQ.E.D.Dprove $ \(a :: SSet Integer) -> full `difference` a .== complement aQ.E.D.:prove $ \(a :: SSet Integer) -> a `difference` a .== emptyQ.E.D.Gsbv Synonym for F.0123456789:;<=>?@ABCDEFG0123456789:;<=>?@ABCDEFGG9 -(c) Joel Burget Levent ErkokBSD3erkokl@gmail.com experimentalNoneSXk! Hsbv The symbolic  sNothing :: SMaybe IntegerNothing :: SMaybe IntegerIsbv'Check if the symbolic value is nothing.&isNothing (sNothing :: SMaybe Integer)True"isNothing (sJust (literal "nope"))FalseJsbv Construct an SMaybe a from an SBV asJust 3Just 3 :: SMaybe IntegerKsbv+Check if the symbolic value is not nothing.#isJust (sNothing :: SMaybe Integer)FalseisJust (sJust (literal "yep"))True,prove $ \x -> isJust (sJust (x :: SInteger))Q.E.D.LsbvVReturn the value of an optional value. The default is returned if Nothing. Compare to M.(fromMaybe 2 (sNothing :: SMaybe Integer) 2 :: SInteger'fromMaybe 2 (sJust 5 :: SMaybe Integer) 5 :: SInteger<prove $ \x -> fromMaybe x (sNothing :: SMaybe Integer) .== xQ.E.D.?prove $ \x -> fromMaybe (x+1) (sJust x :: SMaybe Integer) .== xQ.E.D.Msbv`Return the value of an optional value. The behavior is undefined if passed Nothing. Compare to L.fromJust (sJust (literal 'a')) 'a' :: SChar1prove $ \x -> fromJust (sJust x) .== (x :: SChar)Q.E.D..sat $ \x -> x .== (fromJust sNothing :: SChar)Satisfiable. Model: s0 = '\NUL' :: CharNote how we get a satisfying assignment in the last case: The behavior is unspecified, thus the SMT solver picks whatever satisfies the constraints, if there is one.Nsbv Construct an SMaybe a from a  Maybe (SBV a) liftMaybe (Just (3 :: SInteger))Just 3 :: SMaybe Integer%liftMaybe (Nothing :: Maybe SInteger)Nothing :: SMaybe IntegerOsbv Map over the  H side of a  !3prove $ \x -> fromJust (map (+1) (sJust x)) .== x+1Q.E.D.,let f = uninterpret "f" :: SInteger -> SBool-prove $ \x -> map f (sJust x) .== sJust (f x)Q.E.D.map f sNothing .== sNothingTruePsbvCase analysis for symbolic  !s. If the value I#, return the default value; if it K, apply the function.*maybe 0 (`sMod` 2) (sJust (3 :: SInteger)) 1 :: SInteger/maybe 0 (`sMod` 2) (sNothing :: SMaybe Integer) 0 :: SInteger,let f = uninterpret "f" :: SInteger -> SBool+prove $ \x d -> maybe d f (sJust x) .== f xQ.E.D.&prove $ \d -> maybe d f sNothing .== dQ.E.D. HIJKLMNOP JHNPOIKLM-(c) Joel Burget Levent ErkokBSD3erkokl@gmail.com experimentalNone SXk}"QsbvLength of a list.,sat $ \(l :: SList Word16) -> length l .== 2Satisfiable. Model: s0 = [0,0] :: [Word16]+sat $ \(l :: SList Word16) -> length l .< 0 Unsatisfiablebprove $ \(l1 :: SList Word16) (l2 :: SList Word16) -> length l1 + length l2 .== length (l1 .++ l2)Q.E.D.RsbvR s is True iff the list is empty:prove $ \(l :: SList Word16) -> null l .<=> length l .== 0Q.E.D.4prove $ \(l :: SList Word16) -> null l .<=> l .== []Q.E.D.SsbvSG returns the first element of a list. Unspecified if the list is empty.4prove $ \c -> head (singleton c) .== (c :: SInteger)Q.E.D.TsbvT> returns the tail of a list. Unspecified if the list is empty.<prove $ \(h :: SInteger) t -> tail (singleton h .++ t) .== tQ.E.D.Sprove $ \(l :: SList Integer) -> length l .> 0 .=> length (tail l) .== length l - 1Q.E.D.Vprove $ \(l :: SList Integer) -> sNot (null l) .=> singleton (head l) .++ tail l .== lQ.E.D.Usbv@UI returns the pair of the head and tail. Unspecified if the list is empty.VsbvVP returns all but the last element of the list. Unspecified if the list is empty.<prove $ \(h :: SInteger) t -> init (t .++ singleton h) .== tQ.E.D.WsbvW x6 is the list of length 1 that contains the only value x.4prove $ \(x :: SInteger) -> head (singleton x) .== xQ.E.D.6prove $ \(x :: SInteger) -> length (singleton x) .== 1Q.E.D.XsbvX l offset. List of length 1 at offset in l). Unspecified if index is out of bounds._prove $ \(l1 :: SList Integer) l2 -> listToListAt (l1 .++ l2) (length l1) .== listToListAt l2 0Q.E.D.csat $ \(l :: SList Word16) -> length l .>= 2 .&& listToListAt l 0 ./= listToListAt l (length l - 1)Satisfiable. Model: s0 = [0,0,8] :: [Word16]YsbvY l i! is the value stored at location i). Unspecified if index is out of bounds.Mprove $ \i -> i `inRange` (0, 4) .=> [1,1,1,1,1] `elemAt` i .== (1::SInteger)Q.E.D.*>>> prove $ (l :: SList Integer) i e -> i e (0, length l - 1) .&& l Y2 i .== e .=> indexOf l (singleton e) .<= i Q.E.D.ZsbvShort cut for Y[sbv[ es is the list of length |es|T containing precisely those elements. Note that there is no corresponding function explode8, since we wouldn't know the length of a symbolic list.Fprove $ \(e1 :: SInteger) e2 e3 -> length (implode [e1, e2, e3]) .== 3Q.E.D.nprove $ \(e1 :: SInteger) e2 e3 -> map (elemAt (implode [e1, e2, e3])) (map literal [0 .. 2]) .== [e1, e2, e3]Q.E.D.\sbv Concatenate two lists. See also `.]sbv$Prepend an element, the traditional cons.^sbvAppend an element_sbvNEmpty list. This value has the property that it's the only list with length 0:>prove $ \(l :: SList Integer) -> length l .== 0 .<=> l .== nilQ.E.D.`sbvShort cut for \.Qsat $ \x y z -> length x .== 5 .&& length y .== 1 .&& x .++ y .++ z .== [1 .. 12]Satisfiable. Model:$ s0 = [1,2,3,4,5] :: [Integer]$ s1 = [6] :: [Integer]$ s2 = [7,8,9,10,11,12] :: [Integer]asbva e l. Does l contain the element e?bsbvb e l. Does l not contain the element e?csbvc sub l. Does l contain the subsequence sub?Iprove $ \(l1 :: SList Integer) l2 l3 -> l2 `isInfixOf` (l1 .++ l2 .++ l3)Q.E.D.[prove $ \(l1 :: SList Integer) l2 -> l1 `isInfixOf` l2 .&& l2 `isInfixOf` l1 .<=> l1 .== l2Q.E.D.dsbvd pre l. Is pre a prefix of l?@prove $ \(l1 :: SList Integer) l2 -> l1 `isPrefixOf` (l1 .++ l2)Q.E.D.[prove $ \(l1 :: SList Integer) l2 -> l1 `isPrefixOf` l2 .=> subList l2 0 (length l1) .== l1Q.E.D.esbve suf l. Is suf a suffix of l??prove $ \(l1 :: SList Word16) l2 -> l2 `isSuffixOf` (l1 .++ l2)Q.E.D.pprove $ \(l1 :: SList Word16) l2 -> l1 `isSuffixOf` l2 .=> subList l2 (length l2 - length l1) (length l1) .== l1Q.E.D.fsbvf len l. Corresponds to Haskell's f on symbolic lists.Fprove $ \(l :: SList Integer) i -> i .>= 0 .=> length (take i l) .<= iQ.E.D.gsbvg len s. Corresponds to Haskell's g on symbolic-lists.@prove $ \(l :: SList Word16) i -> length (drop i l) .<= length lQ.E.D.=prove $ \(l :: SList Word16) i -> take i l .++ drop i l .== lQ.E.D.hsbvh s offset len is the sublist of s at offset offset with length lenY. This function is under-specified when the offset is outside the range of positions in s or len is negative or  offset+len exceeds the length of s.sprove $ \(l :: SList Integer) i -> i .>= 0 .&& i .< length l .=> subList l 0 i .++ subList l i (length l - i) .== lQ.E.D.?sat $ \i j -> subList [1..5] i j .== ([2..4] :: SList Integer)Satisfiable. Model: s0 = 1 :: Integer s1 = 3 :: Integer?sat $ \i j -> subList [1..5] i j .== ([6..7] :: SList Integer) Unsatisfiableisbvi l src dst". Replace the first occurrence of src by dst in sTprove $ \l -> replace [1..5] l [6..10] .== [6..10] .=> l .== ([1..5] :: SList Word8)Q.E.D.Zprove $ \(l1 :: SList Integer) l2 l3 -> length l2 .> length l1 .=> replace l1 l2 l3 .== l1Q.E.D.jsbvj l sub. Retrieves first position of sub in l, -1- if there are no occurrences. Equivalent to k l sub 0.1>>> prove $ (l :: SList Int8) i -> i .> 0 .&& i . lengthl .=( indexOf l (subList l i 1) .<= i Q.E.D.Sprove $ \(l1 :: SList Word16) l2 -> length l2 .> length l1 .=> indexOf l1 l2 .== -1Q.E.D.ksbvk l sub offset. Retrieves first position of sub at or after offset in l, -1 if there are no occurrences.Iprove $ \(l :: SList Int8) sub -> offsetIndexOf l sub 0 .== indexOf l subQ.E.D.gprove $ \(l :: SList Int8) sub i -> i .>= length l .&& length sub .> 0 .=> offsetIndexOf l sub i .== -1Q.E.D.Rprove $ \(l :: SList Int8) sub i -> i .> length l .=> offsetIndexOf l sub i .== -1Q.E.D. Isbv!Lift a unary operator over lists. Jsbv"Lift a binary operator over lists. Ksbv#Lift a ternary operator over lists. Lsbv!Concrete evaluation for unary ops Msbv"Concrete evaluation for binary ops Nsbv#Concrete evaluation for ternary ops Osbv#Is the list concretely known empty?QRSTUVWXYZ[\]^_`abcdefghijkQRSTUVWXYZ[\]^_`abcedfghijk]5`5-(c) Joel Burget Levent ErkokBSD3erkokl@gmail.com experimentalNoneSXk lsbv Construct an  SEither a b from an SBV asLeft 3 :: SEither Integer BoolLeft 3 :: SEither Integer BoolmsbvReturn z if the given symbolic value is  R, { otherwise(isLeft (sLeft 3 :: SEither Integer Bool)True-isLeft (sRight sTrue :: SEither Integer Bool)Falsensbv Construct an  SEither a b from an SBV b%sRight sFalse :: SEither Integer Bool#Right False :: SEither Integer BoolosbvReturn z if the given symbolic value is  S, { otherwise)isRight (sLeft 3 :: SEither Integer Bool)False.isRight (sRight sTrue :: SEither Integer Bool)Truepsbv Construct an  SEither a b from an Either (SBV a) (SBV b),liftEither (Left 3 :: Either SInteger SBool)Left 3 :: SEither Integer Bool1liftEither (Right sTrue :: Either SInteger SBool)"Right True :: SEither Integer BoolqsbvCase analysis for symbolic  "s. If the value m#, apply the first function; if it o, apply the second function.either (*2) (*3) (sLeft 3) 6 :: SIntegereither (*2) (*3) (sRight 3) 9 :: SInteger/let f = uninterpret "f" :: SInteger -> SInteger/let g = uninterpret "g" :: SInteger -> SInteger*prove $ \x -> either f g (sLeft x) .== f xQ.E.D.+prove $ \x -> either f g (sRight x) .== g xQ.E.D.rsbv"Map over both sides of a symbolic  " at the same time/let f = uninterpret "f" :: SInteger -> SInteger/let g = uninterpret "g" :: SInteger -> SInteger4prove $ \x -> fromLeft (bimap f g (sLeft x)) .== f xQ.E.D.6prove $ \x -> fromRight (bimap f g (sRight x)) .== g xQ.E.D.ssbvMap over the left side of an  "/let f = uninterpret "f" :: SInteger -> SIntegerJprove $ \x -> first f (sLeft x :: SEither Integer Integer) .== sLeft (f x)Q.E.D.Hprove $ \x -> first f (sRight x :: SEither Integer Integer) .== sRight xQ.E.D.tsbvMap over the right side of an  "/let f = uninterpret "f" :: SInteger -> SIntegerMprove $ \x -> second f (sRight x :: SEither Integer Integer) .== sRight (f x)Q.E.D.Gprove $ \x -> second f (sLeft x :: SEither Integer Integer) .== sLeft xQ.E.D.usbv]Return the value from the left component. The behavior is undefined if passed a right value.6fromLeft (sLeft (literal 'a') :: SEither Char Integer) 'a' :: SCharIprove $ \x -> fromLeft (sLeft x :: SEither Char Integer) .== (x :: SChar)Q.E.D.?sat $ \x -> x .== (fromLeft (sRight 4 :: SEither Char Integer))Satisfiable. Model: s0 = '\NUL' :: CharNote how we get a satisfying assignment in the last case: The behavior is unspecified, thus the SMT solver picks whatever satisfies the constraints, if there is one.vsbv]Return the value from the right component. The behavior is undefined if passed a left value.8fromRight (sRight (literal 'a') :: SEither Integer Char) 'a' :: SCharNprove $ \x -> fromRight (sRight x :: SEither Char Integer) .== (x :: SInteger)Q.E.D.Ksat $ \x -> x .== (fromRight (sLeft (literal 'a') :: SEither Char Integer))Satisfiable. Model: s0 = 0 :: IntegerNote how we get a satisfying assignment in the last case: The behavior is unspecified, thus the SMT solver picks whatever satisfies the constraints, if there is one. lmnopqrstuv lnpqrstmouvF(c) Levent ErkokBSD3erkokl@gmail.com experimentalNone .=?HUVXk:wsbv:A helper class to convert sized bit-vectors to/from bytes.xsbvConvert to a sequence of bytesSprove $ \a b c d -> toBytes ((fromBytes [a, b, c, d]) :: SWord 32) .== [a, b, c, d]Q.E.D.ysbv Convert from a sequence of bytes7prove $ \r -> fromBytes (toBytes r) .== (r :: SWord 64)Q.E.D.zsbv3A symbolic signed bit-vector carrying its size info{sbv*A signed bit-vector carrying its size info|sbv9Type family to create the appropriate non-zero constraint PsbvCatch 0-width cases}sbv5A symbolic unsigned bit-vector carrying its size info~sbv-An unsigned bit-vector carrying its size info Qsbv Grab the bit-size from the proxysbvGeneralization of G RsbvGeneralization of HsbvGeneralization of sbvGeneralization of I SsbvGeneralization of JsbvGeneralization of Ksbv7Extract a portion of bits to form a smaller bit-vector.iprove $ \x -> bvExtract (Proxy @7) (Proxy @3) (x :: SWord 12) .== bvDrop (Proxy @4) (bvTake (Proxy @9) x)Q.E.D.sbvJoin two bitvectors.Zprove $ \x y -> x .== bvExtract (Proxy @79) (Proxy @71) ((x :: SWord 9) # (y :: SWord 71))Q.E.D.sbvZero extend a bit-vector.\prove $ \x -> bvExtract (Proxy @20) (Proxy @12) (zeroExtend (x :: SInt 12) :: SInt 21) .== 0Q.E.D.sbvSign extend a bit-vector.mprove $ \x -> sNot (msb x) .=> bvExtract (Proxy @20) (Proxy @12) (signExtend (x :: SInt 12) :: SInt 21) .== 0Q.E.D.xprove $ \x -> msb x .=> bvExtract (Proxy @20) (Proxy @12) (signExtend (x :: SInt 12) :: SInt 21) .== complement 0Q.E.D.sbv'Drop bits from the top of a bit-vector.5prove $ \x -> bvDrop (Proxy @0) (x :: SWord 43) .== xQ.E.D.Dprove $ \x -> bvDrop (Proxy @20) (x :: SWord 21) .== ite (lsb x) 1 0Q.E.D.sbv'Take bits from the top of a bit-vector.6prove $ \x -> bvTake (Proxy @13) (x :: SWord 13) .== xQ.E.D.Cprove $ \x -> bvTake (Proxy @1) (x :: SWord 13) .== ite (msb x) 1 0Q.E.D.Kprove $ \x -> bvTake (Proxy @4) x # bvDrop (Proxy @4) x .== (x :: SWord 23)Q.E.D. TsbvShow instance for ~ Usbv Optimizing ~ VsbvConstructing models for ~ WsbvM instance for ~ XsbvF instance for } YsbvF instance for ~ Zsbv] instance for ~ [sbv  instance for ~ \sbv  instance for ~ ]sbv  instance for ~ ^sbv  instance for ~ _sbv ` instance for ~ asbv2 instance for ~ bsbv~ has a kind csbv Optimizing { dsbvConstructing models for { esbvM instance for { fsbvF instance for { gsbv] instance for { hsbv  instance for { isbv  instance for { jsbv  instance for { ksbv  instance for { lsbv ` instance for { msbv2 instance for { nsbv{ has a kind osbvShow instance for { psbvF instance for z qsbv} 1024 instance for w rsbv} 512 instance for w ssbv} 256 instance for w tsbv} 128 instance for w usbv} 64 instance for w vsbv} 32 instance for w wsbv} 16 instance for w xsbv} 8 instance for wsbvi : Start position, numbered from n-1 to 0sbvj: End position, numbered from n-1 to 0, j <= i must holdsbvInput bit vector of size nsbvOutput is of size  i - j + 1sbvFirst input, of size n, becomes the left sidesbvSecond input, of size m, becomes the right sidesbvConcatenation, of size n+msbvInput, of size nsbvOutput, of size m. n < m must holdsbvInput, of size nsbvOutput, of size m. n < m must holdsbvi: Number of bits to drop. i < n must hold.sbvInput, of size nsbvOutput, of size m.  m = n - i holds.sbvi: Number of bits to take.  0 < i <= n must hold.sbvInput, of size nsbvOutput, of size iwxyz{|}~ R S5(c) Levent ErkokBSD3erkokl@gmail.com experimentalNone .=>?HV &qsbvpImplements polynomial addition, multiplication, division, and modulus operations over GF(2^n). NB. Similar to G, division by 0 is interpreted as follows: x  0 = (0, x)for all x (including 0)Minimal complete definition: , , sbv@Given bit-positions to be set, create a polynomial For instance polynomial [0, 1, 3] :: SWord8will evaluate to 11, since it sets the bits 0, 1, and 30. Mathematicans would write this polynomial as  x^3 + x + 1. And in fact,  will show it like that.sbvAdd two polynomials in GF(2^n).sbvMultiply two polynomials in GF(2^n), and reduce it by the irreducible specified by the polynomial as specified by coefficients of the third argument. Note that the third argument is specifically left in this form as it is usally in GF(2^(n+1)), which is not available in our formalism. (That is, we would need SWord9 for SWord8 multiplication, etc.) Also note that we do not support symbolic irreducibles, which is a minor shortcoming. (Most GF's will come with fixed irreducibles, so this should not be a problem in practice.)Passing [] for the third argument will multiply the polynomials and then ignore the higher bits that won't fit into the resulting size.sbvDDivide two polynomials in GF(2^n), see above note for division by 0.sbvOCompute modulus of two polynomials in GF(2^n), see above note for modulus by 0.sbv%Division and modulus packed together.sbvCDisplay a polynomial like a mathematician would (over the monomial x), with a type.sbvCDisplay a polynomial like a mathematician would (over the monomial xC), the first argument controls if the final type is shown as well. ysbvPretty print as a polynomialsbvAdd two polynomialssbvRun down a boolean condition over two lists. Note that this is different than zipWith as shorter list is assumed to be filled with sFalse at the end (i.e., zero-bits); which nicely pads it when considered as an unsigned number in little-endian form. zsbv}Multiply two polynomials and reduce by the third (concrete) irreducible, given by its coefficients. See the remarks for the  function for this design choicesbv8Compute modulus/remainder of polynomials on bit-vectors.sbv(Compute CRCs over bit-vectors. The call  crcBV n m p" computes the CRC of the message m with respect to polynomial p@. The inputs are assumed to be blasted big-endian. The number n5 specifies how many bits of CRC is needed. Note that n+ is actually the degree of the polynomial p, and thus it seems redundant to pass it in. However, in a typical proof context, the polynomial can be symbolic, so we cannot compute the degree easily. While this can be worked-around by generating code that accounts for all possible degrees, the resulting code would be unnecessarily big and complicated, and much harder to reason with. (Also note that a CRC is just the remainder from the polynomial division, but this routine is much faster in practice.)NB. The nth bit of the polynomial p mustQ be set for the CRC to be computed correctly. Note that the polynomial argument p[ will not even have this bit present most of the time, as it will typically contain bits 0 through n-13 as usual in the CRC literature. The higher order nth bit is simply assumed to be set, as it does not make sense to use a polynomial of a lesser degree. This is usually not a problem since CRC polynomials are designed and expressed this way.sNB. The literature on CRC's has many variants on how CRC's are computed. We follow the following simple procedure:Extend the message m by adding n 0 bits on the right+Divide the polynomial thus obtained by the pThe remainder is the CRC value.{There are many variants on final XOR's, reversed polynomials etc., so it is essential to double check you use the correct  algorithm.sbvACompute CRC's over polynomials, i.e., symbolic words. The first  b0 argument plays the same role as the one in the  function.L(c) Levent ErkokBSD3erkokl@gmail.com experimentalNone 8=?HSVXk —6sbv=Capture convertability from/to FloatingPoint representations.Conversions to float:  and i simply return the nearest representable float from the given type based on the rounding mode provided.Conversions from float:  and  functions do the reverse conversion. However some care is needed when given values that are not representable in the integral target domain. For instance, converting an e to an k* is problematic. The rules are as follows:If the input value is a finite point and when rounded in the given rounding mode to an integral value lies within the target bounds, then that result is returned. (This is the regular interpretation of rounding in IEEE754.)Otherwise (i.e., if the integral value in the float or double domain) doesn't fit into the target type, then the result is unspecified. Note that if the input is +oo, -oo, or NaN!, then the result is unspecified.?Due to the unspecified nature of conversions, SBV will never constant fold conversions from floats to integral values. That is, you will always get a symbolic value as output. (Conversions from floats to other floats will be constant folded. Conversions from integral values to floats will also be constant folded.)Note that unspecified really means unspecified: In particular, SBV makes no guarantees about matching the behavior between what you might get in Haskell, via SMT-Lib, or the C-translation. If the input value is out-of-bounds as defined above, or is NaN or oo or -oo%, then all bets are off. In particular C and SMTLib are decidedly undefine this case, though that doesn't mean they do the same thing! Same goes for Haskell, which seems to convert via Int64, but we do not model that behavior in SBV as it doesn't seem to be intentional nor well documented.You can check for NaN, oo and -oo, using the predicates , , and ,  predicates, respectively; and do the proper conversion based on your needs. (0 is a good choice, as are min/max bounds of the target type.)Currently, SBV provides no predicates to check if a value would lie within range for a particular conversion task, as this depends on the rounding mode and the types involved and can be rather tricky to determine. (See  ,http://github.com/LeventErkok/sbv/issues/456 for a discussion of the issues involved.) In a future release, we hope to be able to provide underflow and overflow predicates for these conversions as well.sbv.Convert from an IEEE74 single precision float.sbv.Convert to an IEEE-754 Single-precision float.:{XroundTrip :: forall a. (Eq a, IEEEFloatConvertible a) => SRoundingMode -> SBV a -> SBool1roundTrip m x = fromSFloat m (toSFloat m x) .== x:}prove $ roundTrip @Int8Q.E.D.prove $ roundTrip @Word8Q.E.D.prove $ roundTrip @Int16Q.E.D.prove $ roundTrip @Word16Q.E.D.prove $ roundTrip @Int32Falsifiable. Counter-example:- s0 = RoundNearestTiesToEven :: RoundingMode& s1 = -264306721 :: Int32Note how we get a failure on  U. The counter-example value is not representable exactly as a single precision float: toRational (-264306721 :: Float)(-264306720) % 1Note how the numerator is different, it is off by 1. This is hardly surprising, since floats become sparser as the magnitude increases to be able to cover all the integer values representable.sbv.Convert from an IEEE74 double precision float.sbv.Convert to an IEEE-754 Double-precision float.:{XroundTrip :: forall a. (Eq a, IEEEFloatConvertible a) => SRoundingMode -> SBV a -> SBool3roundTrip m x = fromSDouble m (toSDouble m x) .== x:}prove $ roundTrip @Int8Q.E.D.prove $ roundTrip @Word8Q.E.D.prove $ roundTrip @Int16Q.E.D.prove $ roundTrip @Word16Q.E.D.prove $ roundTrip @Int32Q.E.D.prove $ roundTrip @Word32Q.E.D.prove $ roundTrip @Int64Falsifiable. Counter-example:+ s0 = RoundTowardNegative :: RoundingMode$ s1 = -8069753317450726624 :: Int64Just like in the el case, once we reach 64-bits, we no longer can exactly represent the integer value for all possible values:,toRational ( -8069753317450726624 :: Double)(-8069753317450726400) % 1)In this case the numerator is off by 224!sbvA class of floating-point (IEEE754) operations, some of which behave differently based on rounding modes. Note that unless the rounding mode is concretely RoundNearestTiesToEven, we will not concretely evaluate these, but rather pass down to the SMT solver.sbv*Compute the floating point absolute value.sbv&Compute the unary negation. Note that 0 - x is not equivalent to -x for floating-point, since -0 and 0 are different.sbv<Add two floating point values, using the given rounding modesbvASubtract two floating point values, using the given rounding modesbvAMultiply two floating point values, using the given rounding modesbv?Divide two floating point values, using the given rounding modesbvOFused-multiply-add three floating point values, using the given rounding mode. fpFMA x y z = x*y+z but with only one rounding done for the whole operation; not two. Note that we will never concretely evaluate this function since Haskell lacks an FMA implementation.sbvACompute the square-root of a float, using the given rounding modesbvCompute the remainder:  x - y * n, where nY is the truncated integer nearest to x/y. The rounding mode is implicitly assumed to be RoundNearestTiesToEven.sbvCRound to the nearest integral value, using the given rounding mode.sbv,Compute the minimum of two floats, respects infinity and NaN valuessbv,Compute the maximum of two floats, respects infinity and NaN valuessbv4Are the two given floats exactly the same. That is, NaN will compare equal to itself, +0 will not compare equal to -0h etc. This is the object level equality, as opposed to the semantic equality. (For the latter, just use g.)sbvFIs the floating-point number a normal value. (i.e., not denormalized.)sbvIIs the floating-point number a subnormal value. (Also known as denormal.)sbvWIs the floating-point number 0? (Note that both +0 and -0 will satisfy this predicate.)sbv`Is the floating-point number infinity? (Note that both +oo and -oo will satisfy this predicate.)sbv)Is the floating-point number a NaN value?sbv]Is the floating-point number negative? Note that -0 satisfies this predicate but +0 does not.sbv]Is the floating-point number positive? Note that +0 satisfies this predicate but -0 does not.sbv Is the floating point number -0?sbv Is the floating point number +0?sbvyIs the floating-point number a regular floating point, i.e., not NaN, nor +oo, nor -oo. Normals or denormals are allowed. {sbvA generic from-float converter. Note that this function does no constant folding since it's behavior is undefined when the input float is out-of-bounds or not a point. |sbv_A generic to-float converter, which will constant-fold as necessary, but only in the sRNE mode. }sbvqConcretely evaluate one arg function, if rounding mode is RoundNearestTiesToEven and we have enough concrete data ~sbvqConcretely evaluate two arg function, if rounding mode is RoundNearestTiesToEven and we have enough concrete data sbvConcretely evaluate a bool producing two arg function, if rounding mode is RoundNearestTiesToEven and we have enough concrete data sbvqConcretely evaluate two arg function, if rounding mode is RoundNearestTiesToEven and we have enough concrete data sbv7Add the converted rounding mode if given as an argument sbvLift a 1 arg FP-op sbvLift an FP predicate sbvLift a 2 arg FP-op sbvLift min/max: Note that we protect against constant folding if args are alternating sign 0's, since SMTLib is deliberately nondeterministic in this case sbv"Lift a 2 arg FP-op, producing bool sbvLift a 3 arg FP-opsbv Convert an e to an mM, preserving the bit-correspondence. Note that since the representation for NaNTs are not unique, this function will return a symbolic value when given a concrete NaN.IImplementation note: Since there's no corresponding function in SMTLib for conversion to bit-representation due to partiality, we use a translation trick by allocating a new word variable, converting it to float, and requiring it to be equivalent to the input. In code-generation mode, we simply map it to a simple conversion.sbv Convert an d to an lM, preserving the bit-correspondence. Note that since the representation for NaNTs are not unique, this function will return a symbolic value when given a concrete NaN. See the implementation note for , as it applies here as well.sbvExtract the sign/exponent/mantissa of a single-precision float. The output will have 8 bits in the second argument for exponent, and 23 in the third for the mantissa.sbvExtract the sign/exponent/mantissa of a single-precision float. The output will have 11 bits in the second argument for exponent, and 52 in the third for the mantissa.sbvQReinterpret the bits in a 32-bit word as a single-precision floating point numbersbvQReinterpret the bits in a 32-bit word as a single-precision floating point numbersbv Convert a float to a comparable m. The trick is to ignore the sign of -0, and if it's a negative value flip all the bits, and otherwise only flip the sign bit. This is known as the lexicographic ordering on floats and it works as long as you do not have a NaN.sbv!Convert a double to a comparable l. The trick is to ignore the sign of -0, and if it's a negative value flip all the bits, and otherwise only flip the sign bit. This is known as the lexicographic ordering on doubles and it works as long as you do not have a NaN. sbv  instance for 9, goes through the lexicographic ordering on  ~2. It implicitly makes sure that the value is not NaN. sbv $ instance for 9, goes through the lexicographic ordering on  2. It implicitly makes sure that the value is not NaN. sbvSDouble instance sbvSFloat instance%(c) Levent ErkokBSD3erkokl@gmail.com experimentalNoneSX sbvIs the character in the string?:set -XOverloadedStrings"prove $ \c -> c `elem` singleton cQ.E.D. prove $ \c -> sNot (c `elem` "")Q.E.D.sbv#Is the character not in the string?4prove $ \c s -> c `elem` s .<=> sNot (c `notElem` s)Q.E.D.sbvThe  of a character.sbv*Conversion from an integer to a character.8prove $ \x -> 0 .<= x .&& x .< 256 .=> ord (chr x) .== xQ.E.D.prove $ \x -> chr (ord x) .== xQ.E.D.sbvConvert to lower-case./prove $ \c -> toLower (toLower c) .== toLower cQ.E.D.5prove $ \c -> isLower c .=> toLower (toUpper c) .== cQ.E.D.sbv:Convert to upper-case. N.B. There are three special cases!The character 223 is special. It corresponds to the German Eszett, it is considered lower-case, and furthermore it's upper-case maps back to itself within our character-set. So, we leave it untouched.The character 181 maps to upper-case 924, which is beyond our character set. We leave it untouched. (This is the A with an acute accent.)The character 255 maps to upper-case 376, which is beyond our character set. We leave it untouched. (This is the non-breaking space character.)/prove $ \c -> toUpper (toUpper c) .== toUpper cQ.E.D.5prove $ \c -> isUpper c .=> toUpper (toLower c) .== cQ.E.D.sbvmConvert a digit to an integer. Works for hexadecimal digits too. If the input isn't a digit, then return -1.Wprove $ \c -> isDigit c .|| isHexDigit c .=> digitToInt c .>= 0 .&& digitToInt c .<= 15Q.E.D.Gprove $ \c -> sNot (isDigit c .|| isHexDigit c) .=> digitToInt c .== -1Q.E.D.sbv-Convert an an integer to a digit, inverse of . If the integer is out of bounds, we return the arbitrarily chosen space character. Note that for hexadecimal letters, we return the corresponding lowercase letter.Fprove $ \i -> i .>= 0 .&& i .<= 15 .=> digitToInt (intToDigit i) .== iQ.E.D.Gprove $ \i -> i .< 0 .|| i .> 15 .=> digitToInt (intToDigit i) .== -1Q.E.D.Pprove $ \c -> digitToInt c .== -1 .<=> intToDigit (digitToInt c) .== literal ' 'Q.E.D.sbv\Is this a control character? Control characters are essentially the non-printing characters.sbv1Is this white-space? That is, one of "tnvfr 160".sbvIs this a lower-case character?/prove $ \c -> isUpper c .=> isLower (toLower c)Q.E.D.sbv Is this an upper-case character?,prove $ \c -> sNot (isLower c .&& isUpper c)Q.E.D.sbvIs this an alphabet character? That is lower-case, upper-case and title-case letters, plus letters of caseless scripts and modifiers letters.sbv Is this an  or .8prove $ \c -> isAlphaNum c .<=> isAlpha c .|| isNumber cQ.E.D.sbv=Is this a printable character? Essentially the complement of ], with one exception. The Latin-1 character 173 is neither control nor printable. Go figure.Hprove $ \c -> c .== literal '\173' .|| isControl c .<=> sNot (isPrint c)Q.E.D.sbv%Is this an ASCII digit, i.e., one of 0..9 . Note that this is a subset of &prove $ \c -> isDigit c .=> isNumber cQ.E.D.sbv%Is this an Octal digit, i.e., one of 0..7.(prove $ \c -> isOctDigit c .=> isDigit cQ.E.D.sbv!Is this a Hex digit, i.e, one of 0..9, a..f, A..F.+prove $ \c -> isHexDigit c .=> isAlphaNum cQ.E.D.sbvHIs this an alphabet character. Note that this function is equivalent to .'prove $ \c -> isLetter c .<=> isAlpha cQ.E.D.sbvIs this a mark? Note that the Latin-1 subset doesn't have any marks; so this function is simply constant false for the time being.prove $ sNot . isMarkQ.E.D.sbvIs this a number character? Note that this set contains not only the digits, but also the codes for a few numeric looking characters like 1/2 etc. Use  for the digits 0 through 9.sbvIs this a punctuation mark?sbvIs this a symbol?sbvIs this a separator?)prove $ \c -> isSeparator c .=> isSpace cQ.E.D.sbv;Is this an ASCII character, i.e., the first 128 characters.sbvIIs this a Latin1 character? Note that this function is always true since c5 corresponds precisely to Latin1 for the time being.prove isLatin1Q.E.D.sbvIs this an ASCII letter?Dprove $ \c -> isAsciiLetter c .<=> isAsciiUpper c .|| isAsciiLower cQ.E.D.sbv*Is this an ASCII Upper-case letter? i.e., A thru Z]prove $ \c -> isAsciiUpper c .<=> ord c .>= ord (literal 'A') .&& ord c .<= ord (literal 'Z')Q.E.D.9prove $ \c -> isAsciiUpper c .<=> isAscii c .&& isUpper cQ.E.D.sbv*Is this an ASCII Lower-case letter? i.e., a thru z]prove $ \c -> isAsciiLower c .<=> ord c .>= ord (literal 'a') .&& ord c .<= ord (literal 'z')Q.E.D.9prove $ \c -> isAsciiLower c .<=> isAscii c .&& isLower cQ.E.D.(c) Levent ErkokBSD3erkokl@gmail.com experimentalNone=?SXk Zsbv/Matchable class. Things we can match against a X . (TODO: Currently SBV does *not* optimize this call if the input is a concrete string or a character, but rather directly calls down to the solver. We might want to perform the operation on the Haskell side for performance reasons, should this become important.)EFor instance, you can generate valid-looking phone numbers like this::set -XOverloadedStringslet dig09 = Range '0' '9'let dig19 = Range '1' '9'"let pre = dig19 * Loop 2 2 dig09"let post = dig19 * Loop 3 3 dig09let phone = pre * "-" * post(sat $ \s -> (s :: SString) `match` phoneSatisfiable. Model: s0 = "100-1000" :: Stringsbv s r checks whether s! is in the language generated by r.sbvQA literal regular-expression, matching the given string exactly. Note that with OverloadedStringsk extension, you can simply use a Haskell string to mean the same thing, so this function is rarely needed.Kprove $ \(s :: SString) -> s `match` exactly "LITERAL" .<=> s .== "LITERAL"Q.E.D.sbv#Helper to define a character class.Vprove $ \(c :: SChar) -> c `match` oneOf "ABCD" .<=> sAny (c .==) (map literal "ABCD")Q.E.D.sbvARecognize a newline. Also includes carriage-return and form-feed.newline=(re.union (str.to.re "\n") (str.to.re "\r") (str.to.re "\f"))-prove $ \c -> c `match` newline .=> isSpace cQ.E.D.sbvRecognize a tab.tab(str.to.re "\x09")2prove $ \c -> c `match` tab .=> c .== literal '\t'Q.E.D.sbv.Recognize white-space, but without a new line.whiteSpaceNoNewLine\(re.union (str.to.re "\x09") (re.union (str.to.re "\v") (str.to.re "\xa0") (str.to.re " ")))[prove $ \c -> c `match` whiteSpaceNoNewLine .=> c `match` whiteSpace .&& c ./= literal '\n'Q.E.D.sbvRecognize white space.0prove $ \c -> c `match` whiteSpace .=> isSpace cQ.E.D.sbvIRecognize a punctuation character. Anything that satisfies the predicate L will be accepted. (TODO: Will need modification when we move to unicode.)7prove $ \c -> c `match` punctuation .=> isPunctuation cQ.E.D.sbv$Recognize an alphabet letter, i.e., A..Z, a..z. asciiLetter0(re.union (re.range "a" "z") (re.range "A" "Z"))Fprove $ \c -> c `match` asciiLetter .<=> toUpper c `match` asciiLetterQ.E.D.Fprove $ \c -> c `match` asciiLetter .<=> toLower c `match` asciiLetterQ.E.D.sbv$Recognize an ASCII lower case letter asciiLower(re.range "a" "z")Hprove $ \c -> (c :: SChar) `match` asciiLower .=> c `match` asciiLetterQ.E.D.Dprove $ \c -> c `match` asciiLower .=> toUpper c `match` asciiUpperQ.E.D.Dprove $ \c -> c `match` asciiLetter .=> toLower c `match` asciiLowerQ.E.D.sbvRecognize an upper case letter asciiUpper(re.range "A" "Z")Hprove $ \c -> (c :: SChar) `match` asciiUpper .=> c `match` asciiLetterQ.E.D.Dprove $ \c -> c `match` asciiUpper .=> toLower c `match` asciiLowerQ.E.D.Dprove $ \c -> c `match` asciiLetter .=> toUpper c `match` asciiUpperQ.E.D.sbvRecognize a digit. One of 0..9.digit(re.range "0" "9")Nprove $ \c -> c `match` digit .<=> let v = digitToInt c in 0 .<= v .&& v .< 10Q.E.D.sbv!Recognize an octal digit. One of 0..7.octDigit(re.range "0" "7")Pprove $ \c -> c `match` octDigit .<=> let v = digitToInt c in 0 .<= v .&& v .< 8Q.E.D.?prove $ \(c :: SChar) -> c `match` octDigit .=> c `match` digitQ.E.D.sbv&Recognize a hexadecimal digit. One of 0..9, a..f, A..F.hexDigitC(re.union (re.range "0" "9") (re.range "a" "f") (re.range "A" "F"))Qprove $ \c -> c `match` hexDigit .<=> let v = digitToInt c in 0 .<= v .&& v .< 16Q.E.D.?prove $ \(c :: SChar) -> c `match` digit .=> c `match` hexDigitQ.E.D.sbvRecognize a decimal number.decimal(re.+ (re.range "0" "9"))Qprove $ \s -> (s::SString) `match` decimal .=> sNot (s `match` KStar asciiLetter)Q.E.D.sbv:Recognize an octal number. Must have a prefix of the form 0o/0O.octalN(re.++ (re.union (str.to.re "0o") (str.to.re "0O")) (re.+ (re.range "0" "7")))Bprove $ \s -> s `match` octal .=> sAny (.== take 2 s) ["0o", "0O"]Q.E.D.sbv?Recognize a hexadecimal number. Must have a prefix of the form 0x/0X. hexadecimal(re.++ (re.union (str.to.re "0x") (str.to.re "0X")) (re.+ (re.union (re.range "0" "9") (re.range "a" "f") (re.range "A" "F"))))Hprove $ \s -> s `match` hexadecimal .=> sAny (.== take 2 s) ["0x", "0X"]Q.E.D.sbvRecognize a floating point number. The exponent part is optional if a fraction is present. The exponent may or may not have a sign.3prove $ \s -> s `match` floating .=> length s .>= 3Q.E.D.sbvFor the purposes of this regular expression, an identifier consists of a letter followed by zero or more letters, digits, underscores, and single quotes. The first letter must be lowercase.<prove $ \s -> s `match` identifier .=> isAsciiLower (head s)Q.E.D.5prove $ \s -> s `match` identifier .=> length s .>= 1Q.E.D. sbv#Lift a unary operator over strings. sbv!Concrete evaluation for unary ops sbv$Quiet GHC about testing only importssbvMatching symbolic strings.sbvIMatching a character simply means the singleton string matches the regex. XYZb\[]^_`ac XYZb\[]^_`acM(c) Levent ErkokBSD3erkokl@gmail.com experimentalNone1WX bsbvCheck whether the given solver is installed and is ready to go. This call does a simple call to the solver to ensure all is well.sbv:The default configs corresponding to supported SMT solverssbvEReturn the known available solver configs, installed on your machine.sbv$Make an enumeration a symbolic type.N1(c) Brian Schroeder Levent ErkokBSD3erkokl@gmail.com experimentalNone W2sbvAsk solver for info.CNB. For a version which generalizes over the underlying monad, see sbvRetrieve the value of an  'SMTOption.'h The curious function argument is on purpose here, simply pass the constructor name. Example: the call  O will return either Nothing or Just (ProduceUnsatCores True) or Just (ProduceUnsatCores False).Result will be  , if the solver does not support this option.CNB. For a version which generalizes over the underlying monad, see Psbv-Get the reason unknown. Only internally used.CNB. For a version which generalizes over the underlying monad, see osbv0Get the observables recorded during a query run.CNB. For a version which generalizes over the underlying monad, see Q sbv?Get the uinterpreted constants/functions recorded during a run.CNB. For a version which generalizes over the underlying monad, see sbv*Issue check-sat and get an SMT Result out.CNB. For a version which generalizes over the underlying monad, see  sbv@Issue check-sat and get results of a lexicographic optimization.CNB. For a version which generalizes over the underlying monad, see  sbvGIssue check-sat and get results of an independent (boxed) optimization.CNB. For a version which generalizes over the underlying monad, see  sbv,Construct a pareto-front optimization resultCNB. For a version which generalizes over the underlying monad, see sbvXCollect model values. It is implicitly assumed that we are in a check-sat context. See = for a variant that issues a check-sat first and returns an .CNB. For a version which generalizes over the underlying monad, see sbvACheck for satisfiability, under the given conditions. Similar to kg except it allows making further assumptions as captured by the first argument of booleans. (Also see Q for a variant that returns the subset of the given assumptions that led to the R conclusion.)CNB. For a version which generalizes over the underlying monad, see lsbvpCheck for satisfiability, under the given conditions. Returns the unsatisfiable set of assumptions. Similar to kn except it allows making further assumptions as captured by the first argument of booleans. If the result is RP, the user will also receive a subset of the given assumptions that led to the Rv conclusion. Note that while this set will be a subset of the inputs, it is not necessarily guaranteed to be minimal.IYou must have arranged for the production of unsat assumptions first via  S $ T  H for this call to not error out! Usage note:   is usually easier to use than <, as it allows the use of named assertions, as obtained by U. If  9 fills your needs, you should definitely prefer it over .CNB. For a version which generalizes over the underlying monad, see sbv)The current assertion stack depth, i.e., push - &pops after start. Always non-negative.CNB. For a version which generalizes over the underlying monad, see sbvoRun the query in a new assertion stack. That is, we push the context, run the query commands, and pop it back.CNB. For a version which generalizes over the underlying monad, see sbv@Push the context, entering a new one. Pushes multiple levels if n > 1.CNB. For a version which generalizes over the underlying monad, see sbv<Pop the context, exiting a new one. Pops multiple levels if n3 > 1. It's an error to pop levels that don't exist.CNB. For a version which generalizes over the underlying monad, see sbvSearch for a result via a sequence of case-splits, guided by the user. If one of the conditions lead to a satisfiable result, returns Just+ that result. If none of them do, returns Nothing. Note that we automatically generate a coverage case and search for it automatically as well. In that latter case, the string returned will be Coverage?. The first argument controls printing progress messages See ,Documentation.SBV.Examples.Queries.CaseSplit for an example use case.CNB. For a version which generalizes over the underlying monad, see  sbvReset the solver, by forgetting all the assertions. However, bindings are kept as is, as opposed to a full reset of the solver. Use this variant to clean-up the solver state while leaving the bindings intact. Pops all assertion levels. Declarations and definitions resulting from the jl command are unaffected. Note that SBV implicitly uses global-declarations, so bindings will remain intact.CNB. For a version which generalizes over the underlying monad, see  sbvGEcho a string. Note that the echoing is done by the solver, not by SBV.CNB. For a version which generalizes over the underlying monad, see  sbvExit the solver. This action will cause the solver to terminate. Needless to say, trying to communicate with the solver after issuing "exit" will simply fail.CNB. For a version which generalizes over the underlying monad, see  sbv^Retrieve the unsat-core. Note you must have arranged for unsat cores to be produced first via  S $ O  H for this call to not error out!NB. There is no notion of a minimal unsat-core, in case unsatisfiability can be derived in multiple ways. Furthermore, Z3 does not guarantee that the generated unsat core does not have any redundant assertions either, as doing so can incur a performance penalty. (There might be assertions in the set that is not needed.) To ensure all the assertions in the core are relevant, use:  S $ V ":smt.core.minimize" ["true"] "Note that this only works with Z3.CNB. For a version which generalizes over the underlying monad, see n sbvTRetrieve the proof. Note you must have arranged for proofs to be produced first via  S $ W  H for this call to not error out!A proof is simply a  , as returned by the solver. In the future, SBV might provide a better datatype, depending on the use cases. Please get in touch if you use this function and can suggest a better API.CNB. For a version which generalizes over the underlying monad, see sbv1Interpolant extraction for MathSAT. Compare with J, which performs similar function (but with a different use model) in Z3.!Retrieve an interpolant after an R[ result is obtained. Note you must have arranged for interpolants to be produced first via  S $ X  H for this call to not error out!-To get an interpolant for a pair of formulas A and B, use a Y( call to attach interplation groups to A and B . Then call  ["A"]@, assuming those are the names you gave to the formulas in the A group.An interpolant for A and B is a formula I such that: # A .=> I and B .=> sNot I That is, it's evidence that A and B cannot be true together since A implies I but B implies not I; establishing that A and B5 cannot be satisfied at the same time. Furthermore, I0 will have only the symbols that are common to A and B.NB. Interpolant extraction isn't standardized well in SMTLib. Currently both MathSAT and Z3 support them, but with slightly differing APIs. So, we support two APIs with slightly differing types to accommodate both. See /Documentation.SBV.Examples.Queries.Interpolants& for example usages in these solvers.CNB. For a version which generalizes over the underlying monad, see sbv,Interpolant extraction for z3. Compare with O, which performs similar function (but with a different use model) in MathSAT.3Unlike the MathSAT variant, you should simply call @ on symbolic booleans to retrieve the interpolant. Do not call  or create named constraints. This makes it harder to identify formulas, but the current state of affairs in interpolant API requires this kludge.An interpolant for A and B is a formula I such that: " A ==> I and B ==> not I That is, it's evidence that A and B cannot be true together since A implies I but B implies not I; establishing that A and B5 cannot be satisfied at the same time. Furthermore, I0 will have only the symbols that are common to A and B.In Z3, interpolants generalize to sequences: If you pass more than two formulas, then you will get a sequence of interpolants. In general, for NC formulas that are not satisfiable together, you will be returned N-1 interpolants. If formulas are A1 .. An, then interpolants will be  I1 .. I(N-1) , such that  A1 ==> I1, A2 /\ I1 ==> I2, A3 /\ I2 ==> I3, ..., and finally AN ===> not I(N-1).aCurrently, SBV only returns simple and sequence interpolants, and does not support tree-interpolants. If you need these, please get in touch. Furthermore, the result will be a list of mere strings representing the interpolating formulas, as opposed to a more structured type. Please get in touch if you use this function and can suggest a better API.NB. Interpolant extraction isn't standardized well in SMTLib. Currently both MathSAT and Z3 support them, but with slightly differing APIs. So, we support two APIs with slightly differing types to accommodate both. See /Documentation.SBV.Examples.Queries.Interpolants& for example usages in these solvers.CNB. For a version which generalizes over the underlying monad, see sbvZRetrieve assertions. Note you must have arranged for assertions to be available first via  S $ Z  H for this call to not error out!^Note that the set of assertions returned is merely a list of strings, just like the case for  . In the future, SBV might provide a better datatype, depending on the use cases. Please get in touch if you use this function and can suggest a better API.CNB. For a version which generalizes over the underlying monad, see sbv:Retrieve the assignment. This is a lightweight version of K, where the solver returns the truth value for all named subterms of type  &.?You must have first arranged for assignments to be produced via  S $ [  H for this call to not error out!CNB. For a version which generalizes over the underlying monad, see sbv,Produce the query result from an assignment.CNB. For a version which generalizes over the underlying monad, see sbvPerform an arbitrary IO action.CNB. For a version which generalizes over the underlying monad, see  sbvModify the query stateCNB. For a version which generalizes over the underlying monad, see  sbv$Execute in a new incremental contextCNB. For a version which generalizes over the underlying monad, see sbv Similar to ", except creates unnamed variable.CNB. For a version which generalizes over the underlying monad, see sbvYCreate a fresh variable in query mode. You should prefer creating input variables using , \, etc., which act as primary inputs to the model and can be existential or universal. Use i only in query mode for anonymous temporary variables. Such variables are always existential. Note that r should hardly be needed: Your input variables and symbolic expressions should suffice for most major use cases.CNB. For a version which generalizes over the underlying monad, see sbv Similar to , except creates unnamed array.CNB. For a version which generalizes over the underlying monad, see sbvmCreate a fresh array in query mode. Again, you should prefer creating arrays before the queries start using , but this method can come in handy in occasional cases where you need a new array after you start the query based interaction.CNB. For a version which generalizes over the underlying monad, see sbvIf \ is  HQ, print the message, useful for debugging messages in custom queries. Note that ]T will be respected: If a file redirection is given, the output will go to the file.CNB. For a version which generalizes over the underlying monad, see  sbv4Send a string to the solver, and return the responseCNB. For a version which generalizes over the underlying monad, see  sbv6Send a string to the solver. If the first argument is  HR, we will require a "success" response as well. Otherwise, we'll fire and forget.CNB. For a version which generalizes over the underlying monad, see  sbvRetrieve a responses from the solver until it produces a synchronization tag. We make the tag unique by attaching a time stamp, so no need to worry about getting the wrong tag unless it happens in the very same picosecond! We return multiple valid s-expressions till the solver responds with the tag. Should only be used for internal tasks or when we want to synchronize communications, and not on a regular basis! Use  'send'/'ask' for that purpose. This comes in handy, however, when solvers respond multiple times as in optimization for instance, where we both get a check-sat answer and some objective values.CNB. For a version which generalizes over the underlying monad, see sbvGet the value of a term.CNB. For a version which generalizes over the underlying monad, see msbv3Get the value of an uninterpreted sort, as a StringCNB. For a version which generalizes over the underlying monad, see sbvGet the value of an uninterpreted function, as a list of domain, value pairs. The final value is the "else" clause, i.e., what the function maps values outside of the domain of the first list. sbvGet the value of a term. If the kind is Real and solver supports decimal approximations, we will "squash" the representations.CNB. For a version which generalizes over the underlying monad, see  sbvAGet the value of an uninterpreted function as an association listCNB. For a version which generalizes over the underlying monad, see sbvCheck for satisfiability.CNB. For a version which generalizes over the underlying monad, see ksbvZEnsure that the current context is satisfiable. If not, this function will throw an error.CNB. For a version which generalizes over the underlying monad, see sbv?Check for satisfiability with a custom check-sat-using command.CNB. For a version which generalizes over the underlying monad, see  sbvCRetrieve the set of unsatisfiable assumptions, following a call to i. Note that this function isn't exported to the user, but rather used internally. The user simple calls .CNB. For a version which generalizes over the underlying monad, see sbvqTimeout a query action, typically a command call to the underlying SMT solver. The duration is in microseconds (1/10^6~ seconds). If the duration is negative, then no timeout is imposed. When specifying long timeouts, be careful not to exceed maxBound :: Intz. (On a 64 bit machine, this bound is practically infinite. But on a 32 bit machine, it corresponds to about 36 minutes!)Semantics: The call  timeout n qj causes the timeout value to be applied to all interactive calls that take place as we execute the query q:. That is, each call that happens during the execution of qe gets a separate time-out value, as opposed to one timeout value that limits the whole query. This is typically the intended behavior. It is advisible to apply this combinator to calls that involve a single call to the solver for finer control, as opposed to an entire set of interactions. However, different use cases might call for different scenarios.If the solver responds within the time-out specified, then we continue as usual. However, if the backend solver times-out using this mechanism, there is no telling what the state of the solver will be. Thus, we raise an error in this case.CNB. For a version which generalizes over the underlying monad, see  sbv)Bail out if we don't get what we expectedCNB. For a version which generalizes over the underlying monad, see  sbvExecute a query.CNB. For a version which generalizes over the underlying monad, see 2            (c) Levent ErkokBSD3erkokl@gmail.com experimentalNone, Z sbvRun a custom query[ !"#$%&'()*+,-./01234567=>?@EGABCDFHIJKLTU"#$%&'(,-      [TU,-#$%&'(" IJKL  @EGABCDFH=>?./01234567    !"#$%&'()*+,-^(c) Levent ErkokBSD3erkokl@gmail.com experimentalNone=?M W4!sbvCDifferent kinds of "files" we can produce. Currently this is quite C specific.&sbv5Representation of a collection of generated programs.(sbvPossible mappings for the fC type when translated to C. Used in conjunction with the function M. Note that the particular characteristics of the mapped types depend on the platform and the compiler used for compiling the generated C program. See  )http://en.wikipedia.org/wiki/C_data_types for details.)sbv float*sbv double+sbv  long double,sbvThe code-generation monad. Allows for precise layout of input values reference parameters (for returning composite values in languages such as C), and return values..sbvCode-generation state7sbv%Abstraction of target language values:sbvOptions for code-generation.<sbvIf  HR, perform run-time-checks for index-out-of-bounds or shifting-by-large values etc.=sbv2Bit-size to use for representing SInteger (if any)>sbv+Type to use for representing SReal (if any)?sbvYValues to use for the driver program generated, useful for generating non-random drivers.@sbvIf  H , will generate a driver programAsbvIf  H, will generate a makefileBsbvIf  H, will ignore  callsCsbvIf  H7, will overwrite the generated files without prompting.DsbvIf  Hp, then 8-bit unsigned values will be shown in hex as well, otherwise decimal. (Other types always shown in hex.)Esbv5Abstract over code generation for different languagesHsbvuDefault options for code generation. The run-time checks are turned-off, and the driver values are completely random.Isbv)Initial configuration for code-generationJsbv.Reach into symbolic monad from code-generationKsbvaSets RTC (run-time-checks) for index-out-of-bounds, shift-with-large value etc. on/off. Default:  %.Lsbv4Sets number of bits to be used for representing the g< type in the generated C code. The argument must be one of 8, 16, 32, or 64. Note that this is essentially unsafe as the semantics of unbounded Haskell integers becomes reduced to the corresponding bit size, as typical in most C implementations.Msbv0Sets the C type to be used for representing the f> type in the generated C code. The setting can be one of C's "float", "double", or  "long double", types, depending on the precision needed. Note that this is essentially unsafe as the semantics of infinite precision SReal values becomes reduced to the corresponding floating point type in C, and hence it is subject to rounding errors.Nsbv.Should we generate a driver program? Default:  Hl. When a library is generated, it will have a driver if any of the contituent functions has a driver. (See _.)Osbv(Should we generate a Makefile? Default:  H.PsbvSets driver program run time values, useful for generating programs with fixed drivers for testing. Default: None, i.e., use random values.Qsbv&Ignore assertions (those generated by  calls) in the generated C codeRsbvoAdds the given lines to the header file generated, useful for generating programs with uninterpreted functions.Ssbv If passed  Ho, then we will not ask the user if we're overwriting files as we generate the C code. Otherwise, we'll prompt.Tsbv If passed  H, then we will show 'SWord 8' type in hex. Otherwise we'll show it in decimal. All signed types are shown decimal, and all unsigned larger types are shown hexadecimal otherwise.UsbvpAdds the given lines to the program file generated, useful for generating programs with uninterpreted functions.VsbvjAdds the given words to the compiler options in the generated Makefile, useful for linking extra stuff in.Wsbv.Creates an atomic input in the generated code.Xsbv-Creates an array input in the generated code.Ysbv/Creates an atomic output in the generated code.Zsbv.Creates an array output in the generated code.[sbv9Creates a returned (unnamed) value in the generated code.\sbv?Creates a returned (unnamed) array value in the generated code.]sbv.Creates an atomic input in the generated code.^sbv-Creates an array input in the generated code._sbv/Creates an atomic output in the generated code.`sbv.Creates an array output in the generated code.asbv9Creates a returned (unnamed) value in the generated code.bsbv?Creates a returned (unnamed) array value in the generated code.csbvIs this a driver program?dsbvIs this a make file?esbv}Generate code for a symbolic program, returning a Code-gen bundle, i.e., collection of makefiles, source code, headers, etc.fsbv4Render a code-gen bundle to a directory or to stdout sbvAn alternative to Pretty's renderb, which might have "leading" white-space in empty lines. This version eliminates such whitespace.F!"#$%&'()*+,-./0123456789:;<=>?@ABCDEGFHIJKLMNOPQRSTUVWXYZ[\]^_`abcdef`(c) Levent ErkokBSD3erkokl@gmail.com experimentalNone gsbvgGiven a symbolic computation, render it as an equivalent collection of files that make up a C program:The first argument is the directory name under which the files will be saved. To save files in the current directory pass  H ".". Use   for printing to stdout.>The second argument is the name of the C function to generate.2The final argument is the function to be compiled.!Compilation will also generate a Makefile, a header file, and a driver (test) program, etc. As a result, we return whatever the code-gen function returns. Most uses should simply have (){ as the return type here, but the value can be useful if you want to chain the result of one compilation act to the next.hsbvLower level version of g, producing a &isbvCreate code to generate a library archive (.a) from given symbolic functions. Useful when generating code from multiple functions that work together as a library.The first argument is the directory name under which the files will be saved. To save files in the current directory pass  H ".". Use   for printing to stdout.;The second argument is the name of the archive to generate.The third argument is the list of functions to include, in the form of function-name/code pairs, similar to the second and third arguments of g, except in a list.jsbvLower level version of i, producing a & sbvPretty print a functions type. If there is only one output, we compile it as a function that returns that value. Otherwise, we compile it as a void function that takes return values as pointers to be updated. sbvTRenders as "const SWord8 s0", etc. the first parameter is the width of the typefield sbvAReturn the proper declaration and the result as a pair. No consts sbv3Renders as "s0", etc, or the corresponding constant sbv!Words as it would map to a C word sbvAlmost a "show", but map SWord1 to SBool- which is used for extracting one-bit words. sbv!The printf specifier for the type sbvMake a constant value of the given type. We don't check for out of bounds here, as it should not be needed. There are many options here, using binary, decimal, etc. We simply use decimal for values 8-bits or less, and hex otherwise. sbvDGenerate a makefile. The first argument is True if we have a driver. sbvGenerate the header sbv"Generate an example driver program sbvGenerate the C program sbvMerge a bunch of bundles to generate code for a library. For the final config, we simply return the first config we receive, or the default if none. sbv!Create a Makefile for the library sbvCreate a driver for a libraryghij(c) Levent ErkokBSD3erkokl@gmail.com experimentalNone $()*+,JKLMNOPQRSTUV]^_`abgi,JKPNOST]^_`abRUVQLM()*+gi(c) Levent ErkokBSD3erkokl@gmail.com experimentalNone ksbvSend an arbitrary string to the solver in a query. Note that this is inherently dangerous as it can put the solver in an arbitrary state and confuse SBV. If you use this feature, you are on your own!lsbvvRetrieve multiple responses from the solver, until it responds with a user given tag that we shall arrange for internally. The optional timeout is in milliseconds. If the time-out is exceeded, then we will raise an error. Note that this is inherently dangerous as it can put the solver in an arbitrary state and confuse SBV. If you use this feature, you are on your own!msbvSend an arbitrary string to the solver in a query, and return a response. Note that this is inherently dangerous as it can put the solver in an arbitrary state and confuse SBV.SMNOPQSVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~      !)*+./0123456789:;=<>?@ABCDEFGHIJKLMNOPQRSTUVWXYZb\[]^_`acdefghijklmnopqrstuvwxyz{|}~%&'()*+-,./012=789:;<>?@A4B5CD63EFGOHIJKNMLPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~qrs!"#$%&'()*+,-./0123456789:;<=>?@ABCDEGFHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefhjklm !    ponmlkjihgfedcba`_]\[ZYXWV^vwxyR2=789:;<>?@A4B5CD63OPQMNz{|}~qrs +-,./01%&'()*FGVWXYZ[\]^_`abcdefghrstuvwxyz{|}~defghijklmnopqMNOPQRSTUVWXYZb\[]^_`acBCDEtuijklmnopqrstuvwEF !GOHIJKNMLPQHIJKLS>?@A;=<789:./0123456)*+STUqrshj,-J]^_`abWXYZ[\KPRUVQSTLM()*+EGF:;<=>?@ABCD./0123456&'!"#$%789HIcdNOefxyz{|}~kmla1(c) Brian Schroeder Levent ErkokBSD3erkokl@gmail.com experimentalNone .8=>?HUV R~ sbv7Conversion from a fixed-sized BV to a sized bit-vector.nsbvVConvert a fixed-sized bit-vector to the corresponding sized bit-vector, for instance n to 'SWord 16'. See also p.osbv<Capture the correspondence between fixed-sized and sized BVs sbv7Conversion from a sized BV to a fixed-sized bit-vector.psbvdConvert a sized bit-vector to the corresponding fixed-sized bit-vector, for instance 'SWord 16' to n . See also n.qsbv<Capture the correspondence between sized and fixed-sized BVs sbvPCapturing non-matching instances for better error messages, conversions to sized sbvRCapturing non-matching instances for better error messages, conversions from sizedrsbvTurns a value into a universally quantified predicate, internally naming the inputs. In this case the sbv library will use names of the form s1, s2(, etc. to name these variables Example: / forAll_ $ \(x::SWord8) y -> x `shiftL` 2 .== y]is a predicate with two arguments, captured using an ordinary Haskell function. Internally, x will be named s0 and y will be named s1.CNB. For a version which generalizes over the underlying monad, see ssbv]Turns a value into a predicate, allowing users to provide names for the inputs. If the user does not provide enough number of names for the variables, the remaining ones will be internally generated. Note that the names are only used for printing models and has no other significance; in particular, we do not check that they are unique. Example: 9 forAll ["x", "y"] $ \(x::SWord8) y -> x `shiftL` 2 .== y>This is the same as above, except the variables will be named x and yG respectively, simplifying the counter-examples when they are printed.CNB. For a version which generalizes over the underlying monad, see tsbvCTurns a value into an existentially quantified predicate. (Indeed, R would have been a better choice here for the name, but alas it's already taken.)CNB. For a version which generalizes over the underlying monad, see usbv Version of u that allows user defined names.CNB. For a version which generalizes over the underlying monad, see vsbv,Prove a predicate, using the default solver.CNB. For a version which generalizes over the underlying monad, see wsbv/Prove the predicate using the given SMT-solver.CNB. For a version which generalizes over the underlying monad, see xsbvGFind a satisfying assignment for a predicate, using the default solver.CNB. For a version which generalizes over the underlying monad, see ysbv8Find a satisfying assignment using the given SMT-solver.CNB. For a version which generalizes over the underlying monad, see zsbvJFind all satisfying assignments, using the default solver. Equivalent to { b. See { for details.CNB. For a version which generalizes over the underlying monad, see {sbvReturn all satisfying assignments for a predicate. Note that this call will block until all satisfying assignments are found. If you have a problem with infinitely many satisfying models (consider gh) or a very large number of them, you might have to wait for a long time. To avoid such cases, use the |c! parameter in the configuration.rNB. Uninterpreted constant/function values and counter-examples for array values are ignored for the purposes of z&. That is, only the satisfying assignments modulo uninterpreted functions and array inputs will be returned. This is due to the limitation of not having a robust means of getting a function counter-example back from the SMT solver. Find all satisfying assignments using the given SMT-solverCNB. For a version which generalizes over the underlying monad, see |sbvOptimize a given collection of 7s.CNB. For a version which generalizes over the underlying monad, see }sbv4Optimizes the objectives using the given SMT-solver.CNB. For a version which generalizes over the underlying monad, see ~sbvHCheck if the constraints given are consistent, using the default solver.CNB. For a version which generalizes over the underlying monad, see sbvDDetermine if the constraints are vacuous using the given SMT-solver.CNB. For a version which generalizes over the underlying monad, see sbv,Checks theoremhood using the default solver.CNB. For a version which generalizes over the underlying monad, see sbv,Check whether a given property is a theorem.CNB. For a version which generalizes over the underlying monad, see sbv/Checks satisfiability using the default solver.CNB. For a version which generalizes over the underlying monad, see sbv.Check whether a given property is satisfiable.CNB. For a version which generalizes over the underlying monad, see sbv5Run an arbitrary symbolic computation, equivalent to  bCNB. For a version which generalizes over the underlying monad, see sbvGRuns an arbitrary symbolic computation, exposed to the user in SAT modeCNB. For a version which generalizes over the underlying monad, see sbvCNB. For a version which generalizes over the underlying monad, see sbvCNB. For a version which generalizes over the underlying monad, see sbv&Check safety using the default solver.CNB. For a version which generalizes over the underlying monad, see sbvCheck if any of the  calls can be violated.CNB. For a version which generalizes over the underlying monad, see  sbvCreate a symbolic variable.CNB. For a version which generalizes over the underlying monad, see  sbv<Convert a symbolic value to an SV, inside the Symbolic monadCNB. For a version which generalizes over the underlying monad, see dsbvMark an interim result as an output. Useful when constructing Symbolic programs that return multiple values, or when the result is programmatically computed.CNB. For a version which generalizes over the underlying monad, see sbv%Create a user named input (universal)CNB. For a version which generalizes over the underlying monad, see sbv#Create an automatically named inputCNB. For a version which generalizes over the underlying monad, see sbvGet a bunch of new wordsCNB. For a version which generalizes over the underlying monad, see sbvCreate an existential variableCNB. For a version which generalizes over the underlying monad, see sbv2Create an automatically named existential variableCNB. For a version which generalizes over the underlying monad, see sbvCreate a bunch of existentialsCNB. For a version which generalizes over the underlying monad, see sbv@Create a free variable, universal in a proof, existential in satCNB. For a version which generalizes over the underlying monad, see sbvGCreate an unnamed free variable, universal in proof, existential in satCNB. For a version which generalizes over the underlying monad, see sbvCreate a bunch of free varsCNB. For a version which generalizes over the underlying monad, see sbv,Similar to free; Just a more convenient nameCNB. For a version which generalizes over the underlying monad, see sbvISimilar to mkFreeVars; but automatically gives names based on the stringsCNB. For a version which generalizes over the underlying monad, see sbvOne stop allocatorCNB. For a version which generalizes over the underlying monad, see sbvDCreate a new anonymous array, possibly with a default initial value.CNB. For a version which generalizes over the underlying monad, see sbv@Create a named new array, possibly with a default initial value.CNB. For a version which generalizes over the underlying monad, see  sbvGenerically make a symbolic varCNB. For a version which generalizes over the underlying monad, see sbvDeclare a named pCNB. For a version which generalizes over the underlying monad, see sbvDeclare an unnamed pCNB. For a version which generalizes over the underlying monad, see sbvDeclare a list of psCNB. For a version which generalizes over the underlying monad, see sbvDeclare a named oCNB. For a version which generalizes over the underlying monad, see sbvDeclare an unnamed oCNB. For a version which generalizes over the underlying monad, see  sbvDeclare a list of osCNB. For a version which generalizes over the underlying monad, see  sbvDeclare a named nCNB. For a version which generalizes over the underlying monad, see  sbvDeclare an unnamed nCNB. For a version which generalizes over the underlying monad, see  sbvDeclare a list of nsCNB. For a version which generalizes over the underlying monad, see  sbvDeclare a named mCNB. For a version which generalizes over the underlying monad, see sbvDeclare an unamed mCNB. For a version which generalizes over the underlying monad, see sbvDeclare a list of msCNB. For a version which generalizes over the underlying monad, see sbvDeclare a named lCNB. For a version which generalizes over the underlying monad, see sbvDeclare an unnamed lCNB. For a version which generalizes over the underlying monad, see sbvDeclare a list of lsCNB. For a version which generalizes over the underlying monad, see sbvDeclare a named }CNB. For a version which generalizes over the underlying monad, see GsbvDeclare an unnamed }CNB. For a version which generalizes over the underlying monad, see HsbvDeclare a list of osCNB. For a version which generalizes over the underlying monad, see esbvDeclare a named kCNB. For a version which generalizes over the underlying monad, see sbvDeclare an unnamed kCNB. For a version which generalizes over the underlying monad, see sbvDeclare a list of ksCNB. For a version which generalizes over the underlying monad, see sbvDeclare a named jCNB. For a version which generalizes over the underlying monad, see sbvDeclare an unnamed jCNB. For a version which generalizes over the underlying monad, see sbvDeclare a list of jsCNB. For a version which generalizes over the underlying monad, see sbvDeclare a named iCNB. For a version which generalizes over the underlying monad, see sbvDeclare an unnamed iCNB. For a version which generalizes over the underlying monad, see sbvDeclare a list of isCNB. For a version which generalizes over the underlying monad, see sbvDeclare a named hCNB. For a version which generalizes over the underlying monad, see sbvDeclare an unnamed hCNB. For a version which generalizes over the underlying monad, see sbvDeclare a list of hsCNB. For a version which generalizes over the underlying monad, see sbvDeclare a named zCNB. For a version which generalizes over the underlying monad, see IsbvDeclare an unnamed zCNB. For a version which generalizes over the underlying monad, see JsbvDeclare a list of zsCNB. For a version which generalizes over the underlying monad, see KsbvDeclare a named gCNB. For a version which generalizes over the underlying monad, see  sbvDeclare an unnamed gCNB. For a version which generalizes over the underlying monad, see !sbvDeclare a list of gsCNB. For a version which generalizes over the underlying monad, see "sbvDeclare a named fCNB. For a version which generalizes over the underlying monad, see #sbvDeclare an unnamed fCNB. For a version which generalizes over the underlying monad, see $sbvDeclare a list of fsCNB. For a version which generalizes over the underlying monad, see %sbvDeclare a named eCNB. For a version which generalizes over the underlying monad, see &sbvDeclare an unnamed eCNB. For a version which generalizes over the underlying monad, see 'sbvDeclare a list of esCNB. For a version which generalizes over the underlying monad, see (sbvDeclare a named dCNB. For a version which generalizes over the underlying monad, see )sbvDeclare an unnamed dCNB. For a version which generalizes over the underlying monad, see *sbvDeclare a list of dsCNB. For a version which generalizes over the underlying monad, see +sbvDeclare a named cCNB. For a version which generalizes over the underlying monad, see ,sbvDeclare an unnamed cCNB. For a version which generalizes over the underlying monad, see -sbvDeclare a list of csCNB. For a version which generalizes over the underlying monad, see .sbvDeclare a named bCNB. For a version which generalizes over the underlying monad, see /sbvDeclare an unnamed bCNB. For a version which generalizes over the underlying monad, see 0sbvDeclare a list of bsCNB. For a version which generalizes over the underlying monad, see 1sbvDeclare a named aCNB. For a version which generalizes over the underlying monad, see 2sbvDeclare an unnamed aCNB. For a version which generalizes over the underlying monad, see 3sbvDeclare a list of asCNB. For a version which generalizes over the underlying monad, see 4sbvDeclare a named tuple.CNB. For a version which generalizes over the underlying monad, see 5sbvDeclare an unnamed tuple.CNB. For a version which generalizes over the underlying monad, see 6sbvDeclare a list of tuples.CNB. For a version which generalizes over the underlying monad, see 7sbvDeclare a named f.CNB. For a version which generalizes over the underlying monad, see 8sbvDeclare an unnamed f.CNB. For a version which generalizes over the underlying monad, see 9sbvDeclare a list of f values.CNB. For a version which generalizes over the underlying monad, see :sbvDeclare a named g.CNB. For a version which generalizes over the underlying monad, see ;sbvDeclare an unnamed g.CNB. For a version which generalizes over the underlying monad, see <sbvDeclare a list of g values.CNB. For a version which generalizes over the underlying monad, see =sbvDeclare a named h.CNB. For a version which generalizes over the underlying monad, see >sbvDeclare an unnamed h.CNB. For a version which generalizes over the underlying monad, see isbvDeclare a list of h values.CNB. For a version which generalizes over the underlying monad, see jsbvForm the symbolic conjunction of a given list of boolean conditions. Useful in expressing problems with constraints, like the following: X sat $ do [x, y, z] <- sIntegers ["x", "y", "z"] solve [x .> 5, y + z .< x] CNB. For a version which generalizes over the underlying monad, see ?sbv4Introduce a soft assertion, with an optional penaltyCNB. For a version which generalizes over the underlying monad, see BsbvMinimize a named metricCNB. For a version which generalizes over the underlying monad, see CsbvMaximize a named metricCNB. For a version which generalizes over the underlying monad, see D sbv<Convert a symbolic value to an SV, inside the Symbolic monadCNB. For a version which generalizes over the underlying monad, see  sbvHRun a symbolic computation, and return a extra value paired up with the CNB. For a version which generalizes over the underlying monad, see  sbvAdd a new optionCNB. For a version which generalizes over the underlying monad, see  sbvHandling constraintsCNB. For a version which generalizes over the underlying monad, see  sbvAdd an optimization goalCNB. For a version which generalizes over the underlying monad, see  sbvMark an interim result as an output. Useful when constructing Symbolic programs that return multiple values, or when the result is programmatically computed.CNB. For a version which generalizes over the underlying monad, see  n o p q rstuvwxyz{|}~   1(c) Brian Schroeder Levent ErkokBSD3erkokl@gmail.com experimentalNone % b | Q ~       89:;<OVWXYZ[\]^_`abcdefghijklmnopqrstuvw789:;=<>?@A%(+,-./02=789:;<>?@A4B5CD63FPLMNKJIHORabcdefghijklmnopqvwxyz{|}~     ! "#$%&'()*+,-./0123456789:;<=>?@ABCEDFGHIJKLMPNOQRSTUVWXYZ[\]^e_`abcdfghkijlmnotuvwxyz{|}~z{|}~nopqpz{|}~onml}~kjihz{|qopngedfOcba+,-./0(%tvxz|~uwy{}fghkijlmno^e_`abcd78CED]FGHIJKLMPNOQRSTUVWXYZ[\Rvwxy?@ABO#"!  +,-02/1.3HIJK6    >?@A789:9:;<=>;=<89:;<$%&'()*N MLPqVWXYZ[\]^_`abcdefghijklmnopqrstuvw2=789:;<>?@A4B5CD63F45(c) Levent ErkokBSD3erkokl@gmail.com experimentalNone 3X b | Q ~       89:;<ORVWXYZ[\]^_`abcdefghijklmnopqrstuvw789:;=<>?@A%(+./026DC5B4PLMNKJIHORVWXYZ[\]^_`abcdefghijklmnopqvwxyz{|}~ "#$%&'()*+,-./01236789:;<=>?@ABCEDFGHIJKLMPNOQRSTUVWXYZ[\]^e_`abcdfghkijlmnopwxyz{|}~nopqrstuvwxyz{|}~&pz{|}~onml}~kjihz{|qopngedfORcbap]\[ZYXWV_`^+./0(%fghkijlmno^e_`abcd78CED]FGHIJKLMPNOQRSTUVWXYZ[\wxyRvwxy?@ABO#" rstuvwxyz{|}~+,-02/1.3HIJK6>?@A789:9:;<=>;=<89:;<$%&'()*N MLPqVWXYZ[\]^_`abcdefghijklmnopqrstuvw24B5CD6(c) Levent ErkokBSD3erkokl@gmail.com experimentalNone$>@AX ]?0sbv,Are we in a good state, or in a stuck state?sbv&Execution finished in the given state.sbv(Execution got stuck, with the failing VC sbvA  ; is a nesting of locations. We store this in reverse order. sbvJTracking locations: Either a line (sequence) number, or an iteration countsbvConfiguration for WP proofs.sbvSMT Solver to usesbvShould we be chatty?sbv+The result of a weakest-precondition proof.sbvThe property holds. If  & is  H,, then total correctness, otherwise partial.sbvfFailed to establish correctness. Happens when the proof obligations lead to the SMT solver to return Unkd. This can happen, for instance, if you have non-linear constraints, causing the solver to give up.sbv?The property fails, failing to establish the conditions listed.sbv-A verification condition. Upon failure, each | carries enough state and diagnostic information to indicate what particular proof obligation failed for further debugging.sbv7The precondition doesn't hold. This can only happen in  .sbvThe postcondition doesn't holdsbvStability condition is violatedsbv&The named abort condition is reachablesbv3Invariant doesn't hold upon entry to the named loopsbv&Invariant isn't maintained by the bodysbv*Measure cannot be shown to be non-negativesbv:Measure cannot be shown to decrease through each iterationsbvDA statement in our imperative program, parameterized over the state.sbvSkip, do nothing.sbv5Abort execution. The name is for diagnostic purposes.sbv.Assignment: Transform the state by a function.sbv Conditional: "If condition thenBranch elseBranch.sbvA while loop: +While name invariant measure condition body. The string name7 is merely for diagnostic purposes. If the measure is  =, then only partial correctness of this loop will be proven.sbvA sequence of statements.sbv}A measure takes the state and returns a sequence of integers. The ordering will be done lexicographically over the elements.sbv6An invariant takes a state and evaluates to a boolean.sbvIA stability condition captures a primary input that does not change. Use " to create elements of this type.sbvA program over a state is simply a statement, together with a pre-condition capturing environmental assumptions and a post-condition that states its correctness. In the usual Hoare-triple notation, it captures: ' {precondition} program {postcondition}BWe also allow for a stability check, which is ensured at every assignment statement to deal with ghost variables. In general, this is useful for making sure what you consider as "primary inputs" remain unaffected. Of course, you can also put any arbitrary condition you want to check that you want performed for each  statement.Note that stability is quite a strong condition: It is intended to capture constants that never change during execution. So, if you have a program that changes an input temporarily but always restores it at the end, it would still fail the stability condition.The v field is reserved for any symbolic code you might want to run before the proof takes place, typically for calls to M. If not needed, simply pass  return ()O. For an interesting use case where we use setup to axiomatize the spec, see 3Documentation.SBV.Examples.WeakestPreconditions.Fib and 3Documentation.SBV.Examples.WeakestPreconditions.GCD.sbvAny set-up requiredsbvEnvironmental assumptionssbvProgramsbvCorrectness statementsbv&Each assignment must satisfy stabilitysbvAn W is a quick way of ensuring some condition holds. If it does, then it's equivalent to !. Otherwise, it is equivalent to .sbvStability: A call of the form  stable "f" f means the value of the field f does not change during any assignment. The string argument is for diagnostic purposes only. Note that we use strong-equality here, so if the program is manipulating floats, we don't get a false-positive on NaN and also not miss +0 and - @ changes. sbv*Are all the termination measures provided? sbv&Helper function to display VC's nicelysbvChecking WP based correctnesssbv:Check correctness using the default solver. Equivalent to  .sbvFDefault WP configuration: Uses the default solver, and is not verbose. sbvcTrace the execution of a program, starting from a sufficiently concrete state. (Sufficiently here means that all parts of the state that is used uninitialized must have concrete values, i.e., essentially the inputs. You can leave the "temporary" variables initialized by the program before use undefined or even symbolic.) The return value will have a \ state to indicate the program ended successfully, if that is the case. The result will be R if the program aborts without completing: This can happen either by executing an b statement, or some invariant gets violated, or if a metric fails to go down through a loop body. sbvShow instance for VC's sbv -& instance for proofs, for readability. sbvShow instance for  sbvProgramsbv*Starting state. It must be fully concrete.+ + (c) Levent ErkokBSD3erkokl@gmail.com experimentalNone>X v  sbv7A range is a pair of boundaries: Lower and upper boundssbvA boundary valuesbv UnboundedsbvExclusive of the pointsbvInclusive of the point sbvIs this a closed value?sbv{Given a single predicate over a single variable, find the contiguous ranges over which the predicate is satisfied. SBV will make one call to the optimizer, and then as many calls to the solver as there are disjoint ranges that the predicate is satisfied over. (Linear in the number of ranges.) Note that the number of ranges is large, this can take a long time! Some examples: #ranges (\(_ :: SInteger) -> sFalse)[]"ranges (\(_ :: SInteger) -> sTrue) [(-oo,oo)]Aranges (\(x :: SInteger) -> sAnd [x .<= 120, x .>= -12, x ./= 3])[[-12,3),(3,120]]Hranges (\(x :: SInteger) -> sAnd [x .<= 75, x .>= 5, x ./= 6, x ./= 67])[[5,6),(6,67),(67,75]]?ranges (\(x :: SInteger) -> sAnd [x .<= 75, x ./= 3, x ./= 67])[(-oo,3),(3,67),(67,75]]5ranges (\(x :: SReal) -> sAnd [x .> 3.2, x .< 12.7]) [(3.2,12.7)]5ranges (\(x :: SReal) -> sAnd [x .> 3.2, x .<= 12.7]) [(3.2,12.7]]4ranges (\(x :: SReal) -> sAnd [x .<= 12.7, x ./= 8])[(-oo,8.0),(8.0,12.7]]5ranges (\(x :: SReal) -> sAnd [x .>= 12.7, x ./= 15])[[12.7,15.0),(15.0,oo)]1ranges (\(x :: SInt8) -> sAnd [x .<= 7, x ./= 6])[[-128,6),(6,7]]ranges $ \x -> x .> (0::SReal) [(0.0,oo)]ranges $ \x -> x .< (0::SReal) [(-oo,0.0)]$ranges $ \(x :: SWord8) -> 2*x .== 4[[2,3),(129,130]]sbv5Compute ranges, using the given solver configuration.sbvShow instance for    (c) Levent ErkokBSD3erkokl@gmail.com experimentalNone> JsbvHResult of an inductive proof, with a counter-example in case of failure.$If a proof is found (indicated by a  result), then the invariant holds and the goal is established once the termination condition holds. If it fails, then it can fail either in an initiation step or in a consecution step:A  result in an $ step means that the invariant does notE hold for the initial state, and thus indicates a true failure.A  result in a  step will return a state s&. This state is known as a CTI (counterexample to inductiveness): It will lead to a violation of the invariant in one step. However, this does not mean the property is invalid: It could be the case that it is simply not inductive. In this case, human intervention---or a smarter algorithm like IC3 for certain domains---is needed to see if one can strengthen the invariant so an inductive proof can be found. How this strengthening can be done remains an art, but the science is improving with algorithms like IC3.A  result in a  step means that the invariant holds, but assuming the termination condition the goal still does not follow. That is, the partial correctness does not hold.sbv;A step in an inductive proof. If the tag is present (i.e., Just nmS), then the step belongs to the subproof that establishes the strengthening named nm.sbv0Induction engine, using the default solver. See 0Documentation.SBV.Examples.ProofTools.Strengthen and )Documentation.SBV.Examples.ProofTools.Sum for examples.sbv.Induction engine, configurable with the solversbvShow instance for , diagnostic purposes only. sbvShow instance for , diagnostic purposes only.sbv Verbose modesbv.Setup code, if necessary. (Typically used for M calls. Pass  return () if not needed.)sbvInitial conditionsbvTransition relationsbvStrengthenings, if any. The String is a simple tag.sbv0Invariant that ensures the goal upon terminationsbv/Termination condition and the goal to establishsbvQEither proven, or a concrete state value that, if reachable, fails the invariant.  (c) Levent ErkokBSD3erkokl@gmail.com experimentalNone SX H sbv1Case analysis on a symbolic list. (Not exported.)!sbvBounded fold from the right."sbv$Bounded monadic fold from the right.#sbvBounded fold from the left.$sbv#Bounded monadic fold from the left.%sbv Bounded sum.&sbvBounded product.'sbv Bounded map.(sbvBounded monadic map.)sbvBounded filter.*sbvBounded logical and+sbvBounded logical or,sbv Bounded any-sbv Bounded all.sbv,Bounded maximum. Undefined if list is empty./sbv,Bounded minimum. Undefined if list is empty.0sbvBounded zipWith1sbvBounded element check2sbvBounded reverse sbv$Bounded paramorphism (not exported). sbv4Insert an element into a sorted list (not exported).3sbvBounded insertion sort!"#$%&'()*+,-./0123!"#$'()01%&*+,-./23(c) Levent ErkokBSD3erkokl@gmail.com experimentalNone> 4sbv(Bounded fixed-point operation. The call  bfix bnd nm f unrolls the recursion in f at most bnd5 times, and uninterprets the function (with the name nm) after the bound is reached.This combinator is handy for dealing with recursive definitions that are not symbolically terminating and when the property we are interested in does not require an infinite unrolling, or when we are happy with a bounded proof. In particular, this operator can be used as a basis of software-bounded model checking algorithms built on top of SBV. The bound can be successively refined in a CEGAR like loop as necessary, by analyzing the counter-examples and rejecting them if they are false-negatives.dFor instance, we can define the factorial function using the bounded fixed-point operator like this: t bfac :: SInteger -> SInteger bfac = bfix 10 "fac" fact where fact f n = ite (n .== 0) 1 (n * f (n-1)) xThis definition unrolls the recursion in factorial at most 10 times before uninterpreting the result. We can now prove:?prove $ \n -> n .>= 1 .&& n .<= 9 .=> bfac n .== n * bfac (n-1)Q.E.D.[And we would get a bogus counter-example if the proof of our property needs a larger bound:-prove $ \n -> n .== 10 .=> bfac n .== 3628800Falsifiable. Counter-example: s0 = 10 :: Integer fac :: Integer -> Integer fac _ = 2CThe counter-example is telling us how it instantiated the function fac< when the recursion bottomed out: It simply made it return 2S for all arguments at that point, which provides the (unintended) counter-example.%By design, if a function defined via 4* is given a concrete argument, it will unroll the recursion as much as necessary to complete the call (which can of course diverge). The bound only applies if the given argument is symbolic. This fact can be used to observe concrete values to see where the bounded-model-checking approach fails:Tprove $ \n -> n .== 10 .=> observe "bfac_n" (bfac n) .== observe "bfac_10" (bfac 10)Falsifiable. Counter-example: bfac_10 = 3628800 :: Integer bfac_n = 7257600 :: Integer s0 = 10 :: Integer fac :: Integer -> Integer fac _ = 2YHere, we see further evidence that the SMT solver must have decided to assign the value 2o in the final call just as it was reaching the base case, and thus got the final result incorrect. (Note that 7257600 = 2 * 3628800<.) A wrapper algorithm can then assert the actual value of bfac 10? here as an extra constraint and can search for "deeper bugs."44(c) Levent ErkokBSD3erkokl@gmail.com experimentalNone> ~5sbv6Bounded model checking, using the default solver. See )Documentation.SBV.Examples.ProofTools.BMC for an example use case.yNote that the BMC engine does *not* guarantee that the solution is unique. However, if it does find a solution at depth i7, it is guaranteed that there are no shorter solutions.6sbv4Bounded model checking, configurable with the solver5sbvOptional boundsbvVerbose: prints iteration countsbv.Setup code, if necessary. (Typically used for M calls. Pass  return () if not needed.)sbvInitial conditionsbvTransition relationsbvNGoal to cover, i.e., we find a set of transitions that satisfy this predicate.sbvTEither a result, or a satisfying path of given length and intermediate observations.5656(c) Brian HuffmanBSD3erkokl@gmail.com experimentalNone37sbvDynamic variant of quick-check8sbvCreate SMT-Lib benchmarks. The first argument is the basename of the file, we will automatically add ".smt2" per SMT-Lib2 convention. The  & argument controls whether this is a SAT instance, i.e., translate the query directly, or a PROVE instance, i.e., translate the negated query.9sbv/Proves the predicate using the given SMT-solver:sbv7Find a satisfying assignment using the given SMT-solver;sbv'Check safety using the given SMT-solver<sbv:Find all satisfying assignments using the given SMT-solver=sbv~Prove a property with multiple solvers, running them in separate threads. The results will be returned in the order produced.>sbvProve a property with multiple solvers, running them in separate threads. Only the result of the first one to finish will be returned, remaining threads will be killed.?sbvProve a property with query mode using multiple threads. Each query computation will spawn a thread and a unique instance of your solver to run asynchronously. The  Y is duplicated for each thread. This function will block until all child threads return.@sbvProve a property with query mode using multiple threads. Each query computation will spawn a thread and a unique instance of your solver to run asynchronously. The  z is duplicated for each thread. This function will return the first query computation that completes, killing the others.AsbvFind a satisfying assignment to a property with multiple solvers, running them in separate threads. The results will be returned in the order produced.BsbvFind a satisfying assignment to a property with multiple solvers, running them in separate threads. Only the result of the first one to finish will be returned, remaining threads will be killed.CsbvUFind a satisfying assignment to a property with multiple threads in query mode. The   represents what is known to all child query threads. Each query thread will spawn a unique instance of the solver. Only the first one to finish will be returned and the other threads will be killed.DsbvUFind a satisfying assignment to a property with multiple threads in query mode. The   represents what is known to all child query threads. Each query thread will spawn a unique instance of the solver. This function will block until all child threads have completed.EsbvExtract a model, the result is a tuple where the first argument (if True) indicates whether the model was "probable". (i.e., if the solver returned unknown.)FsbvExtract a model dictionary. Extract a dictionary mapping the variables to their respective values as returned by the SMT solver. Also see kl.VWXYZ[\]^_`abcdefghijklmnopqrstuvwJKL      !"#$$%&'()*()*+,KLMNOPQRUVWXYZ[\gi789:;<=>?@ABCDEFVWXYZ[\]^_`abcdefghijklmnopqrstuvw !"#JKL$     9:<;=>AB?@CD7EF$%&'()*,KPNOWXYZ[\RUVQLM()*+gi8(c) Levent ErkokBSD3erkokl@gmail.com experimentalNone>aGsbv Formalizes Chttp://graphics.stanford.edu/~seander/bithacks.html#IntegerMinOrMaxHsbv Formalizes Chttp://graphics.stanford.edu/~seander/bithacks.html#IntegerMinOrMaxIsbv Formalizes Ghttp://graphics.stanford.edu/~seander/bithacks.html#DetectOppositeSignsJsbv Formalizes ]http://graphics.stanford.edu/~seander/bithacks.html#ConditionalSetOrClearBitsWithoutBranchingKsbv Formalizes Ghttp://graphics.stanford.edu/~seander/bithacks.html#DetermineIfPowerOf2LsbvCollection of queriesGHIJKLGHIJKL(c) Levent ErkokBSD3erkokl@gmail.com experimentalNone,,MsbvModel the mid-point computation of the binary search, which is broken due to arithmetic overflow. Note how we use the overflow checking variants of the arithmetic operators. We have:!checkArithOverflow midPointBrokenkDocumentation/SBV/Examples/BitPrecise/BrokenSearch.hs:35:28:+!: SInt32 addition overflows: Violated. Model: low = 2147475457 :: Int32 high = 2147483645 :: Int32Indeed:*(2147475457 + 2147483645) `div` (2::Int32)-4097%giving us a negative mid-point value!Nsbv~The correct version of how to compute the mid-point. As expected, this version doesn't have any underflow or overflow issues: checkArithOverflow midPointFixedNo violations detected.1As expected, the value is computed correctly too:"checkCorrectMidValue midPointFixedQ.E.D.OsbvAShow that the variant suggested by the blog post is good as well: 4mid = ((unsigned int)low + (unsigned int)high) >> 1;SIn this case the overflow is eliminated by doing the computation at a wider range:&checkArithOverflow midPointAlternativeNo violations detected.)And the value computed is indeed correct:(checkCorrectMidValue midPointAlternativeQ.E.D.Psbv=A helper predicate to check safety under the conditions that low is at least 0 and high is at least low.QsbvAnother helper to show that the result is actually the correct value, if it was done over 64-bit integers, which is sufficiently large enough.MNOPQMNOPQ(c) Levent ErkokBSD3erkokl@gmail.com experimentalNone.79cM(Rsbv4Helper synonym for capturing relevant bits of MostekSsbvAn instruction is modeled as a TM transformer. We model mostek programs in direct continuation passing style.TsbvBPrograms are essentially state transformers (on the machine state)Usbv0Given a machine state, compute a value out of itVsbvAbstraction of the machine: The CPU consists of memory, registers, and flags. Unlike traditional hardware, we assume the program is stored in some other memory area that we need not model. (No self modifying programs!)V+ is equipped with an automatically derived C! instance because each field is C.[sbv2Memory is simply an array from locations to values\sbv?We have three memory locations, sufficient to model our problem]sbv multiplicand^sbv multiplier_sbv'low byte of the result gets stored here`sbv Flag bankasbv Register bankbsbv-Convenient synonym for symbolic machine bits.csbvMostek was an 8-bit machine.dsbvThe carry flag (e) and the zero flag (f)gsbvXWe model only two registers of Mostek that is used in the above algorithm, can add more.jsbv!Get the value of a given registerksbv!Set the value of a given registerlsbvGet the value of a flagmsbvSet the value of a flagnsbv Read memoryosbvWrite to memorypsbv-Checking overflow. In Legato's multipler the ADC instruction needs to see if the expression x + y + c overflowed, as checked by this function. Note that we verify the correctness of this check separately below in q.qsbvCorrectness theorem for our p implementation.We have:checkOverflowCorrectQ.E.D.rsbvLDX: Set register X to value vssbvLDA: Set register A to value vtsbvCLC: Clear the carry flagusbv9ROR, memory version: Rotate the value at memory location aP to the right by 1 bit, using the carry flag as a transfer position. That is, the final bit of the memory location becomes the new carry and the carry moves over to the first bit. This very instruction is one of the reasons why Legato's multiplier is quite hard to understand and is typically presented as a verification challenge.vsbvROR, register version: Same as u, except through register r.wsbvBCC: branch to label l if the carry flag is sFalsexsbv%ADC: Increment the value of register A. by the value of memory contents at location a7, using the carry-bit as the carry-in for the addition.ysbv%DEX: Decrement the value of register Xzsbv&BNE: Branch if the zero-flag is sFalse{sbvThe {U combinator "stops" our program, providing the final continuation that does nothing.|sbvMultiplies the contents of F1 and F2), storing the low byte of the result in LO% and the high byte of it in register Am. The implementation is a direct transliteration of Legato's algorithm given at the top, using our notation.}sbvGiven values for F1 and F2,  runLegato" takes an arbitrary machine state m; and returns the high and low bytes of the multiplication.~sbv{Create an instance of the Mostek machine, initialized by the memory and the relevant values of the registers and the flagssbvNThe correctness theorem. For all possible memory configurations, the factors (x and y below), the location of the low-byte result and the initial-values of registers and the flags, this function will return True only if running Legato's algorithm does indeed compute the product of x and y correctly.sbvThe correctness theorem.sbvFGenerate a C program that implements Legato's algorithm automatically.0RSTUVWYXZ[\_^]`abcdfegihjklmnopqrstuvwxyz{|}~0gihdfecba`\_^][VWYXZUTjklmnopqSrstuvwxyz{|}R~(c) Levent ErkokBSD3erkokl@gmail.com experimentalNoneysbvIElement type of lists we'd like to sort. For simplicity, we'll just use o) here, but we can pick any symbolic type.sbv5Merging two given sorted lists, preserving the order.sbvSimple merge-sort implementation. We simply divide the input list in two two halves so long as it has at least two elements, sort each half on its own, and then merge.sbv1Check whether a given sequence is non-decreasing.sbvCheck whether two given sequences are permutations. We simply check that each sequence is a subset of the other, when considered as a set. The check is slightly complicated for the need to account for possibly duplicated elements.sbv9Asserting correctness of merge-sort for a list of the given size. Note that we can only check correctness for fixed-size lists. Also, the proof will get more and more complicated for the backend SMT solver as the list size increases. A value around 5 or 6 should be fairly easy to prove. For instance, we have: correctness 5Q.E.D.sbv3Generate C code for merge-sorting an array of size n. Again, we're restricted to fixed size inputs. While the output is not how one would code merge sort in C by hand, it's a faithful rendering of all the operations merge-sort would do as described by its Haskell counterpart.(c) Levent ErkokBSD3erkokl@gmail.com experimentalNonesbv7Find the multiplier and the mask as described. We have: maskAndMultSatisfiable. Model:% mask = 0x8080808080808080 :: Word64% mult = 0x0002040810204081 :: Word64wThat is, any 64 bit value masked by the first and multipled by the second value above will have its bits at positions [7,15,23,31,39,47,55,63] moved to positions [56,57,58,59,60,61,62,63] respectively.NB. Depending on your z3 version, you might also get the following multiplier as the result: 0x8202040810204081. That value works just fine as well!eNote that we have to use a custom SAT command for this problem, as otherwise it takes too long. See  *https://github.com/Z3Prover/z3/issues/2587 for details.(c) Levent ErkokBSD3erkokl@gmail.com experimentalNoneSX> sbvIA poor man's representation of powerlists and basic operations on them:  (http://dl.acm.org/citation.cfm?id=1973564 We merely represent power-lists by ordinary lists.sbv The tie operator, concatenation.sbvaThe zip operator, zips the power-lists of the same size, returns a powerlist of double the size.sbvInverse of zipping.sbvReference prefix sum (ps) is simply Haskell's scanl1 function.sbvThe Ladner-Fischer (lf$) implementation of prefix-sum. See  Jhttp://www.cs.utexas.edu/~plaxton/c/337/05f/slides/ParallelRecursion-4.pdf or pg. 16 of (http://dl.acm.org/citation.cfm?id=197356sbvgCorrectness theorem, for a powerlist of given size, an associative operator, and its left-unit element.sbvNProves Ladner-Fischer is equivalent to reference specification for addition. 0; is the left-unit element, and we use a power-list of size 8 . We have:thm1Q.E.D.sbvPProves Ladner-Fischer is equivalent to reference specification for the function max. 0; is the left-unit element, and we use a power-list of size 16 . We have:thm2Q.E.D.   (c) Levent ErkokBSD3erkokl@gmail.com experimentalNone*sbv,Simple function that returns add/sum of argssbvKGenerate C code for addSub. Here's the output showing the generated C code: genAddSubi%== BEGIN: "Makefile" ================C# Makefile for addSub. Automatically generated by SBV. Do not edit!=# include any user-defined .mk file in the current directory. -include *.mkCC?=gcc0CCFLAGS?=-Wall -O3 -DNDEBUG -fomit-frame-pointerall: addSub_driveraddSub.o: addSub.c addSub.h ${CC} ${CCFLAGS} -c $< -o $@ addSub_driver.o: addSub_driver.c ${CC} ${CCFLAGS} -c $< -o $@'addSub_driver: addSub.o addSub_driver.o ${CC} ${CCFLAGS} $^ -o $@clean: rm -f *.overyclean: clean rm -f addSub_driver%== END: "Makefile" ==================%== BEGIN: "addSub.h" ================J/* Header file for addSub. Automatically generated by SBV. Do not edit! */##ifndef __addSub__HEADER_INCLUDED__##define __addSub__HEADER_INCLUDED__#include <stdio.h>#include <stdlib.h>#include <inttypes.h>#include <stdint.h>#include <stdbool.h>#include <string.h>#include <math.h>/* The boolean type */typedef bool SBool;/* The float type */typedef float SFloat;/* The double type */typedef double SDouble;/* Unsigned bit-vectors */typedef uint8_t SWord8;typedef uint16_t SWord16;typedef uint32_t SWord32;typedef uint64_t SWord64;/* Signed bit-vectors */typedef int8_t SInt8;typedef int16_t SInt16;typedef int32_t SInt32;typedef int64_t SInt64;/* Entry point prototype: */8void addSub(const SWord8 x, const SWord8 y, SWord8 *sum, SWord8 *dif);(#endif /* __addSub__HEADER_INCLUDED__ */%== END: "addSub.h" ==================,== BEGIN: "addSub_driver.c" ================(/* Example driver program for addSub. */:/* Automatically generated by SBV. Edit as you see fit! */#include <stdio.h>#include "addSub.h"int main(void){ SWord8 sum; SWord8 dif; addSub(132, 241, &sum, &dif);. printf("addSub(132, 241, &sum, &dif) ->\n");$ printf(" sum = %"PRIu8"\n", sum);$ printf(" dif = %"PRIu8"\n", dif); return 0;},== END: "addSub_driver.c" ==================%== BEGIN: "addSub.c" ================D/* File: "addSub.c". Automatically generated by SBV. Do not edit! */#include "addSub.h"8void addSub(const SWord8 x, const SWord8 y, SWord8 *sum, SWord8 *dif){ const SWord8 s0 = x; const SWord8 s1 = y; const SWord8 s2 = s0 + s1; const SWord8 s3 = s0 - s1; *sum = s2; *dif = s3;}%== END: "addSub.c" ==================!(c) Levent ErkokBSD3erkokl@gmail.com experimentalNone=sbvThe USB CRC polynomial:  x^5 + x^2 + 1. Although this polynomial needs just 6 bits to represent (5 if higher order bit is implicitly assumed to be set), we'll simply use a 16 bit number for its representation to keep things simple for code generation purposes.sbv Given an 11 bit message, compute the CRC of it using the USB polynomial, which is 5 bits, and then append it to the msg to get a 16-bit word. Again, the incoming 11-bits is represented as a 16-bit word, with 5 highest bits essentially ignored for input purposes.sbv(Alternate method for computing the CRC, mathematically. We shift the number to the left by 5, and then compute the remainder from the polynomial division by the USB polynomial. The result is then appended to the end of the message.sbvProve that the custom ^ function is equivalent to the mathematical definition of CRC's for 11 bit messages. We have:crcGoodQ.E.D.sbvOGenerate a C function to compute the USB CRC, using the internal CRC function.sbvGenerate a C function to compute the USB CRC, using the mathematical definition of the CRCs. While this version generates functionally eqivalent C code, it's less efficient; it has about 30% more code. So, the above version is preferable for code generation purposes."*(c) Lee Pike Levent ErkokBSD3erkokl@gmail.com experimentalNone&^sbvcThis is a naive implementation of fibonacci, and will work fine (albeit slow) for concrete inputs:map fib0 [0..6]\[0 :: SWord64,1 :: SWord64,1 :: SWord64,2 :: SWord64,3 :: SWord64,5 :: SWord64,8 :: SWord64]However, it is not suitable for doing proofs or generating code, as it is not symbolically terminating when it is called with a symbolic value n. When we recursively call fib0 on n-1 (or n-2), the test against 0 will always explore both branches since the result will be symbolic, hence will not terminate. (An integrated theorem prover can establish termination after a certain number of unrollings, but this would be quite expensive to implement, and would be impractical.)sbvcThe recursion-depth limited version of fibonacci. Limiting the maximum number to be 20, we can say:map (fib1 20) [0..6]\[0 :: SWord64,1 :: SWord64,1 :: SWord64,2 :: SWord64,3 :: SWord64,5 :: SWord64,8 :: SWord64]KThe function will work correctly, so long as the index we query is at most top*, and otherwise will return the value at top}. Note that we also use accumulating parameters here for efficiency, although this is orthogonal to the termination concern.A note on modular arithmetic: The 64-bit word we use to represent the values will of course eventually overflow, beware! Fibonacci is a fast growing function..sbvWe can generate code for  using the T action. Note that the generated code will grow larger as we pick larger values of topI, but only linearly, thanks to the accumulating parameter trick used by D. The following is an excerpt from the code generated for the call  genFib1 10;, where the code will work correctly for indexes up to 10: SWord64 fib1(const SWord64 x) { const SWord64 s0 = x; const SBool s2 = s0 == 0x0000000000000000ULL; const SBool s4 = s0 == 0x0000000000000001ULL; const SBool s6 = s0 == 0x0000000000000002ULL; const SBool s8 = s0 == 0x0000000000000003ULL; const SBool s10 = s0 == 0x0000000000000004ULL; const SBool s12 = s0 == 0x0000000000000005ULL; const SBool s14 = s0 == 0x0000000000000006ULL; const SBool s17 = s0 == 0x0000000000000007ULL; const SBool s19 = s0 == 0x0000000000000008ULL; const SBool s22 = s0 == 0x0000000000000009ULL; const SWord64 s25 = s22 ? 0x0000000000000022ULL : 0x0000000000000037ULL; const SWord64 s26 = s19 ? 0x0000000000000015ULL : s25; const SWord64 s27 = s17 ? 0x000000000000000dULL : s26; const SWord64 s28 = s14 ? 0x0000000000000008ULL : s27; const SWord64 s29 = s12 ? 0x0000000000000005ULL : s28; const SWord64 s30 = s10 ? 0x0000000000000003ULL : s29; const SWord64 s31 = s8 ? 0x0000000000000002ULL : s30; const SWord64 s32 = s6 ? 0x0000000000000001ULL : s31; const SWord64 s33 = s4 ? 0x0000000000000001ULL : s32; const SWord64 s34 = s2 ? 0x0000000000000000ULL : s33; return s34; }sbv,Compute the fibonacci numbers statically at code-generation0 time and put them in a table, accessed by the E call. sbv Once we have s, we can generate the C code straightforwardly. Below is an excerpt from the code that SBV generates for the call  genFib2 64. Note that this code is a constant-time look-up table implementation of fibonacci, with no run-time overhead. The index can be made arbitrarily large, naturally. (Note that this function returns 0> if the index is larger than 64, as specified by the call to E with default 0.) SSWord64 fibLookup(const SWord64 x) { const SWord64 s0 = x; static const SWord64 table0[] = { 0x0000000000000000ULL, 0x0000000000000001ULL, 0x0000000000000001ULL, 0x0000000000000002ULL, 0x0000000000000003ULL, 0x0000000000000005ULL, 0x0000000000000008ULL, 0x000000000000000dULL, 0x0000000000000015ULL, 0x0000000000000022ULL, 0x0000000000000037ULL, 0x0000000000000059ULL, 0x0000000000000090ULL, 0x00000000000000e9ULL, 0x0000000000000179ULL, 0x0000000000000262ULL, 0x00000000000003dbULL, 0x000000000000063dULL, 0x0000000000000a18ULL, 0x0000000000001055ULL, 0x0000000000001a6dULL, 0x0000000000002ac2ULL, 0x000000000000452fULL, 0x0000000000006ff1ULL, 0x000000000000b520ULL, 0x0000000000012511ULL, 0x000000000001da31ULL, 0x000000000002ff42ULL, 0x000000000004d973ULL, 0x000000000007d8b5ULL, 0x00000000000cb228ULL, 0x0000000000148addULL, 0x0000000000213d05ULL, 0x000000000035c7e2ULL, 0x00000000005704e7ULL, 0x00000000008cccc9ULL, 0x0000000000e3d1b0ULL, 0x0000000001709e79ULL, 0x0000000002547029ULL, 0x0000000003c50ea2ULL, 0x0000000006197ecbULL, 0x0000000009de8d6dULL, 0x000000000ff80c38ULL, 0x0000000019d699a5ULL, 0x0000000029cea5ddULL, 0x0000000043a53f82ULL, 0x000000006d73e55fULL, 0x00000000b11924e1ULL, 0x000000011e8d0a40ULL, 0x00000001cfa62f21ULL, 0x00000002ee333961ULL, 0x00000004bdd96882ULL, 0x00000007ac0ca1e3ULL, 0x0000000c69e60a65ULL, 0x0000001415f2ac48ULL, 0x000000207fd8b6adULL, 0x0000003495cb62f5ULL, 0x0000005515a419a2ULL, 0x00000089ab6f7c97ULL, 0x000000dec1139639ULL, 0x000001686c8312d0ULL, 0x000002472d96a909ULL, 0x000003af9a19bbd9ULL, 0x000005f6c7b064e2ULL, 0x000009a661ca20bbULL }; const SWord64 s65 = s0 >= 65 ? 0x0000000000000000ULL : table0[s0]; return s65; }#(c) Levent ErkokBSD3erkokl@gmail.com experimentalNoneXsbv>The symbolic GCD algorithm, over two 8-bit numbers. We define sgcd a 0 to be a for all a, which implies  sgcd 0 0 = 0. Note that this is essentially Euclid's algorithm, except with a recursion depth counter. We need the depth counter since the algorithm is not symbolically terminatingE, as we don't have a means of determining that the second argument (b) will eventually reach 0 in a symbolic context. Hence we stop after 12 iterations. Why 12? We've empirically determined that this algorithm will recurse at most 12 times for arbitrary 8-bit numbers. Of course, this is a claim that we shall prove below.sbvWe have:prove sgcdIsCorrectQ.E.D.sbv`This call will generate the required C files. The following is the function body generated for ,. (We are not showing the generated header, Makefile, and the driver programs for brevity.) Note that the generated function is a constant time algorithm for GCD. It is not necessarily fastest, but it will take precisely the same amount of time for all values of x and y. (/* File: "sgcd.c". Automatically generated by SBV. Do not edit! */ #include <stdio.h> #include <stdlib.h> #include <inttypes.h> #include <stdint.h> #include <stdbool.h> #include "sgcd.h" SWord8 sgcd(const SWord8 x, const SWord8 y) { const SWord8 s0 = x; const SWord8 s1 = y; const SBool s3 = s1 == 0; const SWord8 s4 = (s1 == 0) ? s0 : (s0 % s1); const SWord8 s5 = s3 ? s0 : s4; const SBool s6 = 0 == s5; const SWord8 s7 = (s5 == 0) ? s1 : (s1 % s5); const SWord8 s8 = s6 ? s1 : s7; const SBool s9 = 0 == s8; const SWord8 s10 = (s8 == 0) ? s5 : (s5 % s8); const SWord8 s11 = s9 ? s5 : s10; const SBool s12 = 0 == s11; const SWord8 s13 = (s11 == 0) ? s8 : (s8 % s11); const SWord8 s14 = s12 ? s8 : s13; const SBool s15 = 0 == s14; const SWord8 s16 = (s14 == 0) ? s11 : (s11 % s14); const SWord8 s17 = s15 ? s11 : s16; const SBool s18 = 0 == s17; const SWord8 s19 = (s17 == 0) ? s14 : (s14 % s17); const SWord8 s20 = s18 ? s14 : s19; const SBool s21 = 0 == s20; const SWord8 s22 = (s20 == 0) ? s17 : (s17 % s20); const SWord8 s23 = s21 ? s17 : s22; const SBool s24 = 0 == s23; const SWord8 s25 = (s23 == 0) ? s20 : (s20 % s23); const SWord8 s26 = s24 ? s20 : s25; const SBool s27 = 0 == s26; const SWord8 s28 = (s26 == 0) ? s23 : (s23 % s26); const SWord8 s29 = s27 ? s23 : s28; const SBool s30 = 0 == s29; const SWord8 s31 = (s29 == 0) ? s26 : (s26 % s29); const SWord8 s32 = s30 ? s26 : s31; const SBool s33 = 0 == s32; const SWord8 s34 = (s32 == 0) ? s29 : (s29 % s32); const SWord8 s35 = s33 ? s29 : s34; const SBool s36 = 0 == s35; const SWord8 s37 = s36 ? s32 : s35; const SWord8 s38 = s33 ? s29 : s37; const SWord8 s39 = s30 ? s26 : s38; const SWord8 s40 = s27 ? s23 : s39; const SWord8 s41 = s24 ? s20 : s40; const SWord8 s42 = s21 ? s17 : s41; const SWord8 s43 = s18 ? s14 : s42; const SWord8 s44 = s15 ? s11 : s43; const SWord8 s45 = s12 ? s8 : s44; const SWord8 s46 = s9 ? s5 : s45; const SWord8 s47 = s6 ? s1 : s46; const SWord8 s48 = s3 ? s0 : s47; return s48; }$(c) Levent ErkokBSD3erkokl@gmail.com experimentalNonesbv(Given a 64-bit quantity, the simplest (and obvious) way to count the number of bits that are set in it is to simply walk through all the bits and add 1 to a running count. This is slow, as it requires 64 iterations, but is simple and easy to convince yourself that it is correct. For instance:popCountSlow 0x0123456789ABCDEF 32 :: SWord8sbvFaster version. This is essentially the same algorithm, except we go 8 bits at a time instead of one by one, by using a precomputed table of population-count values for each byte. This algorithm loops= only 8 times, and hence is at least 8 times more efficient.sbvLook-up table, containing population counts for all possible 8-bit value, from 0 to 255. Note that we do not "hard-code" the values, but merely use the slow version to compute them.sbvStates the correctness of faster population-count algorithm, with respect to the reference slow version. Turns out Z3's default solver is rather slow for this one, but there's a magic incantation to make it go fast. See  )http://github.com/Z3Prover/z3/issues/1150 for details.xlet cmd = "(check-sat-using (then (using-params ackermannize_bv :div0_ackermann_limit 1000000) simplify bit-blast sat))"0proveWith z3{satCmd = cmd} fastPopCountIsCorrectQ.E.D.sbvNot only we can prove that faster version is correct, but we can also automatically generate C code to compute population-counts for us. This action will generate all the C files that you will need, including a driver program for test purposes.'Below is the generated header file for :genPopCountInC%== BEGIN: "Makefile" ================E# Makefile for popCount. Automatically generated by SBV. Do not edit!=# include any user-defined .mk file in the current directory. -include *.mkCC?=gcc0CCFLAGS?=-Wall -O3 -DNDEBUG -fomit-frame-pointerall: popCount_driver!popCount.o: popCount.c popCount.h ${CC} ${CCFLAGS} -c $< -o $@$popCount_driver.o: popCount_driver.c ${CC} ${CCFLAGS} -c $< -o $@-popCount_driver: popCount.o popCount_driver.o ${CC} ${CCFLAGS} $^ -o $@clean: rm -f *.overyclean: clean rm -f popCount_driver%== END: "Makefile" =================='== BEGIN: "popCount.h" ================L/* Header file for popCount. Automatically generated by SBV. Do not edit! */%#ifndef __popCount__HEADER_INCLUDED__%#define __popCount__HEADER_INCLUDED__#include <stdio.h>#include <stdlib.h>#include <inttypes.h>#include <stdint.h>#include <stdbool.h>#include <string.h>#include <math.h>/* The boolean type */typedef bool SBool;/* The float type */typedef float SFloat;/* The double type */typedef double SDouble;/* Unsigned bit-vectors */typedef uint8_t SWord8;typedef uint16_t SWord16;typedef uint32_t SWord32;typedef uint64_t SWord64;/* Signed bit-vectors */typedef int8_t SInt8;typedef int16_t SInt16;typedef int32_t SInt32;typedef int64_t SInt64;/* Entry point prototype: */!SWord8 popCount(const SWord64 x);*#endif /* __popCount__HEADER_INCLUDED__ */'== END: "popCount.h" ==================.== BEGIN: "popCount_driver.c" ================*/* Example driver program for popCount. */:/* Automatically generated by SBV. Edit as you see fit! */#include <stdio.h>#include "popCount.h"int main(void){: const SWord8 __result = popCount(0x1b02e143e4f0e0e5ULL);C printf("popCount(0x1b02e143e4f0e0e5ULL) = %"PRIu8"\n", __result); return 0;}.== END: "popCount_driver.c" =================='== BEGIN: "popCount.c" ================F/* File: "popCount.c". Automatically generated by SBV. Do not edit! */#include "popCount.h" SWord8 popCount(const SWord64 x){ const SWord64 s0 = x;" static const SWord8 table0[] = {G 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, 1, 2, 2, 3, 2, 3,G 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4,G 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 1, 2,G 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5,G 3, 4, 4, 5, 4, 5, 5, 6, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5,G 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 1, 2, 2, 3,G 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4,G 4, 5, 4, 5, 5, 6, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,G 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 2, 3, 3, 4, 3, 4,G 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6,G 5, 6, 6, 7, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 4, 5,. 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8 };1 const SWord64 s11 = s0 & 0x00000000000000ffULL;" const SWord8 s12 = table0[s11]; const SWord64 s14 = s0 >> 8;2 const SWord64 s15 = 0x00000000000000ffULL & s14;" const SWord8 s16 = table0[s15]; const SWord8 s17 = s12 + s16; const SWord64 s18 = s14 >> 8;2 const SWord64 s19 = 0x00000000000000ffULL & s18;" const SWord8 s20 = table0[s19]; const SWord8 s21 = s17 + s20; const SWord64 s22 = s18 >> 8;2 const SWord64 s23 = 0x00000000000000ffULL & s22;" const SWord8 s24 = table0[s23]; const SWord8 s25 = s21 + s24; const SWord64 s26 = s22 >> 8;2 const SWord64 s27 = 0x00000000000000ffULL & s26;" const SWord8 s28 = table0[s27]; const SWord8 s29 = s25 + s28; const SWord64 s30 = s26 >> 8;2 const SWord64 s31 = 0x00000000000000ffULL & s30;" const SWord8 s32 = table0[s31]; const SWord8 s33 = s29 + s32; const SWord64 s34 = s30 >> 8;2 const SWord64 s35 = 0x00000000000000ffULL & s34;" const SWord8 s36 = table0[s35]; const SWord8 s37 = s33 + s36; const SWord64 s38 = s34 >> 8;2 const SWord64 s39 = 0x00000000000000ffULL & s38;" const SWord8 s40 = table0[s39]; const SWord8 s41 = s37 + s40; return s41;}'== END: "popCount.c" ==================%(c) Levent ErkokBSD3erkokl@gmail.com experimentalNone'sbvVA definition of shiftLeft that can deal with variable length shifts. (Note that the ` ` method from the   class requires an  b shift amount.) Unfortunately, this'll generate rather clumsy C code due to the use of tables etc., so we uninterpret it for code generation purposes using the A function.sbvTest function that uses shiftLeft defined above. When used as a normal Haskell function or in verification the definition is fully used, i.e., no uninterpretation happens. To wit, we have:tstShiftLeft 3 4 5224 :: SWord32,prove $ \x y -> tstShiftLeft x y 0 .== x + yQ.E.D.sbvGenerate C code for "tstShiftLeft". In this case, SBV will *use* the user given definition verbatim, instead of generating code for it. (Also see the functions U, V, and R.)&(c) Levent ErkokBSD3erkokl@gmail.com experimentalNone.Jk7-sbv,The key schedule. AES executes in rounds, and it treats first and last round keys slightly differently than the middle ones. We reflect that choice by being explicit about it in our type. The length of the middle list of keys depends on the key-size, which in turn determines the number of rounds.sbvWThe key, which can be 128, 192, or 256 bits. Represented as a sequence of 32-bit words.sbvAES state. The state consists of four 32-bit words, each of which is in turn treated as four GF28's, i.e., 4 bytes. The T-Box implementation keeps the four-bytes together for efficient representation.sbvAn element of the Galois Field 2^8, which are essentially polynomials with maximum degree 7. They are conveniently represented as values between 0 and 255.sbvlMultiplication in GF(2^8). This is simple polynomial multipliation, followed by the irreducible polynomial x^8+x^4+x^3+x^1+1. We simply use the 0 function exported by SBV to do the operation. sbvExponentiation by a constant in GF(2^8). The implementation uses the usual square-and-multiply trick to speed up the computation.sbvyComputing inverses in GF(2^8). By the mathematical properties of GF(2^8) and the particular irreducible polynomial used x^8+x^5+x^3+x^1+1{, it turns out that raising to the 254 power gives us the multiplicative inverse. Of course, we can prove this using SBV::prove $ \x -> x ./= 0 .=> x `gf28Mult` gf28Inverse x .== 1Q.E.D.Note that we exclude 0? in our theorem, as it does not have a multiplicative inverse.sbv4Rotating a state row by a fixed amount to the right.sbvODefinition of round-constants, as specified in Section 5.2 of the AES standard.sbvThe  InvMixColumns transformation, as described in Section 5.3.3 of the standard. Note that this transformation is only used explicitly during key-expansion in the T-Box implementation of AES.sbvKey expansion. Starting with the given key, returns an infinite sequence of words, as described by the AES standard, Section 5.2, Figure 11.sbv7The values of the AES S-box table. Note that we describe the S-box programmatically using the mathematical construction given in Section 5.1.1 of the standard. However, the code-generation will turn this into a mere look-up table, as it is just a constant table, all computation being done at "compile-time".sbvwThe sbox transformation. We simply select from the sbox table. Note that we are obliged to give a default value (here 0A) to be used if the index is out-of-bounds as required by SBV's EW function. However, that will never happen since the table has all 256 elements in it.sbvOThe values of the inverse S-box table. Again, the construction is programmatic.sbv!The inverse s-box transformation.sbvProve that the  and  are inverses. We have:prove sboxInverseCorrectQ.E.D.sbvAdding the round-key to the current state. We simply exploit the fact that addition is just xor in implementing this transformation.sbv.T-box table generation function for encryptionsbv&First look-up table used in encryptionsbv'Second look-up table used in encryptionsbv&Third look-up table used in encryptionsbv'Fourth look-up table used in encryptionsbv.T-box table generating function for decryptionsbv&First look-up table used in decryptionsbv'Second look-up table used in decryptionsbv&Third look-up table used in decryptionsbv'Fourth look-up table used in decryptionsbvGeneric round function. Given the function to perform one round, a key-schedule, and a starting state, it performs the AES rounds.sbvOne encryption round. The first argument indicates whether this is the final round or not, in which case the construction is slightly different.sbv|One decryption round. Similar to the encryption round, the first argument indicates whether this is the final round or not.sbvKey schedule. Given a 128, 192, or 256 bit key, expand it to get key-schedules for encryption and decryption. The key is given as a sequence of 32-bit words. (4 elements for 128-bits, 6 for 192, and 8 for 256.)sbvBlock encryption. The first argument is the plain-text, which must have precisely 4 elements, for a total of 128-bits of input. The second argument is the key-schedule to be used, obtained by a call to H. The output will always have 4 32-bit words, which is the cipher-text.sbv3Block decryption. The arguments are the same as in `, except the first argument is the cipher-text and the output is the corresponding plain-text.sbv?128-bit encryption test, from Appendix C.1 of the AES standard:map hex8 t128Enc-["69c4e0d8","6a7b0430","d8cdb780","70b4c55a"]sbv?128-bit decryption test, from Appendix C.1 of the AES standard:map hex8 t128Dec-["00112233","44556677","8899aabb","ccddeeff"]sbv?192-bit encryption test, from Appendix C.2 of the AES standard:map hex8 t192Enc-["dda97ca4","864cdfe0","6eaf70a0","ec0d7191"]sbv?192-bit decryption test, from Appendix C.2 of the AES standard:map hex8 t192Dec-["00112233","44556677","8899aabb","ccddeeff"]sbv:256-bit encryption, from Appendix C.3 of the AES standard:map hex8 t256Enc-["8ea2b7ca","516745bf","eafc4990","4b496089"]sbv:256-bit decryption, from Appendix C.3 of the AES standard:map hex8 t256Dec-["00112233","44556677","8899aabb","ccddeeff"]sbv;Correctness theorem for 128-bit AES. Ideally, we would run:  prove aes128IsCorrect >to get a proof automatically. Unfortunately, while SBV will successfully generate the proof obligation for this theorem and ship it to the SMT solver, it would be naive to expect the SMT-solver to finish that proof in any reasonable time with the currently available SMT solving technologies. Instead, we can issue:  quickCheck aes128IsCorrect and get some degree of confidence in our code. Similar predicates can be easily constructed for 192, and 256 bit cases as well.sbv+Code generation for 128-bit AES encryption.]The following sample from the generated code-lines show how T-Boxes are rendered as C arrays: . static const SWord32 table1[] = { 0xc66363a5UL, 0xf87c7c84UL, 0xee777799UL, 0xf67b7b8dUL, 0xfff2f20dUL, 0xd66b6bbdUL, 0xde6f6fb1UL, 0x91c5c554UL, 0x60303050UL, 0x02010103UL, 0xce6767a9UL, 0x562b2b7dUL, 0xe7fefe19UL, 0xb5d7d762UL, 0x4dababe6UL, 0xec76769aUL, ... } The generated program has 5 tables (one sbox table, and 4-Tboxes), all converted to fast C arrays. Here is a sample of the generated straightline C-code: * const SWord8 s1915 = (SWord8) s1912; const SWord8 s1916 = table0[s1915]; const SWord16 s1917 = (((SWord16) s1914) << 8) | ((SWord16) s1916); const SWord32 s1918 = (((SWord32) s1911) << 16) | ((SWord32) s1917); const SWord32 s1919 = s1844 ^ s1918; const SWord32 s1920 = s1903 ^ s1919; xThe GNU C-compiler does a fine job of optimizing this straightline code to generate a fairly efficient C implementation.sbvGComponents of the AES implementation that the library is generated fromsbv8Generate code for AES functionality; given the key size.sbvEGenerate a C library, containing functions for performing 128-bit encdeckey-expansion. A note on performance: In a very rough speed test, the generated code was able to do 6.3 million block encryptions per second on a decent MacBook Pro. On the same machine, OpenSSL reports 8.2 million block encryptions per second. So, the generated code is about 25% slower as compared to the highly optimized OpenSSL implementation. (Note that the speed test was done somewhat simplistically, so these numbers should be considered very rough estimates.)sbvFor doctest purposes onlysbvplain-text wordssbv key-wordssbv+True if round-trip gives us plain-text back--'(c) Austin SeippBSD3erkokl@gmail.com experimentalNoneXY sbv:Represents the current state of the RC4 stream: it is the S array along with the i and j index values used by the PRGA.sbvThe key is a stream of   values.sbvZRC4 State contains 256 8-bit values. We use the symbolically accessible full-binary type ~ to represent the state, since RC4 needs access to the array via a symbolic index and it's important to minimize access time.sbvSConstruct the fully balanced initial tree, where the leaves are simply the numbers 0 through 255.sbv$Swaps two elements in the RC4 array.sbvZImplements the PRGA used in RC4. We return the new state and the next key value generated.sbv@Constructs the state to be used by the PRGA using the given key.sbvCThe key-schedule. Note that this function returns an infinite list.sbv0Generate a key-schedule from a given key-string.sbvpRC4 encryption. We generate key-words and xor it with the input. The following test-vectors are from Wikipedia  http://en.wikipedia.org/wiki/RC4:*concatMap hex2 $ encrypt "Key" "Plaintext""bbf316e8d940af0ad3"'concatMap hex2 $ encrypt "Wiki" "pedia" "1021bf0420"2concatMap hex2 $ encrypt "Secret" "Attack at dawn""45a01f645fc35b383552544b9bf5"sbvWRC4 decryption. Essentially the same as decryption. For the above test vectors we have:Ddecrypt "Key" [0xbb, 0xf3, 0x16, 0xe8, 0xd9, 0x40, 0xaf, 0x0a, 0xd3] "Plaintext"-decrypt "Wiki" [0x10, 0x21, 0xbf, 0x04, 0x20]"pedia"edecrypt "Secret" [0x45, 0xa0, 0x1f, 0x64, 0x5f, 0xc3, 0x5b, 0x38, 0x35, 0x52, 0x54, 0x4b, 0x9b, 0xf5]"Attack at dawn"sbvProve that round-trip encryption/decryption leaves the plain-text unchanged. The theorem is stated parametrically over key and plain-text sizes. The expression performs the proof for a 40-bit key (5 bytes) and 40-bit plaintext (again 5 bytes).Note that this theorem is trivial to prove, since it is essentially establishing xor'in the same value twice leaves a word unchanged (i.e., x   y   y = xk). However, the proof takes quite a while to complete, as it gives rise to a fairly large symbolic trace.sbvFor doctest purposes only  ((c) Levent ErkokBSD3erkokl@gmail.com experimentalNone$.SXk$sbv5 is a synonym for lists, but makes the intent clear.sbvhParameterized SHA representation, that captures all the differences between variants of the algorithm. w is the word-size type.sbv/Section 1 : Word size we operate withsbv-Section 1 : Block size for messagessbv7Section 4.1.2-3 : Coefficients of the Sum0 functionsbv7Section 4.1.2-3 : Coefficients of the Sum1 functionsbv9Section 4.1.2-3 : Coefficients of the sigma0 functionsbv9Section 4.1.2-3 : Coefficients of the sigma1 functionsbv)Section 4.2.2-3 : Magic SHA constantssbv(Section 5.3.2-6 : Initial hash valuesbvESection 6.2.2, 6.4.2: How many iterations are there in the inner loopsbvThe choose function.sbvThe majority function.sbv|The sum-0 function. We parameterize over the rotation amounts as different variants of SHA use different rotation amnounts.sbv)The sum-1 function. Again, parameterized.sbv#The sigma0 function. Parameterized.sbv#The sigma1 function. Parameterized.sbvParameterization for SHA224.sbv9Parameterization for SHA256. Inherits mostly from SHA224.sbvParameterization for SHA384. sbv9Parameterization for SHA512. Inherits mostly from SHA384. sbv<Parameterization for SHA512_224. Inherits mostly from SHA512 sbv<Parameterization for SHA512_256. Inherits mostly from SHA512 sbvPrepare the message by turning it into blocks. We also check for the message size requirement here. Note that this won't actually happen in practice as the input length would be > 2^64 (or 2^128), and you'd run out of memory first! Such a check sbvHash one block of message, starting from a previous hash. This function corresponds to body of the for-loop in the spec. This function always produces a list of length 8, corresponding to the final 8 values of the H.sbvTCompute the hash of a given string using the specified parameterized hash algorithm.sbvSHA224 digest.sbvSHA256 digest.sbvSHA384 digest.sbvSHA512 digest.sbvSHA512_224 digest.sbvSHA512_256 digest.sbvCollection of known answer tests for SHA. Since these tests take too long during regular regression runs, we pass as an argument how many to run. Increase the below number to 24 to run all tests. We have:knownAnswerTests 1TruesbvWGenerate code for one block of SHA256 in action, starting from an arbitrary hash value.sbvTHelper for chunking a list by given lengths and combining each chunk with a functionsbv'Nicely lay out a hash value as a string&     &     )(c) Levent ErkokBSD3erkokl@gmail.com experimentalNone.sbvFCompute the 16 bit CRC of a 48 bit message, using the given polynomialsbvACount the differing bits in the message and the corresponding CRCsbvGiven a hamming distance value hd,  returns trueJ if the 16 bit polynomial can distinguish all messages that has at most hd? different bits. Note that we express this conversely: If the sent and receivedy messages are different, then it must be the case that that must differ from each other (including CRCs), in more than hd bits.sbvKGenerate good CRC polynomials for 48-bit words, given the hamming distance hd.sbvaFind and display all degree 16 polynomials with hamming distance at least 4, for 48 bit messages.When run, this function prints:  Polynomial #1. x^16 + x^3 + x^2 + 1 Polynomial #2. x^16 + x^3 + x^2 + x + 1 Polynomial #3. x^16 + x^3 + x + 1 Polynomial #4. x^16 + x^15 + x^2 + 1 Polynomial #5. x^16 + x^15 + x^2 + x + 1 Found: 5 polynomail(s). Note that different runs can produce different results, depending on the random numbers used by the solver, solver version, etc. (Also, the solver will take some time to generate these results. On my machine, the first five polynomials were generated in about 5 minutes.)*(c) Levent ErkokBSD3erkokl@gmail.com experimentalNonesbvFor a homogeneous problem, the solution is any linear combination of the resulting vectors. For a non-homogeneous problem, the solution is any linear combination of the vectors in the second component plus one of the vectors in the first component.!sbv1ldn: Solve a (L)inear (D)iophantine equation, returning minimal solutions over (N)aturals. The input is given as a rows of equations, with rhs values separated into a tuple. The first parameter limits the search to bound: In case there are too many solutions, you might want to limit your search space."sbvEFind the basis solution. By definition, the basis has all non-trivial (i.e., non-0) solutions that cannot be written as the sum of two other solutions. We use the mathematically equivalent statement that a solution is in the basis if it's least according to the natural partial order using the ordinary less-than relation.#sbvSolve the equation: 2x + y - z = 2We have:test2NonHomogeneous [[0,2,0],[1,0,0]] [[0,1,1],[1,0,2]]/which means that the solutions are of the form: 9(0, 2, 0) + k (0, 1, 1) + k' (1, 0, 2) = (k', 2+k, k+2k')OR 9(1, 0, 0) + k (0, 1, 1) + k' (1, 0, 2) = (1+k', k, k+2k')for arbitrary k, k'. It's easy to see that these are really solutions to the equation given. It's harder to see that they cover all possibilities, but a moments thought reveals that is indeed the case.$sbvA puzzle: Five sailors and a monkey escape from a naufrage and reach an island with coconuts. Before dawn, they gather a few of them and decide to sleep first and share the next day. At night, however, one of them awakes, counts the nuts, makes five parts, gives the remaining nut to the monkey, saves his share away, and sleeps. All other sailors do the same, one by one. When they all wake up in the morning, they again make 5 shares, and give the last remaining nut to the monkey. How many nuts were there at the beginning?7We can model this as a series of diophantine equations:  x_0 = 5 x_1 + 1 4 x_1 = 5 x_2 + 1 4 x_2 = 5 x_3 + 1 4 x_3 = 5 x_4 + 1 4 x_4 = 5 x_5 + 1 4 x_5 = 5 x_6 + 1 We need to solve for x_0, over the naturals. If you run this program, z3 takes its time (quite long!) but, it eventually computes: [15621,3124,2499,1999,1599,1279,1023] as the answer.That is:  * There was a total of 15621 coconuts * 1st sailor: 15621 = 3124*5+1, leaving 15621-3124-1 = 12496 * 2nd sailor: 12496 = 2499*5+1, leaving 12496-2499-1 = 9996 * 3rd sailor: 9996 = 1999*5+1, leaving 9996-1999-1 = 7996 * 4th sailor: 7996 = 1599*5+1, leaving 7996-1599-1 = 6396 * 5th sailor: 6396 = 1279*5+1, leaving 6396-1279-1 = 5116 * In the morning, they had: 5116 = 1023*5+1. Note that this is the minimum solution, that is, we are guaranteed that there's no solution with less number of coconuts. In fact, any member of [15625*k-4 | k <- [1..]] is a solution, i.e., so are 31246, 46871, 62496, 78121, etc.vNote that we iteratively deepen our search by requesting increasing number of solutions to avoid the all-sat pitfall. !"#$ !"#$+(c) Levent ErkokBSD3erkokl@gmail.com experimentalNone 129X&sbv,Each agent can be in one of the three states'sbv Regular work(sbv!Intention to enter critical state)sbvIn the critical state*sbvThe type synonym * is mnemonic for symbolic state.+sbvSymbolic version of ',sbvSymbolic version of (-sbvSymbolic version of ).sbvA bounded mutex property holds for two sequences of state transitions, if they are not in their critical section at the same time up to that given bound./sbv1A sequence is valid upto a bound if it starts at '', and follows the mutex rules. That is:From ' it can switch to ( or stay 'From ( it can switch to ) if it's its turnFrom ) it can either stay in ) or go back to ' The variable me identifies the agent id.0sbvOThe mutex algorithm, coded implicity as an assignment to turns. Turns start at 1, and at each stage is either 1 or 2; giving preference to that process. The only condition is that if either process is in its critical section, then the turn value stays the same. Note that this is sufficient to satisfy safety (i.e., mutual exclusion), though it does not guarantee liveness.1sbv1Check that we have the mutex property so long as / and 0 holds; i.e., so long as both the agents and the arbiter act according to the rules. The check is bounded up-to-the given concrete bound; so this is an example of a bounded-model-checking style proof. We have: checkMutex 20 All is good!2sbv/Our algorithm is correct, but it is not fair. It does not guarantee that a process that wants to enter its critical-section will always do so eventually. Demonstrate this by trying to show a bounded trace of length 10, such that the second process is ready but never transitions to critical. We have: ghci> notFair 10 Fairness is violated at bound: 10 P1: [Idle,Idle,Ready,Critical,Idle,Idle,Ready,Critical,Idle,Idle] P2: [Idle,Ready,Ready,Ready,Ready,Ready,Ready,Ready,Ready,Ready] Ts: [1,2,1,1,1,1,1,1,1,1]As expected, P2 gets ready but never goes critical since the arbiter keeps picking P1 unfairly. (You might get a different trace depending on what z3 happens to produce!)$Exercise for the reader: Change the 0 function so that it alternates the turns from the previous value if neither process is in critical. Show that this makes the 2d function below no longer exhibits the issue. Is this sufficient? Concurrent programming is tricky!3sbvMake & a symbolic enumeration &)('*+,-./012 &)('*+,-./012,(c) Joel BurgetBSD3erkokl@gmail.com experimentalNone;sbv3Compute a prefix of the fibonacci numbers. We have: mkFibs 10[1,1,2,3,5,8,13,21,34,55]<sbv]Generate fibonacci numbers as a sequence. Note that we constrain only the first 200 entries.;<;<-(c) Levent ErkokBSD3erkokl@gmail.com experimentalNone X=sbv>Simple example demonstrating the use of nested lists. We have:Turned off. See:  *https://github.com/Z3Prover/z3/issues/28208 nestedExample [[1,2,3],[4,5,6,7],[8,9,10],[11,12,13]]==.(c) Levent ErkokBSD3erkokl@gmail.com experimentalNone>sbv+A simple predicate, based on two variables x and y , true when  0 <= x <= 1 and  x - abs y is 0.?sbv=Generate all satisfying assignments for our problem. We have: allModels Solution #1: x = 0 :: Integer y = 0 :: Integer Solution #2: x = 1 :: Integer y = 1 :: Integer Solution #3: x = 1 :: Integer y = -1 :: IntegerFound 3 different solutions.Note that solutions 2 and 3 share the value x = 1&, since there are multiple values of y% that make this particular choice of x satisfy our constraint.@sbv@Generate all satisfying assignments, but we first tell SBV that yM should not be considered as a model problem, i.e., it's auxiliary. We have:modelsWithYAux Solution #1: x = 0 :: Integer Solution #2: x = 1 :: IntegerFound 2 different solutions.GNote that we now have only two solutions, one for each unique value of x that satisfy our constraint.>?@>?@/(c) Levent ErkokBSD3erkokl@gmail.com experimentalNone129X}AsbvA simple enumerated type, that we'd like to translate to SMT-Lib intact; i.e., this type will not be uninterpreted but rather preserved and will be just like any other symbolic type SBV provides.-Also note that we need to have the following LANGUAGE options defined: TemplateHaskell, StandaloneDeriving, DeriveDataTypeable, DeriveAnyClass for this to work.Esbv(Give a name to the symbolic variants of A, for convenienceFsbvBHave the SMT solver enumerate the elements of the domain. We have:elts Solution #1: s0 = A :: E Solution #2: s0 = B :: E Solution #3: s0 = C :: EFound 3 different solutions.Gsbv9Shows that if we require 4 distinct elements of the type AA, we shall fail; as the domain only has three elements. We have:four UnsatisfiableHsbvxEnumerations are automatically ordered, so we can ask for the maximum element. Note the use of quantification. We have:maxESatisfiable. Model: maxE = C :: EIsbv/Similarly, we get the minumum element. We have:minESatisfiable. Model: minE = A :: EJsbvMake A a symbolic value. ABCDEFGHI ABCDEFGHI0(c) Levent ErkokBSD3erkokl@gmail.com experimentalNoneXOtRsbv}Prove that floating point addition is not associative. For illustration purposes, we will require one of the inputs to be a NaN . We have:prove $ assocPlus (0/0)Falsifiable. Counter-example: s0 = 0.0 :: Float s1 = 0.0 :: FloatIndeed:let i = 0/0 :: Floati + (0.0 + 0.0)NaN((i + 0.0) + 0.0)NaNBut keep in mind that NaN< does not equal itself in the floating point world! We have:$let nan = 0/0 :: Float in nan == nanFalseSsbv:Prove that addition is not associative, even if we ignore NaN/Infinity+ values. To do this, we use the predicate -, which is true of a floating point number (e or d) if it is neither NaN nor InfinityA. (That is, it's a representable point in the real-number line.)We have:assocPlusRegularFalsifiable. Counter-example: x = 128.00029 :: Float y = -7.27236e-4 :: Float z = -6.875994e-3 :: FloatIndeed, we have:let x = 128.00029 :: Floatlet y = -7.27236e-4 :: Floatlet z = -6.875994e-3 :: Float x + (y + z) 127.99268 (x + y) + z 127.99269#Note the difference in the results!TsbvDemonstrate that a+b = a does not necessarily mean b is 0O in the floating point world, even when we disallow the obvious solution when a and b are  Infinity. We have:nonZeroAdditionFalsifiable. Counter-example: a = 5.060287e28 :: Float b = 3.6780381e19 :: FloatIndeed, we have:let a = 5.060287e28 :: Floatlet b = 3.6780381e19 :: Float a + b == aTrueb == 0FalseUsbvThis example illustrates that  a * (1/a) does not necessarily equal 1). Again, we protect against division by 0 and NaN/Infinity.We have: multInverseFalsifiable. Counter-example: a = 2.4907063e38 :: FloatIndeed, we have:let a = 2.4907063e38 :: Float a * (1/a) 1.0000001VsbvOne interesting aspect of floating-point is that the chosen rounding-mode can effect the results of a computation if the exact result cannot be precisely represented. SBV exports the functions , , , ,  and 2 which allows users to specify the IEEE supported  for the operation. This example illustrates how SBV can be used to find rounding-modes where, for instance, addition can produce different results. We have: roundingAddSatisfiable. Model:* rm = RoundTowardPositive :: RoundingMode# x = -2.3509886e-38 :: Float# y = -6.0e-45 :: Float(Note that depending on your version of Z3, you might get a different result.) Unfortunately we can't directly validate this result at the Haskell level, as Haskell only supports  . We have:$-2.3509886e-38 + (-6.0e-45) :: Float-2.3509893e-389While we cannot directly see the result when the mode is C in Haskell, we can use SBV to provide us with that result thusly:Rsat $ \z -> z .== fpAdd sRoundTowardPositive (-2.3509886e-38) (-6.0e-45 :: SFloat)Satisfiable. Model: s0 = -2.350989e-38 :: Float:We can see why these two resuls are indeed different: The u (which rounds towards positive infinity from zero) produces a larger result. Indeed, if we treat these numbers as   values, we get: '> -2.3509886e-38 + (-6.0e-45) :: Double 2.3509892e-38>we see that the "more precise" result is larger than what the  $- value is, justifying the larger value with . A more detailed study is beyond our current scope, so we'll merely note that floating point representation and semantics is indeed a thorny subject, and point to  Ohttp://ece.uwaterloo.ca/~dwharder/NumericalAnalysis/02Numerics/Double/paper.pdf as an excellent guide.RSTUVRSTUV1(c) Levent ErkokBSD3erkokl@gmail.com experimentalNoneXWsbvA simple function to generate a new integer value, that is not in the given set of values. We also require the value to be non-negativeXsbvWe now use "outside" repeatedly to generate 10 integers, such that we not only disallow previously generated elements, but also any value that differs from previous solutions by less than 5. Here, we use the < function. We could have also extracted the dictionary via < and did fancier programming as well, as necessary. We have:genVals[45,40,35,30,25,20,15,10,5,0]WXWX22(c) Curran McConnell Levent ErkokBSD3erkokl@gmail.com experimentalNoneMXl YsbvSymbolic version of Z.ZsbvBSimilarly, we can create another newtype, this time wrapping over  . As an example, consider measuring the human height in centimetres? The tallest person in history, Robert Wadlow, was 272 cm. We don't need negative values, so  , is the smallest type that suits our needs.\sbvSymbolic version of ].]sbvA ] is a newtype wrapper around  ._sbv5The tallest human ever was 272 cm. We can simply use 4# to lift it to the symbolic space.`sbvGiven a distance between a floor and a ceiling, we can see whether the human can stand in that room. Comparison is expressed using .asbvNow, suppose we want to see whether we could design a room with a ceiling high enough that any human could stand in it. We have: sat problemSatisfiable. Model:! floorToCeiling = 3 :: Integer humanheight = 255 :: Word16bsbvThe 2 instance simply uses stock definitions. This is always possible for newtypes that simply wrap over an existing symbolic type.csbvTo use ]I symbolically, we associate it with the underlying symbolic type's kind.dsbvSimilarly here, for the 2 instance.esbv@Symbolic instance simply follows the underlying type, just like ]. YZ[\]^_`a ]^\Z[Y_`a3(c) Levent ErkokBSD3erkokl@gmail.com experimentalNonevrsbvhA simple variant of division, where we explicitly require the caller to make sure the divisor is not 0.ssbv#Check whether an arbitrary call to r5 is safe. Clearly, we do not expect this to be safe:test1f[Documentation/SBV/Examples/Misc/NoDiv0.hs:38:14:checkedDiv: Divisor should not be 0: Violated. Model: s0 = 0 :: Int32 s1 = 0 :: Int32]tsbvVRepeat the test, except this time we explicitly protect against the bad case. We have:test2m[Documentation/SBV/Examples/Misc/NoDiv0.hs:46:41:checkedDiv: Divisor should not be 0: No violations detected]rstrst4(c) Levent ErkokBSD3erkokl@gmail.com experimentalNoneusbvHelper synonym for representing GF(2^8); which are merely 8-bit unsigned words. Largest term in such a polynomial has degree 7.vsbvMultiplication in Rijndael's field; usual polynomial multiplication followed by reduction by the irreducible polynomial. The irreducible used by Rijndael's field is the polynomial x^8 + x^4 + x^3 + x + 1 , which we write by giving it's  exponents in SBV. See:  Nhttp://en.wikipedia.org/wiki/Finite_field_arithmetic#Rijndael.27s_finite_fieldI. Note that the irreducible itself is not in GF28! It has a degree of 8.NB. You can use the F function to print polynomials nicely, as a mathematician would write.wsbv States that the unit polynomial 1, is the unit elementxsbv)States that multiplication is commutativeysbvsStates that multiplication is associative, note that associativity proofs are notoriously hard for SAT/SMT solverszsbvQStates that the usual multiplication rule holds over GF(2^n) polynomials Checks:  if (a, b) = x  y then x = y  a + b being careful about y = 0z. When divisor is 0, then quotient is defined to be 0 and the remainder is the numerator. (Note that addition is simply   in GF(2^8).){sbvQueriesuvwxyz{uvwxyz{5(c) Levent ErkokBSD3erkokl@gmail.com experimentalNone<|sbvXAbbreviation for set of integers. For convenience only in monomorphising the properties.||6(c) Levent ErkokBSD3erkokl@gmail.com experimentalNonev}sbvCreate two strings, requiring one to be a particular value, constraining the other to be different than another constant string. But also add soft constraints to indicate our preferences for each of these variables. We get:exampleSatisfiable. Model:( x = "x-must-really-be-hello" :: String( y = "default-y-value" :: StringNote how the value of xJ is constrained properly and thus the default value doesn't kick in, but yS takes the default value since it is acceptable by all the other hard constraints.}}7-(c) Joel Burget Levent ErkokBSD3erkokl@gmail.com experimentalNoneX~sbvFA dictionary is a list of lookup values. Note that we store the type [(a, b)]8 as a symbolic value here, mixing sequences and tuples.sbvCreate a dictionary of length 5, such that each element has an string key and each value is the length of the key. We impose a few more constraints to make the output interesting. For instance, you might get: N ghci> example [("nt_",3),("dHAk",4),("kzkk0",5),("mZxs9s",6),("c32'dPM",7)] Depending on your version of z3, a different answer might be provided. Here, we check that it satisfies our length conditions: import Data.List (genericLength)Vexample >>= \ex -> return (length ex == 5 && all (\(l, i) -> genericLength l == i) ex)True~~8(c) Levent ErkokBSD3erkokl@gmail.com experimentalNone 129HVXsbvA simple enumerationsbv(Give a name to the symbolic variants of , for conveniencesbvIdentify weekend dayssbvHUsing optimization, find the latest day that is not a weekend. We have: almostWeekendOptimal model: almostWeekend = Fri :: Day last-day = 4 :: Word8sbvCUsing optimization, find the first day after the weekend. We have:weekendJustOverOptimal model: weekendJustOver = Mon :: Day first-day = 0 :: Word8sbv9Using optimization, find the first weekend day: We have: firstWeekendOptimal model: firstWeekend = Sat :: Day first-weekend = 5 :: Word8sbv0Make day an optimizable value, by mapping it to  _ in the most obvious way. We can map it to any value the underlying solver can optimize, but  ( is the simplest and it'll fit the bill.sbvMake  a symbolic value.  9(c) Levent ErkokBSD3erkokl@gmail.com experimentalNonensbvOptimization goals where min/max values might require assignments to values that are infinite (integer case), or infinite/epsion (real case). This simple example demostrates how SBV can be used to extract such values.We have:optimize Independent problem 1Objective "one-x": Optimal in an extension field:* one-x = oo :: Integer' min_y = 7.0 + (3.0 * epsilon) :: Real' min_z = 5.0 + (2.0 * epsilon) :: Real1Objective "min_y": Optimal in an extension field:* one-x = oo :: Integer' min_y = 7.0 + (3.0 * epsilon) :: Real' min_z = 5.0 + (2.0 * epsilon) :: Real1Objective "min_z": Optimal in an extension field:* one-x = oo :: Integer' min_y = 7.0 + (3.0 * epsilon) :: Real' min_z = 5.0 + (2.0 * epsilon) :: Real:(c) Levent ErkokBSD3erkokl@gmail.com experimentalNonesbv Taken from 6http://people.brunel.ac.uk/~mastjjb/jeb/or/morelp.htmlmaximize 5x1 + 6x2 subject to  x1 + x2 <= 10 x1 - x2 >= 35x1 + 4x2 <= 35x1 >= 0x2 >= 0optimize Lexicographic problemOptimal model: x1 = 47 % 9 :: Real x2 = 20 % 9 :: Real goal = 355 % 9 :: Real;(c) Levent ErkokBSD3erkokl@gmail.com experimentalNoneIsbv Taken from 6http://people.brunel.ac.uk/~mastjjb/jeb/or/morelp.htmlDA company makes two products (X and Y) using two machines (A and B).Each unit of X that is produced requires 50 minutes processing time on machine A and 30 minutes processing time on machine B.Each unit of Y that is produced requires 24 minutes processing time on machine A and 33 minutes processing time on machine B.At the start of the current week there are 30 units of X and 90 units of Y in stock. Available processing time on machine A is forecast to be 40 hours and on machine B is forecast to be 35 hours.jThe demand for X in the current week is forecast to be 75 units and for Y is forecast to be 95 units.yCompany policy is to maximise the combined sum of the units of X and the units of Y in stock at the end of the week.<How much of each product should we make in the current week?We have:!optimize Lexicographic productionOptimal model: X = 45 :: Integer Y = 6 :: Integer stock = 1 :: Integer]That is, we should produce 45 X's and 6 Y's, with the final maximum stock of just 1 expected!<(c) Levent ErkokBSD3erkokl@gmail.com experimentalNonesbv%The allocation problem. Inspired by: 7http://rise4fun.com/Z3/tutorialcontent/optimization#h25\We have three virtual machines (VMs) which require 100, 50 and 15 GB hard disk respectively.KThere are three servers with capabilities 100, 75 and 200 GB in that order.4Find out a way to place VMs into servers in order to#Minimize the number of servers used_Minimize the operation cost (the servers have fixed daily costs 10, 5 and 20 USD respectively.)We have:optimize Lexicographic allocate Optimal model: x11 = False :: Bool x12 = False :: Bool x13 = True :: Bool x21 = False :: Bool x22 = False :: Bool x23 = True :: Bool x31 = False :: Bool x32 = False :: Bool x33 = True :: Bool noOfServers = 1 :: Integer cost = 20 :: IntegerPThat is, we should put all the jobs on the third server, for a total cost of 20.=(c) Levent ErkokBSD3erkokl@gmail.com experimentalNone$456=?@Asbv*System state, containing the two integers.sbv@We parameterize over the initial state for different variations.sbvExample 1: We start from x=0, y=10, and search up to depth 10 . We have:ex1BMC: Iteration: 0BMC: Iteration: 1BMC: Iteration: 2BMC: Iteration: 3"BMC: Solution found at iteration 3%Right (3,[(0,10),(2,10),(2,6),(2,2)])kAs expected, there's a solution in this case. Furthermore, since the BMC engine found a solution at depth 34, we also know that there is no solution at depths 0, 1, or 2; i.e., this is "a" shortest solution. (That is, it may not be unique, but there isn't a shorter sequence to get us to our goal.)sbvExample 2: We start from x=0, y=11, and search up to depth 10 . We have:ex2 BMC: Iteration: 0BMC: Iteration: 1BMC: Iteration: 2BMC: Iteration: 3BMC: Iteration: 4BMC: Iteration: 5BMC: Iteration: 6BMC: Iteration: 7BMC: Iteration: 8BMC: Iteration: 9Left "BMC limit of 10 reached"As expected, there's no solution in this case. While SBV (and BMC) cannot establish that there is no solution at a larger depth, you can see that this will never be the case: In each step we do not change the parity of either variable. That is, x will remain even, and y will remain odd. So, there will never be a solution at any depth. This isn't the only way to see this result of course, but the point remains that BMC is just not capable of establishing inductive facts.sbv' instance for our statesbvSymbolic equality for S.sbvShow the state as a pair>(c) Levent ErkokBSD3erkokl@gmail.com experimentalNone $45679=?@AWsbv}System state. We simply have two components, parameterized over the type so we can put in both concrete and symbolic values.sbv;Encoding partial correctness of the sum algorithm. We have: fibCorrectQ.E.D.NB. In my experiments, I found that this proof is quite fragile due to the use of quantifiers: If you make a mistake in your algorithm or the coding, z3 pretty much spins forever without finding a counter-example. However, with the correct coding, the proof is almost instantaneous!sbv' instance for our state?(c) Levent ErkokBSD3erkokl@gmail.com experimentalNone$456=?@A# sbv}System state. We simply have two components, parameterized over the type so we can put in both concrete and symbolic values.sbviWe parameterize over the transition relation and the strengthenings to investigate various combinations.sbv2The first program, coded as a transition relation:sbv3The second program, coded as a transition relation:sbv:Example 1: First program, with no strengthenings. We have:ex1&Failed while establishing consecution.!Counter-example to inductiveness: S {x = -1, y = 1}sbv,Example 2: First program, strengthened with x >= 0 . We have:ex2Q.E.D.sbv;Example 3: Second program, with no strengthenings. We have:ex3&Failed while establishing consecution.!Counter-example to inductiveness: S {x = -1, y = 1}sbv-Example 4: Second program, strengthened with x >= 0 . We have:ex4AFailed while establishing consecution for strengthening "x >= 0".!Counter-example to inductiveness: S {x = 0, y = -1}sbv-Example 5: Second program, strengthened with x >= 0 and y >= 1 separately. We have:ex5AFailed while establishing consecution for strengthening "x >= 0".!Counter-example to inductiveness: S {x = 0, y = -1} Note how this was sufficient in M to establish the invariant for the first program, but fails for the second.sbv-Example 6: Second program, strengthened with x >= 0 /\ y >= 1 simultaneously. We have:ex6Q.E.D.Compare this to .. As pointed out by Bradley, this shows that ca conjunction of assertions can be inductive when none of its components, on its own, is inductive.T It remains an art to find proper loop invariants, though the science is improving!sbv' instance for our state  @(c) Levent ErkokBSD3erkokl@gmail.com experimentalNone $45679=?@A) sbv}System state. We simply have two components, parameterized over the type so we can put in both concrete and symbolic values.sbv;Encoding partial correctness of the sum algorithm. We have: sumCorrectQ.E.D.sbv' instance for our stateA(c) Levent ErkokBSD3erkokl@gmail.com experimentalNone@ sbvNRepresent day by 8-bit words; Again, an uninterpreted type would work as well.sbvbRepresent month by 8-bit words; We can also use an uninterpreted type, but numbers work well here.sbv!Months referenced in the problem.sbv!Months referenced in the problem.sbv!Months referenced in the problem.sbv!Months referenced in the problem.sbv<Check that a given month/day combo is a possible birth-date.sbvBAssert that the given function holds for one of the possible days.sbvBAssert that the given function holds for all of the possible days.sbvDAssert that the given function holds for one of the possible months.sbvDAssert that the given function holds for all of the possible months.sbv/Encode the conversation as given in the puzzle.NB. Lee Pike pointed out that not all the constraints are actually necessary! (Private communication.) The puzzle still has a unique solution if the statements a1 and b1i (i.e., Albert and Bernard saying they themselves do not know the answer) are removed. To experiment you can simply comment out those statements and observe that there still is a unique solution. Thanks to Lee for pointing this out! In fact, it is instructive to assert the conversation line-by-line, and see how the search-space gets reduced in each step.sbv4Find all solutions to the birthday problem. We have:cheryl Solution #1: birthDay = 16 :: Word8 birthMonth = 7 :: Word8This is the only solution.  B(c) Levent ErkokBSD3erkokl@gmail.com experimentalNoneP sbvQWe will represent coins with 16-bit words (more than enough precision for coins).sbvCreate a coin. The argument Int argument just used for naming the coin. Note that we constrain the value to be one of the valid U.S. coin values as we create it.sbv0Return all combinations of a sequence of values.sbv.Constraint 1: Cannot make change for a dollar.sbv3Constraint 2: Cannot make change for half a dollar.sbv/Constraint 3: Cannot make change for a quarter.sbv,Constraint 4: Cannot make change for a dime.sbv-Constraint 5: Cannot make change for a nickelsbvConstraint 6: Cannot buy the candy either. Here's where we need to have the extra knowledge that the vending machines do not take 50 cent coins.sbvSolve the puzzle. We have:puzzleSatisfiable. Model: c1 = 50 :: Word16 c2 = 25 :: Word16 c3 = 10 :: Word16 c4 = 10 :: Word16 c5 = 10 :: Word16 c6 = 10 :: Word16<i.e., your friend has 4 dimes, a quarter, and a half dollar.  C(c) Levent ErkokBSD3erkokl@gmail.com experimentalNone^&sbvYWe will assume each number can be represented by an 8-bit word, i.e., can be at most 128.sbvOGiven a number, increment the count array depending on the digits of the numbersbvEncoding of the puzzle. The solution is a sequence of 10 numbers for the occurrences of the digits such that if we count each digit, we find these numbers.sbv6Finds all two known solutions to this puzzle. We have:counts Solution #1In this sentence, the number of occurrences of 0 is 1, of 1 is 11, of 2 is 2, of 3 is 1, of 4 is 1, of 5 is 1, of 6 is 1, of 7 is 1, of 8 is 1, of 9 is 1. Solution #2In this sentence, the number of occurrences of 0 is 1, of 1 is 7, of 2 is 3, of 3 is 2, of 4 is 1, of 5 is 1, of 6 is 1, of 7 is 2, of 8 is 1, of 9 is 1.Found: 2 solution(s).D(c) Levent ErkokBSD3erkokl@gmail.com experimentalNoneasbvPrints the only solution:puzzle Solution #1: dog = 3 :: Integer cat = 41 :: Integer mouse = 56 :: IntegerThis is the only solution.E(c) Levent ErkokBSD3erkokl@gmail.com experimentalNoneisbvIThe given guesses and the correct digit counts, encoded as a simple list.sbv$Encode the problem, note that we check digits are within 0-9 as we use 8-bit words to represent them. Otherwise, the constraints are simply generated by zipping the alleged solution with each guess, and making sure the number of matching digits match what's given in the problem statement.sbv'Print out the solution nicely. We have: solveEuler1854640261571849533Number of solutions: 1F(c) Levent ErkokBSD3erkokl@gmail.com experimentalNone129Xu sbvColors of housessbvNationalities of the occupantssbvMake  a symbolic value.sbvBeverage choices sbvMake  a symbolic value.sbvPets they keepsbvMake  a symbolic value.#sbvSports they engage in)sbvMake  a symbolic value.1sbvWe have: fishOwnerGermanIt's not hard to modify this program to grab the values of all the assignments, i.e., the full solution to the puzzle. We leave that as an exercise to the interested reader! NB. We use the  configuration to indicate that the uninterpreted function changes do not matter for generating different values. All we care is that the fishOwner changes!2sbvMake # a symbolic value.    #('&%$1    #('&%$1G(c) Levent ErkokBSD3erkokl@gmail.com experimentalNone129:sbvColors of the flowers>sbv&Represent flowers by symbolic integers?sbvThe uninterpreted function ? assigns a color to each flower.@sbv'Describe a valid pick of three flowers i, j, k, assuming we have nV flowers to start with. Essentially the numbers should be within bounds and distinct.AsbvACount the number of flowers that occur in a given set of flowers.BsbvSmullyan's puzzle.CsbvSolve the puzzle. We have: flowerCount Solution #1: N = 3 :: Integer>This is the only solution. (Unique up to prefix existentials.)So, a garden with 3 flowers is the only solution. (Note that we simply skip over the prefix existentials and the assignments to uninterpreted function ?I for model purposes here, as they don't represent a different solution.)DsbvMake : a symbolic value. :=<;>?@ABC :=<;>?@ABCH(c) Levent ErkokBSD3erkokl@gmail.com experimentalNone129X LsbvColors we're allowedQsbv6The grid is an array mapping each button to its color.RsbvSymbolic version of button.SsbvEUse 8-bit words for button numbers, even though we only have 1 to 19.Tsbv,Give symbolic colors a name for convenience.UsbvGiven a button press, and the current grid, compute the next grid. If the button is "unpressable", i.e., if it is not one of the center buttons or it is currently colored black, we return the grid unchanged.VsbvIteratively search at increasing depths of button-presses to see if we can transform from the initial board position to a final board position.Wsbv"A particular example run. We have:example Searching at depth: 0Searching at depth: 1Searching at depth: 2Searching at depth: 3Searching at depth: 4Searching at depth: 5Searching at depth: 6Found: [10,10,11,9,14,6]Found: [10,10,9,11,14,6]There are no more solutions.XsbvMake L a symbolic value. LMNOPQRSTUVW LMNOPTSRQUVWI(c) Levent ErkokBSD3erkokl@gmail.com experimentalNone`sbvPrints the only solution: ladyAndTigers Solution #1: sign1 = False :: Bool sign2 = False :: Bool sign3 = True :: Bool tiger1 = False :: Bool tiger2 = True :: Bool tiger3 = True :: BoolThis is the only solution.GThat is, the lady is in room 1, and only the third room's sign is true.``J(c) Levent ErkokBSD3erkokl@gmail.com experimentalNoneasbv"The puzzle board is a list of rowsbsbvA row is a list of elementscsbvUse 32-bit words for elements.dsbv4Checks that all elements in a list are within boundsesbv#Get the diagonal of a square matrixfsbv'Test if a given board is a magic squaregsbv3Group a list of elements in the sublists of length ihsbvGiven n, magic n prints all solutions to the nxn magic square problemabcdefghcbadefghK(c) Levent ErkokBSD3erkokl@gmail.com experimentalNoneisbvEA solution is a sequence of row-numbers where queens should be placedjsbv Checks that a given solution of n5-queens is valid, i.e., no queen captures any other.ksbvGiven n, it solves the n-queens) puzzle, printing all possible solutions.ijkijkL(c) Levent ErkokBSD3erkokl@gmail.com experimentalNone.lsbvSolve the puzzle. We have: sendMoreMoney Solution #1: s = 9 :: Integer e = 5 :: Integer n = 6 :: Integer d = 7 :: Integer m = 1 :: Integer o = 0 :: Integer r = 8 :: Integer y = 2 :: IntegerThis is the only solution.That is:9567 + 1085 == 10652TruellM(c) Levent ErkokBSD3erkokl@gmail.com experimentalNonemsbvA puzzle is a pair: First is the number of missing elements, second is a function that given that many elements returns the final board.nsbv&A Sudoku board is a sequence of 9 rowsosbv\A row is a sequence of 8-bit words, too large indeed for representing 1-9, but does not harmpsbvfGiven a series of elements, make sure they are all different and they all are numbers between 1 and 9qsbv1Given a full Sudoku board, check that it is validrsbv*Solve a given puzzle and print the resultsssbvTHelper function to display results nicely, not really needed, but helps presentationtsbvFind all solutions to a puzzleusbvFind an arbitrary good boardvsbv(A random puzzle, found on the internet..wsbv.Another random puzzle, found on the internet..xsbv.Another random puzzle, found on the internet..ysbvdAccording to the web, this is the toughest sudoku puzzle ever.. It even has a name: Al Escargot: Jhttp://zonkedyak.blogspot.com/2006/11/worlds-hardest-sudoku-puzzle-al.htmlzsbv/This one has been called diabolical, apparently{sbv)The following is nefarious according to %http://haskell.org/haskellwiki/Sudoku|sbvFSolve them all, this takes a fraction of a second to run for each casemnopqrstuvwxyz{|onpqmrstuvwxyz{|N(c) Levent ErkokBSD3erkokl@gmail.com experimentalNone1279=?:(}sbvsU2 band members. We want to translate this to SMT-Lib as a data-type, and hence the call to mkSymbolicEnumeration.sbvLocation of the flashsbvSymbolic variant for timesbvModel time using 32 bitssbvSymbolic shorthand for a }sbv/Shorthands for symbolic versions of the memberssbv/Shorthands for symbolic versions of the memberssbv/Shorthands for symbolic versions of the memberssbv/Shorthands for symbolic versions of the memberssbv*Crossing times for each member of the bandsbv6The symbolic variant.. The duplication is unfortunate.sbvMake } a symbolic value.sbvA move action is a sequence of triples. The first component is symbolically True if only one member crosses. (In this case the third element of the triple is irrelevant.) If the first component is (symbolically) False, then both members move togethersbv/A puzzle move is modeled as a state-transformersbv(The status of the puzzle after each move4This type is equipped with an automatically derived C! instance because each field is C. A  : instance must also be derived for this to work, and the DeriveAnyClass2 language extension must be enabled. The derived Cj instance simply walks down the structure field by field and merges each one. An equivalent hand-written C* instance is provided in a comment below.sbv elapsed timesbvlocation of the flashsbvlocation of Bonosbvlocation of Edgesbvlocation of Adamsbvlocation of LarrysbvSymbolic variant of sbv-Shorthands for symbolic versions of locationssbv-Shorthands for symbolic versions of locationssbv8Start configuration, time elapsed is 0 and everybody is sbv'Read the state via an accessor functionsbv.Given an arbitrary member, return his locationsbv(Transferring the flash to the other sidesbv'Transferring a person to the other sidesbv0Increment the time, when only one person crossessbv2Increment the time, when two people cross togethersbvSymbolic version of mnsbv.Move one member, remembering to take the flashsbv&Move two members, again with the flashsbv Run a sequence of given actions.sbvCheck if a given sequence of actions is valid, i.e., they must all cross the bridge according to the rules and in less than 17 secondssbv.See if there is a solution that has precisely n stepssbvSolve the U2-bridge crossing puzzle, starting by testing solutions with increasing number of steps, until we find one. We have:solveU2#Checking for solutions with 1 move.$Checking for solutions with 2 moves.$Checking for solutions with 3 moves.$Checking for solutions with 4 moves.$Checking for solutions with 5 moves. Solution #1: 0 --> Edge, Bono 2 <-- Bono 3 --> Larry, Adam 13 <-- Edge15 --> Edge, BonoTotal time: 17 Solution #2: 0 --> Edge, Bono 2 <-- Edge 4 --> Larry, Adam 14 <-- Bono15 --> Edge, BonoTotal time: 17 Found: 2 solutions with 5 moves.-Finding all possible solutions to the puzzle.sbvMergeable instance for [ simply pushes the merging the data after run of each branch starting from the same state.sbvMake  a symbolic value.,}~,}~O(c) Levent ErkokBSD3erkokl@gmail.com experimentalNonesbvFind all solutions to  x + y .== 10 for positive x and yC, but at each iteration we would like to ensure that the value of x we get is one more than the previous one. This is rather silly, but demonstrates how we can dynamically query the result and put in new constraints based on those.sbvRun the query. We have:demoStarting the all-sat engine! Iteration: 1Current solution is: (0,10) Iteration: 2Current solution is: (1,9) Iteration: 3Current solution is: (2,8) Iteration: 4Current solution is: (3,7) Iteration: 5Current solution is: (4,6) Iteration: 6Current solution is: (5,5) Iteration: 7Current solution is: (6,4) Iteration: 8Current solution is: (7,3) Iteration: 9Current solution is: (8,2) Iteration: 10Current solution is: (9,1) Iteration: 11Current solution is: (10,0) Iteration: 12No other solution!E[(0,10),(1,9),(2,8),(3,7),(4,6),(5,5),(6,4),(7,3),(8,2),(9,1),(10,0)]P(c) Levent ErkokBSD3erkokl@gmail.com experimentalNonesbvA simple floating-point problem, but we do the sat-analysis via a case-split. Due to the nature of floating-point numbers, a case-split on the characteristics of the number (such as NaN, negative-zero, etc. is most suitable.)We have:csDemo1 Case fpIsNegativeZero: Starting$Case fpIsNegativeZero: UnsatisfiableCase fpIsPositiveZero: Starting$Case fpIsPositiveZero: UnsatisfiableCase fpIsNormal: StartingCase fpIsNormal: UnsatisfiableCase fpIsSubnormal: Starting!Case fpIsSubnormal: UnsatisfiableCase fpIsPoint: StartingCase fpIsPoint: UnsatisfiableCase fpIsNaN: StartingCase fpIsNaN: Satisfiable("fpIsNaN",NaN)sbv!Demonstrates the "coverage" case.We have:csDemo2Case negative: StartingCase negative: UnsatisfiableCase less than 8: StartingCase less than 8: UnsatisfiableCase Coverage: StartingCase Coverage: Satisfiable("Coverage",10)Q/(c) Jeffrey Young Levent ErkokBSD3erkokl@gmail.com experimentalNone4sbvFind all solutions to  x + y .== 10 for positive x and yC, but at each iteration we would like to ensure that the value of x we get is at least twice as large as the previous one. This is rather silly, but demonstrates how we can dynamically query the result and put in new constraints based on those.sbv6In our first query we'll define a constraint that will not be known to the shared or second query and then solve for an answer that will differ from the first query. Note that we need to pass an MVar in so that we can operate on the shared variables. In general, the variables you want to operate on should be defined in the shared part of the query and then passed to the children queries via channels, MVars, or TVars. In this query we constrain x to be less than y and then return the sum of the values. We add a threadDelay just for demonstration purposessbv{In the second query we constrain for an answer where y is smaller than x, and then return the product of the found values.sbvQRun the demo several times to see that the children threads will change ordering.sbvExample computation.sbvIn our first query we will make a constrain, solve the constraint and return the values for our variables, then we'll mutate the MVar sending information to the second query. Note that you could use channels, or TVars, or TMVars, whatever you need here, we just use MVars for demonstration purposes. Also note that this effectively creates an ordering between the children queriessbvIn the second query we create a new variable z, and then a symbolic query using information from the first query and return a solution that uses the new variable and the old variables. Each child query is run in a separate instance of z3 so you can think of this query as driving to a point in the search space, then waiting for more information, once it gets that information it will run a completely separate computation from the first one and return its results.sbvGIn our second demonstration we show how through the use of concurrency constructs the user can have children queries communicate with one another. Note that the children queries are independent and so anything side-effectual like a push or a pop will be isolated to that child thread, unless of course it happens in shared.R(c) Levent ErkokBSD3erkokl@gmail.com experimentalNone129X=sbv0Days of the week. We make it symbolic using the  splice.sbvThe type synonym  is the symbolic variant of . (Similar to 'SInteger'/'Integer' and others.)sbvAA trivial query to find three consecutive days that's all before S. The point here is that we can perform queries on such enumerated values and use R on them and return their values from queries just like any other value. We have:findDays[Monday,Tuesday,Wednesday]sbvMake  a symbolic value.  S(c) Levent ErkokBSD3erkokl@gmail.com experimentalNone 129=?Xnpsbv[Supported binary operators. To keep the search-space small, we will only allow division by 2 or 40, and exponentiation will only be to the power 0U. This does restrict the search space, but is sufficient to solve all the instances.sbv&Supported unary operators. Similar to V case, we will restrict square-root and factorial to be only applied to the value @4.sbvMake  a symbolic value.sbvJThe shape of a tree, either a binary node, or a unary node, or the number 4', represented hear by the constructor Fa. We parameterize by the operator type: When doing symbolic computations, we'll fill those with  and G. When finding the shapes, we will simply put unit values, i.e., holes.sbvSymbolic variant of .sbvSymbolic variant of .sbvKConstruct all possible tree shapes. The argument here follows the logic in  !http://www.gigamonkeys.com/trees/f: We simply construct all possible shapes and extend with the operators. The number of such trees is:length allPossibleTrees640Note that this is a lot# smaller than what is generated by  !http://www.gigamonkeys.com/trees/\. (There, the number of trees is 10240000: 16000 times more than what we have to consider!)sbvEGiven a tree with hols, fill it with symbolic operators. This is the trickJ that allows us to consider only 640 trees as opposed to over 10 million.sbvMinor helper for writing "symbolic" case statements. Simply walks down a list of values to match against a symbolic version of the key.sbvEvaluate a symbolic tree, obtaining a symbolic value. Note how we structure this evaluation so we impose extra constraints on what values square-root, divide etc. can take. This is the power of the symbolic approach: We can put arbitrary symbolic constraints as we evaluate the tree.sbv8In the query mode, find a filling of a given tree shape t1, such that it evalutes to the requested number i+. Note that we return back a concrete tree.sbvzGiven an integer, walk through all possible tree shapes (at most 640 of them), and find a filling that solves the puzzle.sbvSolution to the puzzle. When you run this puzzle, the solver can produce different results than what's shown here, but the expressions should still be all valid! ghci> puzzle 0 [OK]: (4 - (4 + (4 - 4))) 1 [OK]: (4 / (4 + (4 - 4))) 2 [OK]: sqrt((4 + (4 * (4 - 4)))) 3 [OK]: (4 - (4 ^ (4 - 4))) 4 [OK]: (4 + (4 * (4 - 4))) 5 [OK]: (4 + (4 ^ (4 - 4))) 6 [OK]: (4 + sqrt((4 * (4 / 4)))) 7 [OK]: (4 + (4 - (4 / 4))) 8 [OK]: (4 - (4 - (4 + 4))) 9 [OK]: (4 + (4 + (4 / 4))) 10 [OK]: (4 + (4 + (4 - sqrt(4)))) 11 [OK]: (4 + ((4 + 4!) / 4)) 12 [OK]: (4 * (4 - (4 / 4))) 13 [OK]: (4! + ((sqrt(4) - 4!) / sqrt(4))) 14 [OK]: (4 + (4 + (4 + sqrt(4)))) 15 [OK]: (4 + ((4! - sqrt(4)) / sqrt(4))) 16 [OK]: (4 * (4 * (4 / 4))) 17 [OK]: (4 + ((sqrt(4) + 4!) / sqrt(4))) 18 [OK]: -(4 + (4 - (sqrt(4) + 4!))) 19 [OK]: -(4 - (4! - (4 / 4))) 20 [OK]: (4 * (4 + (4 / 4))) sbvA rudimentary  -# instance for trees, nothing fancy.sbvMake  a symbolic value.T(c) Levent ErkokBSD3erkokl@gmail.com experimentalNonez sbvcUse the backend solver to guess the number given as argument. The number is assumed to be between 0 and 1000n, and we use a simple binary search. Returns the sequence of guesses we performed during the search process. sbvPlay a round of the game, making the solver guess the secret number 42. Note that you can generate a random-number and make the solver guess it too! We have:play Current bounds: (0,1000)Current bounds: (0,521)Current bounds: (21,521)Current bounds: (31,521)Current bounds: (36,521)Current bounds: (39,521)Current bounds: (40,521)Current bounds: (41,521)Current bounds: (42,521)Solved in: 9 guesses: 971 0 21 31 36 39 40 41 42    U(c) Levent ErkokBSD3erkokl@gmail.com experimentalNone sbvLMathSAT example. Compute the interpolant for the following sets of formulas: {x - 3y >= -1, x + y >= 0}AND {z - 2x >= 3, 2z <= 1}where the variables are integers. Note that these sets of formulas are themselves satisfiable, but not taken all together. The pair (x, y) = (0, 0)# satisfies the first set. The pair (x, z) = (-2, 0)3 satisfies the second. However, there's no triple  (x, y, z)U that satisfies all these four formulas together. We can use SBV to check this fact:Zsat $ \x y z -> sAnd [x - 3*y .>= -1, x + y .>= 0, z - 2*x .>= 3, 2 * z .<= (1::SInteger)] UnsatisfiableAAn interpolant for these sets would only talk about the variable x" that is common to both. We have:!runSMTWith mathSAT exampleMathSAT "(<= 0 s0)"lNotice that we get a string back, not a term; so there's some back-translation we need to do. We know that s0 is xF through our translation mechanism, so the interpolant is saying that x >= 0 is entailed by the first set of formulas, and is inconsistent with the second. Let's use SBV to indeed show that this is the case:Jprove $ \x y -> (x - 3*y .>= -1 .&& x + y .>= 0) .=> (x .>= (0::SInteger))Q.E.D.And:Nprove $ \x z -> (z - 2*x .>= 3 .&& 2 * z .<= 1) .=> sNot (x .>= (0::SInteger))Q.E.D.4This establishes that we indeed have an interpolant! sbv1Z3 example. Compute the interpolant for formulas y = 2x and y = 2z+1.AThese formulas are not satisfiable together since it would mean y is both even and odd at the same time. An interpolant for this pair of formulas is a formula that's expressed only in terms of y6, which is the only common symbol among them. We have:runSMT evenOdd'"(or (= s1 0) (= s1 (* 2 (div s1 2))))"}This is a bit hard to read unfortunately, due to translation artifacts and use of strings. To analyze, we need to know that s1 is yM through SBV's translation. Let's express it in regular infix notation with y for s1: (y == 0) || (y == 2 * (y   2))Notice that the only symbol is y_, as required. To establish that this is indeed an interpolant, we should establish that when y is even, this formula is True ; and if y is odd, then then it should be Falsea. You can argue mathematically that this indeed the case, but let's just use SBV to prove these:Yprove $ \y -> (y `sMod` 2 .== 0) .=> ((y .== 0) .|| (y .== 2 * (y `sDiv` (2::SInteger))))Q.E.D.And:^prove $ \y -> (y `sMod` 2 .== 1) .=> sNot ((y .== 0) .|| (y .== 2 * (y `sDiv` (2::SInteger))))Q.E.D.4This establishes that we indeed have an interpolant!    V(c) Levent ErkokBSD3erkokl@gmail.com experimentalNone sbvA simple goal with three constraints, two of which are conflicting with each other. The third is irrelevant, in the sense that it does not contribute to the fact that the goal is unsatisfiable. sbvExtract the unsat-core of   . We have:ucCore-Unsat core is: ["less than 5","more than 10"]"Demonstrating that the constraint a .> b is not) needed for unsatisfiablity in this case.    W(c) Joel BurgetBSD3erkokl@gmail.com experimentalNone sbv9Solve a given crossword, returning the corresponding rows sbvSolve ;http://regexcrossword.com/challenges/intermediate/puzzles/1puzzle1 ["ATO","WEL"] sbvSolve ;http://regexcrossword.com/challenges/intermediate/puzzles/2puzzle2["WA","LK","ER"] sbvSolve ;http://regexcrossword.com/challenges/palindromeda/puzzles/3puzzle3["RATS","ABUT","TUBA","STAR"]    X(c) Joel BurgetBSD3erkokl@gmail.com experimentalNoneX sbv[Evaluation monad. The state argument is the environment to store variables as we evaluate. sbvSimple expression language sbv-Given an expression, symbolically evaluate it sbvSA simple program to query all messages with a given topic id. In SQL like notation: F query ("SELECT msg FROM msgs where topicid='" ++ my_topicid ++ "'") sbv<Limit names to be at most 7 chars long, with simple letters. sbv:Strings: Again, at most of lenght 5, surrounded by quotes. sbvA "select" command: sbv-A "drop" instruction, which can be exploited! sbvMWe'll greatly simplify here and say a statement is either a select or a drop: sbvRThe exploit: We're looking for a DROP TABLE after at least one legitimate command. sbvAnalyze the program for inputs which result in a SQL injection. There are other possible injections, but in this example we're only looking for a  DROP TABLE command.6Remember that our example program (in pseudo-code) is: F query ("SELECT msg FROM msgs WHERE topicid='" ++ my_topicid ++ "'") BDepending on your z3 version, you might see an output of the form: @ ghci> findInjection exampleProgram "kg'; DROP TABLE 'users" kthough the topic might change obviously. Indeed, if we substitute the suggested string, we get the program: Equery ("SELECT msg FROM msgs WHERE topicid='kg'; DROP TABLE 'users'")which would query for topic kg! and then delete the users table!EHere, we make sure that the injection ends with the malicious string:P("'; DROP TABLE 'users" `Data.List.isSuffixOf`) <$> findInjection exampleProgramTrue sbv6Literals strings can be lifted to be constant programs                          Y(c) Brian SchroederBSD3erkokl@gmail.com experimentalNone&'4HM sbvMonad for querying a solver. sbvThe result of  Hing the combination of a  & and a  ". "sbv$A property describes a quality of a  & . It is a  + yields a boolean value. $sbvMA symbolic value representing the result of running a program -- its output. &sbv2A program that can reference two input variables, x and y. (sbv)Monad for performing symbolic evaluation. +sbv<The term language we use to express programs and properties. 6sbv(Environment holding allocated variables. ;sbv$Monad for allocating free variables. >sbv4Allocate an integer variable with the provided name. ?sbv Allocate an  6- holding all input variables for the program. @sbvRUnsafe cast for symbolic values. In production code, we would check types instead. Asbv!Symbolic evaluation function for  +. Bsbv$Runs symbolic evaluation, sending a  +\ to a symbolic value (or failing). Used for symbolic evaluation of programs and properties. CsbvMakes a  $ from a symbolic value. Dsbv"Performs symbolic evaluation of a  &. Esbv,Performs symbolic evaluation of a 'Property. Fsbv Sends an  1 computation to an arbitrary monadic computation. Gsbv9Creates a computation that queries a solver and yields a  . Hsbv Checks a  " of a  & (or fails). Isbv Check that x+y+1L generates a counter-example for the property that the result is less than 10 when x+y is at least 9 . We have:ex1Right (Counterexample 0 9) JsbvCheck that the program x+y* correctly produces a result greater than 1 when both x and y are at least 1 . We have:ex2 Right Proved KsbvCheck that we catch the cases properly through the monad stack when there is a syntax error, like an undefined variable. We have:ex3Left "unknown variable"0     ! " # $ % & ' ( ) * + 5 1 3 4 0 / . - 2 , 6 7 9 8 : ; < = > ? @ A B C D E F G H I J K0 ; < = 6 7 9 8 : > ? + 5 1 3 4 0 / . - 2 , ( ) * @ A B & ' $ % C D " # E  ! F    G H I J KZ(c) Levent ErkokBSD3erkokl@gmail.com experimentalNoneX asbv%Uninterpreted function in the theorem bsbv3Correctness theorem. We state it for all values of x, y, and the given array aF. Note that we're being generic in the type of array we're expecting. csbvProve it using SMT-Lib arrays. proveSArrayQ.E.D. dsbv0Prove it using SBV's internal functional arrays.proveSFunArrayQ.E.D. a b c d a b c d[(c) Levent ErkokBSD3erkokl@gmail.com experimentalNone29m esbv4Handy shortcut for the type of symbolic values over  f fsbvThe uninterpreted sort  f{, corresponding to the carrier. To prevent SBV from translating it to an enumerated type, we simply attach an unused field hsbv!Uninterpreted logical connective  h isbv!Uninterpreted logical connective  i jsbv!Uninterpreted logical connective  j ksbvDistributivity of OR over AND, as an axiom in terms of the uninterpreted functions we have introduced. Note how variables range over the uninterpreted sort  f. lsbv]One of De Morgan's laws, again as an axiom in terms of our uninterpeted logical connectives. msbv,Double negation axiom, similar to the above. nsbvProves the equivalence >NOT (p OR (q AND r)) == (NOT p AND NOT q) OR (NOT p AND NOT r)>, following from the axioms we have specified above. We have:testQ.E.D. e f g h i j k l m n f g e h i j k l m n\(c) Levent ErkokBSD3erkokl@gmail.com experimentalNone vsbvAn uninterpreted function wsbv Asserts that f x z == f (y+2) z whenever x == y+2. Naturally correct: prove thmGoodQ.E.D. v w v w](c) Levent ErkokBSD3erkokl@gmail.com experimentalNoneX xsbvThe uninterpreted implementation of our 2x2 multiplier. We simply receive two 2-bit values, and return the high and the low bit of the resulting multiplication via two uninterpreted functions that we called mul22_hi and mul22_lo. Note that there is absolutely no computation going on here, aside from simply passing the arguments to the uninterpreted functions and stitching it back together.NB. While definining mul22_lo we used our domain knowledge that the low-bit of the multiplication only depends on the low bits of the inputs. However, this is merely a simplifying assumption; we could have passed all the arguments as well. ysbv/Synthesize a 2x2 multiplier. We use 8-bit inputs merely because that is the lowest bit-size SBV supports but that is more or less irrelevant. (Larger sizes would work too.) We simply assert this for all input values, extract the bottom two bits, and assert that our "uninterpreted" implementation in  x! is precisely the same. We have:sat synthMul22 Satisfiable. Model:2 mul22_hi :: Bool -> Bool -> Bool -> Bool -> Bool) mul22_hi False True True False = True) mul22_hi False True True True = True) mul22_hi True False False True = True) mul22_hi True False True True = True) mul22_hi True True False True = True) mul22_hi True True True False = True* mul22_hi _ _ _ _ = False" mul22_lo :: Bool -> Bool -> Bool mul22_lo True True = True mul22_lo _ _ = FalseIt is easy to see that the low bit is simply the logical-and of the low bits. It takes a moment of staring, but you can see that the high bit is correct as well: The logical formula is  a1b xor a0b1, and if you work out the truth-table presented, you'll see that it is exactly that. Of course, you can use SBV to prove this. First, define the model we were given to make it symbolic: x y x y^(c) Levent ErkokBSD3erkokl@gmail.com experimentalNone Q f _ = Q!val!1 sbvkThis is a variant on the first example, except we also add an axiom for the sort, stating that the domain  R has only one element. In this case the problem naturally becomes unsat. We have:t2 Unsatisfiable  `(c) Levent ErkokBSD3erkokl@gmail.com experimentalNone2g sbv=A "list-like" data type, but one we plan to uninterpret at the SMT level. The actual shape is really immaterial for us, but could be used as a proxy to generate test cases or explore data-space in some other part of a program. Note that we neither rely on the shape of this data, nor need the actual constructors. sbvyAn uninterpreted "classify" function. Really, we only care about the fact that such a function exists, not what it does. sbv_Formulate a query that essentially asserts a cardinality constraint on the uninterpreted sort  '. The goal is to say there are precisely 3 such things, as it might be the case. We manage this by declaring four elements, and asserting that for a free variable of this sort, the shape of the data matches one of these three instances. That is, we assert that all the instances of the data   can be classified into 3 equivalence classes. Then, allSat returns all the possible instances, which of course are all uninterpreted.As expected, we have: allSat genLs Solution #1: l = L!val!0 :: L l0 = L!val!0 :: L l1 = L!val!1 :: L l2 = L!val!2 :: L classify :: L -> Integer classify L!val!2 = 2 classify L!val!1 = 1 classify _ = 0 Solution #2: l = L!val!1 :: L l0 = L!val!0 :: L l1 = L!val!1 :: L l2 = L!val!2 :: L classify :: L -> Integer classify L!val!2 = 2 classify L!val!1 = 1 classify _ = 0 Solution #3: l = L!val!2 :: L l0 = L!val!0 :: L l1 = L!val!1 :: L l2 = L!val!2 :: L classify :: L -> Integer classify L!val!2 = 2 classify L!val!1 = 1 classify _ = 0Found 3 different solutions. sbv Similarly, V's default implementation is sufficient. sbvDeclare instances to make  1 a usable uninterpreted sort. First we need the 21 instance, with the default definition sufficing.  a Levent ErkokBSD3erkokl@gmail.com experimentalNone $79=?@Ax^ sbvHelper type synonym sbvThe concrete counterpart of  2. Again, we can't simply use the duality between SBV a and a due to the difference between SList a and [a]. sbvEThe state of the length program, paramaterized over the element type a sbvThe first input list sbvThe second input list sbvTemporary variable sbvOutput sbv The imperative append algorithm:  zs = [] ts = xs while not (null ts) zs = zs ++ [head ts] ts = tail ts ts = ys while not (null ts) zs = zs ++ [head ts] ts = tail ts sbvGA program is the algorithm, together with its pre- and post-conditions. sbvWe check that zs is xs ++ ys upon termination. correctness!Total correctness is established.Q.E.D. sbvShow instance for  q. The above deriving clause would work just as well, but we want it to be a little prettier here, and hence the OVERLAPS directive. sbv# instance for the program state sbv>Show instance, a bit more prettier than what would be derived: b(c) Levent ErkokBSD3erkokl@gmail.com experimentalNone $45679=?@AH sbvHelper type synonym sbv?The state for the swap program, parameterized over a base type a. sbv Input value sbvOutput sbvThe increment algorithm:  y = x+1 The point here isn't really that this program is interesting, but we want to demonstrate various aspects of WP proofs. So, we take a before and after program to annotate our algorithm so we can experiment later. sbvPrecondition for our program. Strictly speaking, we don't really need any preconditions, but for example purposes, we'll require x to be non-negative. sbvPostcondition for our program: y must x+1. sbv Stability: x must remain unchanged. sbvGA program is the algorithm, together with its pre- and post-conditions. sbvState the correctness with respect to before/after programs. In the simple case of nothing prior/after, we have the obvious proof:correctness Skip Skip!Total correctness is established.Q.E.D. sbv' instance for the program state sbvShow instance for  q. The above deriving clause would work just as well, but we want it to be a little prettier here, and hence the OVERLAPS directive. c(c) Levent ErkokBSD3erkokl@gmail.com experimentalNone $45679=?@A4 sbvHelper type synonym sbv>The state for the sum program, parameterized over a base type a. sbvThe input value sbv Loop counter sbvtracks  fib (i+1) sbvtracks fib i sbv#The imperative fibonacci algorithm: Q i = 0 k = 1 m = 0 while i < n: m, k = k, m + k i++ When the loop terminates, m contains fib(n). sbvSymbolic fibonacci as our specification. Note that we cannot really implement the fibonacci function since it is not symbolically terminating. So, we instead uninterpret and axiomatize it below.ANB. The concrete part of the definition is only used in calls to  = and is not needed for the proof. If you don't need to call  <, you can simply ignore that part and directly uninterpret. sbvqConstraints and axioms we need to state explicitly to tell the SMT solver about our specification for fibonacci. sbvPrecondition for our program: n must be non-negative. sbvPostcondition for our program:  m = fib n sbv(Stability condition: Program must leave n unchanged. sbvGA program is the algorithm, together with its pre- and post-conditions. sbvAWith the axioms in place, it is trivial to establish correctness: correctness!Total correctness is established.Q.E.D.Note that I found this proof to be quite fragile: If you do not get the algorithm right or the axioms aren't in place, z3 simply goes to an infinite loop, instead of providing counter-examples. Of course, this is to be expected with the quantifiers present. sbv' instance for the program state sbvShow instance for  q. The above deriving clause would work just as well, but we want it to be a little prettier here, and hence the OVERLAPS directive.  d(c) Levent ErkokBSD3erkokl@gmail.com experimentalNone $45679=?@A sbvHelper type synonym sbv>The state for the sum program, parameterized over a base type a. sbv First value sbv Second value sbvCopy of x to be modified sbvCopy of y to be modified sbv9The imperative GCD algorithm, assuming strictly positive x and y:  i = x j = y while i != j -- While not equal if i > j i = i - j -- i is greater; reduce it by j else j = j - i -- j is greater; reduce it by i When the loop terminates, i equals j and contains  GCD(x, y). sbvSymbolic GCD as our specification. Note that we cannot really implement the GCD function since it is not symbolically terminating. So, we instead uninterpret and axiomatize it below.ANB. The concrete part of the definition is only used in calls to  = and is not needed for the proof. If you don't need to call  l, you can simply ignore that part and directly uninterpret. In that case, we simply use Prelude's version. sbvkConstraints and axioms we need to state explicitly to tell the SMT solver about our specification for GCD. sbvPrecondition for our program: x and y must be strictly positive sbvPostcondition for our program: i == j and  i = gcd x y sbv(Stability condition: Program must leave x and y unchanged. sbvGA program is the algorithm, together with its pre- and post-conditions. sbvAWith the axioms in place, it is trivial to establish correctness: correctness!Total correctness is established.Q.E.D.Note that I found this proof to be quite fragile: If you do not get the algorithm right or the axioms aren't in place, z3 simply goes to an infinite loop, instead of providing counter-examples. Of course, this is to be expected with the quantifiers present. sbv' instance for the program state sbvShow instance for  q. The above deriving clause would work just as well, but we want it to be a little prettier here, and hence the OVERLAPS directive.  e(c) Levent ErkokBSD3erkokl@gmail.com experimentalNone $45679=?@Al sbvHelper type synonym sbvCThe state for the division program, parameterized over a base type a. sbv The dividend sbv The divisor sbv The quotient sbv The remainder sbv9The imperative division algorithm, assuming non-negative x and strictly positive y:  r = x -- set remainder to x q = 0 -- set quotient to 0 while y <= r -- while we can still subtract r = r - y -- reduce the remainder q = q + 1 -- increase the quotient Note that we need to explicitly annotate each loop with its invariant and the termination measure. For convenience, we take those two as parameters for simplicity. sbvPrecondition for our program: x must non-negative and yD must be strictly positive. Note that there is an explicit call to on in our program to protect against this case, so if we do not have this precondition, all programs will fail. sbvLPostcondition for our program: Remainder must be non-negative and less than y, and it must hold that  x = q*y + r: sbv Stability: x and y must remain unchanged. sbvGA program is the algorithm, together with its pre- and post-conditions. sbvThe invariant is simply that  x = q * y + r holds at all times and r$ is strictly positive. We need the y > 0d part of the invariant to establish the measure decreases, which is guaranteed by our precondition. sbvThe measure. In each iteration r0 decreases, but always remains positive. Since y is strictly positive, r% can serve as a measure for the loop. sbvHCheck that the program terminates and the post condition holds. We have: correctness!Total correctness is established.Q.E.D. sbv' instance for the program state sbvShow instance for  q. The above deriving clause would work just as well, but we want it to be a little prettier here, and hence the OVERLAPS directive.  f(c) Levent ErkokBSD3erkokl@gmail.com experimentalNone $45679=?@A  sbvHelper type synonym sbvCThe state for the division program, parameterized over a base type a. sbv The input sbvThe floor of the square root sbv%Successive squares, as the sum of j's sbvSuccessive odds sbv<The imperative square-root algorithm, assuming non-negative x  sqrt = 0 -- set sqrt to 0 i = 1 -- set i to 1, sum of j's so far j = 1 -- set j to be the first odd number i while i <= x -- while the sum hasn't exceeded x yet sqrt = sqrt + 1 -- increase the sqrt j = j + 2 -- next odd number i = i + j -- running sum of j's Note that we need to explicitly annotate each loop with its invariant and the termination measure. For convenience, we take those two as parameters for simplicity. sbvPrecondition for our program: x? must be non-negative. Note that there is an explicit call to on in our program to protect against this case, so if we do not have this precondition, all programs will fail. sbv#Postcondition for our program: The sqrt' squared must be less than or equal to x, and sqrt+1 squared must strictly exceed x. sbv(Stability condition: Program must leave x unchanged. sbvGA program is the algorithm, together with its pre- and post-conditions. sbv4The invariant is that at each iteration of the loop sqrt8 remains below or equal to the actual square-root, and i9 tracks the square of the next value. We also have that j is the sqrt'th odd value. Coming up with this invariant is not for the faint of heart, for details I would strongly recommend looking at Manna's seminal "Mathematical Theory of Computation book (chapter 3). The j .> 0. part is needed to establish the termination. sbvThe measure. In each iteration i4 strictly increases, thus reducing the differential x - i sbvHCheck that the program terminates and the post condition holds. We have: correctness!Total correctness is established.Q.E.D. sbv' instance for the program state sbvShow instance for  q. The above deriving clause would work just as well, but we want it to be a little prettier here, and hence the OVERLAPS directive.                    g(c) Levent ErkokBSD3erkokl@gmail.com experimentalNone$79=?@A- sbvHelper type synonym sbvThe concrete counterpart to  !6. Note that we can no longer use the duality between SBV a and aK as in other examples and just use one datatype for both. This is because SList a and [a] are fundamentally different types. This can be a bit confusing at first, but the point is that it is the list that is symbolic in case of an SList a, not that we have a concrete list with symbolic elements in it. Subtle difference, but it is important to keep these two separate. !sbvEThe state of the length program, paramaterized over the element type a #sbvThe input list $sbv Copy of input %sbvRunning length &sbv The imperative length algorithm: L ys = xs l = 0 while not (null ys) l = l+1 ys = tail ys Note that we need to explicitly annotate each loop with its invariant and the termination measure. For convenience, we take those two as parameters, so we can experiment later. 'sbv>Precondition for our program. Nothing! It works for all lists. (sbvPostcondition for our program: l& must be the length of the input list. )sbv(Stability condition: Program must leave xs unchanged. *sbvGA program is the algorithm, together with its pre- and post-conditions. +sbvThe invariant simply relates the length of the input to the length of the current suffix and the length of the prefix traversed so far. ,sbv'The measure is obviously the length of ys1, as we peel elements off of it through the loop. -sbvWe check that l! is the length of the input list xs upon termination. Note that even though this is an inductive proof, it is fairly easy to prove with our SMT based technology, which doesn't really handle induction at all! The usual inductive proof steps are baked into the invariant establishment phase of the WP proof. We have: correctness!Total correctness is established.Q.E.D. .sbvIShow instance: A simplified version of what would otherwise be generated. /sbv'We have to write the bijection between  ! and  B explicitly. Luckily, the definition is more or less boilerplate. 0sbv@Show instance: Similarly, we want to be a bit more concise here.   ! " $ # % & ' ( ) * + , - ! " $ # %   & ' ( ) * + , -h(c) Levent ErkokBSD3erkokl@gmail.com experimentalNone $45679=?@AW 3sbvHelper type synonym 4sbv>The state for the sum program, parameterized over a base type a. 6sbvThe input value 7sbv Loop counter 8sbv Running sum 9sbv#The imperative summation algorithm: ; i = 0 s = 0 while i < n i = i+1 s = s+i Note that we need to explicitly annotate each loop with its invariant and the termination measure. For convenience, we take those two as parameters, so we can experiment later. :sbvPrecondition for our program: n? must be non-negative. Note that there is an explicit call to on in our program to protect against this case, so if we do not have this precondition, all programs will fail. ;sbvPostcondition for our program: s5 must be the sum of all numbers up to and including n. <sbv(Stability condition: Program must leave n unchanged. =sbvGA program is the algorithm, together with its pre- and post-conditions. >sbv&Check that the program terminates and s equals  n*(n+1)/26 upon termination, i.e., the sum of all numbers upto n . Note that this only holds if n >= 0B to start with, as guaranteed by the precondition of our program.#The correct termination measure is n-i9: It goes down in each iteration provided we start with n >= 0 and it always remains non-negative while the loop is executing. Note that we do not need a lexicographic measure in this case, hence we simply return a list of one element.<The correct invariant is a conjunction of two facts. First, s& is equivalent to the sum of numbers 0 upto i-. This clearly holds at the beginning when  i = s = 0Q, and is maintained in each iteration of the body. Second, it always holds that i <= n{ as long as the loop executes, both before and after each execution of the body. When the loop terminates, it holds that i = n. Since the invariant says s3 is the sum of all numbers up to but not including i, we conclude that s/ is the sum of all numbers up to and including n, as requested.Note that coming up with this invariant is neither trivial, nor easy to automate by any means. What SBV provides is a way to check that your invariant and termination measures are correct, not a means of coming up with them in the first place.We have::set -XNamedFieldPunsBlet invariant SumS{n, i, s} = s .== (i*(i+1)) `sDiv` 2 .&& i .<= n%let measure SumS{n, i} = [n - i]$correctness invariant (Just measure)!Total correctness is established.Q.E.D. ?sbv' instance for the program state @sbvShow instance for  4q. The above deriving clause would work just as well, but we want it to be a little prettier here, and hence the OVERLAPS directive. 3 4 5 6 7 8 9 : ; < = > 4 5 6 7 8 3 9 : ; < = > ipiqirisitiuiviwixiyizi{i|i}i~iiiiiiiiiiiiiiiiiiiiZi[iWiXiTiOiiiiViiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiRippppppqrrvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvwwwwwwwwzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz z z z z {{{{{||||||||||||||| |!|"|#|$|$|%|&|'|(|)|*|+|,|-|-|.|/|0|1|2|2|\|3|4|5|6|c|7|8|9|:|;|<|=|>|?|@|A|B|]|C|D|E|F|G|H|I|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|W|X|Y|Z||[|\|]|^|^|_|`|a|b|c|d|e|f|g|h|i|j|k|l|m|m|n|o|p|q|r|s|t|u|v|w|x|y|z|{||||}|~||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| | | | | ||||||||||||||||||||||||||||| |!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijkllmnnopqrstuvwxyz{|}~UYSjhgfdlmkQPoln     ~}b !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQ    "#%&()+,./124?RSTUVWXYZ[\]^_`abcdefghijkBl m n o p q r s t u v w x y z { | } ~                                                                                                                                        FFFFFFFF FGFeFIFKF!F"F#F$F%F&'()*+,-./0123456789:;<=L>L?L@LALBLCLDLELFLGLHLILJLKLLLMLxLyLLNLOLPLQLRLSLTLULVLWLXLYLZL[L\L]L^L_  `abcdefghijklmnopqrstuvwxyz{|}~MMMMNNPNoNQNNNlNNNNNNNNNNnNNNNNNNNNNNNNmNNNkNNN^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^```_`aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa a a a a aaaaaaaGaHaeaaaaaaaaaaaaaIaJaKa a!a"a#a$a%a&a'a(a)a*a+a,a-a.a/a0a1a2a3a4a5a6a7a8a9a:a;a<a=a>aiaja?aBaCaD      !"#$%&'()*+,-./0123456789:;<=>>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~  !!!!!!"""""###$$$$$%%%&&&_&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&'''''''''''''(((((((((((((((((((((((((((((((((((((()))))********+_+++ + + + + +++++++++++++,,-... /w/!/"//#/$/%/&/'/(/)/*/+/,/-/.//00010203041516272828292:2:2;2<22=2>2?2@2A2B2C2D2E2F2G2H2I2J2K2L3M3N3O44P4Q4R4S4T4U5V6W7X7W8Y8Z8[8\8]8^88_8`8a8b8c8d8e8f8g8h8i8j8k8l8m9:;n<o===p=q==r=s=t=u=v=w=x=y>>>z>{>|>}>~>t>v>>>w>x>y???p?q????r?s?????t?v?w?x?y@@@@z@}@@t@v@@@w@x@yAYAAAAAAAAAAAABBBBBBBBBBCCCCDEEEFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFGGGGGGGGGGGGGGGGGGHHHHHHHHHHHHWHHHHHHHHIJJJJJJJJKKKLMMMMMMMMMMMM M M M M NNNNNNCNNNNNNNNNNNNNN N!N"N#N$N%N&N'NNN(N)N*N+N,N-N.N/N0N1NUN2N3N4N5N6N7N8N9N:NN;N<N=N>N?N@NANBNCNDNrNENqOFOGPHPIQJQKQLQGQMQNQOQPRYRQRRRSRTRURVRWR`RXRfRgRhRiRjRkRlRmSYSSSSZS[S\S]S^S_S`SaSbScSdSeSfSgShS"SiSjSkSlSmSnSoSpSqSrSSsStSuSvSwSxSySzS{T|T}U~UVVWWWW XXXXXXXpXXXXXXXXXYYYYYYYYYmYmYYYYYYYYYYYYYYYYYYYYYYYYYYYYpYYYYYYYYrYsYYYYYYYYYYYYYYYYYYYYYYZZZZ[["["[[[[[[[[[[[[[[\\]]^^^^^^^^^^^^____________````````````a!aaaaaaaaaaa|aaaa a b b b bpbqbb b b b b|b b b b b b b b cjc c c}czc{c|cc c c c c c c|c c c c c c c c d@d d dpdqdzd dd d d d d d d|d !d "d #d $d %d &d 'd (e )e *e *epeqe +e ,ee e e e -e .e /e|e 0e 1e 2e 3e 4e 5e 6e 7ff 8f 8fpf 9fzf ff f f f :f .f /f|f ;f <f =f >f ?f @f Af Bgg Cg Cg Dg Dggg Egg g g g Fg .g /g|g Gg Hg Ig Jg Khh Lh Lh}hzhhh h h h Mh|h Nh Oh Ph Qh Rh Sh Th Ui V W X Yi Zi [p \p ]p ^p _p `p a b c d b e f b e gp hp i W X jr k l m nr o l p nr q l r sr t l u vr wu xu yu zu {u |u }u ~u u u u u b v v v v v v v v v z z W  z z z z z z z z W  z z z z z z z  | | | | | | | | | | | | | | b  || | | | | | | | | | | | | | | | | | | | | W X | | | || | | | ||| | | | | | | | b  b b | | | | | | | | | W W | | | | | |_| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |         ! " # $ % &z ' ( ) * + , b - . / 0 1 2 3 4 5" b  6 b e 7 W X 8 W X 9 W X : W X ; b < b < b < = b < > ? @ b A B C D E F G H I J K L M N O P Q R S T U V W X Y Z [ \ ] ^ _ ` a b c d e f g h i j k l m n o p q r s t u v W X w x y z { | } ~  b  b  b  b  b  b  b  b  }~     b  b c b c b  b c b c b c b c b b b W X W W     !$'*-0356789:;<=>ij    ' (   b c  b b b b     CD                                     ! " # $ % & ' b < ( b  ) ! " # $ % & 'F *F +FHFJF ,F -F .F /F 0F 1F 2F 3F 4F 5F 6F 7 b  8F 9F :F ;F <F =F >F ?F @F AF BF CF DF EF FF GF HF IF JF KF LF MF NF OF P Q RL SL TL $L %L UL &L VL !L WL "L XL YL #L ZL [L \L ] ! $ ^NNNN b _ `NNNNNNNNNN^ a` b` c` d` e` f` g` h` i` j` k` l` m` n` o` pa qa ra sa taadaaaaaaaa ua v b c w W X x b y z b { b | b } b ~ b  b b b b b b b b b b b b b b b b b b b b b b c b c b c  C      b  sbv-8.7-DbQHjiKtor73WzWR2O4MT3Data.SBV.TransData.SBV.Trans.ControlData.SBV.InternalsData.SBVData.SBV.ControlData.SBV.RegExpData.SBV.DynamicData.SBV.Tools.GenTestData.SBV.TupleData.SBV.Tools.STreeData.SBV.Tools.OverflowData.SBV.String Data.SBV.SetData.SBV.Maybe Data.SBV.ListData.SBV.EitherData.SBV.Tools.Polynomial Data.SBV.CharData.SBV.Tools.CodeGen#Data.SBV.Tools.WeakestPreconditionsData.SBV.Tools.RangeData.SBV.Tools.InductionData.SBV.Tools.BoundedListData.SBV.Tools.BoundedFixData.SBV.Tools.BMC/Documentation.SBV.Examples.BitPrecise.BitTricks2Documentation.SBV.Examples.BitPrecise.BrokenSearch,Documentation.SBV.Examples.BitPrecise.Legato/Documentation.SBV.Examples.BitPrecise.MergeSort.Documentation.SBV.Examples.BitPrecise.MultMask/Documentation.SBV.Examples.BitPrecise.PrefixSum0Documentation.SBV.Examples.CodeGeneration.AddSub2Documentation.SBV.Examples.CodeGeneration.CRC_USB53Documentation.SBV.Examples.CodeGeneration.Fibonacci-Documentation.SBV.Examples.CodeGeneration.GCD9Documentation.SBV.Examples.CodeGeneration.PopulationCount7Documentation.SBV.Examples.CodeGeneration.Uninterpreted%Documentation.SBV.Examples.Crypto.AES%Documentation.SBV.Examples.Crypto.RC4%Documentation.SBV.Examples.Crypto.SHA5Documentation.SBV.Examples.Existentials.CRCPolynomial3Documentation.SBV.Examples.Existentials.Diophantine-Documentation.SBV.Examples.Lists.BoundedMutex*Documentation.SBV.Examples.Lists.Fibonacci'Documentation.SBV.Examples.Lists.Nested)Documentation.SBV.Examples.Misc.Auxiliary)Documentation.SBV.Examples.Misc.Enumerate(Documentation.SBV.Examples.Misc.Floating,Documentation.SBV.Examples.Misc.ModelExtract(Documentation.SBV.Examples.Misc.Newtypes&Documentation.SBV.Examples.Misc.NoDiv0+Documentation.SBV.Examples.Misc.Polynomials*Documentation.SBV.Examples.Misc.SetAlgebra-Documentation.SBV.Examples.Misc.SoftConstrain%Documentation.SBV.Examples.Misc.Tuple1Documentation.SBV.Examples.Optimization.Enumerate0Documentation.SBV.Examples.Optimization.ExtField1Documentation.SBV.Examples.Optimization.LinearOpt2Documentation.SBV.Examples.Optimization.Production*Documentation.SBV.Examples.Optimization.VM)Documentation.SBV.Examples.ProofTools.BMC/Documentation.SBV.Examples.ProofTools.Fibonacci0Documentation.SBV.Examples.ProofTools.Strengthen)Documentation.SBV.Examples.ProofTools.Sum+Documentation.SBV.Examples.Puzzles.Birthday(Documentation.SBV.Examples.Puzzles.Coins)Documentation.SBV.Examples.Puzzles.Counts.Documentation.SBV.Examples.Puzzles.DogCatMouse+Documentation.SBV.Examples.Puzzles.Euler185'Documentation.SBV.Examples.Puzzles.Fish)Documentation.SBV.Examples.Puzzles.Garden,Documentation.SBV.Examples.Puzzles.HexPuzzle0Documentation.SBV.Examples.Puzzles.LadyAndTigers.Documentation.SBV.Examples.Puzzles.MagicSquare*Documentation.SBV.Examples.Puzzles.NQueens0Documentation.SBV.Examples.Puzzles.SendMoreMoney)Documentation.SBV.Examples.Puzzles.Sudoku+Documentation.SBV.Examples.Puzzles.U2Bridge)Documentation.SBV.Examples.Queries.AllSat,Documentation.SBV.Examples.Queries.CaseSplit.Documentation.SBV.Examples.Queries.Concurrency(Documentation.SBV.Examples.Queries.Enums,Documentation.SBV.Examples.Queries.FourFours.Documentation.SBV.Examples.Queries.GuessNumber/Documentation.SBV.Examples.Queries.Interpolants,Documentation.SBV.Examples.Queries.UnsatCore1Documentation.SBV.Examples.Strings.RegexCrossword/Documentation.SBV.Examples.Strings.SQLInjection4Documentation.SBV.Examples.Transformers.SymbolicEval,Documentation.SBV.Examples.Uninterpreted.AUF/Documentation.SBV.Examples.Uninterpreted.Deduce1Documentation.SBV.Examples.Uninterpreted.Function1Documentation.SBV.Examples.Uninterpreted.Multiply0Documentation.SBV.Examples.Uninterpreted.Shannon-Documentation.SBV.Examples.Uninterpreted.Sort5Documentation.SBV.Examples.Uninterpreted.UISortAllSat6Documentation.SBV.Examples.WeakestPreconditions.Append6Documentation.SBV.Examples.WeakestPreconditions.Basics3Documentation.SBV.Examples.WeakestPreconditions.Fib3Documentation.SBV.Examples.WeakestPreconditions.GCD6Documentation.SBV.Examples.WeakestPreconditions.IntDiv7Documentation.SBV.Examples.WeakestPreconditions.IntSqrt6Documentation.SBV.Examples.WeakestPreconditions.Length3Documentation.SBV.Examples.WeakestPreconditions.SumData.SBV.Control.TypessetLogiccheckSatcheckSatAssuminggetValue getUnsatCoregetUnknownReasonData.SBV.Core.AlgRealsData.SBV.SMT.SMTLibNamesData.SBV.Utils.ExtractIOControl.ConcurrentcatchesData.SBV.Utils.LibData.SBV.Core.KindData.SBV.Utils.NumericfpMinfpMaxData.SBV.Core.ConcreteData.SBV.Utils.TDiffData.SBV.Core.Symbolicz3yicescvc4 boolectormathSATallSatsatSymbolicQuerymatchRegExpMatchable svToSymSVgenTestsWordNsWordN_sIntNsIntN_ runSymbolicaddNewSMTOptionimposeConstraintaddSValOptGoal outputSVal Data.BitsBitsData.SBV.Core.OperationsData.SBV.Core.Dataabc newArray_newArraymkSymValforallforall_ mkForallVarsexistsexists_ mkExistVarsfreefree_ mkFreeVarssymbolic symbolicsoutputtimeOutDataSetmkSymSBV sbvToSymSW EqSymbolicData.SBV.Utils.SExprData.SBV.Utils.PrettyNumData.SBV.SMT.UtilsData.SBV.SMT.SMTLib2 registerKindData.SBV.SMT.SMTLibData.SBV.SMT.SMToptimizesafeproveData.SBV.Provers.Z3Data.SBV.Provers.YicesData.SBV.Provers.MathSATData.SBV.Provers.CVC4Data.SBV.Provers.BoolectorData.SBV.Provers.ABCData.SBV.Control.UtilssAssertiomodifyQueryState inNewContext freshVar_freshVar freshArray_ freshArray queryDebugasksendretrieveResponse getFunctiongetUninterpretedValue getValueCVgetUIFunCVAssoc checkSatUsingobservegetUIsgetUnsatAssumptionstimeout unexpected executeQueryQueryTData.SBV.Control.QuerygetInfo ensureSat getSMTResultgetLexicographicOptResultsgetIndependentOptResultsgetParetoOptResultsgetModel$checkSatAssumingWithUnsatisfiableSetgetAssertionStackDepthinNewAssertionStackpushpop caseSplitresetAssertionsechoexitgetProofgetInterpolantMathSATgetInterpolantZ3 getAssertions getAssignment mkSMTResultData.SBV.Provers.ProversName_sNamesafeWithforAll_forAllforSome_forSome proveWithsatWith allSatWith optimizeWith isVacuous isVacuousWith isTheorem isTheoremWith isSatisfiableisSatisfiableWithrunSMT runSMTWithData.SBV.Core.ModelStatusfpIsEqualObject genMkSymVarsBoolsBool_sBoolssWord8sWord8_sWord8ssWord16sWord16_sWord16ssWord32sWord32_sWord32ssWord64sWord64_sWord64ssInt8sInt8_sInt8ssInt16sInt16_sInt16ssInt32sInt32_sInt32ssInt64sInt64_sInt64ssInteger sInteger_ sIntegerssRealsReal_sRealssFloatsFloat_sFloatssDoublesDouble_sDoublessCharsChar_sCharssStringsString_sStringssListsList_sListssTuplesTuple_sTuplessEithersEither_sEitherssMaybesMaybe_sMaybessSetsolveGGenericsassertWithPenaltyminimizemaximizecardData.SBV.Core.SizedsWordsWord_sIntsInt_sIntsData.SBV.Core.FloatingData.SBV.ClientData.SBV.Control.BaseIOProduceUnsatCores getOptiongetObservablesUnsat setOptionProduceUnsatAssumptionsnamedConstraint OptionKeyword ProduceProofsProduceInterpolantsconstrainWithAttributeProduceAssertionsProduceAssignmentsverboseredirectVerboseData.SBV.Compilers.CodeGen compileToCLibData.SBV.Compilers.CData.SBV.Client.BaseIO defaultSMTCfgallSatMaxModelCount sbvToSymSVsWordsSEitherSMaybeSSetsSet_sSets Data.SBV.SMTgetModelDictionaries Control.MonadwhenabortLogicAUFLIAAUFLIRAAUFNIRALRAQF_ABVQF_AUFBV QF_AUFLIAQF_AXQF_BVQF_IDLQF_LIAQF_LRAQF_NIAQF_NRAQF_RDLQF_UFQF_UFBVQF_UFIDLQF_UFLIAQF_UFLRAQF_UFNRA QF_UFNIRAUFLRAUFNIAQF_FPBVQF_FPQF_FDQF_S Logic_ALL Logic_NONE CustomLogic SMTOptionDiagnosticOutputChannel RandomSeedReproducibleResourceLimit SMTVerbositySetLogicSetInfoSMTInfoResponseResp_UnsupportedResp_AllStatisticsResp_AssertionStackLevels Resp_Authors Resp_Error Resp_NameResp_ReasonUnknown Resp_VersionResp_InfoKeywordSMTReasonUnknown UnknownMemOutUnknownIncompleteUnknownTimeOut UnknownOtherSMTErrorBehaviorErrorImmediateExitErrorContinuedExecution SMTInfoFlag AllStatisticsAssertionStackLevelsAuthors ErrorBehaviorName ReasonUnknownVersion InfoKeywordCheckSatResultSatUnk AlgRealPolyAlgReal AlgRational AlgPolyRootalgRealToRationalsmtLibReservedNames ExtractIO extractIOHasKindkindOfhasSign intSizeOf isBoolean isBoundedisRealisFloatisDouble isUnboundedisUninterpretedisCharisStringisListisSetisTupleisMaybeisEithershowTypeKindKBoolKBounded KUnboundedKRealKUninterpretedKFloatKDoubleKCharKStringKListKSetKTupleKMaybeKEitherfpMaxHfpMinHfp2fpfpRemHfpRoundToIntegralHfpIsEqualObjectHfpCompareObjectHfpIsNormalizedHExtCVInfiniteEpsilonInterval BoundedCVAddExtCVMulExtCV GeneralizedCV ExtendedCV RegularCVCV_cvKindcvValCValCAlgRealCIntegerCFloatCDoubleCCharCStringCListCSet CUserSortCTupleCMaybeCEitherRCSet RegularSet ComplementSet isRegularCV cvSameTypecvToBoolnormCVfalseCVtrueCVliftCV2mapCVmapCV2 mkConstCVTimingNoTiming PrintTiming SaveTiming showTDiff QueryContext QueryInternal QueryExternal SMTSolvername executable preprocessoptionsengine capabilitiesSolverZ3Yices BoolectorCVC4MathSATABC SMTScript scriptBody scriptModel SMTResult Unsatisfiable Satisfiable SatExtFieldUnknown ProofErrorSMTModelmodelObjectives modelBindings modelAssocs modelUIFuns SMTConfigtiming printBase printRealPrecsatCmdallSatPrintAlong satTrackUFs isNonModelVar validateModeloptimizeValidateConstraints transcript smtLibVersionsolverallowQuantifiedQueries roundingModesolverSetOptionsignoreExitCode RoundingModeRoundNearestTiesToEvenRoundNearestTiesToAwayRoundTowardPositiveRoundTowardNegativeRoundTowardZeroSolverCapabilitiessupportsQuantifierssupportsUninterpretedSortssupportsUnboundedInts supportsRealssupportsApproxRealssupportsIEEE754 supportsSetssupportsOptimizationsupportsPseudoBooleanssupportsCustomQueriessupportsGlobalDeclssupportsDataTypessupportsFlattenedModels SMTLibPgm SMTLibVersionSMTLib2Cached SymbolicT MonadSymbolic symbolicEnvSValState SBVRunModeSMTModeCodeGenConcreteIStageISetupISafeIRun ArrayInfo ArrayContext ArrayFree ArrayMutate ArrayMergeResultreskinds resTracesresObservables resUISegs resInputs resConsts resTables resArrays resUIConsts resAxiomsresAsgnsresConstraints resAssertions resOutputs QueriablecreateprojectembedFreshfresh runQueryT MonadQuery queryState QueryStatequeryAsk querySendqueryRetrieveResponse queryConfigqueryTerminatequeryTimeOutValuequeryAssertionStackDepth ObjectiveMinimizeMaximizeAssertWithPenaltyPenaltyDefaultPenalty OptimizeStyle Lexicographic IndependentPareto NamedSymVarSBVPgmpgmAssignmentsSBVExprSBVAppSBVType QuantifierALLEXSeqOp SeqConcatSeqLenSeqUnitSeqNth SeqSubseq SeqIndexOf SeqContains SeqPrefixOf SeqSuffixOf SeqReplaceRegExpLiteralAllNoneRangeConcKStarKPlusOptLoopUnionInterStrOp StrConcatStrLenStrUnitStrNth StrSubstr StrIndexOf StrContains StrPrefixOf StrSuffixOf StrReplace StrStrToNat StrNatToStrStrInRePBOp PB_AtMost PB_AtLeast PB_ExactlyPB_LePB_GePB_EqFPOpFP_CastFP_ReinterpretFP_AbsFP_NegFP_AddFP_SubFP_MulFP_DivFP_FMAFP_SqrtFP_RemFP_RoundToIntegralFP_MinFP_Max FP_ObjEqual FP_IsNormalFP_IsSubnormal FP_IsZero FP_IsInfiniteFP_IsNaN FP_IsNegative FP_IsPositiveOpPlusTimesMinusUNegAbsQuotRemEqualNotEqualLessThan GreaterThanLessEq GreaterEqIteAndOrXOrNotShlShrRolRorExtractJoinLkUpArrEqArrReadKindCast UninterpretedLabelIEEEFP PseudoBoolean OverflowOpSetOpTupleConstructor TupleAccessEitherConstructorEitherIs EitherAccessMaybeConstructorMaybeIs MaybeAccessSVNodeId forceSVArgfalseSVtrueSVneedsExistentials isCodeGenMode inSMTModesvUninterpretednewUninterpretedinternalVariable getTableIndexnewExpr svMkSymVarextractSymbolicSimulationStateinternalConstraintcacheuncache uncacheAIsmtLibVersionExtensionSFunArrSArrsvTruesvFalsesvBool svIntegersvFloatsvDoublesvRealsvAsBool svAsInteger svNumerator svDenominatorsvEnumFromThenTosvPlussvTimessvMinussvUNegsvAbssvDividesvExp svBlastLEsvSetBit svBlastBE svWordFromLE svWordFromBE svAddConstant svIncrement svDecrementsvQuotsvRem svQuotRemsvEqual svNotEqual svLessThan svGreaterThansvLessEq svGreaterEqsvAndsvOrsvXOrsvNotsvShlsvShrsvRolsvRor svExtractsvJoinsvIte svLazyItesvSymbolicMergesvSelectsvSignsvUnsignsvFromIntegral svToWord1 svFromWord1 svTestBit svShiftLeft svShiftRight svRotateLeftsvBarrelRotateLeftsvBarrelRotateRight svRotateRightreadSArr writeSArr mergeSArrnewSArreqSArr readSFunArr writeSFunArr mergeSFunArr newSFunArrsvStructuralLessThan SFunArray unSFunArraySArrayunSArraySymArray readArray writeArray mergeArraysnewArrayInStateSymValliteralfromCV isConcretely unliteral isConcrete isSymbolic Outputtable SolverContext constrain softConstrainsetInfoaddAxiom setTimeOut contextState SRoundingMode SMTProblem smtLibPgmSTuple8STuple7STuple6STuple5STuple4STuple3STuple2STupleSListSStringSCharSDoubleSFloatSRealSIntegerSInt64SInt32SInt16SInt8SWord64SWord32SWord16SWord8SBoolSBVunSBVgetPathConditionextendPathConditionnaninfinitysNaN sInfinitysTruesFalsesNot.&&.||.<+>.~&.~|.=>.<=>fromBoolsAndsOrsAnysAllsRoundNearestTiesToEvensRoundNearestTiesToAwaysRoundTowardPositivesRoundTowardNegativesRoundTowardZerosRNEsRNAsRTPsRTNsRTZsbvToSV PrettyNumhexSbinShexPbinPhexbinshexchexshexIsbinsbinIreadBin showCFloat showCDouble showHFloat showHDouble showSMTFloat showSMTDoublesmtRoundingMode cvToSMTLib mkSkolemZero TestStyleHaskellCForte TestVectors getTestValues renderTest SBVExceptionsbvExceptionDescriptionsbvExceptionSentsbvExceptionExpectedsbvExceptionReceivedsbvExceptionStdOutsbvExceptionStdErrsbvExceptionExitCodesbvExceptionConfigsbvExceptionReasonsbvExceptionHint Modelable modelExistsgetModelAssignmentgetModelDictionary getModelValuegetModelUninterpretedValue extractModelgetModelObjectivesgetModelObjectiveValuegetModelUIFunsgetModelUIFunValueSatModelparseCVscvtModelOptimizeResultLexicographicResult ParetoResultIndependentResult SafeResult AllSatResult SatResult ThmResultgenParse extractModelsgetModelValuesgetModelUninterpretedValues displayModels showModelregisterUISMTFunction|->query SExecutableProvable MProvablevalidateGoal Predicate proveWithAll proveWithAny satWithAll satWithAnysatConcurrentWithAnyproveConcurrentWithAnysatConcurrentWithAllproveConcurrentWithAllgenerateSMTBenchmarkisSafeEquality===Metric MetricSpace toMetricSpacefromMetricSpace msMinimize msMaximize uninterpret cgUninterpretsbvUninterpret Mergeable symbolicMergeselect SDivisiblesQuotRemsDivModsQuotsRemsDivsMod SFiniteBitssFiniteBitSizelsbmsbblastBEblastLE fromBitsBE fromBitsLEsTestBit sExtractBits sPopCountsetBitTo fullAdderfullMultipliersCountLeadingZerossCountTrailingZeros SIntegral OrdSymbolic.<.<=.>.>=sminsmaxinRange.==./=.===./==distinctdistinctExceptallEqualsElemsNotElemSymTuple genLiteral genFromCVsRealToSIntegerlabel observeIfsObserveoneIfpbAtMost pbAtLeast pbExactlypbLepbGepbEq pbMutexedpbStronglyMutexed.^ sFromIntegral sShiftLeft sShiftRightsSignedShiftArithRight sRotateLeftsBarrelRotateLeft sRotateRightsBarrelRotateRightliftQRemliftDModiteiteLazy sbvQuickCheckuntupletuple^._1_2_3_4_5_6_7_8$fMetric(,,,,,,,)$fMetric(,,,,,,)$fMetric(,,,,,)$fMetric(,,,,) $fMetric(,,,) $fMetric(,,) $fMetric(,)$fHasField"_8"h(,,,,,,,)$fHasField"_7"g(,,,,,,,)$fHasField"_7"g(,,,,,,)$fHasField"_6"f(,,,,,,,)$fHasField"_6"f(,,,,,,)$fHasField"_6"f(,,,,,)$fHasField"_5"e(,,,,,,,)$fHasField"_5"e(,,,,,,)$fHasField"_5"e(,,,,,)$fHasField"_5"e(,,,,)$fHasField"_4"d(,,,,,,,)$fHasField"_4"d(,,,,,,)$fHasField"_4"d(,,,,,)$fHasField"_4"d(,,,,)$fHasField"_4"d(,,,)$fHasField"_3"c(,,,,,,,)$fHasField"_3"c(,,,,,,)$fHasField"_3"c(,,,,,)$fHasField"_3"c(,,,,)$fHasField"_3"c(,,,)$fHasField"_3"c(,,)$fHasField"_2"b(,,,,,,,)$fHasField"_2"b(,,,,,,)$fHasField"_2"b(,,,,,)$fHasField"_2"b(,,,,)$fHasField"_2"b(,,,)$fHasField"_2"b(,,)$fHasField"_2"b(,)$fHasField"_1"a(,,,,,,,)$fHasField"_1"a(,,,,,,)$fHasField"_1"a(,,,,,)$fHasField"_1"a(,,,,)$fHasField"_1"a(,,,)$fHasField"_1"a(,,)$fHasField"_1"a(,)$fTuple(,,,,,,,)(,,,,,,,)$fTuple(,,,,,,)(,,,,,,)$fTuple(,,,,,)(,,,,,)$fTuple(,,,,)(,,,,)$fTuple(,,,)(,,,)$fTuple(,,)(,,) $fTuple(,)(,)STree readSTree writeSTreemkSTree$fMergeableSTreeInternal$fShowSTreeInternalCheckedArithmetic+!-!*!/! negateChecked ArithOverflowbvAddObvSubObvMulO bvMulOFastbvDivObvNegOsFromIntegralOsFromIntegralChecked$fArithOverflowSVal$fArithOverflowSBV$fArithOverflowSBV0$fArithOverflowSBV1$fArithOverflowSBV2$fArithOverflowSBV3$fArithOverflowSBV4$fArithOverflowSBV5$fArithOverflowSBV6$fCheckedArithmeticInt64$fCheckedArithmeticInt32$fCheckedArithmeticInt16$fCheckedArithmeticInt8$fCheckedArithmeticWord64$fCheckedArithmeticWord32$fCheckedArithmeticWord16$fCheckedArithmeticWord8lengthnullheadtailunconsinit singleton strToStrAt strToCharAt.!!implode.:snocnilconcat.++ isInfixOf isPrefixOf isSuffixOftakedropsubStrreplaceindexOf offsetIndexOfstrToNatnatToStremptyfull universalfromList complementinsertdeletemember notMemberisEmptyisFull isUniversalhasSize isSubsetOfisProperSubsetOfdisjointunionunions intersection intersections difference\\sNothing isNothingsJustisJust fromMaybefromJust liftMaybemapmaybe listToListAtelemAtelemnotElemsubListsLeftisLeftsRightisRight liftEithereitherbimapfirstsecondfromLeft fromRight ByteConvertertoBytes fromBytesSIntIntN IsNonZeroSWordWordN bvExtract# zeroExtend signExtendbvDropbvTake Polynomial polynomialpAddpMultpDivpModpDivModshowPolyshowPolynomialaddPolyitesmdpcrcBVcrc$fPolynomialSBV$fPolynomialSBV0$fPolynomialSBV1$fPolynomialSBV2$fPolynomialSBV3$fPolynomialWord64$fPolynomialWord32$fPolynomialWord16$fPolynomialWord8IEEEFloatConvertible fromSFloattoSFloat fromSDouble toSDouble IEEEFloatingfpAbsfpNegfpAddfpSubfpMulfpDivfpFMAfpSqrtfpRemfpRoundToIntegral fpIsNormal fpIsSubnormalfpIsZero fpIsInfinitefpIsNaN fpIsNegative fpIsPositivefpIsNegativeZerofpIsPositiveZero fpIsPointsFloatAsSWord32sDoubleAsSWord64 blastSFloat blastSDoublesWord32AsSFloatsWord64AsSDoublesFloatAsComparableSWord32sDoubleAsComparableSWord64ordchrtoLowertoUpper digitToInt intToDigit isControlisSpaceisLowerisUpperisAlpha isAlphaNumisPrintisDigit isOctDigit isHexDigitisLetterisMarkisNumber isPunctuationisSymbol isSeparatorisAsciiisLatin1 isAsciiLetter isAsciiUpper isAsciiLowerexactlyoneOfnewlinetabwhiteSpaceNoNewLine whiteSpace punctuation asciiLetter asciiLower asciiUpperdigitoctDigithexDigitdecimaloctal hexadecimalfloating identifier$fRegExpMatchableSBV$fRegExpMatchableSBV0sbvCheckSolverInstallationdefaultSolverConfigsbvAvailableSolversmkSymbolicEnumeration CgPgmKind CgMakefileCgHeaderCgSourceCgDriver CgPgmBundle CgSRealTypeCgFloatCgDouble CgLongDouble SBVCodeGenCgStatecgInputs cgOutputs cgReturns cgPrototypescgDecls cgLDFlags cgFinalConfigCgValCgAtomicCgArrayCgConfigcgRTC cgIntegercgReal cgDriverVals cgGenDriver cgGenMakefilecgIgnoreAssertscgOverwriteGenerated cgShowU8InHexCgTarget targetName translatedefaultCgConfig initCgStatecgSym cgPerformRTCs cgIntegerSize cgSRealTypecgGenerateDrivercgGenerateMakefilecgSetDriverValuescgIgnoreSAssertcgAddPrototypecgOverwriteFilescgShowU8UsingHex cgAddDecl cgAddLDFlags svCgInput svCgInputArr svCgOutput svCgOutputArr svCgReturn svCgReturnArrcgInput cgInputArrcgOutput cgOutputArrcgReturn cgReturnArr isCgDriver isCgMakefilecodeGenrenderCgPgmBundle compileToC compileToC'compileToCLib'sendStringToSolverretrieveResponseFromSolversendRequestToSolvertoSizedToSized fromSized FromSizedGoodStuckWPConfigwpSolver wpVerbose ProofResultProven IndeterminateFailedVCBadPreconditionBadPostconditionUnstableAbortReachable InvariantPreInvariantMaintain MeasureBoundMeasureDecreaseStmtSkipAbortAssignIfWhileSeqMeasure InvariantStableProgramsetup preconditionprogram postcondition stabilityassertstable wpProveWithwpProve defaultWPCfgtraceExecution$fShowVC$fShowProofResult $fShowStatusBoundary UnboundedOpenClosedranges rangesWith $fShowRangeInductionResult InductionStep Initiation ConsecutionPartialCorrectnessinduct inductWith$fShowInductionStep$fShowInductionResultbfoldrbfoldrMbfoldlbfoldlMbsumbprodbmapbmapMbfilterbandborbanyballbmaximumbminimumbzipWithbelembreversebsortbfixbmcbmcWith svQuickCheckfastMinCorrectfastMaxCorrectoppositeSignsCorrectconditionalSetClearCorrectpowerOfTwoCorrectqueriesmidPointBroken midPointFixedmidPointAlternativecheckArithOverflowcheckCorrectMidValueInitVals InstructionMostekmemory registersflagsMemoryLocationF1F2LOFlags RegistersBitValueFlagFlagCFlagZRegisterRegXRegAgetRegsetReggetFlagsetFlagpeekpoke checkOverflowcheckOverflowCorrectldxldaclcrorMrorRbccadcdexbneendlegato runLegato initMachinelegatoIsCorrectcorrectnessTheorem legatoInC $fEqRegister $fOrdRegister $fIxRegister$fBoundedRegister$fEqFlag $fOrdFlag$fIxFlag $fBoundedFlag $fEqLocation $fOrdLocation $fIxLocation$fBoundedLocation$fGenericMostek$fMergeableMostekEmerge mergeSort nonDecreasingisPermutationOf correctness maskAndMult PowerListtiePLzipPLunzipPLpslf flIsCorrectthm1thm2addSub genAddSubusb5crcUSBcrcUSB'crcGoodcg1cg2fib0fib1genFib1fib2genFib2sgcd sgcdIsCorrect genGCDInC popCountSlow popCountFastpop8fastPopCountIsCorrectgenPopCountInC shiftLeft tstShiftLeftgenCCodeKSKeyGF28gf28Multgf28Pow gf28InverserotRroundConstants invMixColumns keyExpansion sboxTablesbox unSBoxTableunSBoxsboxInverseCorrect addRoundKeyt0Funct0t1t2t3u0Funcu0u1u2u3doRoundsaesRound aesInvRoundaesKeySchedule aesEncrypt aesDecryptt128Enct128Dect192Enct192Dect256Enct256Decaes128IsCorrectcgAES128BlockEncryptaesLibComponents cgAESLibrarycgAES128Libraryhex8RC4SinitSswapprgainitRC4 keySchedulekeyScheduleStringencryptdecrypt rc4IsCorrecthex2BlockSHAwordSize blockSizesum0Coefficientssum1Coefficientssigma0Coefficientssigma1Coefficients shaConstantsh0 shaLoopCountchmajsum0sum1sigma0sigma1sha224Psha256Psha384Psha512P sha512_224P sha512_256PprepareMessage hashBlockshaPsha224sha256sha384sha512 sha512_224 sha512_256knownAnswerTestscgSHA256chunkByshowHash crc_48_16 diffCountgenPolyfindHD4PolynomialsSolution HomogeneousNonHomogeneousldnbasistestsailors$fShowSolutionIdleReadyCriticalSStateidlereadycriticalmutex validSequence validTurns checkMutexnotFair$fSatModelState$fHasKindState $fSymValState $fDataState $fReadState $fOrdState $fShowState $fEqStatemkFibsgenFibs nestedExampleproblem allModelsmodelsWithYAuxABSEeltsfourmaxEminE $fSatModelE $fHasKindE $fSymValE$fDataE$fReadE$fOrdE$fShowE$fEqE assocPlusassocPlusRegularnonZeroAddition multInverse roundingAddoutsidegenValsSHumanHeightInCmHumanHeightInCmSMetresMetrestallestHumanEverceilingHighEnoughForHuman$fSymValMetres$fHasKindMetres$fSymValHumanHeightInCm$fHasKindHumanHeightInCm $fRealMetres$fIntegralMetres $fNumMetres $fEnumMetres $fEqMetres $fOrdMetres$fRealHumanHeightInCm$fIntegralHumanHeightInCm$fNumHumanHeightInCm$fEnumHumanHeightInCm$fEqHumanHeightInCm$fOrdHumanHeightInCm checkedDivtest1test2gfMultmultUnitmultComm multAssoc polyDivModtestGF28SIexampleDictDayMonTueWedThuFriSunSDay isWeekend almostWeekendweekendJustOver firstWeekend $fMetricDay $fSatModelDay $fHasKindDay $fSymValDay $fDataDay $fReadDay$fOrdDay $fShowDay$fEqDay productionallocatexyex1ex2 $fFreshIOS $fEqSymbolicS$fShowS $fFunctorS $fFoldableS$fTraversableSikmn fibCorrect $fMergeableS $fGenericSpgm1pgm2ex3ex4ex5ex6s sumCorrectMonthmayjunejulyaugustvalid existsDay forallDay existsMonth forallMonthpuzzlecherylCoinmkCoin combinationsc1c2c3c4c5c6Countcountcountsguesseseuler185 solveEuler185ColorRedGreenWhiteYellowBlue NationalityBritonDaneSwede NorwegianGerman$fSatModelColor$fHasKindColor $fSymValColor $fDataColor $fReadColor $fOrdColor $fShowColor $fEqColorBeverageTeaCoffeeMilkBeerWater$fSatModelNationality$fHasKindNationality$fSymValNationality$fDataNationality$fReadNationality$fOrdNationality$fShowNationality$fEqNationalityPetDogHorseCatBirdFish$fSatModelBeverage$fHasKindBeverage$fSymValBeverage$fDataBeverage$fReadBeverage $fOrdBeverage$fShowBeverage $fEqBeverageSportFootballBaseball VolleyballHockeyTennis $fSatModelPet $fHasKindPet $fSymValPet $fDataPet $fReadPet$fOrdPet $fShowPet$fEqPet fishOwner$fSatModelSport$fHasKindSport $fSymValSport $fDataSport $fReadSport $fOrdSport $fShowSport $fEqSportFlowercol validPick flowerCountBlackGridSButtonButtonSColornextsearch ladyAndTigersBoardRowElemcheckdiagisMagicchunkmagicisValidnQueens sendMoreMoneyPuzzlesudoku dispSolutionsolveAllpuzzle0puzzle1puzzle2puzzle3puzzle4puzzle5puzzle6 allPuzzlesU2MemberBonoEdgeAdamLarryHereThereSTimeTime SU2Memberbonoedgeadamlarry crossTime sCrossTime$fSatModelU2Member$fHasKindU2Member$fSymValU2Member$fDataU2Member$fReadU2Member $fOrdU2Member$fShowU2Member $fEqU2MemberActionsMovetimeflashlBonolEdgelAdamlLarry SLocationheretherestartwhereIs xferFlash xferPerson bumpTime1 bumpTime2whenSmove1move2runsolveNsolveU2$fMergeableStateT$fGenericStatus$fMergeableStatus$fSatModelLocation$fHasKindLocation$fSymValLocation$fDataLocation$fReadLocation$fShowLocationgoodSumdemocsDemo1csDemo2sharedqueryOnequeryTwosharedDependent firstQuery secondQuery demoDependentMondayTuesday WednesdayThursdayFridaySaturdaySundayfindDaysBinOpDivideExptUnOpNegateSqrt Factorial$fSatModelBinOp$fHasKindBinOp $fSymValBinOp $fDataBinOp $fReadBinOp $fOrdBinOp $fShowBinOp $fEqBinOpTUFSUnOpSBinOpallPossibleTreesfillsCaseevalgeneratefind$fShowT$fSatModelUnOp $fHasKindUnOp $fSymValUnOp $fDataUnOp $fReadUnOp $fOrdUnOp $fShowUnOp$fEqUnOpguessplayexampleMathSATevenOddpucCoresolveCrosswordMSQLExprConstConcatReadVarexampleProgramnameRestrReselectRedropRe statementRe exploitRe findInjection$fIsStringSQLExprQrunQ CheckResultProvedCounterexamplePropertyEvalunEvalTermVarLitEqualsImpliesEnvenvXenvYresultAllocrunAllocallocallocEnv unsafeCastSBVrunEvalmkResultrunProgramEvalrunPropertyEval generalizemkQuery$fFunctorAlloc$fApplicativeAlloc $fMonadAlloc$fMonadIOAlloc$fMonadErrorAlloc$fMonadSymbolicAlloc$fEqEnv $fShowEnv $fFunctorEval$fApplicativeEval $fMonadEval$fMonadReaderEval$fMonadErrorEval$fEqCheckResult$fShowCheckResult $fFunctorQ$fApplicativeQ$fMonadQ $fMonadIOQ $fMonadErrorQ $fMonadQueryQfthm proveSArrayproveSFunArraySBandornotax1ax2ax3$fEqB$fOrdB$fShowB$fReadB$fDataB $fSymValB $fHasKindBthmGoodmul22 synthMul22BinaryTernaryposnegshannonshannon2 derivativenoWiggleunivOK existentialexistsOK$fEqQ$fOrdQ$fDataQ$fReadQ$fShowQ $fSymValQ $fHasKindQLNilConsclassifygenLs $fHasKindL $fSymValL$fEqL$fOrdL$fShowL$fReadL$fDataLAppCAppSxsystszs algorithmimperativeAppend $fShowAppS$fQueriableIOAppSAppC $fShowAppC $fGenericAppS$fMergeableAppSIIncSprepostnoChange imperativeInc $fFreshIOIncS $fShowIncS $fShowIncS0 $fGenericIncS$fMergeableIncS $fFunctorIncS$fFoldableIncS$fTraversableIncSFibSfib axiomatizeFib imperativeFib $fFreshIOFibS $fShowFibS $fShowFibS0 $fGenericFibS$fMergeableFibS $fFunctorFibS$fFoldableFibS$fTraversableFibSGCDSjgcd axiomatizeGCD imperativeGCD $fFreshIOGCDS $fShowGCDS $fShowGCDS0 $fGenericGCDS$fMergeableGCDS $fFunctorGCDS$fFoldableGCDS$fTraversableGCDSDDivSqr imperativeDiv invariantmeasure $fFreshIODivS $fShowDivS $fShowDivS0 $fGenericDivS$fMergeableDivS $fFunctorDivS$fFoldableDivS$fTraversableDivSSqrtSsqrtimperativeSqrt$fFreshIOSqrtS $fShowSqrtS $fShowSqrtS0$fGenericSqrtS$fMergeableSqrtS$fFunctorSqrtS$fFoldableSqrtS$fTraversableSqrtSLenCLenSlimperativeLength $fShowLenS$fQueriableIOLenSLenC $fShowLenC $fGenericLenS$fMergeableLenSSumS imperativeSum $fFreshIOSumS $fShowSumS $fShowSumS0 $fGenericSumS$fMergeableSumS $fFunctorSumS$fFoldableSumS$fTraversableSumSisStartModeOptionghc-prim GHC.TypesTrue setSMTOption$fShowSMTReasonUnknownisExactRational mkPolyRealalgRealStructuralEqualalgRealStructuralComparealgRealToSMTLib2algRealToHaskellbaseGHC.RealRational Data.EitherLeftRight mergeAlgReals$fFractionalAlgRealIO$fExtractIOWriterTtransformers-0.5.5.0!Control.Monad.Trans.Writer.StrictWriterT$fExtractIOWriterT0Control.Monad.Trans.Writer.Lazy$fExtractIOExceptTControl.Monad.Trans.ExceptExceptT$fExtractIOMaybeTControl.Monad.Trans.MaybeMaybeT $fExtractIOIO isKStringmlift2mlift3mlift4mlift5mlift6mlift7mlift8joinArgs splitArgs qfsToString stringToQFS Data.Data showBaseKind kindParensmtType kindHasSignconstructUKindhasUninterpretedSortsneedsFlattening $fShowKind$fHasKindProxyeqRCSet compareRCSet GHC.ClassesOrdcvRank showExtCVliftCVshowCV randomCValrandomCV $fShowRCSet $fOrdCValEq$fEqCVal$fShowCV $fHasKindCV $fShowExtCV$fHasKindExtCV$fShowGeneralizedCV$fHasKindGeneralizedCV time-1.8.0.2(Data.Time.Clock.Internal.NominalDiffTimeNominalDiffTime SMTEngine FArrayIndex ArrayIndexpathCondIncStateCacheCgMapUIMap FArrayMapArrayMapTableMapKindSetCnstMapExprMap GHC.MaybeNothingOvOpOverflow_SMul_OVFLOverflow_SMul_UDFLOverflow_UMul_OVFLswKindreorder objectiveNameisSafetyCheckingIStage isSetupIStage isRunIStage newIncStatewithNewIncStategetSValPathConditionextendSValPathCondition noInteractive modifyStatemodifyIncStaterecordObservableincrementInternalCounter addAssertionnewSVDouble registerLabelnewConstsvToSV mapSymbolicTsvMkTrackerVar svMkSymVarGenintroduceUserName uncacheFAI uncacheGenvalidationRequested$fOrdSV$fEqSV $fShowOvOp $fShowRegExp $fNumRegExpGHC.NumNum+*$fIsStringRegExp $fShowStrOp $fShowSeqOp$fShowQuantifier$fShowArrayIndex$fShowFArrayIndex$fHasKindRoundingMode$fShowQueryContext$fEqSVal==/=$fMonadSymbolicSymbolicT unFArrayIndex unArrayIndexrunMode rIncState startTimerCInfo rObservablesrctr rUsedKinds rUsedLblsrinps rConstraintsroutsrtblMapspgm rconstMaprexprMap rArrayMap rFArrayMaprUIMaprCgMapraxioms rSMTOptions rOptGoalsrAssertsrSVCacherAICache rFAICache rQueryStaterNewInps rNewKinds rNewConstsrNewArrsrNewTblsrNewUIs rNewAsgnsrNewConstraintsSetEqual SetMember SetInsert SetDelete SetIntersectSetUnion SetSubset SetDifference SetComplement SetHasSizesvStringsvChar eqOptBool svSetEqual svStrongEqualrotsvShift svMkOverflow nodeIdToSValswToSValsvEqualWithConsts mkSymOpSCmkSymOpeqOptisConcreteZero isConcreteOneisConcreteOnes integer-gmpGHC.Integer.TypeIntegertestBit isConcreteMax isConcreteMin rationalCheck nonzeroCheckrationalSBVChecktupleLTmaybeLTeitherLTMaybeEitherCharFloatFalseBool Data.Foldableanyall$fEqSBV $fShowSBVGHC.ShowShow$fSymValRoundingMode $fIsListSBVSExprtokenize parenDeficit parseSExprrdFPgetTripleFloatgetTripleDouble constantMapparseSExprFunctionparseLambdaExpressionparseStoreAssociations chainAssignsEConENumERealEFloatEDoubleEApppads2s16toSMTLibRationalSMTLibIncConverterSMTLibConverteraddAnnotationsshowTimeoutValuealignDiagnostic alignPlainalignWithPrefixdebug mergeSExpr$fShowSBVException$fExceptionSBVExceptioncvtdeclSort declTuplefindTupleArities containsSum containsMaybecvtInctoSMTLib toIncSMTLib toSMTLib2 toIncSMTLib2 SolverLine SolverRegular SolverTimeoutSolverException resultConfig parseModelOutInt showSMTResultshowModelDictionary showModelUIshCV pipeProcessstandardEnginestandardSolver runSolver recordEndTimestartTranscriptfinalizeTranscript$fSatModel(,,,,,,)$fSatModel(,,,,,)$fSatModel(,,,,)$fSatModel(,,,)$fSatModel(,,) $fSatModel(,) $fSatModel[]$fSatModelRoundingMode $fSatModelCV$fSatModelDouble$fSatModelFloat$fSatModelAlgReal$fSatModelInteger$fSatModelInt64GHC.IntInt64$fSatModelWord64GHC.WordWord64$fSatModelInt32Int32$fSatModelWord32Word32$fSatModelInt16Int16$fSatModelWord16Word16$fSatModelInt8Int8$fSatModelWord8Word8$fSatModelBool $fSatModel()$fModelableSMTResult$fModelableSatResult$fModelableThmResult SMTFunctionaddQueryConstraint getConfig getObjectives getSBVPgmgetSBVAssertions syncUpSolver getQueryState mkFreshArray askIgnoringpointWiseExtractmkArggetValueCVHelperdefaultKindedValue sexprToValrecoverKindedValuegetQuantifiedInputsgetAllSatResultparse runProofOn$fQueriablemtt$fQueriablemSBVa$fSolverContextQueryT$fSMTFunction->(,,,,,,,)r$fSMTFunction->(,,,,,,)r$fSMTFunction->(,,,,,)r$fSMTFunction->(,,,,)r$fSMTFunction->(,,,)r$fSMTFunction->(,,)r$fSMTFunction->(,)r$fSMTFunction->ar sexprToArg smtFunNamesmtFunSaturate smtFunType smtFunDefault sexprToFun Assignment classifyModelgetModelAtIndexgetObjectiveValuescheckSatAssumingHelperrestoreTablesAndArraysgetUnsatCoreIfRequested allOnStdOut runWithQuery runInThread sbvWithAny sbvWithAll GMergeablesymbolicMergeDefault GHC.GenericsGenericIntegralRealGHC.EnumEnumquotRemdivModquotdivpopCountsetBitclearBitOrderingmaxmingenVargenVar_checkObservableNameliftPB pbToIntegerlift1Flift1FNSlift2FNS fromIntegral liftViaSValshiftLshiftRrotateLrotateRenumCvtsymbolicMergeWithKind cannotMerge addSymAxiomslet$fSolverContextSymbolicT $fBitsSBV $fFloatingSBV$fSymVal(,,,,,,,)$fSymVal(,,,,,,)$fSymVal(,,,,,)$fSymVal(,,,,) $fSymVal(,,,) $fSymVal(,,) $fSymVal(,) $fSymVal()$fOrdSymbolicSBVTupleHasFieldsymbolicFieldAccesszxsxsignBitsameSigndiffSignsvAllallZeroallOnebvuaddobvsaddobvusubobvssubobvumulobvsmuloknown bvumuloFast bvsmuloFastbvudivobvsdivobvunegobvsnegolift1lift2lift3 concEval1 concEval2 concEval3isConcretelyEmptyfoldrJust ZeroWidth intOfProxy $fShowWordN $fMetricWordN$fSatModelWordN$fSFiniteBitsWordN$fSDivisibleSBV$fSDivisibleWordN$fSIntegralWordN$fIntegralWordN $fRealWordN $fEnumWordN $fNumWordN$fBoundedWordNBounded $fSymValWordN$fHasKindWordN $fMetricIntN$fSatModelIntN$fSFiniteBitsIntN$fSDivisibleIntN$fSIntegralIntN$fIntegralIntN $fRealIntN $fEnumIntN $fNumIntN $fBoundedIntN $fSymValIntN $fHasKindIntN $fShowIntN$fSDivisibleSBV0$fByteConverterSBV$fByteConverterSBV0$fByteConverterSBV1$fByteConverterSBV2$fByteConverterSBV3$fByteConverterSBV4$fByteConverterSBV5$fByteConverterSBV6sppolyMultgenericFromFloatgenericToFloat concEval2BaddRMlift1BliftMMlift2B$fMetricDouble $fMetricFloat$fIEEEFloatingDouble$fIEEEFloatingFloat__unusedGHC.BaseStringrender' pprCFunHeaderdeclSV declSVNoConstshowSVpprCWord showCType specifiermkConstgenMake genHeader genDrivergenCProg mergeToLib genLibMake mergeDrivers ToSizedBV FromSizedBV ToSizedErr FromSizedErr ToSizedCstr FromSizedCstrRatioWord Data.RatioapproxRational byteSwap64 byteSwap32 byteSwap16toIntegralSizedpopCountDefaulttestBitDefault bitDefault.&..|.xorshiftrotatezeroBitsbit complementBit bitSizeMaybebitSizeisSigned unsafeShiftL unsafeShiftR FiniteBits finiteBitSizecountLeadingZeroscountTrailingZeros denominator numerator%LocisTotaldispVCisClosedlcasebparabinsertData.Functor.IdentityIdentity