c z      !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~      !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~      !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~      !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMN O P Q R S T U V W X Y Z [ \ ] ^ _ ` a b c defghijklmnopqrstuvwxyz{|}~                                                          !"#$%&' ( ) * + , - . / 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 R S T U V W X Y Z [ \ ] ^ _ ` a b c d e f ghijklmnopqrstuvwxyz{|}~       !!!!!!!!!! ! ! ! ! !!!!!!!!!"#$%&&&&&& &!&"&#&$&%&&&''(')'*'+','-'.'/'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+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+y+z+{+|+}+~+++++++,,,,,,,,---.////////////////00000000000000000000000000000000000000000000000000000000000000000112233333333333333333334444444444444444 4 4 4 4 4444444444444444444 4!4"4#5$5%6&7'7(8)8*8+8,9-9.9/909192939495969798999:9;9<:=:>:?:@: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?y?_@(c) Levent ErkokBSD3erkokl@gmail.com experimentalSafe68+SMT-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 setLogicr 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.Formulas 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.yLinear formulas with free sort and function symbols over one- and two-dimentional arrays of integer index and real value.tFormulas with free function and predicate symbols over a theory of arrays of arrays of integer index and real value.*Linear formulas in linear real arithmetic.LQuantifier-free formulas over the theory of bitvectors and bitvector arrays.yQuantifier-free formulas over the theory of bitvectors and bitvector arrays extended with free sort and function symbols.oQuantifier-free linear formulas over the theory of integer arrays extended with free sort and function symbols.GQuantifier-free formulas over the theory of arrays with extensionality. BQuantifier-free formulas over the theory of fixed-size bitvectors. Difference 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. Unquantified linear integer arithmetic. In essence, Boolean combinations of inequations between linear polynomials over integer variables. Unquantified linear real arithmetic. In essence, Boolean combinations of inequations between linear polynomials over real variables. #Quantifier-free integer arithmetic. Quantifier-free real arithmetic.Difference 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.eUnquantified formulas built over a signature of uninterpreted (i.e., free) sort and function symbols.SUnquantified formulas over bitvectors with uninterpreted sort function and symbols.aDifference Logic over the integers (in essence) but with uninterpreted sort and function symbols.TUnquantified linear integer arithmetic with uninterpreted sort and function symbols.QUnquantified linear real arithmetic with uninterpreted sort and function symbols.UUnquantified non-linear real arithmetic with uninterpreted sort and function symbols.]Unquantified non-linear real integer arithmetic with uninterpreted sort and function symbols.DLinear real arithmetic with uninterpreted sort and function symbols.KNon-linear integer arithmetic with uninterpreted sort and function symbols.\Quantifier-free formulas over the theory of floating point numbers, arrays, and bit-vectors.CQuantifier-free formulas over the theory of floating point numbers.Quantifier-free finite domains.4Quantifier-free formulas over the theory of strings.The catch-all value.=Use this value when you want SBV to simply not set the logic.(In case you need a really custom string! POption 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..(Collectable information from the solver.8Reason for reporting unknown.<"Behavior of the solver for errors.?(Collectable information from the solver.H Result of a checkSat or checkSatAssuming call.I=Satisfiable: A model is available, which can be queried with A.JHUnsatisfiable: No model is available. Unsat cores might be obtained via B.K Unknown: Use C5 to obtain an explanation why this might be the case.z7Can this command only be run at the very beginning? If {z then we will reject setting these options in the query mode. Note that this classification follows the SMTLib document.|MTranslate an option setting to SMTLib. Note the SetLogic/SetInfo discrepancy.N  !"#$%&'()*+,-./0123456789:;<=>?DF@ABCEGHIJKz|  !"#$%&'()*+,-. /0123456789:;<=>?@ABCDEFGHIJKD(c) Levent ErkokBSD3erkokl@gmail.com experimentalSafe;= LA univariate polynomial, represented simply as a coefficient list. For instance, "5x^3 + 2x - 5" is represented as [(5, 3), (2, 1), (-5, 0)]MAlgebraic reals. Note that the representation is left abstract. We represent rational results explicitly, while the roots-of-polynomials are represented implicitly by their defining equationNLbool says it's exact (i.e., SMT-solver did not return it with ? at the end.)Ojwhich root of this polynomial and an approximate decimal representation with given precision, if available}2Check wheter a given argument is an exact rational~cConstruct a poly-root real with a given approximate value (either as a decimal, or polynomial-root)AStructural equality for AlgReal; used when constants are Map keysDStructural comparisons for AlgReal; used when constants are Map keys Render an MA as an SMTLib2 value. Only supports rationals for the time being. Render an M as a Haskell value. Only supports rationals, since there is no corresponding standard Haskell type that can represent root-of-polynomial variety.cMerge 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).2NB: Following the other types we have, we require `a/0` to be `0` for all a. LMNO}~LMNOE(c) Levent ErkokBSD3erkokl@gmail.com experimentalNone7;=VPA 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 Data instance; this is useful for creating uninterpreted sorts. So, in reality, end users should almost never need to define any methods.^Kind of symbolic value!Helper for Eq/Ord instances below+Does this kind represent a signed quantity?Construct 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(We want to order user-sorts only by name)We want to equate user-sorts only by namePWQRSTUVXYZ[\]^_`abcdefgPQRSTUVWXYZ[\]Q^ _`abcdefgF(c) Levent ErkokBSD3erkokl@gmail.com experimentalNone#hYA simple expression type over extendent values, covering infinity, epsilon and intervals.ovA generalized CW allows for expressions involving infinite and epsilon values/intervals Used in optimization problems.rrx represents a concrete word of a fixed size: For signed words, the most significant digit is considered to be the sign.vA constant valuewalgebraic realxbit-vector/unbounded integeryfloatzdouble{ character|string}Xvalue of an uninterpreted/user kind. The Maybe Int shows index position for enumerations*Show an extended CW, with kind if required~Is this a regular CW?Are two CW's of the same type?DConvert a CW to a Haskell boolean (NB. Assumes input is well-kinded)5Normalize a CW. 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.)BConstant False as a CW. We represent it using the integer value 0.AConstant True as a CW. We represent it using the integer value 1."Lift a unary function through a CW#Lift a binary function through a CW"Map a unary function through a CW.#Map a binary function through a CW.)Show a CW, with kind info if bool is True;A version of show for kinds that says Bool instead of SBool(Create a constant word from an integral."Generate a random constant value (v) of the correct kind."Generate a random constant value (r) of the correct kind.-Ord instance for CWVal. Same comments as the % instance why this cannot be derived.Eq instance for CWVal. Note that we cannot simply derive Eq/Ord, since CWAlgReal 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:Show instance for r.^ instance for CW"Show instance, shows with the kindKind instance for Extended CWShow instance for Generalized r^ instance for generalized CW&hijklmnopqrstuv|wxyz{}~hijklmnopqrstuvwxyz{|}G(c) Levent ErkokBSD3erkokl@gmail.com experimentalSafeyNames reserved by SMTLib. This list is current as of Dec 6 2015; but of course there's no guarantee it'll stay that way.H(c) Levent ErkokBSD3erkokl@gmail.com experimentalSafe;The & class: a generalization of Haskell's  type Haskell  and SBV's SBoolG are instances of this class, unifying the treatment of boolean values.Minimal complete definition: , , $ However, it's advisable to define , and " as well (typically), for clarity. logical true logical false complementandornandnorxorimplies equivalencecast from BoolGeneralization of Generalization of Generalization of Generalization of  3232611I(c) Levent ErkokBSD3erkokl@gmail.com experimentalSafe Monadic lift over 2-tuplesMonadic lift over 3-tuplesMonadic lift over 4-tuplesMonadic lift over 5-tuplesMonadic lift over 6-tuplesMonadic lift over 7-tuplesMonadic lift over 8-tuplesGiven 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"CGiven a string, split into the available arguments. The inverse of #. Courtesy of the cmdargs package.cGiven a QF_S string (i.e., one that works in the string theory), convert it to a Haskell equivalentGiven 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! J(c) Levent ErkokBSD3erkokl@gmail.com experimentalSafe CA variant of round; except defaulting to 0 when fed NaN or InfinityHA variant of toRational; except defaulting to 0 when fed NaN or InfinityThe 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:  -https://ghc.haskell.org/trac/ghc/ticket/10378  (https://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-deterministic SMTLib compliant definition for fpMin. See the comments for fpMax..Convert double to float and back. Essentially fromRational . toRational, except careful on NaN, Infinities, and -0.kCompute 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.BConvert a float to the nearest integral representable in that type|Check that two floats are the exact same values, i.e., +0/-0 does not compare equal, and NaN's compare equal to themselves.Check 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! K(c) Levent ErkokBSD3erkokl@gmail.com experimentalSafe 2Specify how to save timing information, if at all.Show  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.L(c) Levent ErkokBSD3erkokl@gmail.com experimentalNone$13;=>?KNQSTV. An SMT solverThe solver in useThe path to its executable Options to provide to the solver=The solver engine, responsible for interpreting solver output"Various capabilities of the solverSolvers that SBV is aware of An SMT engine%A script, to be passed to the solver. Initial feed'Continuation script, to extract resultsGThe 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.)YUnsatisfiable. If unsat-cores are enabled, they will be returned in the second parameter.Satisfiable with modelNProver returned a model, but in an extension field containing Infinite/epsilon.Prover returned unknown, with the given reasonProver errored out A model, as returned by a solver/Mapping of symbolic values to objective values.(Mapping of symbolic values to constants.Solver configuration. See also z3, yices, cvc4,  boolector, mathSAT, 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. Debug modeXPrint timing information on how long different phases took (construction, solving, etc.)CPrint integral literals in this base (2, 10, and 16 are supported.)EPrint algebraic real values with this precision. (SReal, default: 16)UUsually "(check-sat)". However, users might tweak it based on solver characteristics.KIn an allSat call, return at most this many models. If nothing, return all.When constructing a model, ignore variables whose name satisfy this predicate. (Default: (const False), i.e., don't ignore anything)cIf Just, the entire interaction will be recorded as a playable file (for debugging purposes mostly)+What version of SMT-lib we use for the toolThe actual SMT solver.3Rounding mode to use for floating-point conversions%Options to set as we start the solverSIf true, we shall ignore the exit code upon exit. Otherwise we require ExitSuccess.QRedirect the verbose output to this file if given. If Nothing, stdout is implied.aRounding 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.yRound 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.)Round 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.)HRound towards positive infinity. (Also known as rounding-up or ceiling.)HRound towards negative infinity. (Also known as rounding-down or floor.)/Round towards zero. (Also known as truncation.)KTranslation tricks needed for specific capabilities afforded by each solver'Support for SMT-Lib2 style quantifiers?.Support for SMT-Lib2 style uninterpreted-sortsSupport for unbounded integers?Support for reals?-Supports printing of approximations of reals?#Support for floating point numbers?"Support for optimization routines?&Support for pseudo-boolean operations?,Support for interactive queries per SMT-Lib?.Support for global decls, needed for push-pop.URepresentation of an SMT-Lib program. In between pre and post goes the refuted modelsRepresentation 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.%An array index is simple an int valueWe 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!+Arrays implemented in terms of SMT-arrays: 2http://smtlib.cs.uiowa.edu/theories-ArraysEx.shtmlMaps directly to SMT-lib arraysIReading from an unintialized value is OK and yields an unspecified result&Can check for equality of these arrays"Cannot quick-check theorems using SArr valuesITypically slower as it heavily relies on SMT-solving for the array theoryA 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.The Symbolic value. Either a constant (Left) or a symbolic value ( Right CachedH). Note that caching is essential for making sure sharing is preserved.Return and clean and incState%The state of the symbolic interpreter kind KBool1The state in query mode, i.e., additional context3Different means of running a symbolic piece of code;In regular mode, with a stage. Bool is True if this is SAT.Code generation mode.Concrete simulation mode.Stage of an interactive run#Cached values, implementing sharing?Code-segments for Uninterpreted-constants, as given by the user7Uninterpreted-constants generated during a symbolic run&Arrays generated during a symbolic run"Representation for symbolic arrays&Tables generated during a symbolic runOKinds used in the program; used for determining the final SMT-Lib logic to pick\Constants are stored in a map, for hash-consing. The bool is needed to tell -0 from +0, sigh%Expression map, used for hash-consing*The context of a symbolic array as created+A new array, the contents are uninitialized:An array created by mutating another array at a given cell9An array created by symbolically merging two other arrays(Result of running a symbolic computationkinds used in the program0quick-check counter-example information (if any)*observable expressions (part of the model)uninterpeted code segments,inputs (possibly existential) + tracker vars constantsJtables (automatically constructed) (tableno, index-type, result-type) eltsarrays (user specified)uninterpreted constantsaxioms assignments additional constraints (boolean)  assertions outputs _A query is a user-guided mechanism to directly communicate and extract results from the solver. 9The state we keep track of as we interact with the solveruObjective of optimization. We can minimize, maximize, or give a soft assertion with a penalty for not satisfying it.Minimize this metricMaximize this metric,A soft assertion, with an associated penalty5Penalty 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.Default: Penalty of 1 and no group attached+Penalty with a weight and an optional groupStyle 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.jObjectives are optimized in the order given, earlier objectives have higher priority. This is the default.*Each objective is optimized independently. }Objectives are optimized according to pareto front: That is, no objective can be made better without making some other worse.!!B pairs symbolic words and user given/automatically generated names"&A program is a sequence of assignments%A symbolic expression'A 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.)FQuantifiers: forall or exists. Note that we allow arbitrary nestings.,URegular expressions. Note that regular expressions themselves are concrete, but the match function from the RegExpMatchableZ 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.- Precisely match the given string.Accept every string/Accept no strings0Accept range of characters1 Concatenation2Kleene Star: Zero or more3Kleene Plus: One or more4 Zero or one5From n repetitions to m repetitions6Union of regular expressions7#Intersection of regular expressions8.String operations. Note that we do not define StrAt as it translates to  StrSubStr trivially.9$Concatenation of one or more strings: String length; Unit string<Retrieves substring of s at offset=Retrieves first position of sub in s, -1 if there are no occurrences>Does s contain the substring sub??Is pre a prefix of s?@Is suf a suffix of s?A Replace the first occurrence of src by dst in sB#Retrieve integer encoded by string s (ground rewriting only)C#Retrieve string encoded by integer i (ground rewriting only)D,Check if string is in the regular expressionEPseudo-boolean operationsF At most kG At least kH Exactly kI:At most k, with coefficients given. Generalizes PB_AtMostJ;At least k, with coefficients given. Generalizes PB_AtLeastK;Exactly k, with coefficients given. Generalized PB_ExactlyLFloating point operationscSymbolic operations3A symbolic word, tracking it's signedness and size.A symbolic node idKind of a symbolic word.Forcing 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'sFConstant False as an SW. Note that this value always occupies slot -2.EConstant True as an SW. Note that this value always occupies slot -1.&Are there any existential quantifiers?`To improve hash-consing, take advantage of commutative operators by reordering their arguments.The name of the objective.Is this a CodeGen run? (i.e., generating code)Get a new IncStateGet a new IncStateGet the current path condition4Extend the path condition with the given test value.Are we running in proof mode??Things we do not support in interactive mode, at least for now! 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.)Modify the incremental stateAdd an observableIncrement the variable counter@Create a new uninterpreted symbol, possibly with user given code"Add a new sAssert based constraintCreate 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.Create a new SWRegister 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 u for the first time and using a BV logic, then things would fall apart. But this should be rare, and hopefully the success 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 setLogic9 appropriately, so it seems safe to just allow for this.NRegister a new label with the system, making sure they are unique and have no '|' s in themACreate a new constant; hash-cons as necessary NB. For each constant, we also store weather it's negative-0 or not, as otherwise +0 == -0 and thus we'd confuse those entries. That's a bummer as we incur an extra boolean for this rare case, but it's simple and hopefully we don't generate a ton of constants in general.*Create a new table; hash-cons as necessary/Create a new expression; hash-cons as necessary+Convert a symbolic value to a symbolic-word<Convert a symbolic value to an SW, inside the Symbolic monadCreate 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. randomCWG is used for generating random values for this variable when used for  quickCheck or genTest purposes.3Create an existentially quantified tracker variable0Create an N-bit symbolic unsigned named variable2Create an N-bit symbolic unsigned unnamed variable.Create an N-bit symbolic signed named variable0Create an N-bit symbolic signed unnamed variableCreate 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. randomCWG is used for generating random values for this variable when used for  quickCheck or genTest purposes..Introduce a new user name. We die if repeated.Add 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.HRun a symbolic computation, and return a extra value paired up with the :Grab the program from a running symbolic simulation state.Add a new optionHandling constraintsURequire a boolean condition to be true in the state. Only used for internal purposes.Add an optimization goalMark an interim result as an output. Useful when constructing Symbolic programs that return multiple values, or when the result is programmatically computed.Read the array element at aUpdate the element at a to be b?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 elements8Create a named new array, with an optional initial valueCompare two arrays for equalityCache a state-based computation'Uncache a previously cached computation!Uncache, retrieving array indexesSGeneric uncaching. Note that this is entirely safe, since we do it in the IO monad.)The extension associated with the versionShow instance for ,R. The mapping is done so the outcome matches the SMTLib string reg-exp operationsRegular expressions as a  instance. Note that only  (union) and  (concatenation) make sense.HWith overloaded strings, we can have direct literal regular expressions.Show instance for 8V. Note that the mapping here is important to match the SMTLib equivalents, see here: 1https://rise4fun.com/z3/tutorialcontent/sequences kindqEquality constraint on SBV values. Not desirable since we can't really compare two symbolic values, but will do.current configuration$the state in which to run the engineprogram continuation4      !"#$%&'()*+,-.46/01235789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcurszhidefgjklmnopqtvwxy{|}~$       "#$%&'()*+, -./012345678 9:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abc!defghijklmnopqrstuvwxyz{|}~M(c) Levent ErkokBSD3erkokl@gmail.com experimentalNoneSL Boolean True.Boolean False.Convert from a Boolean.Convert from an Integer.Convert from a FloatConvert from a FloatConvert from a StringConvert from a CharConvert from a Rational<Extract a bool, by properly interpreting the integer stored.)Extract an integer from a concrete value.,Grab the numerator of an SReal, if available.Grab the denominator of an SReal, if availableConstructing [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. Addition.Multiplication. Subtraction. Unary minus.Absolute value. Division.Exponentiation.<Bit-blast: Little-endian. Assumes the input is a bit-vector.Set a given bit at index9Bit-blast: Big-endian. Assumes the input is a bit-vector.nUn-bit-blast from big-endian representation to a word of the right size. The input is assumed to be unsigned.qUn-bit-blast from little-endian representation to a word of the right size. The input is assumed to be unsigned.Add a constant value: Increment: Decrement:Quotient: 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.FRemainder: 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.Combination of quot and remDOptimize away x == true and x /= false to x; otherwise just do eqOpt Equality. Inequality. Less than. Greater than.Less than or equal to.Greater than or equal to. Bitwise and. Bitwise or. Bitwise xor.Bitwise complement.QShift left by a constant amount. Translates to the "bvshl" operation in SMT-Lib.Shift 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.Rotate-left, by a constantRotate-right, by a constantuGeneric rotation. Since the underlying representation is just Integers, rotations has to be careful on the bit-size.Extract bit-sequences. Join two words, by concatanetingUninterpreted 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.+If-then-else. This one will force branches.YLazy If-then-else. This one will delay forcing the branches unless it's really necessary.#Merge two symbolic values, at kind k , possibly forceH'ing the branches to make sure they do not evaluate to the same result.Total 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.5Convert a symbolic bitvector from unsigned to signed.5Convert a symbolic bitvector from signed to unsigned.?Convert a symbolic bitvector from one integral kind to another.BConvert an SVal from kind Bool to an unsigned bitvector of size 1.MConvert an SVal from a bitvector of size 1 (signed or unsigned) to kind Bool.Test 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.Generalization of %, where the shift-amount is symbolic.Generalization of %, where the shift-amount is symbolic.XNB. If the shiftee is signed, then this is an arithmetic shift; otherwise it's logical..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.Generalization of s, where the rotation amount is symbolic. If the first argument is not bounded, then the this is the same as shift.Generalization of s, where the rotation amount is symbolic. If the first argument is not bounded, then the this is the same as shift. -eqOpt says the references are to the same SW, 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. :Predicate for optimizing word operations like (+) and (*). :Predicate for optimizing word operations like (+) and (*). ,Predicate for optimizing bitwise operations. %Predicate for optimizing comparisons.%Predicate for optimizing comparisons.&Predicate for optimizing conditionals.jMost operations on concrete rationals require a compatibility check to avoid faulting on algebraic reals.;Quot/Rem operations require a nonzero check on the divisor.'Same as rationalCheck, except for SBV's?N(c) Levent ErkokBSD3erkokl@gmail.com experimentalNone $678;=>?STV >P7Internal representation of a symbolic simulation result'SMTLib representation, given the config*Arrays implemented internally as functions;Internally handled by the library and not mapped to SMT-LibLReading an uninitialized value is considered an error (will throw exception)?Cannot check for equality (internally represented as functions)Can quick-check<Typically faster as it gets compiled away during translation+Arrays implemented in terms of SMT-arrays: 2http://smtlib.cs.uiowa.edu/theories-ArraysEx.shtmlMaps directly to SMT-lib arraysIReading from an unintialized value is OK and yields an unspecified result&Can check for equality of these arrays"Cannot quick-check theorems using SArray valuesITypically slower as it heavily relies on SMT-solving for the array theory#Flat arrays of symbolic values An  array a b! is an array indexed by the type  a, with elements of type  b.>While it's certainly possible for user to create instances of , the  and  instances already provided should cover most use cases in practice. (There are some differences between these models, however, see the corresponding declaration.)CMinimal complete definition: All methods are required, no defaults.Create a new anonymous arrayCreate a named new arrayRead the array element at aUpdate the element at a to be b?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 elementsA  is a potential symbolic bitvector that can be created instances of to be fed to a symbolic program. Note that these methods are typically not needed in casual uses with prove, sat, allSatE etc, as default instances automatically provide the necessary bits.%Create a user named input (universal)#Create an automatically named inputGet a bunch of new wordsCreate an existential variable2Create an automatically named existential variableCreate a bunch of existentials@Create a free variable, universal in a proof, existential in satGCreate an unnamed free variable, universal in proof, existential in satCreate a bunch of free vars,Similar to free; Just a more convenient nameISimilar to mkFreeVars; but automatically gives names based on the strings#Turn a literal constant to symbolic+Extract a literal, if the value is concrete+Extract a literal, from a CW representationIs the symbolic word concrete?%Is the symbolic word really symbolic?/Does it concretely satisfy the given predicate?One stop allocatorFA class representing what can be returned from a symbolic computation.Mark an interim result as an output. Useful when constructing Symbolic programs that return multiple values, or when the result is programmatically computed.jActions 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.EAdd a constraint, any satisfying instance must satisfy this conditionBAdd a named constraint. The name is used in unsat-core extraction. Set info. Example: setInfo ":status" ["unsat"]. Set an option. Set the logic. hSet 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 timeOut: for finer level control of time-outs, directly from SBV. The symbolic variant of 2A 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  is a symbolic value of its own, of possibly arbitrary length, and internally processed as one unit as opposed to a fixed-length list of characters.A 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.shtml0IEEE-754 double-precision floating point numbers0IEEE-754 single-precision floating point numbers0Infinite precision symbolic algebraic real value(Infinite precision signed symbolic value;64-bit signed symbolic value, 2's complement representation;32-bit signed symbolic value, 2's complement representation;16-bit signed symbolic value, 2's complement representation:8-bit signed symbolic value, 2's complement representation64-bit unsigned symbolic value32-bit unsigned symbolic value16-bit unsigned symbolic value8-bit unsigned symbolic valueA symbolic boolean/bitThe Symbolic value. The parameter aV is phantom, but is extremely important in keeping the user interface strongly typed. Get the current path condition!4Extend the path condition with the given test value."Not-A-Number for  and X. Surprisingly, Haskell Prelude doesn't have this value defined, so we provide it here.# Infinity for  and X. Surprisingly, Haskell Prelude doesn't have this value defined, so we provide it here.$@Symbolic variant of Not-A-Number. This value will inhabit both  and .%<Symbolic variant of infinity. This value will inhabit both  and .&Symbolic variant of 'Symbolic variant of (Symbolic variant of RoundNearestPositive)Symbolic variant of *Symbolic variant of + Alias for &, Alias for '- Alias for (. Alias for )/ Alias for *0+Convert a symbolic value to a symbolic-word1Create a symbolic variable.2<Convert a symbolic value to an SW, inside the Symbolic monad3<Declare a new symbolic array, with a potential initial value4mDeclare a new functional symbolic array. Note that a read from an uninitialized cell will result in an error.5ZLift a function to an array. Useful for creating arrays in a pure context. (Otherwise use .)Equality constraint on SBV values. Not desirable since we can't really compare two symbolic values, but will do. Note that we do need this instance since we want Bits as a class for SBV that we implement, which necessiates the Eq class.A  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! can be used symbolicallyLMNOPWQRSTUVXYZ[\]^_`abcdefghijklmnopqrstuv|wxyz{}~      !"#$%&'()*+,-.46/01235789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcurszhidefgjklmnopqtvwxy{|}~      !"#$%&'()*+,-./012345    O(c) Levent ErkokBSD3erkokl@gmail.com experimentalNoneNADT S-Expression format, suitable for representing get-model output of SMT-Lib:Extremely simple minded tokenizer, good for our use model.IThe balance of parens in this string. If 0, this means it's a legit line!GParse a string into an SExpr, potentially failing with an error messageMParses the Z3 floating point formatted numbers like so: 1.321p5/1.2123e9 etc.,Convert an (s, e, m) triple to a float value,Convert an (s, e, m) triple to a float value \Special constants of SMTLib2 and their internal translation. Mainly rounding modes for now. !"#$%&!"#$%&P(c) Levent ErkokBSD3erkokl@gmail.com experimentalNone;=V9K6iPrettyNum class captures printing of numbers in hex and binary formats; also supporting negative numbers.Minimal complete definition: 7 and 87,Show a number in hexadecimal (starting with 0x and type.)8'Show a number in binary (starting with 0b and type.)9/Show a number in hex, without prefix, or types.:/Show a number in bin, without prefix, or types.;Show 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.<Show 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.= Similar to ;; except in binary.> Similar to <; except in binary.'UPad a string to a given length. If the string is longer, then we don't drop anything.(Binary printer) Hex printer?VA more convenient interface for reading binary numbers, also supports negative numbers@vA version of show for floats that generates correct C literals for nan/infinite. NB. Requires "math.h" to be included.AwA version of show for doubles that generates correct C literals for nan/infinite. NB. Requires "math.h" to be included.BUA version of show for floats that generates correct Haskell literals for nan/infiniteCVA version of show for doubles that generates correct Haskell literals for nan/infiniteD[A version of show for floats that generates correct SMTLib literals using the rounding modeE\A version of show for doubles that generates correct SMTLib literals using the rounding mode* Show a rational in SMTLib formatF;Convert a rounding mode to the format SMT-Lib2 understands.G*Convert a CW to an SMTLib2 compliant valueHCreate a skolem 0 for the kind6:978;<=>?@ABCDEFGH6789:(c) Levent ErkokBSD3erkokl@gmail.com experimentalNoneGITest output styleJ"As a Haskell value with given nameK'As a C array of structs with given nameLAs 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 valuesMType of test vectors (abstract)NZRetrieve the test vectors for further processing. This function is useful in cases where PK is not sufficient and custom output (or further preprocessing) is needed.OGenerate 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 G call to indicate what fields should be in the test result. (Also see ' for filtering acceptable test values.)P7Render the test as a Haskell value with the given name n.IKJLMNOPOMNPIJKLIJKLM+Q(c) Levent ErkokBSD3erkokl@gmail.com experimentalNone$e QAn SMT exception generated by the back-end solver and is thrown from SBV. If the solver ever responds with a non-success value for a command, SBV will throw an Q;, 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.,yAn instance of SMT-Lib converter; instantiated for SMT-Lib v1 and v2. (And potentially for newer versions in the future.)-yAn instance of SMT-Lib converter; instantiated for SMT-Lib v1 and v2. (And potentially for newer versions in the future.).,Create an annotated term with the given name/1Show a millisecond time-out value somewhat nicely0XNicely align a potentially multi-line message with some tag, but prefix with three stars1GNicely align a potentially multi-line message with some tag, no prefix.2Align with some given prefix3Diagnostic message when verbose4In case the SMT-Lib solver returns a response over multiple lines, compress them so we have each S-Expression spanning only a single line.5?A fairly nice rendering of the exception, for display purposes.6SMTExceptions are throwable. A simple "show" will render this exception nicely though of course you can inspect the individual fields as necessary.,inputsNewly registered kinds constantsnewly created arraysnewly created tables assignments configuration-Kinds used in the problemis this a sat problem?extra comments to place on top&inputs and aliasing names and trackersskolemized inputs constantsauto-generated tablesuser specified arrays!uninterpreted functions/constants user given axioms  assignments extra constraints output variable  configurationQRSTUVWXYZ[\,-./0134Q RSTUVWXYZ[\R(c) Levent ErkokBSD3erkokl@gmail.com experimentalNonehw7*Translate a problem into an SMTLib2 script8Declare new sorts9Convert in a query context79S(c) Levent ErkokBSD3erkokl@gmail.com experimentalNone$k:.Convert to SMT-Lib, in a full program context.;4Convert to SMT-Lib, in an incremental query context.<Convert to SMTLib-2 format=Convert to SMTLib-2 format:;T(c) Levent ErkokBSD3erkokl@gmail.com experimentalNone$7KQVB>0An internal type to track of solver interactions? All is well@Timeout expiredASomething else went wrong]6Various SMT results that we can extract models out of.^Is there a model?_Extract 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.)`Extract a model dictionary. Extract a dictionary mapping the variables to their respective values as returned by the SMT solver. Also see w.a4Extract a model value for a given element. Also see x.bExtract 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 y.cA simpler variant of _% to get a model out without the fuss.d;Extract model objective values, for all optimization goals.e!Extract the value of an objectivef Instances of f can be automatically extracted from models returned by the solvers. The idea is that the sbv infrastructure provides a stream of CW'9s (constant-words) 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: ggEGiven 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 h2Given 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.iAn optimize call results in a i . In the k case, the boolean is {^ if we reached pareto-query limit and so there might be more unqueried results remaining. If BA, it means that we have all the pareto fronts returned. See the    for details.mA safe call results in a moAn allSat call results in a o. The first boolean says whether we hit the max-model limit as we searched. The second boolean says whether there were prefix-existentials.qA sat call results in a q# The reason for having a separate q is to have a more meaningful  instance.sA prove call results in a sC-Extract the final configuration from a resultu1Parse a signed/sized value from a sequence of CWsvReturn all the models from an allSat call, similar to c3 but is suitable for the case of multiple results.w2Get dictionaries from an all-sat call. Similar to `.x=Extract value of a variable from an all-sat call. Similar to a.yLExtract value of an uninterpreted variable from an all-sat call. Similar to b.D@Extract a model out, will throw error if parsing is unsuccessfulz Given an allSatT call, we typically want to iterate over it and print the results in sequence. The z) function automates this task by calling disp+ on each result, consecutively. The first E 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)F"Show an SMTResult; generic version{Show 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 purposesG:Show bindings in a generalized model dictionary, tabulatedH1Show a constant value, in the user-specified baseI-Helper function to spin off to an SMT solver.JUA standard engine interface. Most solvers follow-suit here in how we "chat" to them..K}A standard solver interface. If the solver is SMT-Lib compliant, then this function should suffice in communicating with it.L A variant of readProcessWithExitCode(; except it deals with SBV continuationsMCompute and report the end timeN&Start a transcript file, if requested.OFinish up the transcript file.P7-Tuples extracted from a modelQ6-Tuples extracted from a modelR5-Tuples extracted from a modelS4-Tuples extracted from a modelT3-Tuples extracted from a modelUTuples extracted from a modelVA 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!WFA rounding mode, extracted from a model. (Default definition suffices)Xr. as extracted from a model; trivial definitionY as extracted from a modelZ as extracted from a model[M as extracted from a model\] as extracted from a model^_ as extracted from a model`a as extracted from a modelbc as extracted from a modelde as extracted from a modelfg as extracted from a modelhi as extracted from a modeljk as extracted from a modellm as extracted from a modeln as extracted from a modeloBase case for f= at unit type. Comes in handy if there are no real variables.p as a generic model providerqq as a generic model providerrs as a generic model providerKThe currrent configurationContext in which we are running The programThe continuation ]_`^abcdefghijklmnopqrstuvwxyz{J>?@A]^_`abcdefghgijklmnopqrstU(c) Levent ErkokBSD3erkokl@gmail.com experimentalNoneVésAThe 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.sV(c) Levent ErkokBSD3erkokl@gmail.com experimentalNoneVtCThe 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.tW(c) Levent ErkokBSD3erkokl@gmail.com experimentalNoneVuEThe 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.uX(c) Levent ErkokBSD3erkokl@gmail.com experimentalNoneVvBThe 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.vY(c) Levent ErkokBSD3erkokl@gmail.com experimentalNoneZwGThe 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.wZ(c) Adam FoltzerBSD3erkokl@gmail.com experimentalNonex2The 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.x[(c) Levent ErkokBSD3erkokl@gmail.com experimentalNone $7;=NV])(#|3A class which allows for sexpr-conversion to valuesy@Adding a constraint, possibly named. Only used internally. Use  and  from user programs.zGet the current configuration{Get the objectives|Get the program}Get the assertions put in via sAssert~Perform an arbitrary IO action.~>Sync-up the external solver with new context we have generatedRetrieve the query contextModify the query state$Execute in a new incremental context Similar to ", except creates unnamed variable.YCreate a fresh variable in query mode. You should prefer creating input variables using sBool, sInt32\, 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.If  is {Q, 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.4Send a string to the solver, and return the responsezSend a string to the solver, and return the response. Except, if the response is one of the "ignore" ones, keep querying.6Send a string to the solver. If the first argument is {R, we will require a "success" response as well. Otherwise, we'll fire and forget.Retrieve 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.$Integral values are easy to convert:Get the value of a term.3Get the value of an uninterpreted sort, as a StringrGet the value of a term, but in CW form. Used internally. The model-index, in particular is extremely Z3 specific!CRecover a given solver-printed value with a possible interpretationGet the value of a term. If the kind is Real and solver supports decimal approximations, we will "squash" the representations.Check for satisfiability.?Check for satisfiability with a custom check-sat-using command.NWhat are the top level inputs? Trackers are returned as top level existentialsKGet observables, i.e., those explicitly labeled by the user with a call to observe.Repeatedly issue check-sat, after refuting the previous model. The bool is true if the model is unique upto prefix existentials.CRetrieve the set of unsatisfiable assumptions, following a call to $checkSatAssumingWithUnsatisfiableSeti. Note that this function isn't exported to the user, but rather used internally. The user simple calls $checkSatAssumingWithUnsatisfiableSet.qTimeout 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.Bail out if a parse goes bad)Bail out if we don't get what we expected(Convert a query result to an SMT Problem  as a .|}z{|}~|}}\(c) Levent ErkokBSD3erkokl@gmail.com experimentalNone$NQV] An Assignment of a model bindingAsk solver for info.Retrieve the value of an  'SMTOption.'h The curious function argument is on purpose here, simply pass the constructor name. Example: the call  ' will return either Nothing or Just (ProduceUnsatCores True) or Just (ProduceUnsatCores False).Result will be , if the solver does not support this option.-Get the reason unknown. Only internally used.*Issue check-sat and get an SMT Result out.CClassify a model based on whether it has unbound objectives or not.@Issue check-sat and get results of a lexicographic optimization.GIssue check-sat and get results of an independent (boxed) optimization.,Construct a pareto-front optimization resultXCollect 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 .@Get a model stored at an index. This is likely very Z3 specific!kJust after a check-sat is issued, collect objective values. Used internally only, not exposed to the user.ACheck for satisfiability, under the given conditions. Similar to g 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 J conclusion.)pCheck for satisfiability, under the given conditions. Returns the unsatisfiable set of assumptions. Similar to n except it allows making further assumptions as captured by the first argument of booleans. If the result is JP, the user will also receive a subset of the given assumptions that led to the Jv conclusion. Note that while this set will be a subset of the inputs, it is not necessarily guaranteed to be minimal.GYou must have arranged for the production of unsat assumptions first (via   $ & {") 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  namedAssert. If 9 fills your needs, you should definitely prefer it over .GHelper for the two variants of checkSatAssuming we have. Internal only.)The current assertion stack depth, i.e., push - &pops after start. Always non-negative.oRun the query in a new assertion stack. That is, we push the context, run the query commands, and pop it back.@Push the context, entering a new one. Pushes multiple levels if n > 1.<Pop the context, exiting a new one. Pops multiple levels if n3 > 1. It's an error to pop levels that don't exist.Search 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.eReset the solver, by forgetting all the assertions. However, bindings are kept as is, as opposed to reset. Use this variant to clean-up the solver state while leaving the bindings intact. Pops all assertion levels. Declarations and definitions resulting from the  l command are unaffected. Note that SBV implicitly uses global-declarations, so bindings will remain intact.GEcho a string. Note that the echoing is done by the solver, not by SBV.Exit 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.\Retrieve the unsat-core. Note you must have arranged for unsat cores to be produced first (via   $ ' {") for this call to not error out!@Retrieve the unsat core if it was asked for in the configurationRRetrieve the proof. Note you must have arranged for proofs to be produced first (via   $ $ {") 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.Retrieve interpolants after an JY result is obtained. Note you must have arranged for interpolants to be produced first (via   $ % {") for this call to not error out!-To get an interpolant for a pair of formulas A and B, use a  to attach names to A and B . Then call   ["A", "B"]9, assuming those are the names you gave to the formulas.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.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.XRetrieve assertions. Note you must have arranged for assertions to be available first (via   $ " {") 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.:Retrieve the assignment. This is a lightweight version of K, where the solver returns the truth value for all named subterms of type .Make 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.,Produce the query result from an assignment.t  !"#$%&'()*+,-./0123456789:;<=>?DF@ABCEGHIJK~1(c) Levent ErkokBSD3erkokl@gmail.com experimentalNone$Run a custom queryp  !"#$%&'()*+,-./0123456789:;<=>?DF@ABCEGHIJK |}~q HIJK|}}?@ABCDEFG<=>89:;./01234567~ !"#$%&'()*+,- ](c) Levent ErkokBSD3erkokl@gmail.com experimentalNone$;=V,ISymbolically 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.&Check safety using the default solver.Check if any of the sAssert calls can be violated.A 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.)Turns 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.]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.CTurns 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.) Version of  that allows user defined names.,Prove a predicate, using the default solver./Prove the predicate using the given SMT-solver.GFind a satisfying assignment for a predicate, using the default solver.8Find a satisfying assignment using the given SMT-solver.?Find all satisfying assignments, using the default solver. See  for details.AReturn all satisfying assignments for a predicate, equivalent to  . Note that this call will block until all satisfying assignments are found. If you have a problem with infinitely many satisfying models (consider h) or a very large number of them, you might have to wait for a long time. To avoid such cases, use the ! parameter in the configuration.rNB. Uninterpreted constant/function values and counter-examples for array values are ignored for the purposes of &. 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-solverOptimize a given collection of s4Optimizes the objectives using the given SMT-solver.HCheck if the constraints given are consistent, using the default solver.DDetermine if the constraints are vacuous using the given SMT-solver.,Checks theoremhood using the default solver.,Check whether a given property is a theorem./Checks satisfiability using the default solver..Check whether a given property is satisfiable.~Prove a property with multiple solvers, running them in separate threads. The results will be returned in the order produced.Prove 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 a  ThreadKilled 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.Find a satisfying assignment to a property with multiple solvers, running them in separate threads. The results will be returned in the order produced.Find 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 a  ThreadKilled 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."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.A 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.A 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.qIf supported, this makes all output go to stdout, which works better with SBV Alas, not all solvers support it..2Default configuration for the Boolector SMT solver.Default configuration for the CVC4 SMT Solver./Default configuration for the Yices SMT Solver.+Default configuration for the Z3 SMT solver0Default configuration for the MathSAT SMT solverBDefault configuration for the ABC synthesis and verification tool.<The default solver used by SBV. This is currently set to z3.5Run an arbitrary symbolic computation, equivalent to  GRuns an arbitrary symbolic computation, exposed to the user in SAT modeRuns with a query.0Check if a safe-call was safe or not, turning a m to a Bool.LPerform an action asynchronously, returning results together with diff-time.Perform 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.=Perform action for all given configs, return all the results.c]_`^abcdefghijklmnopqrstvwxyz^(c) Levent ErkokBSD3erkokl@gmail.com experimentalNone 7;<=>?QSTVtwClass of metrics we can optimize for. Currently, bounded signed/unsigned bit-vectors, unbounded integers, and algebraic reals can be optimized. (But not, say, SFloat, SDouble, or SBool.) Minimal complete definition: minimize/maximize.EA good reference on these features is given in the following paper:  Yhttps://www.microsoft.com/en-us/research/wp-content/uploads/2016/02/nbjorner-scss2014.pdf.Minimize a named metricMaximize a named metricUninterpreted 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: . However, most instances in practice are already provided by SBV, so end-users should not need to define their own instances.Uninterpret 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. 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.Most generalized form of uninterpretation, this function should not be needed by end-user-code, but is rather useful for the library development.Not exported. Used only in k. Instances are provided for the generic representations of product types where each element is Mergeable.)Symbolic conditionals are modeled by the  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  instance may be automatically derived for a custom data-type with a single constructor where the type of each field is an instance of ?, such as a record of symbolic values. Users only need to add  and  to the deriving clause for the data-type. See 0_] for an example and an illustration of what the instance would look like if written by hand. The function  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 Q. Note that most types subject to merging are likely to be trivial instances of Generic.'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.Total indexing operation. select xs default index is intuitively the same as  xs !! index, except it evaluates to default if index underflows/overflows.The P 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 ) 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  0 = (0, x) x  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.Minimal complete definition: , ;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: . Bit size.:Least significant bit of a word, always stored at index 0.CMost significant bit of a word, always stored at the last position.,Big-endian blasting of a word into its bits./Little-endian blasting of a word into its bits.4Reconstruct from given bits, given in little-endian.4Reconstruct from given bits, given in little-endian.Replacement for  , returning  instead of . Variant of 2, where we want to extract multiple bit positions. Variant of , returning a symbolic value. A combo of  and %, when the bit to be set is symbolic.NFull adder, returns carry-out from the addition. Only for unsigned quantities.SFull multipler, returns both high and low-order bits. Only for unsigned quantities.9Count leading zeros in a word, big-endian interpretation.:Count trailing zeros in a word, big-endian interpretation.Symbolic 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 , M 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.!Symbolic Comparisons. Similar to  , we cannot implement Haskell's + class since there is no way to return an 1 value from a symbolic comparison. Furthermore,  requires R to implement if-then-else, for the benefit of implementing symbolic versions of  and  functions.Symbolic less than.Symbolic less than or equal to.Symbolic greater than."Symbolic greater than or equal to.Symbolic minimum.Symbolic maximum.!Is the value withing the allowed  inclusive range?4Symbolic 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.Symbolic equality.Symbolic inequality.LReturns (symbolic) true if all the elements of the given list are different.KReturns (symbolic) true if all the elements of the given list are the same.Symbolic membership test.+Generate a finite symbolic bitvector, named-Generate a finite symbolic bitvector, unnamed$Generate a finite constant bitvector'Convert a constant to an integral valueGenerically make a symbolic var Declare an Declare a list of s Declare an Declare a list of s Declare an Declare a list of s Declare an Declare a list of s Declare an Declare a list of s Declare an Declare a list of s Declare an Declare a list of s Declare an  Declare a list of s  Declare an  Declare a list of s  Declare an  Declare a list of s Declare an Declare a list of s Declare an Declare a list of s Declare an Declare a list of s Declare an  Declare an Declare a list of sDeclare a list of sKConvert 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.label: 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."Observe the value of an expression. 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..Returns 1 if the boolean is true, otherwise 0.+Lift a pseudo-boolean op, performing checks if at most k of the input arguments are  if at least k of the input arguments are  if exactly k of the input arguments are  if the sum of coefficients for  elements is at most k. Generalizes .  if the sum of coefficients for  elements is at least k. Generalizes .! if the sum of coefficients for  elements is exactly least k. Useful for coding exactly K-of-N2 constraints, and in particular mutex constraints." if there is at most one set bit# if there is exactly one set bitEConvert a concrete pseudo-boolean to given int; converting to integer:Predicate for optimizing word operations like (+) and (*).:Predicate for optimizing word operations like (+) and (*).$ASymbolic exponentiation using bit blasting and repeated squaring.ZN.B. The exponent must be unsigned/bounded if symbolic. Signed exponents will be rejected.&Lift a 1 arg FP-op, using sRNE default7Lift a float/double unary function, only over constants8Lift a float/double binary function, only over constants%?Conversion between integral-symbolic values, akin to Haskell's Lift 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.&Generalization of 6, when the shift-amount is symbolic. Since Haskell's  only takes an EV as the shift amount, it cannot be used when we have a symbolic amount to shift with.'Generalization of 6, when the shift-amount is symbolic. Since Haskell's  only takes an EV 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.(UArithmetic 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.)Generalization of 6, when the shift-amount is symbolic. Since Haskell's  only takes an E 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.*Generalization of 6, when the shift-amount is symbolic. Since Haskell's  only takes an E 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.*Helper function for use in enum operations+Lift QRem2 to symbolic words. Division by 0 is defined s.t. x/0 = 0; which holds even when x is 0 itself.,Lift DMod2 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)-$If-then-else. This is by definition S with both branches forced. This is typically the desired behavior, but also see . should you need more laziness..A 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./Symbolic assert. Check that the given boolean condition is always true in the given path. The optional first argument can be used to provide call-stack info via GHC's location facilities.#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 2 when needed; which should be rare to start with.)KNot exported. Symbolic merge using the generic representation provided by `a.04Introduce a soft assertion, with an optional penalty11Quick 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.Explicit 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.FSymbolic computations provide a context for writing symbolic programs.'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.CBase type of () allows simple construction for uninterpreted types.s      !"#$%&'()*+,-./01444444(c) Levent ErkokBSD3erkokl@gmail.com experimentalNone;<=V2]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. 27 structures provide logarithmic time reads and writes.3`Reading a value. We bit-blast the index and descend down the full tree according to bit-values.4Writing a value, similar to how reads are done. The important thing is that the tree representation keeps updates to a minimum.5AConstruct the fully balanced initial tree using the given values.23452345(c) Levent ErkokBSD3erkokl@gmail.com experimentalNone;<=8pImplements polynomial addition, multiplication, division, and modulus operations over GF(2^n). NB. Similar to , division by 0 is interpreted as follows: x > 0 = (0, x)for all x (including 0)Minimal complete definition: ;, >, @9@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.:Add two polynomials in GF(2^n).;Multiply 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.<DDivide two polynomials in GF(2^n), see above note for division by 0.=OCompute modulus of two polynomials in GF(2^n), see above note for modulus by 0.>%Division and modulus packed together.?CDisplay a polynomial like a mathematician would (over the monomial x), with a type.@CDisplay a polynomial like a mathematician would (over the monomial xC), the first argument controls if the final type is shown as well.Pretty print as a polynomialAAdd two polynomialsBRun down a boolean condition over two lists. Note that this is different than zipWith as shorter list is assumed to be filled with false at the end (i.e., zero-bits); which nicely pads it when considered as an unsigned number in little-endian form.}Multiply two polynomials and reduce by the third (concrete) irreducible, given by its coefficients. See the remarks for the ; function for this design choiceC8Compute modulus/remainder of polynomials on bit-vectors.D(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.EACompute CRC's over polynomials, i.e., symbolic words. The first E0 argument plays the same role as the one in the D function.89:;<=>?@ABCDE89:;<=>?@EDBCA89:;<=>?@ (c) Joel Burget, Levent ErkokBSD3erkokl@gmail.com experimentalNoneQVwNLength 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.OO 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.PPB returns the head of a string. Unspecified if the string is empty.&prove $ \c -> head (charToStr c) .== cQ.E.D.QQB returns the tail of a string. Unspecified if the string is empty..prove $ \h s -> tail (charToStr h .++ s) .== sQ.E.D.@prove $ \s -> length s .> 0 ==> length (tail s) .== length s - 1Q.E.D.Cprove $ \s -> bnot (null s) ==> charToStr (head s) .++ tail s .== sQ.E.D.RR 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' ==> charToStr c .== "A"Q.E.D.(prove $ \c -> length (charToStr c) .== 1Q.E.D.SS s offset. Substring of length 1 at offset in s). Unspecified if index 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 " :: StringTT 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.Kprove $ \s i c -> s `strToCharAt` i .== c ==> indexOf s (charToStr c) .<= iQ.E.D.UShort cut for TVV 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.W"Concatenate two strings. See also X.XShort cut for W.Vsat $ \x y z -> length x .== 5 &&& length y .== 1 &&& x .++ y .++ z .== "Hello world!"Satisfiable. Model: s0 = "Hello" :: String s1 = " " :: String s2 = "world!" :: StringYY sub s. Does s contain the substring sub?6prove $ \s1 s2 s3 -> s2 `isInfixOf` (s1 .++ s2 .++ s3)Q.E.D.Gprove $ \s1 s2 -> s1 `isInfixOf` s2 &&& s2 `isInfixOf` s1 <=> s1 .== s2Q.E.D.ZZ 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.[[ 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.\\ len s. Corresponds to Haskell's \ on symbolic-strings.3prove $ \s i -> i .>= 0 ==> length (take i s) .<= iQ.E.D.]] 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.^^ 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 sF. For a friendlier version of this function that acts like Haskell's \/], see strTake/strDrop.^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__ 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.`` s sub. Retrieves first position of sub in s, -1- if there are no occurrences. Equivalent to a s sub 0.Kprove $ \s i -> i .> 0 &&& i .< length s ==> indexOf s (subStr s i 1) .<= iQ.E.D.Kprove $ \s i -> i .> 0 &&& i .< length s ==> indexOf s (subStr s i 1) .== iFalsifiable. Counter-example: s0 = "\NUL\NUL\NUL" :: String s1 = 2 :: IntegerAprove $ \s1 s2 -> length s2 .> length s1 ==> indexOf s1 s2 .== -1Q.E.D.aa 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.bb 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'. See  (http://cvc4.cs.stanford.edu/wiki/Strings for details.Jprove $ \s -> let n = strToNat s in n .>= 0 &&& n .< 10 ==> length s .== 1Q.E.D.cc 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. See  (http://cvc4.cs.stanford.edu/wiki/Strings for details.5prove $ \i -> length (natToStr i) .== 3 ==> i .<= 999Q.E.D.#Lift a unary operator over strings.$Lift a binary operator over strings.%Lift a ternary operator over strings.!Concrete evaluation for unary ops"Concrete evaluation for binary ops#Concrete evaluation for ternary ops%Is the string concretely known empty?NOPQRSTUVWXYZ[\]^_`abcNOPQRSTUVWXY[Z\]^_`abcX5b(c) Levent ErkokBSD3erkokl@gmail.com experimentalNone;=>?A}d Splitting an a into two b#'s and joining back. Intuitively, a is a larger bit-size word than b, typically double. The g# operation captures embedding of a b value into an a& without changing its semantic value..Minimal complete definition: All, no defaults.defgdefgf5c(c) Levent ErkokBSD3erkokl@gmail.com experimentalNoneQV.hBCapture convertability from/to FloatingPoint representations NB. i and k- are underspecified when given when given a NaN, +oo, or -oov value that cannot be represented in the target domain. For these inputs, we define the result to be +0, arbitrarily.mA 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.n*Compute the floating point absolute value.o&Compute the unary negation. Note that 0 - x is not equivalent to -x for floating-point, since -0 and 0 are different.p<Add two floating point values, using the given rounding modeqASubtract two floating point values, using the given rounding moderAMultiply two floating point values, using the given rounding modes?Divide two floating point values, using the given rounding modetOFused-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.uACompute the square-root of a float, using the given rounding modevCompute the remainder:  x - y * n, where nY is the truncated integer nearest to x/y. The rounding mode is implicitly assumed to be RoundNearestTiesToEven.wCRound to the nearest integral value, using the given rounding mode.x,Compute the minimum of two floats, respects infinity and NaN valuesy,Compute the maximum of two floats, respects infinity and NaN valuesz4Are 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 .){FIs the floating-point number a normal value. (i.e., not denormalized.)|IIs the floating-point number a subnormal value. (Also known as denormal.)}WIs the floating-point number 0? (Note that both +0 and -0 will satisfy this predicate.)~`Is the floating-point number infinity? (Note that both +oo and -oo will satisfy this predicate.))Is the floating-point number a NaN value?]Is the floating-point number negative? Note that -0 satisfies this predicate but +0 does not.]Is the floating-point number positive? Note that +0 satisfies this predicate but -0 does not. Is the floating point number -0? Is the floating point number +0?yIs the floating-point number a regular floating point, i.e., not NaN, nor +oo, nor -oo. Normals or denormals are allowed.LA generic converter that will work for most of our instances. (But not all!)#Check that a given float is a pointqConcretely evaluate one arg function, if rounding mode is RoundNearestTiesToEven and we have enough concrete dataqConcretely evaluate two arg function, if rounding mode is RoundNearestTiesToEven and we have enough concrete dataConcretely evaluate a bool producing two arg function, if rounding mode is RoundNearestTiesToEven and we have enough concrete dataqConcretely evaluate two arg function, if rounding mode is RoundNearestTiesToEven and we have enough concrete data7Add the converted rounding mode if given as an argumentLift a 1 arg FP-opLift an FP predicateLift a 2 arg FP-opLift min/max: Note that we protect against constant folding if args are alternating sign 0's, since SMTLib is deliberately nondeterministic in this case"Lift a 2 arg FP-op, producing boolLift a 3 arg FP-op Convert an  to an M, 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. Convert an  to an M, 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.Extract 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.Extract 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.QReinterpret the bits in a 32-bit word as a single-precision floating point numberQReinterpret the bits in a 32-bit word as a single-precision floating point numberSDouble instanceSFloat instance#hijklmnopqrstuvwxyz{|}~hijklmnopqrstuvwxyz{|}~ (c) Levent ErkokBSD3erkokl@gmail.com experimentalNoneQVIs the character in the string?:set -XOverloadedStrings"prove $ \c -> c `elem` charToStr cQ.E.D. prove $ \c -> bnot (c `elem` "")Q.E.D.#Is the character not in the string?3prove $ \c s -> c `elem` s <=> bnot (c `notElem` s)Q.E.D.The  of a character.*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.Convert to lower-case./prove $ \c -> toLower (toLower c) .== toLower cQ.E.D.5prove $ \c -> isLower c ==> toLower (toUpper c) .== cQ.E.D.: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.mConvert 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 -> bnot (isDigit c ||| isHexDigit c) ==> digitToInt c .== -1Q.E.D.-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.Oprove $ \c -> digitToInt c .== -1 <=> intToDigit (digitToInt c) .== literal ' 'Q.E.D.\Is this a control character? Control characters are essentially the non-printing characters.1Is this white-space? That is, one of "tnvfr 160".Is this a lower-case character?/prove $ \c -> isUpper c ==> isLower (toLower c)Q.E.D. Is this an upper-case character?,prove $ \c -> bnot (isLower c &&& isUpper c)Q.E.D.Is this an alphabet character? That is lower-case, upper-case and title-case letters, plus letters of caseless scripts and modifiers letters. Is this an  or .7prove $ \c -> isAlphaNum c <=> isAlpha c ||| isNumber cQ.E.D.=Is this a printable character? Essentially the complement of ], with one exception. The Latin-1 character 173 is neither control nor printable. Go figure.Gprove $ \c -> c .== literal '\173' ||| isControl c <=> bnot (isPrint c)Q.E.D.%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.%Is this an Octal digit, i.e., one of 0..7.(prove $ \c -> isOctDigit c ==> isDigit cQ.E.D.!Is this a Hex digit, i.e, one of 0..9, a..f, A..F.+prove $ \c -> isHexDigit c ==> isAlphaNum cQ.E.D.HIs this an alphabet character. Note that this function is equivalent to .&prove $ \c -> isLetter c <=> isAlpha cQ.E.D.Is 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 $ bnot . isMarkQ.E.D.Is 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.Is this a punctuation mark?Is this a symbol?Is this a separator?)prove $ \c -> isSeparator c ==> isSpace cQ.E.D.;Is this an ASCII character, i.e., the first 128 characters.IIs this a Latin1 character? Note that this function is always true since 5 corresponds precisely to Latin1 for the time being.prove isLatin1Q.E.D.Is this an ASCII letter?Cprove $ \c -> isAsciiLetter c <=> isAsciiUpper c ||| isAsciiLower cQ.E.D.*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.8prove $ \c -> isAsciiUpper c <=> isAscii c &&& isUpper cQ.E.D.*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.8prove $ \c -> isAsciiLower c <=> isAscii c &&& isLower cQ.E.D.(c) Levent ErkokBSD3erkokl@gmail.com experimentalNone;=QVaa/Matchable class. Things we can match against a , . (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 = "222-2248" :: String s r checks whether s! is in the language generated by r.QA 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.Jprove $ \(s :: SString) -> s `match` exactly "LITERAL" <=> s .== "LITERAL"Q.E.D.#Helper to define a character class.Uprove $ \(c :: SChar) -> c `match` oneOf "ABCD" <=> bAny (c .==) (map literal "ABCD")Q.E.D.ARecognize 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.Recognize a tab.tab(str.to.re "\x09")2prove $ \c -> c `match` tab ==> c .== literal '\t'Q.E.D..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.Recognize white space.0prove $ \c -> c `match` whiteSpace ==> isSpace cQ.E.D.IRecognize 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.$Recognize an alphabet letter, i.e., A..Z, a..z. asciiLetter0(re.union (re.range "a" "z") (re.range "A" "Z"))Eprove $ \c -> c `match` asciiLetter <=> toUpper c `match` asciiLetterQ.E.D.Eprove $ \c -> c `match` asciiLetter <=> toLower c `match` asciiLetterQ.E.D.$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.Recognize 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.Recognize a digit. One of 0..9.digit(re.range "0" "9")Mprove $ \c -> c `match` digit <=> let v = digitToInt c in 0 .<= v &&& v .< 10Q.E.D.!Recognize an octal digit. One of 0..7.octDigit(re.range "0" "7")Oprove $ \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.&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"))Pprove $ \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.Recognize a decimal number.decimal(re.+ (re.range "0" "9"))Qprove $ \s -> (s::SString) `match` decimal ==> bnot (s `match` KStar asciiLetter)Q.E.D.: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 ==> bAny (.== take 2 s) ["0o", "0O"]Q.E.D.?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 ==> bAny (.== take 2 s) ["0x", "0X"]Q.E.D.Recognize 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.For 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.#Lift a unary operator over strings.!Concrete evaluation for unary ops$Quiet GHC about testing only importsMatching symbolic strings.IMatching a character simply means the singleton string matches the regex. ,-.46/012357 ,-./01234567d(c) Levent ErkokBSD3erkokl@gmail.com experimentalNone;=K1CDifferent kinds of "files" we can produce. Currently this is quite C specific.5Representation of a collection of generated programs.Possible mappings for the C type when translated to C. Used in conjunction with the function . 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. float double  long doubleThe code-generation monad. Allows for precise layout of input values reference parameters (for returning composite values in languages such as C), and return values.Code-generation state%Abstraction of target language valuesOptions for code-generation.If {R, perform run-time-checks for index-out-of-bounds or shifting-by-large values etc.2Bit-size to use for representing SInteger (if any)+Type to use for representing SReal (if any)YValues to use for the driver program generated, useful for generating non-random drivers.If { , will generate a driver programIf {, will generate a makefileIf {, will ignore sAssert calls5Abstract over code generation for different languagesuDefault options for code generation. The run-time checks are turned-off, and the driver values are completely random.)Initial configuration for code-generation.Reach into symbolic monad from code-generationJReach into symbolic monad and output a value. Returns the corresponding SWaSets RTC (run-time-checks) for index-out-of-bounds, shift-with-large value etc. on/off. Default: B.4Sets number of bits to be used for representing the < 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.0Sets the C type to be used for representing the > 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..Should we generate a driver program? Default: {l. When a library is generated, it will have a driver if any of the contituent functions has a driver. (See  compileToCLib.)(Should we generate a Makefile? Default: {.Sets driver program run time values, useful for generating programs with fixed drivers for testing. Default: None, i.e., use random values.&Ignore assertions (those generated by sAssert calls) in the generated C codeoAdds the given lines to the header file generated, useful for generating programs with uninterpreted functions.pAdds the given lines to the program file generated, useful for generating programs with uninterpreted functions.jAdds the given words to the compiler options in the generated Makefile, useful for linking extra stuff in..Creates an atomic input in the generated code.-Creates an array input in the generated code./Creates an atomic output in the generated code..Creates an array output in the generated code.9Creates a returned (unnamed) value in the generated code.?Creates a returned (unnamed) array value in the generated code..Creates an atomic input in the generated code.-Creates an array input in the generated code./Creates an atomic output in the generated code..Creates an array output in the generated code.9Creates a returned (unnamed) value in the generated code.?Creates a returned (unnamed) array value in the generated code.Is this a driver program?Is this a make file?}Generate code for a symbolic program, returning a Code-gen bundle, i.e., collection of makefiles, source code, headers, etc.4Render a code-gen bundle to a directory or to stdoutAn alternative to Pretty's renderb, which might have "leading" white-space in empty lines. This version eliminates such whitespace.Ae(c) Levent ErkokBSD3erkokl@gmail.com experimentalNonegGiven 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  ".". 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 Makefile3, a header file, and a driver (test) program, etc.Lower level version of , producing a Create 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  ".". 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 , except in a list.Lower level version of , producing a Pretty 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.TRenders as "const SWord8 s0", etc. the first parameter is the width of the typefieldAReturn the proper declaration and the result as a pair. No consts3Renders as "s0", etc, or the corresponding constant!Words as it would map to a C wordAlmost a "show", but map SWord1 to SBool- which is used for extracting one-bit words.!The printf specifier for the typeMake 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.DGenerate a makefile. The first argument is True if we have a driver.Generate the header"Generate an example driver programGenerate the C program7Merge a bunch of bundles to generate code for a library!Create a Makefile for the libraryCreate a driver for a library (c) Levent ErkokBSD3erkokl@gmail.com experimentalNone(c) Levent ErkokBSD3erkokl@gmail.com experimentalNone֬Send 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!vRetrieve 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!Send 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.LMNOPWQRSTUVXYZ[\]^_`abcdefghijklmnopqrstuv|wxyz{}~      !"#$%&'()*+,-.46/01235789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcurszhidefgjklmnopqtvwxy{|}~      !"#$%&'()*+,-./0123456:978;<=>?@ABCDEFGHu{+,  "#$% &'()*+,-./rstuvwxyz{|}MNOLhijklmnopq~1502%&PQRSTUVWXYZ[\]Qcdefghijklmnopqrstuvwxyz{|}~EFGHIJKLMNOPQRSTUVWXYZ[\]^_`ab89:;<=>?@ABCD,-./01234567!"#$ !^_`abcdefg      '()*+34    rstuu{+,6789:?;<=>@ABCDEFGH(c) Levent ErkokBSD3erkokl@gmail.com experimentalNone0;=VEquality as a proof method. Allows for very concise construction of equivalence proofs, which is very typical in bit-precise proofs.Form 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]  Check 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. :The default configs corresponding to supported SMT solvers EReturn the known available solver configs, installed on your machine. $Make an enumeration a symbolic type.Ekgc_miea     MPWQRSTUVXYZ[\]^_`abcdefghijklmnopq      "#$%&'()*+,-./5QRSTUVWXYZ[\]_`^abcdefghijklmnopqrstvwxyz      !"#$%&'()*-./01UXdefghijklmnopqrstuvwxyz{|}~    MXU5     -.%&')*(defg$mnopqrstuvwxyz{|}~ "#$%&'()*+,-./hijkl  !"#/1 0hijklmnopqstqropmnijklfghg]^_`abcdezvwxy       QRSTUVWXYZ[\PQRSTUVWXYZ[\]Q^_`abcdefg4(c) Brian HuffmanBSD3erkokl@gmail.com experimentalNone Dynamic variant of quick-checkCreate 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./Proves the predicate using the given SMT-solver7Find a satisfying assignment using the given SMT-solver'Check safety using the given SMT-solver :Find all satisfying assignments using the given SMT-solver!~Prove a property with multiple solvers, running them in separate threads. The results will be returned in the order produced."Prove 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.#Find a satisfying assignment to a property with multiple solvers, running them in separate threads. The results will be returned in the order produced.$Find 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.%Extract 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.)&Extract a model dictionary. Extract a dictionary mapping the variables to their respective values as returned by the SMT solver. Also see getModelDictionaries.PWQRSTUVXYZ[\]^_`abcdefgrstuv|wxyz{})*+ijklmnopqrstu    !"#$%&PQRSTUVWXYZ[\]Q^_`abcdefgrstuvwxyz{|})*+ !"#$stqropmnijklu%&    (c) Levent ErkokBSD3erkokl@gmail.com experimentalNone'' Formalizes Dhttps://graphics.stanford.edu/~seander/bithacks.html#IntegerMinOrMax( Formalizes Dhttps://graphics.stanford.edu/~seander/bithacks.html#IntegerMinOrMax) Formalizes Hhttps://graphics.stanford.edu/~seander/bithacks.html#DetectOppositeSigns* Formalizes ^https://graphics.stanford.edu/~seander/bithacks.html#ConditionalSetOrClearBitsWithoutBranching+ Formalizes Hhttps://graphics.stanford.edu/~seander/bithacks.html#DetermineIfPowerOf2,Collection of queries'()*+,'()*+, (c) Levent ErkokBSD3erkokl@gmail.com experimentalNone68cp&-LChoose the appropriate array model to be used for modeling the memory. (See 7.) The  is the function based model. $ is the SMT-Lib array's based model..4Helper synonym for capturing relevant bits of Mostek/An instruction is modeled as a 0M transformer. We model mostek programs in direct continuation passing style.0BPrograms are essentially state transformers (on the machine state)10Given a machine state, compute a value out of it2Abstraction 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!)2+ is equipped with an automatically derived ! instance because each field is .72The memory maps 32-bit words to 8-bit words. (The -H data-type is defined later, depending on the verification model used.)8 Flag bank9 Register bank:-Convenient synonym for symbolic machine bits.;Mostek was an 8-bit machine.<The carry flag (=) and the zero flag (>)?XWe model only two registers of Mostek that is used in the above algorithm, can add more.B(The memory is addressed by 32-bit words.C!Get the value of a given registerD!Set the value of a given registerEGet the value of a flagFSet the value of a flagG Read memoryHWrite to memoryI-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 J.JCorrectness theorem for our I implementation.We have:checkOverflowCorrectQ.E.D.KLDX: Set register X to value vLLDA: Set register A to value vMCLC: Clear the carry flagN9ROR, 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.OROR, register version: Same as N, except through register r.PBCC: branch to label l if the carry flag is falseQ%ADC: Increment the value of register A- by the value of memory contents at address a7, using the carry-bit as the carry-in for the addition.R%DEX: Decrement the value of register XS%BNE: Branch if the zero-flag is falseTThe TU combinator "stops" our program, providing the final continuation that does nothing.U<Parameterized by the addresses of locations of the factors (F1 and F2f), the following program multiplies them, storing the low-byte of the result in the memory location lowAddr , and the high-byte in register An. The implementation is a direct transliteration of Legato's algorithm given at the top, using our notation.VjGiven address/value pairs for F1 and F2, and the location of where the low-byte of the result should go,  runLegato" takes an arbitrary machine state m; and returns the high and low bytes of the multiplication.W{Create an instance of the Mostek machine, initialized by the memory and the relevant values of the registers and the flagsXNThe 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.YaThe correctness theorem. On a 2011 MacBook, this proof takes about 1 minute 45 seconds with the - memory model using boolector as the solver.ZFGenerate a C program that implements Legato's algorithm automatically..-./0123546789:;<>=?A@BCDEFGHIJKLMNOPQRSTUVWXYZ.B?@A<=>;:9872345610CDEFGHIJ/KLMNOPQRSTUV.WX-YZ23456<=>?@A(c) Levent ErkokBSD3erkokl@gmail.com experimentalNoney`gIElement type of lists we'd like to sort. For simplicity, we'll just use ) here, but we can pick any symbolic type.h5Merging two given sorted lists, preserving the order.iSimple 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.j1Check whether a given sequence is non-decreasing.kCheck 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.lAsserting 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 nY increases. A value around 5 or 6 should be fairly easy to prove. For instance, we have: correctness 5Q.E.D.m3Generate 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.ghijklmghijklm(c) Levent ErkokBSD3erkokl@gmail.com experimentalNone^n7Find the multiplier and the mask as described. We have: maskAndMultSatisfiable. Model:% mask = 0x8080808080808080 :: Word64% mult = 0xc202040810204081 :: 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.nn(c) Levent ErkokBSD3erkokl@gmail.com experimentalNoneQV oIA 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.p The tie operator, concatenation.qaThe zip operator, zips the power-lists of the same size, returns a powerlist of double the size.rInverse of zipping.sReference prefix sum (ps) is simply Haskell's scanl1 function.tThe 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=197356ugCorrectness theorem, for a powerlist of given size, an associative operator, and its left-unit element.vNProves 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.wPProves 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. opqrstuvw opqrstuvw(c) Levent ErkokBSD3erkokl@gmail.com experimentalNonejx,Simple function that returns add/sum of argsyKGenerate 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" ==================xyxy(c) Levent ErkokBSD3erkokl@gmail.com experimentalNone+zThe 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.{ 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.|(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.}Prove that the custom D^ function is equivalent to the mathematical definition of CRC's for 11 bit messages. We have:crcGoodQ.E.D.~OGenerate a C function to compute the USB CRC, using the internal CRC function.Generate 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.z{|}~z{|}~(c) Lee Pike, Levent ErkokBSD3erkokl@gmail.com experimentalNone cThis 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.)cThe 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..We 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; },Compute the fibonacci numbers statically at code-generation0 time and put them in a table, accessed by the  call.  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  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 experimentalNone Q>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.We have:prove sgcdIsCorrectQ.E.D.`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 experimentalNone (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 :: SWord8Faster 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.Look-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.States 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  *https://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.Not 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 VA definition of shiftLeft that can deal with variable length shifts. (Note that the `` method from the  class requires an E 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  function.Test 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.Generate 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 , , and .)(c) Levent ErkokBSD3erkokl@gmail.com experimentalNoneH 1{.,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.WThe key, which can be 128, 192, or 256 bits. Represented as a sequence of 32-bit words.AES 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.An 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.lMultiplication 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. Exponentiation by a constant in GF(2^8). The implementation uses the usual square-and-multiply trick to speed up the computation.yComputing 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.4Conversion from 32-bit words to 4 constituent bytes.:Conversion from 4 bytes, back to a 32-bit row, inverse of R above. We have the following simple theorems stating this relationship formally:Eprove $ \a b c d -> toBytes (fromBytes [a, b, c, d]) .== [a, b, c, d]Q.E.D.)prove $ \r -> fromBytes (toBytes r) .== rQ.E.D.4Rotating a state row by a fixed amount to the right.ODefinition of round-constants, as specified in Section 5.2 of the AES standard.The  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.Key expansion. Starting with the given key, returns an infinite sequence of words, as described by the AES standard, Section 5.2, Figure 11.7The 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".wThe 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 W function. However, that will never happen since the table has all 256 elements in it.OThe values of the inverse S-box table. Again, the construction is programmatic.!The inverse s-box transformation.Prove that the  and  are inverses. We have:prove sboxInverseCorrectQ.E.D.Adding the round-key to the current state. We simply exploit the fact that addition is just xor in implementing this transformation..T-box table generation function for encryption&First look-up table used in encryption'Second look-up table used in encryption&Third look-up table used in encryption'Fourth look-up table used in encryption.T-box table generating function for decryption&First look-up table used in decryption'Second look-up table used in decryption&Third look-up table used in decryption'Fourth look-up table used in decryptionGeneric round function. Given the function to perform one round, a key-schedule, and a starting state, it performs the AES rounds.One encryption round. The first argument indicates whether this is the final round or not, in which case the construction is slightly different.|One decryption round. Similar to the encryption round, the first argument indicates whether this is the final round or not.Key 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.)Block 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.3Block decryption. The arguments are the same as in `, except the first argument is the cipher-text and the output is the corresponding plain-text.?128-bit encryption test, from Appendix C.1 of the AES standard:map hex8 t128Enc-["69c4e0d8","6a7b0430","d8cdb780","70b4c55a"]?128-bit decryption test, from Appendix C.1 of the AES standard:map hex8 t128Dec-["00112233","44556677","8899aabb","ccddeeff"]?192-bit encryption test, from Appendix C.2 of the AES standard:map hex8 t192Enc-["dda97ca4","864cdfe0","6eaf70a0","ec0d7191"]?192-bit decryption test, from Appendix C.2 of the AES standard:map hex8 t192Dec-["00112233","44556677","8899aabb","ccddeeff"]:256-bit encryption, from Appendix C.3 of the AES standard:map hex8 t256Enc-["8ea2b7ca","516745bf","eafc4990","4b496089"]:256-bit decryption, from Appendix C.3 of the AES standard:map hex8 t256Dec-["00112233","44556677","8899aabb","ccddeeff"];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.+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.KComponents of the AES-128 implementation that the library is generated fromEGenerate 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.)For doctest purposes onlyplain-text words key-words+True if round-trip gives us plain-text back..(c) Austin SeippBSD3erkokl@gmail.com experimentalNoneV S :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.The key is a stream of m values.ZRC4 State contains 256 8-bit values. We use the symbolically accessible full-binary type 2~ to represent the state, since RC4 needs access to the array via a symbolic index and it's important to minimize access time.SConstruct the fully balanced initial tree, where the leaves are simply the numbers 0 through 255.$Swaps two elements in the RC4 array.ZImplements the PRGA used in RC4. We return the new state and the next key value generated.@Constructs the state to be used by the PRGA using the given key.CThe key-schedule. Note that this function returns an infinite list.0Generate a key-schedule from a given key-string.pRC4 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"WRC4 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"Prove 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.For doctest purposes only  (c) Levent ErkokBSD3erkokl@gmail.com experimentalNone iJkSBV doesn't support 48 bit words natively. So, we represent them as a tuple, 32 high-bits and 16 low-bits.FCompute the 16 bit CRC of a 48 bit message, using the given polynomialACount the differing bits in the message and the corresponding CRCGiven 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.KGenerate good CRC polynomials for 48-bit words, given the hamming distance hd.aFind 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^2 + x + 1 Polynomial #2. x^16 + x^15 + x^2 + 1 Polynomial #3. x^16 + x^15 + x^2 + x + 1 Polynomial #4. x^16 + x^14 + x^10 + 1 Polynomial #5. x^16 + x^14 + x^9 + 1 ... 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 experimentalNone For 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.1ldn: 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.Find 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 lexicographic order using the ordinary less-than relation. (NB. We explicitly tell z3 to use the logic AUFLIA for this problem, as the BV solver that is chosen automatically has a performance issue. See:  #https://z3.codeplex.com/workitem/88.)Solve 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(1, 0, 0) + k (0, 1, 1) + k' (1, 0, 2) = (1+k', k, k+2k')OR 9(0, 2, 0) + k (0, 1, 1) + k' (1, 0, 2) = (k', 2+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.A 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 5We need to solve for x_0, over the naturals. We have:sailors%[15621,3124,2499,1999,1599,1279,1023]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 l+A simple predicate, based on two variables x and y , true when  0 <= x <= 1 and  x - abs y is 0.=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.@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 experimentalNone018V A 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.(Give a name to the symbolic variants of , for convenienceBHave the SMT solver enumerate the elements of the domain. We have:elts Solution #1: s0 = B :: E Solution #2: s0 = A :: E Solution #3: s0 = C :: EFound 3 different solutions.9Shows that if we require 4 distinct elements of the type A, we shall fail; as the domain only has three elements. We have:four UnsatisfiablexEnumerations are automatically ordered, so we can ask for the maximum element. Note the use of quantification. We have:maxESatisfiable. Model: maxE = C :: E/Similarly, we get the minumum element. We have:minESatisfiable. Model: minE = A :: EMake  a symbolic value.  (c) Levent ErkokBSD3erkokl@gmail.com experimentalNoneV (}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 == nanFalse: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 ( or ) 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 = 1.9259302e-34 :: Float y = -1.9259117e-34 :: Float z = -1.814176e-39 :: FloatIndeed, we have:A((1.9259302e-34) + ((-1.9259117e-34) + (-1.814176e-39))) :: Float 3.4438e-41C(((1.9259302e-34) + ((-1.9259117e-34))) + (-1.814176e-39)) :: Float 3.4014e-41*Note the difference between two additions!Demonstrate 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 = 2.424457e-38 :: Float b = -1.0e-45 :: FloatIndeed, we have:6(2.424457e-38 + (-1.0e-45)) == (2.424457e-38 :: Float)TrueBut:-1.0e-45 == (0 :: Float)FalseThis 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 = 1.119056263978578e-308 :: DoubleIndeed, we have:(let a = 1.119056263978578e-308 :: Double a * (1/a)0.9999999999999999One 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 p, q, r, s, t and u2 which allows users to specify the IEEE supported ) for the operation. (Also see the class  RoundingFloat.) 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 = 1.0 :: Float# y = -6.1035094e-5 :: 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:(1 + (-6.1035094e-5)) :: Float 0.999938969While we cannot directly see the result when the mode is C in Haskell, we can use SBV to provide us with that result thusly:Jsat $ \z -> z .== fpAdd sRoundTowardPositive 1 (-6.1035094e-5 :: SFloat)Satisfiable. Model: s0 = 0.999939 :: Float:We can see why these two resuls are indeed different: The RoundTowardsPositivek (which rounds towards positive-infinity) produces a larger result. Indeed, if we treat these numbers as  values, we get:(1 + (-6.1035094e-5)) :: Double0.999938964906>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  Phttps://ece.uwaterloo.ca/~dwharder/NumericalAnalysis/02Numerics/Double/paper.pdf as an excellent guide.(c) Levent ErkokBSD3erkokl@gmail.com experimentalNone PA 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-negativeWe 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 a< 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](c) Levent ErkokBSD3erkokl@gmail.com experimentalNone hA simple variant of division, where we explicitly require the caller to make sure the divisor is not 0.#Check whether an arbitrary call to 5 is safe. Clearly, we do not expect this to be safe:test1f[Documentation/SBV/Examples/Misc/NoDiv0.hs:36:14:checkedDiv: Divisor should not be 0: Violated. Model: s0 = 0 :: Int32 s1 = 0 :: Int32]VRepeat the test, except this time we explicitly protect against the bad case. We have:test2m[Documentation/SBV/Examples/Misc/NoDiv0.hs:44:41:checkedDiv: Divisor should not be 0: No violations detected] (c) Levent ErkokBSD3erkokl@gmail.com experimentalNone &Helper synonym for representing GF(2^8); which are merely 8-bit unsigned words. Largest term in such a polynomial has degree 7.Multiplication 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. States that the unit polynomial 1, is the unit element)States that multiplication is commutativesStates that multiplication is associative, note that associativity proofs are notoriously hard for SAT/SMT solversQStates 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).)Queries!(c) Brian HuffmanBSD3erkokl@gmail.com experimentalNone1;=>? *SWord4 type synonymWord4 as a newtype. Invariant: Word4 x should satisfy x < 16.3Smart constructor; simplifies conversion from Word8Joining splitting to from Word8)SIntegral instance, using default methods%SDvisible instance, using 0-extension:SatModel instance, merely uses the generic parsing method.CHasKind instance; simply returning the underlying kind for the typeBSymWord instance, allowing this type to be used in proofs/sat etc. $Random instance, used in quick-check  Bits instance Integral instance, again using Word8 instance and casting. NB. we do not need to use the smart constructor here as neither the quotient nor the remainder can overflow a Word4. ,Real instance simply uses the Word8 instance DNum instance, merely lifts underlying 8-bit operation and casts back#Enum instance, trivial definitions.Bounded instance; from 0 to 2553Read instance. We read as an 8-bit word, and coerce Show instance)SDvisible instance, using default methods     "(c) Levent ErkokBSD3erkokl@gmail.com experimentalNone 8EOptimization 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 + (2.0 * epsilon) :: Real' min_z = 5.0 + epsilon :: Real1Objective "min_y": Optimal in an extension field:* one-x = oo :: Integer' min_y = 7.0 + (2.0 * epsilon) :: Real' min_z = 5.0 + epsilon :: Real1Objective "min_z": Optimal in an extension field:* one-x = oo :: Integer' min_y = 7.0 + (2.0 * epsilon) :: Real' min_z = 5.0 + epsilon :: Real#(c) Levent ErkokBSD3erkokl@gmail.com experimentalNone = 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 experimentalNone P 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 experimentalNone _R%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 v% NRepresent day by 8-bit words; Again, an uninterpreted type would work as well.bRepresent month by 8-bit words; We can also use an uninterpreted type, but numbers work well here.!Months referenced in the problem.!Months referenced in the problem.!Months referenced in the problem.!Months referenced in the problem. <Check that a given month/day combo is a possible birth-date.!BAssert that the given function holds for one of the possible days."BAssert that the given function holds for all of the possible days.#DAssert that the given function holds for one of the possible months.$DAssert that the given function holds for all of the possible months.%/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.&4Find all solutions to the birthday problem. We have:cheryl Solution #1: birthDay = 16 :: Word8 birthMonth = 7 :: Word8This is the only solution.  !"#$%&  !"#$%&'(c) Levent ErkokBSD3erkokl@gmail.com experimentalNone 'QWe will represent coins with 16-bit words (more than enough precision for coins).(Create 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.)0Return all combinations of a sequence of values.*.Constraint 1: Cannot make change for a dollar.+3Constraint 2: Cannot make change for half a dollar.,/Constraint 3: Cannot make change for a quarter.-,Constraint 4: Cannot make change for a dime..-Constraint 5: Cannot make change for a nickel/Constraint 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.0Solve 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. '()*+,-./0 '()*+,-./0((c) Levent ErkokBSD3erkokl@gmail.com experimentalNone 1YWe will assume each number can be represented by an 8-bit word, i.e., can be at most 128.2OGiven a number, increment the count array depending on the digits of the number3Encoding 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.46Finds 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 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. Solution #2In 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.Found: 2 solution(s).12341234)(c) Levent ErkokBSD3erkokl@gmail.com experimentalNone )5Prints the only solution:puzzle Solution #1: dog = 3 :: Integer cat = 41 :: Integer mouse = 56 :: IntegerThis is the only solution.55*(c) Levent ErkokBSD3erkokl@gmail.com experimentalNone l6IThe given guesses and the correct digit counts, encoded as a simple list.7$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.8'Print out the solution nicely. We have: solveEuler1854640261571849533Number of solutions: 1678678+(c) Levent ErkokBSD3erkokl@gmail.com experimentalNone018V 9Colors of houses?Nationalities of the occupantsEMake 9 a symbolic value.NBeverage choicesTMake ? a symbolic value.]Pets they keepcMake N a symbolic value.lSports they engage inrMake ] a symbolic value.{We 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!|Make l a symbolic value.9<>=;:?DCBA@NSRQPO]a`_^blqponm{9:;<=>?@ABCDNOPQRS]^_`ablmnopq{9:;<=>?@ABCDNOPQRS]^_`ablmnopq,(c) Levent ErkokBSD3erkokl@gmail.com experimentalNone "The puzzle board is a list of rowsA row is a list of elementsUse 32-bit words for elements.4Checks that all elements in a list are within bounds#Get the diagonal of a square matrix'Test if a given board is a magic square3Group a list of elements in the sublists of length iGiven n, magic n prints all solutions to the nxn magic square problem-(c) Levent ErkokBSD3erkokl@gmail.com experimentalNone EA solution is a sequence of row-numbers where queens should be placed Checks that a given solution of n5-queens is valid, i.e., no queen captures any other.Given n, it solves the n-queens) puzzle, printing all possible solutions..(c) Levent ErkokBSD3erkokl@gmail.com experimentalNone Solve 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 == 10652True/(c) Levent ErkokBSD3erkokl@gmail.com experimentalNone ˣA puzzle is a pair: First is the number of missing elements, second is a function that given that many elements returns the final board.&A Sudoku board is a sequence of 9 rows\A row is a sequence of 8-bit words, too large indeed for representing 1-9, but does not harmfGiven a series of elements, make sure they are all different and they all are numbers between 1 and 91Given a full Sudoku board, check that it is valid*Solve a given puzzle and print the resultsTHelper function to display results nicely, not really needed, but helps presentationFind all solutions to a puzzleFind an arbitrary good board(A random puzzle, found on the internet...Another random puzzle, found on the internet...Another random puzzle, found on the internet..dAccording 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.html/This one has been called diabolical, apparently)The following is nefarious according to %http://haskell.org/haskellwiki/SudokuFSolve them all, this takes a fraction of a second to run for each case0(c) Levent ErkokBSD3erkokl@gmail.com experimentalNone0168;= (sU2 band members. We want to translate this to SMT-Lib as a data-type, and hence the call to mkSymbolicEnumeration.Location of the flashSymbolic variant for timeModel time using 32 bitsSymbolic shorthand for a /Shorthands for symbolic versions of the members/Shorthands for symbolic versions of the members/Shorthands for symbolic versions of the members/Shorthands for symbolic versions of the members*Crossing times for each member of the band6The symbolic variant.. The duplication is unfortunate.Make  a symbolic value.A 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 together/A puzzle move is modeled as a state-transformer(The status of the puzzle after each move4This type is equipped with an automatically derived ! instance because each field is . A : instance must also be derived for this to work, and the DeriveAnyClass2 language extension must be enabled. The derived j instance simply walks down the structure field by field and merges each one. An equivalent hand-written * instance is provided in a comment below. elapsed timelocation of the flashlocation of Bonolocation of Edgelocation of Adamlocation of LarrySymbolic variant of -Shorthands for symbolic versions of locations-Shorthands for symbolic versions of locations8Start configuration, time elapsed is 0 and everybody is 'Read the state via an accessor function.Given an arbitrary member, return his location(Transferring the flash to the other side'Transferring a person to the other side0Increment the time, when only one person crosses2Increment the time, when two people cross togetherSymbolic version of when.Move one member, remembering to take the flash&Move two members, again with the flash Run a sequence of given actions.Check 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 seconds.See if there is a solution that has precisely n stepsSolve 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.Mergeable instance for [ simply pushes the merging the data after run of each branch starting from the same state.Make  a symbolic value.,-1(c) Levent ErkokBSD3erkokl@gmail.com experimentalNone NFind 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.Run 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: (4,6) Iteration: 5Current solution is: (8,2) Iteration: 6No other solution! [(0,10),(1,9),(2,8),(4,6),(8,2)]2(c) Levent ErkokBSD3erkokl@gmail.com experimentalNone 0A 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: Unsatisfiable Case fpIsPositiveZero: Starting Case fpIsPositiveZero: Unsatisfiable Case fpIsNormal: Starting Case fpIsNormal: Unsatisfiable Case fpIsSubnormal: Starting Case fpIsSubnormal: Unsatisfiable Case fpIsPoint: Starting Case fpIsPoint: Unsatisfiable Case fpIsNaN: Starting Case fpIsNaN: Satisfiable ("fpIsNaN",NaN)!Demonstrates the "coverage" case.We have: >>> csDemo2 Case negative: Starting Case negative: Unsatisfiable Case less than 8: Starting Case less than 8: Unsatisfiable Case Coverage: Starting Case Coverage: Satisfiable (Coverage,10)3(c) Levent ErkokBSD3erkokl@gmail.com experimentalNone018V 0Days of the week. We make it symbolic using the   splice.The type synonym  is the symbolic variant of . (Similar to 'SInteger'/'Integer' and others.)AA 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]Make  a symbolic value.  4(c) Levent ErkokBSD3erkokl@gmail.com experimentalNone 018;=V N[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.&Supported unary operators. Similar to V case, we will restrict square-root and factorial to be only applied to the value @4.Make  a symbolic value. JThe 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.Symbolic variant of .Symbolic variant of .KConstruct 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!)EGiven 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.Minor helper for writing "symbolic" case statements. Simply walks down a list of values to match against a symbolic version of the key.Evaluate 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.8In 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.zGiven an integer, walk through all possible tree shapes (at most 640 of them), and find a filling that solves the puzzle.Solution 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))) A rudimentary # instance for trees, nothing fancy.Make  a symbolic value.      5(c) Levent ErkokBSD3erkokl@gmail.com experimentalNone [ #cUse 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.$Play 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: 1000 0 21 31 36 39 40 41 42#$#$6(c) Levent ErkokBSD3erkokl@gmail.com experimentalNone n%%Compute the interpolant for formulas y = 2x and y = 2z+1D. These 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.["(<= 0 (+ (div s1 2) (div (* (- 1) 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:  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:Uprove $ \y -> (y `sMod` 2 .== 0) ==> (0 .<= (y `sDiv` 2) + ((-y) `sDiv` 2::SInteger))Q.E.D.And:Zprove $ \y -> (y `sMod` 2 .== 1) ==> bnot (0 .<= (y `sDiv` 2) + ((-y) `sDiv` 2::SInteger))Q.E.D.4This establishes that we indeed have an interpolant!%%7(c) Levent ErkokBSD3erkokl@gmail.com experimentalNone u&A 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.'Extract 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.&'&'8(c) Joel BurgetBSD3erkokl@gmail.com experimentalNone |A(9Solve a given crossword, returning the corresponding rows)Solve ;http://regexcrossword.com/challenges/intermediate/puzzles/1puzzle1 ["ATO","WEL"]*Solve ;http://regexcrossword.com/challenges/intermediate/puzzles/2puzzle2["WA","LK","ER"]+Solve ;http://regexcrossword.com/challenges/palindromeda/puzzles/3puzzle3["RATS","ABUT","TUBA","STAR"]()*+()*+9(c) Joel BurgetBSD3erkokl@gmail.com experimentalNoneV ,[Evaluation monad. The state argument is the environment to store variables as we evaluate.-Simple expression language2-Given an expression, symbolically evaluate it3SA 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 ++ "'") 4<Limit names to be at most 7 chars long, with simple letters.5:Strings: Again, at most of lenght 5, surrounded by quotes.6A "select" command:7-A "drop" instruction, which can be exploited!8MWe'll greatly simplify here and say a statement is either a select or a drop:9RThe exploit: We're looking for a DROP TABLE after at least one legitimate command.:Analyze 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 ++ "'") We have:findInjection exampleProgram"h'; DROP TABLE 'users"BIndeed, if we substitute the suggested string, we get the program: - query ("SELECT msg FROM msgs where topicid=h ; DROP TABLE users") which would query for topic h! and then delete the users table!;6Literals strings can be lifted to be constant programs,-10./23456789:-./01;,23456789:-./01:(c) Levent ErkokBSD3erkokl@gmail.com experimentalNone 7<This version directly uses SMT-arrays and hence does not need an initializer. Reading an element before writing to it returns an arbitrary value.=The array type, takes symbolic 32-bit unsigned indexes and stores 32-bit unsigned symbolic values. These are functional arrays where reading before writing a cell throws an exception.>%Uninterpreted function in the theorem?3Correctness theorem. We state it for all values of x, y, and the given array a. @#Prints Q.E.D. when run, as expected proveThm1Q.E.D.ASame as ?/, except we don't need an initializer with the  model.B$Prints Q.E.D. when run, as expected: proveThm2Q.E.D.<=>?@AB=>?@<AB;(c) Levent ErkokBSD3erkokl@gmail.com experimentalNone18 C4Handy shortcut for the type of symbolic values over DDThe uninterpreted sort D{, corresponding to the carrier. To prevent SBV from translating it to an enumerated type, we simply attach an unused fieldF!Uninterpreted logical connective FG!Uninterpreted logical connective GH!Uninterpreted logical connective HIDistributivity of OR over AND, as an axiom in terms of the uninterpreted functions we have introduced. Note how variables range over the uninterpreted sort D.J]One of De Morgan's laws, again as an axiom in terms of our uninterpeted logical connectives.K,Double negation axiom, similar to the above.LProves 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. CDEFGHIJKL DECFGHIJKLDE<(c) Levent ErkokBSD3erkokl@gmail.com experimentalNone TAn uninterpreted functionU Asserts that f x z == f (y+2) z whenever x == y+2. Naturally correct: prove thmGoodQ.E.D.TUTU=(c) Levent ErkokBSD3erkokl@gmail.com experimentalNone VA binary boolean functionWA ternary boolean functionXTPositive Shannon cofactor of a boolean function, with respect to its first argumentYTNegative Shannon cofactor of a boolean function, with respect to its first argumentZCShannon's expansion over the first argument of a function. We have:shannonQ.E.D.[WAlternative form of Shannon's expansion over the first argument of a function. We have:shannon2Q.E.D.\Computing the derivative of a boolean function (boolean difference). Defined as exclusive-or of Shannon cofactors with respect to that variable.]fThe no-wiggle theorem: If the derivative of a function with respect to a variable is constant False, then that variable does not "wiggle" the function; i.e., any changes to it won't affect the result of the function. In fact, we have an equivalence: The variable only changes the result of the function iff the derivative with respect to it is not False:noWiggleQ.E.D.^Universal quantification of a boolean function with respect to a variable. Simply defined as the conjunction of the Shannon cofactors._-Show that universal quantification is really meaningful: That is, if the universal quantification with respect to a variable is True, then both cofactors are true for those arguments. Of course, this is a trivial theorem if you think about it for a moment, or you can just let SBV prove it for you:univOKQ.E.D.`Existential quantification of a boolean function with respect to a variable. Simply defined as the conjunction of the Shannon cofactors.a0Show that existential quantification is really meaningful: That is, if the existential quantification with respect to a variable is True, then one of the cofactors must be true for those arguments. Again, this is a trivial theorem if you think about it for a moment, but we will just let SBV prove it:existsOKQ.E.D. VWXYZ[\]^_`a WVXYZ[\]^_`a>(c) Levent ErkokBSD3erkokl@gmail.com experimentalNone18 UbnA new data-type that we expect to use in an uninterpreted fashion in the backend SMT solver. Note the custom deriving clause, which takes care of most of the boilerplate. The () field is needed so SBV will not translate it to an enumerated data-typed5Declare an uninterpreted function that works over Q'seGA satisfiable example, stating that there is an element of the domain b such that dL returns a different element. Note that this is valid only when the domain b$ has at least two elements. We have:t1Satisfiable. Model: x = Q!val!0 :: QfkThis is a variant on the first example, except we also add an axiom for the sort, stating that the domain bR has only one element. In this case the problem naturally becomes unsat. We have:t2 Unsatisfiablebcdefbcdefbc?(c) Levent ErkokBSD3erkokl@gmail.com experimentalNone1 n=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.qyAn uninterpreted "classify" function. Really, we only care about the fact that such a function exists, not what it does.r_Formulate a query that essentially asserts a cardinality constraint on the uninterpreted sort n'. 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 n can be classified into 3 equivalence classes. Then, allSat returns all the possible instances, which of course are all uninterpreted.As expected, we have:genLs Solution #1: l = L!val!0 :: L l0 = L!val!0 :: L l1 = L!val!1 :: L l2 = L!val!2 :: L Solution #2: l = L!val!1 :: L l0 = L!val!0 :: L l1 = L!val!1 :: L l2 = L!val!2 :: L Solution #3: l = L!val!2 :: L l0 = L!val!0 :: L l1 = L!val!1 :: L l2 = L!val!2 :: LFound 3 different solutions.s Similarly, P's default implementation is sufficient.tDeclare instances to make n1 a usable uninterpreted sort. First we need the 1 instance, with the default definition sufficing.npoqrnoptsqrnop@f@g@h@i@j@k@l@m@n@o@p@q@r@s@t@u@v@w@x@y@z@{@|@}@~@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@DDDDEEEEEEEEEEEEEEEEEEEEEEEEFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFGHHHHHHHHHHHHHHHHJJJJJJJJJKKK K K L L L LLLLLLLLLLLLLLLLLLLL L!L"L"L#L$L%L%L&L'L(L)L*L+L,L-L.L/L0L1L2L3L4L5L6L7L8L9L:L:L;L<L=L>L?L@LALBLCLDLELELFLGLHLILJLKLKLLLMLNLOLPLQLRLSLTLULVLWLXLYLYLZL[L\L]L^L_L`LaLbLcLdLeLfLgLhLhLiLiLjLkLlLmLnLoLpLqLrLsLtLuLvLuLwLxLyLzL{L|L|L}L~LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLMMMMMMMMMMMMMMM M M M M MMMMMMMMMMMMMMMMMMM M!M"M#M$M%M&M'M(M)M*M+M,M-M.M/M0M1M2M3M4M5M6M7N8N8N9N:N:N;N;N<N=N>N?N@NANBNCNDNENFNGNHNINJNKNLNMNNNONPNQNRNSNTNUNVNWNXNYNZN[N\N]N^N_N`NaNbNcNdNeNfNgNhNiNjNkNlNmNnNoNoNpNqNrNsNtNuNvNwNxNyNzN{N|N}N~NNNNNNNNPPPPPPPPPPPPPPPPPPPQQQQQQQQQQQQTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT[[[[[[[A[[[[\\\C\\\\\\\\\\\\\B\\\\\\]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]] ] ] ] ] ]]^^^^^^^^^^^^^^^^^^ ^!^"^#^$^%^&^'^(^)^*^+^,^-^.^/^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^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^yz{|}~                      bbbbccccccccccccccccccccccccccccccccccc                             dddd d d d d d dddddddddddddddddddddd d!d"d#d$d%d&d'd(d)d*d+d,d-d.d/d0d1d2d3d4d5d6d7d8d9d:d;d<d=d>d?d@dAdBeCeDeEeFGHIJKLMNOPQRSTUVWXYZ[\]^_ ` a b c d e f g h i  j j k l m n o p q r s t u v w x y z { | } ~                               AL      !"#$%&'(  ) * + , - .!/!0!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&R&S'T'U'V'W'X'Y'Z'['\'R(](^(R(_)R*`*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+{+|+}+~++++++++++++++++++++++++++++++++++++++++++++++++,,,,,,,,---./////M///////////00000000000000000000000000000_0_00000000000~00000000000000000000000011223G333 3 3 3 3 3333333333344444444444 4!4"4#4$4%4&4'4(4)44*4+4,4-4.4/404142434R4445464748494:4;4<4=5>5?6@7A7B8C8889D9E9h9F9G9H919I9J9K9L9M9N9O9P9Q:::R::S::T;U;;;V;W;X;Y;Z;[; ;\;];^;_;`;a;b<R<c=d=e=f=g=h=i=j=k=l=m=n=o>p>p>R>>>q>r>s>t>u>v>w?x?y?z?{?|?}?~?????@@DDDDDDDDDEEEEEFFFFFFFFFFFFFFVWIIIIIIIIIIIILIIILLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLILLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL L L L LHLJM MMMMMMMMMMMMMMNN !N"O#O$O%O&O'O(O)O*O+O,O-O.O/O0P1P2P3P45Q6Q7Q8Q9Q:Q;Q<Q=Q>Q?Q@RARBRCSDSESFSGTHTITJTKLTMTNOTPTQTRTSTTTUTVTWTXTYTZT[T\T]T^T_T`TaTbTcTdTeTfghiTjklTmnoTpkqTrnsTtkuTvnwTxkyTzn{T|T}T~TTU VW XYZ [[[[[[[[[[[[[[[[[[[[[[[[[\\\\\\\\\\]]]]]^^^^^^^^^^^^^^^^^^^       cccccccccccccccdddeeeeeeeeeeeeeeeeennn      sbv-7.7-KHNFtBNwUNU1J81TmQfmcgData.SBV.ControlData.SBV.InternalsData.SBVData.SBV.DynamicData.SBV.RegExpData.SBV.Tools.GenTestData.SBV.Tools.STreeData.SBV.Tools.PolynomialData.SBV.String Data.SBV.CharData.SBV.Tools.CodeGen/Documentation.SBV.Examples.BitPrecise.BitTricks,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.RC45Documentation.SBV.Examples.Existentials.CRCPolynomial3Documentation.SBV.Examples.Existentials.Diophantine)Documentation.SBV.Examples.Misc.Auxiliary)Documentation.SBV.Examples.Misc.Enumerate(Documentation.SBV.Examples.Misc.Floating,Documentation.SBV.Examples.Misc.ModelExtract&Documentation.SBV.Examples.Misc.NoDiv0+Documentation.SBV.Examples.Misc.Polynomials%Documentation.SBV.Examples.Misc.Word40Documentation.SBV.Examples.Optimization.ExtField1Documentation.SBV.Examples.Optimization.LinearOpt2Documentation.SBV.Examples.Optimization.Production*Documentation.SBV.Examples.Optimization.VM+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.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.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.SQLInjection,Documentation.SBV.Examples.Uninterpreted.AUF/Documentation.SBV.Examples.Uninterpreted.Deduce1Documentation.SBV.Examples.Uninterpreted.Function0Documentation.SBV.Examples.Uninterpreted.Shannon-Documentation.SBV.Examples.Uninterpreted.Sort5Documentation.SBV.Examples.Uninterpreted.UISortAllSatData.SBV.Control.TypesgetValue getUnsatCoregetUnknownReasonData.SBV.Core.AlgRealsData.SBV.Core.KindData.SBV.Core.ConcreteData.SBV.SMT.SMTLibNamesData.SBV.Utils.BooleanData.SBV.Utils.LibData.SBV.Utils.NumericData.SBV.Utils.TDiffData.SBV.Core.SymbolicData.SBV.Core.OperationsData.SBV.Core.DataData.SBV.Utils.SExprData.SBV.Utils.PrettyNumData.SBV.SMT.UtilsData.SBV.SMT.SMTLib2Data.SBV.SMT.SMTLibData.SBV.SMT.SMTData.SBV.Provers.Z3Data.SBV.Provers.YicesData.SBV.Provers.MathSATData.SBV.Provers.CVC4Data.SBV.Provers.BoolectorData.SBV.Provers.ABCData.SBV.Control.UtilsData.SBV.Control.QueryData.SBV.Provers.ProverData.SBV.Core.ModelStatusGGenericsData.SBV.Core.SplittableData.SBV.Core.FloatingData.SBV.Compilers.CodeGenData.SBV.Compilers.CLogicAUFLIAAUFLIRAAUFNIRALRAQF_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 SMTOptionDiagnosticOutputChannelProduceAssertionsProduceAssignments ProduceProofsProduceInterpolantsProduceUnsatAssumptionsProduceUnsatCores RandomSeedReproducibleResourceLimit SMTVerbosity OptionKeywordSetLogicSetInfoSMTInfoResponseResp_UnsupportedResp_AllStatisticsResp_AssertionStackLevels Resp_Authors Resp_Error Resp_NameResp_ReasonUnknown Resp_VersionResp_InfoKeywordSMTReasonUnknown UnknownMemOutUnknownIncomplete UnknownOtherSMTErrorBehaviorErrorImmediateExitErrorContinuedExecution SMTInfoFlag AllStatisticsAssertionStackLevelsAuthors ErrorBehaviorName ReasonUnknownVersion InfoKeywordCheckSatResultSatUnsatUnk AlgRealPolyAlgReal AlgRational AlgPolyRootHasKindkindOfhasSign intSizeOf isBoolean isBoundedisRealisFloatisDouble isIntegerisUninterpretedisCharisStringshowTypeKindKBoolKBounded KUnboundedKReal KUserSortKFloatKDoubleKCharKStringExtCWInfiniteEpsilonInterval BoundedCWAddExtCWMulExtCW GeneralizedCW ExtendedCW RegularCWCW_cwKindcwValCWVal CWAlgReal CWIntegerCWFloatCWDoubleCWCharCWString CWUserSort isRegularCW cwSameTypecwToBoolnormCWfalseCWtrueCWliftCW2mapCWmapCW2 mkConstCWsmtLibReservedNamesBooleantruefalsebnot&&&|||~&~|<+>==><=>fromBoolbAndbOrbAnybAllfpRound0fpRatio0fpMaxHfpMinHfp2fpfpRemHfpRoundToIntegralHfpIsEqualObjectHfpIsNormalizedHTimingNoTiming PrintTiming SaveTiming showTDiff SMTSolvername executableoptionsengine capabilitiesSolverZ3Yices BoolectorCVC4MathSATABC SMTScript scriptBody scriptModel SMTResult Unsatisfiable Satisfiable SatExtFieldUnknown ProofErrorSMTModelmodelObjectives modelAssocs SMTConfigverbosetiming printBase printRealPrecsatCmdallSatMaxModelCount isNonModelVar transcript smtLibVersionsolver roundingModesolverSetOptionsignoreExitCoderedirectVerbose RoundingModeRoundNearestTiesToEvenRoundNearestTiesToAwayRoundTowardPositiveRoundTowardNegativeRoundTowardZeroSolverCapabilitiessupportsQuantifierssupportsUninterpretedSortssupportsUnboundedInts supportsRealssupportsApproxRealssupportsIEEE754supportsOptimizationsupportsPseudoBooleanssupportsCustomQueriessupportsGlobalDecls SMTLibPgm SMTLibVersionSMTLib2CachedSArrSymbolicSValState SBVRunModeSMTModeCodeGenConcreteIStageISetupIRun ArrayInfo ArrayContext ArrayFree ArrayMutate ArrayMergeResultreskinds resTracesresObservables resUISegs resInputs resConsts resTables resArrays resUIConsts resAxiomsresAsgnsresConstraints resAssertions resOutputsQuery QueryStatequeryAsk querySendqueryRetrieveResponse queryConfigqueryTerminatequeryTimeOutValuequeryAssertionStackDepth ObjectiveMinimizeMaximize AssertSoftPenaltyDefaultPenalty OptimizeStyle Lexicographic IndependentPareto NamedSymVarSBVPgmpgmAssignmentsSBVExprSBVAppSBVType QuantifierALLEXRegExpLiteralAllNoneRangeConcKStarKPlusOptLoopUnionInterStrOp StrConcatStrLenStrUnit 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 PseudoBooleanSWNodeId forceSWArgfalseSWtrueSWneedsExistentials isCodeGenMode inSMTModenewUninterpretedinternalVariable getTableIndexnewExpr svMkSymVarsWordNsWordN_sIntNsIntN_addAxiom runSymbolicextractSymbolicSimulationStateinternalConstraint outputSValreadSArr writeSArr mergeSArrnewSArreqSArrcacheuncache uncacheAIsmtLibVersionExtensionsvTruesvFalsesvBool svIntegersvFloatsvDoublesvRealsvAsBool svAsInteger svNumerator svDenominatorsvEnumFromThenTosvPlussvTimessvMinussvUNegsvAbssvDividesvExp svBlastLEsvSetBit svBlastBE svWordFromLE svWordFromBE svAddConstant svIncrement svDecrementsvQuotsvRem svQuotRemsvEqual svNotEqual svLessThan svGreaterThansvLessEq svGreaterEqsvAndsvOrsvXOrsvNotsvShlsvShrsvRolsvRor svExtractsvJoinsvUninterpretedsvIte svLazyItesvSymbolicMergesvSelectsvSignsvUnsignsvFromIntegral svToWord1 svFromWord1 svTestBit svShiftLeft svShiftRight svRotateLeft svRotateRight SMTProblem smtLibPgm SFunArraySArrayunSArraySymArray newArray_newArray readArray writeArray mergeArraysSymWordforallforall_ mkForallVarsexistsexists_ mkExistVarsfreefree_ mkFreeVarssymbolic symbolicsliteral unliteralfromCW isConcrete isSymbolic isConcretely mkSymWord Outputtableoutput SolverContext constrainnamedConstraintsetInfo setOptionsetLogic setTimeOut SRoundingModeSStringSCharSDoubleSFloatSRealSIntegerSInt64SInt32SInt16SInt8SWord64SWord32SWord16SWord8SBoolSBVunSBVgetPathConditionextendPathConditionnaninfinitysNaN sInfinitysRoundNearestTiesToEvensRoundNearestTiesToAwaysRoundTowardPositivesRoundTowardNegativesRoundTowardZerosRNEsRNAsRTPsRTNsRTZsbvToSWmkSymSBV sbvToSymSW declNewSArraydeclNewSFunArray mkSFunArray PrettyNumhexSbinShexbinshexshexIsbinsbinIreadBin showCFloat showCDouble showHFloat showHDouble showSMTFloat showSMTDoublesmtRoundingMode cwToSMTLib mkSkolemZero TestStyleHaskellCForte TestVectors getTestValuesgenTest renderTest SMTExceptionsmtExceptionDescriptionsmtExceptionSentsmtExceptionExpectedsmtExceptionReceivedsmtExceptionStdOutsmtExceptionStdErrsmtExceptionExitCodesmtExceptionConfigsmtExceptionReasonsmtExceptionHint Modelable modelExistsgetModelAssignmentgetModelDictionary getModelValuegetModelUninterpretedValue extractModelgetModelObjectivesgetModelObjectiveValueSatModelparseCWscvtModelOptimizeResultLexicographicResult ParetoResultIndependentResult SafeResult AllSatResult SatResult ThmResultgenParse extractModelsgetModelDictionariesgetModelValuesgetModelUninterpretedValues displayModels showModelSMTValue sexprToValio freshVar_freshVar queryDebuggetUninterpretedValuecheckSat checkSatUsingtimeoutgetInfo getOption getSMTResultgetModelcheckSatAssuming$checkSatAssumingWithUnsatisfiableSetgetAssertionStackDepthinNewAssertionStackpushpop caseSplitresetAssertionsechoexitgetProofgetInterpolant getAssertions getAssignment|-> mkSMTResultquery SExecutablesName_sNamesafesafeWithProvableforAll_forAllforSome_forSomeprove proveWithsatsatWithallSat allSatWithoptimize optimizeWith isVacuous isVacuousWith isTheorem isTheoremWith isSatisfiableisSatisfiableWith proveWithAll proveWithAny satWithAll satWithAnygenerateSMTBenchmarkGoal Predicate boolectorcvc4yicesz3mathSATabc defaultSMTCfgrunSMT runSMTWithisSafeMetricminimizemaximize uninterpret cgUninterpretsbvUninterpret Mergeable symbolicMergeselect SDivisiblesQuotRemsDivModsQuotsRemsDivsMod SFiniteBitssFiniteBitSizelsbmsbblastBEblastLE fromBitsBE fromBitsLEsTestBit sExtractBits sPopCountsetBitTo fullAdderfullMultipliersCountLeadingZerossCountTrailingZeros SIntegral OrdSymbolic.<.<=.>.>=sminsmaxinRange EqSymbolic.==./=distinctallEqualsElem genLiteral genFromCW genMkSymVarsBoolsBoolssWord8sWord8ssWord16sWord16ssWord32sWord32ssWord64sWord64ssInt8sInt8ssInt16sInt16ssInt32sInt32ssInt64sInt64ssInteger sIntegerssRealsRealssFloatsFloatssDoublesDoublessCharsStringsCharssStringssRealToSIntegerlabelobserveoneIfpbAtMost pbAtLeast pbExactlypbLepbGepbEq pbMutexedpbStronglyMutexed.^ sFromIntegral sShiftLeft sShiftRightsSignedShiftArithRight sRotateLeft sRotateRightliftQRemliftDModiteiteLazysAssert assertSoft sbvQuickCheckSTree readSTree writeSTreemkSTree$fMergeableSTreeInternal$fShowSTreeInternal Polynomial polynomialpAddpMultpDivpModpDivModshowPolyshowPolynomialaddPolyitesmdpcrcBVcrc$fPolynomialSBV$fPolynomialSBV0$fPolynomialSBV1$fPolynomialSBV2$fPolynomialWord64$fPolynomialWord32$fPolynomialWord16$fPolynomialWord8lengthnullheadtail charToStr strToStrAt strToCharAt.!!implodeconcat.++ isInfixOf isPrefixOf isSuffixOftakedropsubStrreplaceindexOf offsetIndexOfstrToNatnatToStr Splittablesplit#extendIEEEFloatConvertable fromSFloattoSFloat fromSDouble toSDouble IEEEFloatingfpAbsfpNegfpAddfpSubfpMulfpDivfpFMAfpSqrtfpRemfpRoundToIntegralfpMinfpMaxfpIsEqualObject fpIsNormal fpIsSubnormalfpIsZero fpIsInfinitefpIsNaN fpIsNegative fpIsPositivefpIsNegativeZerofpIsPositiveZero fpIsPointsFloatAsSWord32sDoubleAsSWord64 blastSFloat blastSDoublesWord32AsSFloatsWord64AsSDoubleelemnotElemordchrtoLowertoUpper digitToInt intToDigit isControlisSpaceisLowerisUpperisAlpha isAlphaNumisPrintisDigit isOctDigit isHexDigitisLetterisMarkisNumber isPunctuationisSymbol isSeparatorisAsciiisLatin1 isAsciiLetter isAsciiUpper isAsciiLowerRegExpMatchablematchexactlyoneOfnewlinetabwhiteSpaceNoNewLine whiteSpace punctuation asciiLetter asciiLower asciiUpperdigitoctDigithexDigitdecimaloctal hexadecimalfloating identifier$fRegExpMatchableSBV$fRegExpMatchableSBV0 CgPgmKind CgMakefileCgHeaderCgSourceCgDriver CgPgmBundle CgSRealTypeCgFloatCgDouble CgLongDouble SBVCodeGenCgStatecgInputs cgOutputs cgReturns cgPrototypescgDecls cgLDFlags cgFinalConfigCgValCgAtomicCgArrayCgConfigcgRTC cgIntegercgReal cgDriverVals cgGenDriver cgGenMakefilecgIgnoreAssertsCgTarget targetName translatedefaultCgConfig initCgState cgPerformRTCs cgIntegerSize cgSRealTypecgGenerateDrivercgGenerateMakefilecgSetDriverValuescgIgnoreSAssertcgAddPrototype cgAddDecl cgAddLDFlags svCgInput svCgInputArr svCgOutput svCgOutputArr svCgReturn svCgReturnArrcgInput cgInputArrcgOutput cgOutputArrcgReturn cgReturnArr isCgDriver isCgMakefilecodeGenrenderCgPgmBundle compileToC compileToC' compileToCLibcompileToCLib'sendStringToSolverretrieveResponseFromSolversendRequestToSolverEquality===solvesbvCheckSolverInstallationdefaultSolverConfigsbvAvailableSolversmkSymbolicEnumeration$fProvableSymbolic$fEquality(->)$fEquality(->)0$fEquality(->)1$fEquality(->)2$fEquality(->)3$fEquality(->)4$fEquality(->)5$fEquality(->)6$fEquality(->)7$fEquality(->)8$fEquality(->)9$fEquality(->)10$fEquality(->)11 svQuickCheckfastMinCorrectfastMaxCorrectoppositeSignsCorrectconditionalSetClearCorrectpowerOfTwoCorrectqueriesModelInitVals InstructionProgramMostekmemory registersflagsMemoryFlags RegistersBitValueFlagFlagCFlagZRegisterRegXRegAAddressgetRegsetReggetFlagsetFlagpeekpoke checkOverflowcheckOverflowCorrectldxldaclcrorMrorRbccadcdexbneendlegato runLegato initMachinelegatoIsCorrectcorrectnessTheorem legatoInC $fEqRegister $fOrdRegister $fIxRegister$fBoundedRegister$fEnumRegister$fEqFlag $fOrdFlag$fIxFlag $fBoundedFlag $fEnumFlag$fGenericMostek$fMergeableMostekEmerge mergeSort nonDecreasingisPermutationOf correctness maskAndMult PowerListtiePLzipPLunzipPLpslf flIsCorrectthm1thm2addSub genAddSubusb5crcUSBcrcUSB'crcGoodcg1cg2fib0fib1genFib1fib2genFib2sgcd sgcdIsCorrect genGCDInC popCountSlow popCountFastpop8fastPopCountIsCorrectgenPopCountInC shiftLeft tstShiftLeftgenCCodeKSKeyGF28gf28Multgf28Pow gf28InversetoBytes fromBytesrotRroundConstants invMixColumns keyExpansion sboxTablesbox unSBoxTableunSBoxsboxInverseCorrect addRoundKeyt0Funct0t1t2t3u0Funcu0u1u2u3doRoundsaesRound aesInvRoundaesKeySchedule aesEncrypt aesDecryptt128Enct128Dect192Enct192Dect256Enct256Decaes128IsCorrectcgAES128BlockEncryptaes128LibComponentscgAES128Libraryhex8RC4SinitSswapprgainitRC4 keySchedulekeyScheduleStringencryptdecrypt rc4IsCorrecthex2SWord48 crc_48_16 diffCountgenPolyfindHD4PolynomialsSolution HomogeneousNonHomogeneousldnbasistestsailors$fShowSolutionproblem allModelsmodelsWithYAuxABSEeltsfourmaxEminE $fSatModelE $fSMTValueE $fHasKindE $fSymWordE$fDataE$fReadE$fOrdE$fShowE$fEqE assocPlusassocPlusRegularnonZeroAddition multInverse roundingAddoutsidegenVals checkedDivtest1test2gfMultmultUnitmultComm multAssoc polyDivModtestGF28SWord4Word4word4$fSplittableWord8Word4$fSIntegralWord4$fSDivisibleWord4$fSatModelWord4$fHasKindWord4$fSymWordWord4 $fRandomWord4 $fBitsWord4$fIntegralWord4 $fRealWord4 $fNumWord4 $fEnumWord4$fBoundedWord4 $fReadWord4 $fShowWord4$fSDivisibleSBV $fEqWord4 $fOrdWord4 $fDataWord4 productionallocateDayMonthmayjunejulyaugustvalid existsDay forallDay existsMonth forallMonthpuzzlecherylCoinmkCoin combinationsc1c2c3c4c5c6Countcountcountsguesseseuler185 solveEuler185ColorRedGreenWhiteYellowBlue NationalityBritonDaneSwede NorwegianGerman$fSatModelColor$fSMTValueColor$fHasKindColor$fSymWordColor $fDataColor $fReadColor $fOrdColor $fShowColor $fEqColorBeverageTeaCoffeeMilkBeerWater$fSatModelNationality$fSMTValueNationality$fHasKindNationality$fSymWordNationality$fDataNationality$fReadNationality$fOrdNationality$fShowNationality$fEqNationalityPetDogHorseCatBirdFish$fSatModelBeverage$fSMTValueBeverage$fHasKindBeverage$fSymWordBeverage$fDataBeverage$fReadBeverage $fOrdBeverage$fShowBeverage $fEqBeverageSportFootballBaseball VolleyballHockeyTennis $fSatModelPet $fSMTValuePet $fHasKindPet $fSymWordPet $fDataPet $fReadPet$fOrdPet $fShowPet$fEqPet fishOwner$fSatModelSport$fSMTValueSport$fHasKindSport$fSymWordSport $fDataSport $fReadSport $fOrdSport $fShowSport $fEqSportBoardRowElemcheckdiagisMagicchunkmagicisValidnQueens sendMoreMoneyPuzzlesudoku dispSolutionsolveAllpuzzle0puzzle1puzzle2puzzle3puzzle4puzzle5puzzle6 allPuzzlesU2MemberBonoEdgeAdamLarryLocationHereThereSTimeTime SU2Memberbonoedgeadamlarry crossTime sCrossTime$fSatModelU2Member$fSMTValueU2Member$fHasKindU2Member$fSymWordU2Member$fDataU2Member$fReadU2Member $fOrdU2Member$fShowU2Member $fEqU2MemberActionsMovetimeflashlBonolEdgelAdamlLarry SLocationheretherestartwhereIs xferFlash xferPerson bumpTime1 bumpTime2whenSmove1move2runsolveNsolveU2$fMergeableStateT$fGenericStatus$fMergeableStatus$fSatModelLocation$fSMTValueLocation$fHasKindLocation$fSymWordLocation$fDataLocation$fReadLocation $fOrdLocation$fShowLocation $fEqLocationgoodSumdemocsDemo1csDemo2MondayTuesday WednesdayThursdayFridaySaturdaySundaySDayfindDays $fSatModelDay $fSMTValueDay $fHasKindDay $fSymWordDay $fDataDay $fReadDay$fOrdDay $fShowDay$fEqDayBinOpDivideExptUnOpNegateSqrt Factorial$fSatModelBinOp$fSMTValueBinOp$fHasKindBinOp$fSymWordBinOp $fDataBinOp $fReadBinOp $fOrdBinOp $fShowBinOp $fEqBinOpTUFSUnOpSBinOpallPossibleTreesfillsCaseevalgeneratefind$fShowT$fSatModelUnOp$fSMTValueUnOp $fHasKindUnOp $fSymWordUnOp $fDataUnOp $fReadUnOp $fOrdUnOp $fShowUnOp$fEqUnOpguessplayevenOddpucCoresolveCrosswordMSQLExprConstConcatReadVarexampleProgramnameRestrReselectRedropRe statementRe exploitRe findInjection$fIsStringSQLExprf proveThm1 proveThm2SBandornotax1ax2ax3$fEqB$fOrdB$fShowB$fReadB$fDataB $fSymWordB $fHasKindBthmGoodBinaryTernaryposnegshannonshannon2 derivativenoWiggle universalunivOK existentialexistsOKQ$fEqQ$fOrdQ$fDataQ$fReadQ$fShowQ $fSymWordQ $fHasKindQLNilConsclassifygenLs $fHasKindL $fSymWordL$fEqL$fOrdL$fShowL$fReadL$fDataLisStartModeOptionghc-prim GHC.TypesTrue setSMTOptionisExactRational mkPolyRealalgRealStructuralEqualalgRealStructuralComparealgRealToSMTLib2algRealToHaskell mergeAlgReals$fFractionalAlgRealkindRank kindHasSignconstructUKind $fOrdKind$fEqKind showExtCWliftCWshowCW showBaseKind randomCWValrandomCW $fOrdCWVal GHC.ClassesEq $fEqCWVal$fShowCW $fHasKindCW $fShowExtCW$fHasKindExtCW$fShowGeneralizedCW$fHasKindGeneralizedCWBoolbase Data.Foldableanyallmlift2mlift3mlift4mlift5mlift6mlift7mlift8joinArgs splitArgs qfsToString stringToQFSInitNorm time-1.8.0.2(Data.Time.Clock.Internal.NominalDiffTimeNominalDiffTime SMTEngine ArrayIndexpathCondIncStateCacheCgMapUIMapArrayMapTableMapKindSetCnstMapExprMapGHC.BaseNothingswKindreorder objectiveName newIncStatewithNewIncStategetSValPathConditionextendSValPathCondition noInteractive modifyStatemodifyIncStaterecordObservableincrementInternalCounter addAssertionnewSW registerKindDouble registerLabelnewConstsvToSW svToSymSWsvMkTrackerVar svMkSymVarGenintroduceUserNameaddNewSMTOptionimposeConstraintaddSValOptGoal uncacheGen $fShowRegExp $fNumRegExpGHC.NumNum+*$fIsStringRegExp $fShowStrOp$fHasKindRoundingMode$fEqSVal rSMTOptionsrunMode rIncState startTimerCInfo rObservablesrctr rUsedKinds rUsedLblsrinps rConstraintsroutsrtblMapspgm rconstMaprexprMap rArrayMaprUIMaprCgMapraxioms rOptGoalsrAssertsrSWCacherAICache queryStaterNewInps rNewKinds rNewConstsrNewArrsrNewTbls rNewAsgnssvStringsvChar eqOptBoolrotsvShifteqOptisConcreteZero isConcreteOneisConcreteOnes isConcreteMax isConcreteMinareConcretelyEqual rationalCheck nonzeroCheckrationalSBVCheckCharFloat$fEqSBV $fShowSBVGHC.ShowShow$fSymWordRoundingModeSExprtokenize parenDeficit parseSExprrdFPgetTripleFloatgetTripleDouble constantMapEConENumERealEFloatEDoubleEApppads2s16toSMTLibRationalTVSMTLibIncConverterSMTLibConverterannotateWithNameshowTimeoutValuealignDiagnostic alignPlainalignWithPrefixdebug mergeSExpr$fShowSMTException$fExceptionSMTExceptioncvtdeclSortcvtInctoSMTLib toIncSMTLib toSMTLib2 toIncSMTLib2 SolverLine SolverRegular SolverTimeoutSolverExceptionFalse resultConfig parseModelOutInt showSMTResultshowModelDictionaryshCW pipeProcessstandardEnginestandardSolver runSolver recordEndTimestartTranscriptfinalizeTranscript$fSatModel(,,,,,,)$fSatModel(,,,,,)$fSatModel(,,,,)$fSatModel(,,,)$fSatModel(,,) $fSatModel(,) $fSatModel[]$fSatModelRoundingMode $fSatModelCW$fSatModelDouble$fSatModelFloat$fSatModelAlgReal$fSatModelInteger integer-gmpGHC.Integer.TypeInteger$fSatModelInt64GHC.IntInt64$fSatModelWord64GHC.WordWord64$fSatModelInt32Int32$fSatModelWord32Word32$fSatModelInt16Int16$fSatModelWord16Word16$fSatModelInt8Int8$fSatModelWord8Word8$fSatModelBool $fSatModel()$fModelableSMTResult$fModelableSatResult$fModelableThmResultaddQueryConstraint getConfig getObjectives getSBVPgmgetSBVAssertions syncUpSolver getQueryStatemodifyQueryState inNewContextask askIgnoringsendretrieveResponsefromIntegralToValgetValueCWHelperrecoverKindedValue getValueCWgetQuantifiedInputsgetObservablesgetAllSatResultgetUnsatAssumptionsparse unexpected runProofOn$fSolverContextQuery Assignment classifyModelgetLexicographicOptResultsgetIndependentOptResultsgetParetoOptResultsgetModelAtIndexgetObjectiveValuescheckSatAssumingHelpergetUnsatCoreIfRequestedStringAssign allOnStdOut runWithQuery runInThread sbvWithAny sbvWithAll GMergeablesymbolicMergeDefault GHC.GenericsGenericGHC.RealIntegralRealGHC.EnumEnumquotRemdivModquotdiv Data.BitstestBitpopCountsetBitclearBitOrdOrderingmaxmingenVargenVar_liftPB pbToIntegerlift1Flift1FNSlift2FNS fromIntegral liftViaSValshiftLshiftRrotateLrotateRenumCvtsymbolicMergeWithKindslet$fSolverContextSymbolic $fFloatingSBV $fSymWord()symbolicMerge' STreeInternalSLeafSBinsppolyMultlift1lift2lift3 concEval1 concEval2 concEval3isConcretelyEmptygenericFPConverterptCheck concEval2BaddRMlift1BliftMMlift2B$fIEEEFloatingDouble$fIEEEFloatingFloat__unused liftSymbolic cgSBVToSWrender'Just pprCFunHeaderdeclSW declSWNoConstshowSWpprCWord showCType specifiermkConstgenMake genHeader genDrivergenCProg mergeToLib genLibMake mergeDriversSBVToCRatioRationalWord Data.RatioapproxRational byteSwap64 byteSwap32 byteSwap16toIntegralSizedpopCountDefaulttestBitDefault bitDefaultBits.&..|.xor complementshiftrotatezeroBitsbit complementBit bitSizeMaybebitSizeisSigned unsafeShiftL unsafeShiftR FiniteBits finiteBitSizecountLeadingZeroscountTrailingZeros denominator numerator%