h&AK      !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~                                                                          ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! " # # $ $ $ $ $ $ $ $ $ $ % % & ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ( ( ( ( ( ( ( ( ( ( ( ( ( ( ) ) ) * * * * * * * + + + + + + + + + + + + + + + + + , - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - . / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0                                                                                                                                                                                                  1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 3 3 3 4 4 4 4 4 5 5 4 4 4 4 4 4 5 4 4 4 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 8 8 8 8 8 88888888888888888888888899999::::::::::::::::;;5;;;55555;;;;;;<<<<<<<<<<<<<<<<<<<<<<<<<=====>>>???@@@@AAAABBBBBCCCDDDDDDDDDDDDDDDDDDDDEEFFFFFFFFFFFGGGGGGGGGGGGGGGGHHHHIIIIIIJJKKKKKKLLLLLMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMNNNNNOOOOOPPPPPQQRRRRSSSSSTTTTTTTTTTTTTTTTTTTTTTTUUVVWWWWWWXXXXXXYYYYYYYYYYYYZZ[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[\\\\\\]]]]]]]]]]]]]]]]]]]]]]]]^^^^^^^^^^^^^^^^^^^^^^^^^________________________```````````````````````aaaaaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbcccccdddddddddddddddeeeeeeeeeeeeeeeeeeeeeeeeeeeefffffffffffffffffffccgggggggggggggggggggggggggggggggggggggggggggggggggggggggghhhhiijj(C) 2018, Google Inc.BSD2 (see the file LICENSE)-Christiaan Baaij None&/02356789;<8 clash-preludeAnnotation for constructors. Indicates how to match this constructor based off of the whole datatype. clash-prelude7Annotation for custom bit representations of data typesUsing ANN pragma's you can tell the Clash compiler to use a custom bit-representation for a data type. For example: 'data Color = R | G | B {-# ANN module ( $(5 [t|Color|]) 2 [ % 'R 0b11 0b00 [] , % 'G 0b11 0b01 [] , * 'B 0b11 0b10 [] ]) #-} This specifies that R should be encoded as 0b00, G as 0b01, and B* as 0b10. The first binary value in every  ConstrRepr in this example is a mask, indicating which bits in the data type are relevant. In this case all of the bits are.Or if we want to annotate  Maybe Color: {-# ANN module (  $(= [t|Maybe Color|]) 2 [ , 'Nothing 0b11 0b11 [] , 3 'Just 0b00 0b00 [0b11] ] ) #-}  By default,  Maybe Color is a data type which consumes 3 bits. A single bit to indicate the constructor (either Just or Nothing.), and two bits to encode the first field of Just. Notice that we saved a single bit by exploiting the fact that Color only uses three values (0, 1, 2), but takes two bits to encode it. We can therefore use the last - unused - value (3), to encode one of the constructors of Maybe0. We indicate which bits encode the underlying Color field of Just by passing [0b11] to ConstrRepr. This indicates that the first field is encoded in the first and second bit of the whole datatype (0b11).NB6: BitPack for a custom encoding can be derived using ek. clash-preludeBitMask used to mask fields clash-preludeLift values inside of ! to a Template Haskell expression  (C) 2018, Google Inc. 2022, LUMI GUIDE FIETSDETECTIE B.V.BSD2 (see the file LICENSE)-Christiaan Baaij None &/02356789:;<> clash-prelude4Convenience type for index built by buildCustomReprs clash-preludeInternal version of ConstrRepr clash-preludeQualified name of constructor clash-prelude=Syntactical position in the custom representations definition clash-prelude$Mask needed to determine constructor clash-preludeValue after applying mask clash-prelude!Indicates where fields are stored clash-preludeInternal version of DataRepr clash-prelude"Simple representation of data type clash-preludeSize of data type clash-prelude Constructors clash-preludeSimple version of template haskell type. Used internally to match on. clash-preludeType application clash-preludeQualified name of type clash-prelude3Numeral literal (used in BitVector 10, for example) clash-prelude,Symbol literal (used in for example (Signal System Int)) clash-prelude>Convert template haskell type to simple representation of type clash-prelude-Lookup data type representation based on name clash-prelude/Lookup constructor representation based on name clash-prelude"Unchecked version of getConstrRepr clash-preludeNone&/02356789;<C  clash-preludeResult of various utilty functions. Indicates the origin of a certain bit: either a literal from the constructor (or an undefined bit), or from a literal. clash-preludeLiteral (high, low, undefind) clash-prelude#Bits originate from a field. Field fieldnr from downto. clash-preludeHigh clash-preludeLow clash-prelude Undefined clash-preludeSame as bitOrigins, but each item in result list represents a single bit. clash-preludeGiven a type size and one of its constructor this function will yield a specification of which bits the whole type is made up of. I.e., a construction plan on how to make the whole data structure, given its individual constructor fields. clash-preludeDetermine consecutively set bits in word. Will produce ranges from high to low. Examples:bitRanges 0b10 == [(1,1)] bitRanges 0b101 == [(2,2),(0,0)] bitRanges 0b10011001111 == [(10,10),(7,6),(3,0)]  (C) 2017-2019, Myrtle Software 2022, QBayLogic B.V.BSD2 (see the file LICENSE)%QBayLogic B.V. Safe&/02356789:;<V< clash-prelude>Warning that will be emitted on instantiating a guarded value. clash-preludeMarks value as non-synthesizable. This will trigger a warning if instantiated in a non-testbench context. clash-prelude1Always emit warning upon primitive instantiation. clash-preludePrimitive guard to mark a value as either not translatable or as having a blackbox with an optional extra warning. Helps Clash generate better error messages. For use, see , ,  and . clash-preludeMarks value as not translatable. Clash will error if it finds a blackbox definition for it, or when it is forced to translate it. clash-preludeMarks a value as having a blackbox. Clash will error if it hasn't found a blackbox. clash-preludeThe  constructor instructs the clash compiler to look for primitive HDL templates in the indicated directory.  is equivalent but provides the HDL template inline. They are intended for the distribution of new packages with primitive HDL templates. Example of You have some existing IP written in one of HDLs supported by Clash, and you want to distribute some bindings so that the IP can be easily instantiated from Clash.!You create a package which has a myfancyip.cabal file with the following stanza: =data-files: path/to/MyFancyIP.primitives cpp-options: -DCABALand a  MyFancyIP.hs5 module with the simulation definition and primitive. module MyFancyIP where import Clash.Prelude myFancyIP :: ... myFancyIP = ... {-# NOINLINE myFancyIP #-} The NOINLINE? pragma is needed so that GHC will never inline the definition..Now you need to add the following imports and ANN pragma: #ifdef CABAL import Clash.Annotations.Primitive import System.FilePath import qualified Paths_myfancyip import System.IO.Unsafe {-# ANN module (Primitive [VHDL] (unsafePerformIO Paths_myfancyip.getDataDir "path" "to")) #-} #endif Add more files to the  data-files stanza in your .cabal files and more ANN pragma's if you want to add more primitive templates for other HDLs Example of The following example shows off an inline HDL primitive template. It uses the  6https://hackage.haskell.org/package/string-interpolatestring-interpolate& package for nicer multiline strings. {-# LANGUAGE QuasiQuotes #-} module InlinePrimitive where import Clash.Annotations.Primitive import Clash.Prelude import Data.String.Interpolate (__i) {-# ANN example (InlineYamlPrimitive [VHDL] [__i| BlackBox: kind: Declaration name: InlinePrimitive.example template: |- -- begin InlinePrimitive example: ~GENSYM[example][0] : block ~RESULT <= 1 + ~ARG[0]; end block; -- end InlinePrimitive example |]) #-} {-# NOINLINE example #-} example :: Signal System (BitVector 2) -> Signal System (BitVector 2) example = fmap succ  clash-prelude'Description of a primitive for a given s in a file at g clash-prelude'Description of a primitive for a given s as an inline JSON R clash-prelude'Description of a primitive for a given s as an inline YAML R clash-preludeA compilation target HDL. clash-preludeMarks value as not translatable. Clash will error if it finds a blackbox definition for it, or when it is forced to translate it. You can annotate a variable or function f like: {-# ANN f dontTranslate #-}  clash-preludeMarks a value as having a blackbox. Clash will error if it hasn't found a blackbox. You can annotate a variable or function f like: {-# ANN f hasBlackBox #-}  clash-preludeMarks value as non-synthesizable. This will trigger a warning if instantiated in a non-testbench context. You can annotate a variable or function f like: >{-# ANN f (warnNonSynthesizable "Tread carefully, user!") #-} Implies . clash-preludeAlways emit warning upon primitive instantiation. You can annotate a variable or function f like: 4{-# ANN f (warnAlways "Tread carefully, user!") #-} Implies . clash-preludeExtract primitive definition from a PrimitiveGuard. Will yield Nothing for guards of value . clash-preludeExtract primitive warnings from a PrimitiveGuard. Will yield an empty list for guards of value .l(C) 2019 , Myrtle Software Ltd, 2023 , QBayLogic B.V.,BSD2 (see the file LICENSE)%QBayLogic B.V.  Safe-Inferred&/02356789;<X clash-prelude6Whether clash-prelude was compiled with -fsuper-strict clash-prelude:Whether clash-prelude was compiled with -fstrict-mapSignal Safe-Inferred&/02356789;<XS  (C) 2019, Myrtle Software LtdBSD2 (see the file LICENSE)-Christiaan Baaij None&./02356789;<Y clash-preludeCombine multiple lines with line break. Type-level version of the unlines function but for ErrorMessage. 445 (C) 2013-2016, University of Twente 2024, Google LLCBSD2 (see the file LICENSE)-Christiaan Baaij Safe&/02356789;<b\ clash-prelude+ operators in which overflow and underflow behavior can be specified using . clash-prelude:Addition with parameterizable over- and underflow behavior clash-prelude=Subtraction with parameterizable over- and underflow behavior clash-preludeMultiplication with parameterizable over- and underflow behavior clash-prelude;Get successor of (or in other words, add 1 to) given number clash-preludeGet predecessor of (or in other words, subtract 1 from) given number clash-preludeDetermine how overflow and underflow are handled by the functions in  clash-prelude%Wrap around on overflow and underflow clash-preludeBecome T on overflow, and U on underflow clash-preludeBecome 0 on overflow and underflow clash-preludeBecome T on overflow, and (U + 1() on underflow for signed numbers, and U for unsigned numbers. clash-prelude.Become an XException on overflow and underflow clash-preludeAdding, subtracting, and multiplying values of two different (sub-)types. clash-prelude1Type of the result of the addition or subtraction clash-prelude(Type of the result of the multiplication clash-preludeAdd values of different (sub-)types, return a value of a (sub-)type that is potentially different from either argument. clash-preludeSubtract values of different (sub-)types, return a value of a (sub-)type that is potentially different from either argument. clash-preludeMultiply values of different (sub-)types, return a value of a (sub-)type that is potentially different from either argument. clash-preludeAddition that clips to T on overflow, and U on underflow clash-preludeSubtraction that clips to T on overflow, and U on underflow clash-preludeMultiplication that clips to T on overflow, and U on underflow 667667667(C) 2019, QBayLogic B.V. (C) 2021, QBayLogic B.V.BSD2 (see the file LICENSE)$QBayLogic B.V Safe&/02356789;<c#UT$ %S&' ()*+,-~./01V23"! 4sqrut5Z[W\89;IL<=>?@AJKBQOPCDEFMNRXY]^_`abcdefghijklmnopvwxyz{|}#UT$ %S&' ()*+,-~./01V23"! 4sqrut5Z[W\89;IL<=>?@AJKBQOPCDEFMNRXY]^_`abcdefghijklmnopvwxyz{|}32 (C) 2018 , QBayLogic B.V.BSD2 (see the file LICENSE)-Christiaan Baaij  Trustworthy&-/02356789;<l clash-preludeA value reflected to, or hiding at, the  Constraint levele.g. a function: 1f :: Hidden "foo" Int => Bool -> Int f = ... has a normal argument of type Bool, and a hidden argument called "foo" of type Int. In order to apply the Int argument we have to use the  function, so that the hidden+ argument becomes a normal argument again.Original implementation used to be implemented by: :class Hidden (x :: Symbol) a | x -> a where hidden :: a which is equivalent to IP, except that IP has magic inference rules bestowed by GHC so that there's never any ambiguity. We need these magic inference rules so we don't end up in type inference absurdity where asking for the type of an type-annotated value results in a no-instance-in-scope error. clash-prelude Expose a 2 argument so that it can be applied normally, e.g. f :: Hidden "foo" Int => Bool -> Int f = ... g :: Int -> Bool -> Int g =  @"foo" f  clash-preludeUsing -XOverloadedLabels and -XRebindableSyntax , we can turn any value into a hidden argument using the #foo notation, e.g.: f :: Int -> Bool -> Int f = ... g :: Hidden "foo" Bool => Int -> Int g i = f i #foo  clash-preludeFunction with a  argument clash-preludeFunction with the  argument exposed 5(C) 2017, Myrtle Software Ltd, QBayLogic, Google Inc.BSD2 (see the file LICENSE)-Christiaan Baaij Safe&./02356789;<m clash-preludeAnnotate a type with a name (C) 2013-2016, University of Twente 2022 , QBayLogic B.V.BSD2 (see the file LICENSE)%QBayLogic B.V.  Safe-Inferred&'(/02356789;<o} clash-prelude(Singleton value for a type-level string s clash-prelude"Create a singleton symbol literal  s from a proxy for s clash-preludeReify the type-level  s to it's term-level R representation. "(C) 2019-2023, Myrtle Software LtdBSD2 (see the file LICENSE)%QBayLogic B.V. None&/02356789;<  clash-preludeA container for data you only want to have around during simulation and is ignored during synthesis. Useful for carrying around things such as:A map of simulation/vcd traces Co-simulation state or meta-dataetc. clash-prelude2Prefix instance and register names with the given  clash-prelude2Suffix instance and register names with the given  clash-prelude2Suffix instance and register names with the given  clash-prelude2Suffix instance and register names with the given ), but add it in front of other suffixes.When you write %suffixName @"A" (suffixName @"B" f)) +you get register and instance names inside f with the suffix: "_B_A";However, if you want them in the other order you can write: &suffixNameP @"A" (suffixName @"B" f)) so that names inside f will have the suffix "_A_B" clash-prelude2Suffix instance and register names with the given ), but add it in front of other suffixes.When you write &suffixNameNat @1 (suffixName @"B" f)) +you get register and instance names inside f with the suffix: "_B_1";However, if you want them in the other order you can write: 'suffixNameNatP @1 (suffixName @"B" f)) so that names inside f will have the suffix "_1_B" clash-prelude-Name the instance or register with the given , instead of using an auto-generated name. Pre- and suffixes annotated with  and ; will be added to both instances and registers named with 1 and instances and registers that are auto-named. clash-prelude'Name a given term, such as one of type m, using the given . Results in a declaration with the name used as the identifier in the generated HDL code.Example usage: &nameHint (SSymbol @"identifier") term NB: The given name should be considered a hint as it may be expanded, e.g. if it collides with existing identifiers. clash-preludeForce deduplication, i.e. share a function or operator between multiple branches.By default Clash converts $case x of A -> 3 * y B -> x * x to let f_arg0 = case x of {A -> 3; _ -> x} f_arg1 = case x of {A -> y; _ -> x} f_out = f_arg0 * f_arg1 in case x of A -> f_out B -> f_out However, it won't do this for: $case x of A -> 3 + y B -> x + x Because according to the internal heuristics the multiplexer introduced for the deduplication are more expensive than the addition. This might not be the case for your particular platform.5In these cases you can force Clash to deduplicate by: case x of A ->  (3 + y) B ->  (x + x)  clash-preludeDo not deduplicate, i.e. keep, an applied function inside a case-alternative; do not try to share the function between multiple branches.By default Clash converts /case x of A -> f 3 y B -> f x x C -> h x to let f_arg0 = case x of {A -> 3; _ -> x} f_arg1 = case x of {A -> y; _ -> x} f_out = f f_arg0 f_arg1 in case x of A -> f_out B -> f_out C -> h x i.e. it deduplicates functions (and operators such as multiplication) between case-alternatives to save on area. This comes at the cost of multiplexing the arguments for the deduplicated function.There are two reasons you would want to stop Clash from doing this: The deduplicated function is in the critical path, and the addition of the multiplexers further increased the propagation delay.Clash's heuristics were off, and the addition of the multiplexers actually made the final circuit larger instead of smaller.9In these cases you want to tell Clash not to deduplicate: case x of A ->  f 3 y B -> f x x C -> h x Where the application of f in the A-alternative is now explicitly not deduplicated, and given that the f< in the B-alternative is the only remaining application of f5 in the case-expression it is also not deduplicated.Note that if the C(-alternative also had an application of f, then the applications of f in the B- and C-alternatives would have been deduplicated; i.e. the final circuit would have had two application of f. clash-preludeL* in Haskell/Clash simulation. Replaced by I when generating HDL. clash-preludeSame as  but will make HDL generation fail if included in the final circuit.7This is useful for the error case of static assertions.Note that the error message needs to be a literal, and during HDL generation the error message does not include a stack trace, so it had better be descriptive. clash-preludeA hint for a name  n(C) 2024 , QBayLogic B.V.BSD2 (see the file LICENSE)%QBayLogic B.V.  Safe-Inferred&/02356789;<, clash-prelude3Format a range of numbers for use in error messages-If the upper bound is below the lower bound, ""( is returned. If the bounds are equal, "[n]"" is returned (for bounds equal to n). Otherwise, formatRange n m returns "[n..m]". clash-prelude Lower bound clash-prelude Upper bound(C) 2013-2016, University of Twente 2020, Myrtle Software Ltd 2024, QBayLogic B.V.BSD2 (see the file LICENSE)%QBayLogic B.V. Safe&/02356789;<m  clash-prelude>Coerce a value to be represented by a different number of bits clash-prelude"A sign-preserving resize operationFor signed datatypes: Increasing the size of the number replicates the sign bit to the left. Truncating a number to length L keeps the sign bit and the rightmost L-1 bits.For unsigned datatypes: Increasing the size of the number extends with zeros to the left. Truncating a number of length N to a length L just removes the left (most significant) N-L bits. clash-prelude Perform a  for unsigned datatypes, and  for a signed datatypes clash-prelude'Add extra zero bits in front of the MSB clash-prelude'Add extra sign bits in front of the MSB clash-preludeRemove bits from the MSB clash-preludeLike , but errors if a is out of bounds for b. Useful when you "know" a can't be out of bounds, but would like to have your assumptions checked.NB: Check only affects simulation. I.e., no checks will be inserted into the generated HDLNB: 5 is not well suited for Clash as it will go through @3 which is arbitrarily bounded in HDL. Instead use op and the  class. clash-preludeLike , but errors if f a is out of bounds for f b. Useful when you "know" f a can't be out of bounds, but would like to have your assumptions checked.NB: Check only affects simulation. I.e., no checks will be inserted into the generated HDL clash-preludeLike , but errors if  f (a + b) is out of bounds for f a. Useful when you "know"  f (a + b) can't be out of bounds, but would like to have your assumptions checked.NB: Check only affects simulation. I.e., no checks will be inserted into the generated HDL  (C) 2019, Andrew LelechenkoMIT%QBayLogic B.V. None&/02356789;< clash-preludemodular subtraction clash-preludemodular addition clash-preludemodular multiplication clash-preludemodular multiplication for powers of 2, takes a mask instead of a wrap-around point clash-preludemodular negations clash-preludeGiven a size in bits, return a function that complements the bits in a  up to that size. clash-prelude&Keep all the bits up to a certain size  (C) 2016, University of Twente, 2017, QBayLogic, Google Inc. 2017-2019, Myrtle Software LtdBSD2 (see the file LICENSE)-Christiaan Baaij  Trustworthy!&'(/02356789;<>? clash-preludeA class of functors that can be fully evaluated, according to semantics of NFDataX. clash-prelude should reduce its argument to normal form (that is, fully evaluate all sub-components), given an argument to reduce a arguments, and then return ().See  for the generic deriving. clash-preludeHidden internal type-class. Adds a generic implementation for the "NFData" part of  clash-prelude3An exception representing an "uninitialized" value. clash-preludeLike $, but values that normally throw an  are converted to  undefined-, instead of error'ing out with an exception. clash-preludeUse when you want to create a  instance where: There is no 6 instance for your data typeThe 6 derived ShowX method would traverse into the (hidden) implementation details of your data type, and you just want to show the entire value as  undefined.Can be used like: data T = ... instance Show T where ... instance ShowX T where showsPrecX = showsPrecXWith showsPrecq Safe-Inferred&/02356789;< clash-prelude)Compatibility helper to create TySynInstD clash-prelude8Compatibility helper to create (total) tuple expressions(C) 2019, Myrtle Software LtdBSD2 (see the file LICENSE)-Christiaan Baaij  Safe-Inferred&/02356789;<} clash-prelude Creates an instance of the form:/instance (ShowX a0, ShowX a1) => ShowX (a0, a1)With n number of variables. clash-prelude Trustworthy#&'(/02356789;<>?V clash-prelude)Class that houses functions dealing with  undefined values in Clash. See  and . clash-prelude Like the 1* class, but values that normally throw an  are converted to  undefined-, instead of error'ing out with an exception..show (errorX "undefined" :: Integer, 4 :: Int)"(*** Exception: X: undefinedCallStack (from HasCallStack):.../showX (errorX "undefined" :: Integer, 4 :: Int)"(undefined,4)"Can be derived using rs: {-# LANGUAGE DeriveGeneric, DeriveAnyClass #-} import Clash.Prelude import GHC.Generics data T = MkTA Int | MkTB Bool deriving (Show,Generic,ShowX) clash-preludeLike , but throwing an  instead of an The % methods print these error-values as  undefined.; instead of error'ing out with an exception. clash-preludeCreate a value where at the very least the spine is defined. For example:/spined = ensureSpine (errorX "?" :: (Int, Int))case spined of (_, _) -> 'a''a'5fmap (const 'b') (ensureSpine undefined :: Vec 3 Int)'b' :> 'b' :> 'b' :> Nil7fmap (const 'c') (ensureSpine undefined :: RTree 2 Int)<<'c','c'>,<'c','c'>>For users familiar with t): this is the generalized version of it. clash-prelude&Evaluate a value to NF. As opposed to s , it does not bubble up s. clash-preludeDetermines whether any of parts of a given construct contain undefined parts. Note that a negative answer does not mean its bit representation is fully defined. For example:m = Nothing :: Maybe BoolhasUndefined mFalsepack m0b0.hasUndefined (pack m)True clash-prelude.Create a value where all the elements have an , but the spine is defined. clash-preludeLike $, but values that normally throw an  are converted to  undefined-, instead of error'ing out with an exception. clash-prelude$Evaluate a value to WHNF, returning M msg if is a . isX 42 = Right 42 isX (XException msg) = Left msg isX (3, XException msg) = Right (3, XException msg) isX (3, _|_) = Right (3, _|_) isX _|_ = _|_ clash-preludeLike V$, but values that normally throw an  are converted to  undefined-, instead of error'ing out with an exception. clash-preludeLike $, but values that normally throw an  are converted to  undefined-, instead of error'ing out with an exception. clash-preludeEither  or  depending on the value of the cabal flag '-fsuper-strict'. If enabled,  will be  , otherwise . Flag defaults to false and thus . clash-preludeConvert  to +This is useful when tracking the source of  that gets eaten up by uv inside of your circuit; since uv translates  into undefined bits.1So for example if you have some large function f: !f a b = ... pack a ... pack b ...)Where it is basically an error if either a or b ever throws an 2, and so you want that to be reported the moment a or b is used, instead of it being thrown when evaluating the result of f , then do: {-# LANGUAGE ViewPatterns #-} f (xToErrorCtx "a is X" -> a) (xToErrorCtx "b is X" -> b) = ...Where we pass an extra string, for context, to know which argument evaluated to an 8. We can also use BangPatterns to report the potential  being thrown by a or b even earlier, i.e. when f is applied: {-# LANGUAGE ViewPatterns, BangPatterns #-} f (xToErrorCtx "a is X" -> !a) (xToErrorCtx "b is X" -> !b) = ...NB: Fully synthesizable, so doesn't have to be removed before synthesisExample:set -XViewPatterns -XDataKindsimport Clash.Sized.BitVectorimport GHC.Stack:{.let h, h' :: Bit -> BitVector 8 -> BitVector 8 h (xToErrorCtx "a is X" -> a) (xToErrorCtx "b is X" -> b) = slice d7 d0 (pack a ++# b)' h' a b = slice d7 d0 (pack a ++# b):}h' (errorX "QQ") 3 0b0000_0011h (errorX "QQ") 3*** Exception: a is XX: QQCallStack (from HasCallStack): errorX, called at ... clash-preludeConvert  to +This is useful when tracking the source of  that gets eaten up by uv inside of your circuit; since uv translates  into undefined bits.1So for example if you have some large function f: !f a b = ... pack a ... pack b ...)Where it is basically an error if either a or b ever throws an 2, and so you want that to be reported the moment a or b is used, instead of it being thrown when evaluating the result of f , then do: {-# LANGUAGE ViewPatterns #-} f (xToError -> a) (xToError -> b) = ...Unlike , where we have an extra String argument to distinguish one call to  to the other,  will use the rw mechanism to aid the user in distinguishing different call to 8. We can also use BangPatterns to report the potential  being thrown by a or b even earlier, i.e. when f is applied: {-# LANGUAGE ViewPatterns, BangPatterns #-} f (xToError -> !a) (xToError -> !b) = ...NB: Fully synthesizable, so doesn't have to be removed before synthesisExample:set -XViewPatterns -XDataKindsimport Clash.Sized.BitVectorimport GHC.Stack:{let f, g, h, h' :: HasCallStack => Bit -> BitVector 8 -> BitVector 8 f = g g = h h (xToError -> a) (xToError -> b) = slice d7 d0 (pack a ++# b)' h' a b = slice d7 d0 (pack a ++# b):}h' (errorX "QQ") 3 0b0000_0011f (errorX "QQ") 3 -*** Exception: CallStack (from HasCallStack): xToError, called at ... h, called at ... g, called at ... f, called at ...X: QQCallStack (from HasCallStack): errorX, called at ... clash-preludeLike , however, whereas  will always do: seq _|_ b = _|_ will do: 9seqX (XException msg) b = b seqX _|_ b = _|_ clash-preludeLike , but will also catch ErrorCall exceptions which are thrown. This should be used with care. seqErrorX (ErrorCall msg) b = b seqErrorX (XException msg) b = b seqErrorX _|_ b = _|_ clash-preludeLike  in simulation, but will force its first argument to be rendered in HDL. This is useful for components that need to be rendered in hardware, but otherwise have no meaning in simulation. An example of such a component would be an ILA: a component monitoring an internal signal of a design. The output of such a component (typically a unit) can be passed as the first argument to 0 to ensure the ILA ends up in the generated HDL.NB: The result of  must (indirectly) be used at the very top of a design. If it's not, Clash will remove it like it does for any other unused circuit parts.NB: Make sure the blackbox for the component with zero-width results uses xy clash-prelude"Fully evaluate a value, returning J if it throws . Note that non- errors take precedence over  ones. maybeHasX 42 = Just 42 maybeHasX (XException msg) = Nothing maybeHasX (3, XException msg) = Nothing maybeHasX (XException msg, _|_) = _|_ maybeHasX (_|_, XException msg) = _|_ maybeHasX (3, _|_) = _|_ maybeHasX _|_ = _|_ clash-prelude$Evaluate a value to WHNF, returning J if it throws . maybeIsX 42 = Just 42 maybeIsX (XException msg) = Nothing maybeIsX (3, XException msg) = Just (3, XException msg) maybeIsX (3, _|_) = Just (3, _|_) maybeIsX _|_ = _|_ clash-prelude"Fully evaluate a value, returning M msg if it throws . If you want to determine if a value contains undefined parts, use  instead. hasX 42 = Right 42 hasX (XException msg) = Left msg hasX (3, XException msg) = Left msg hasX (XException msg, _|_) = _|_ hasX (_|_, XException msg) = _|_ hasX (3, _|_) = _|_ hasX _|_ = _|_&If a data structure contains multiple s, the "first" message is picked according to the implementation of . clash-preludeLike $, but values that normally throw an  are converted to  undefined,, instead of error'ing out with an exception clash-prelude a variant of & that is useful in some circumstances: forceX x = x `deepseqX` x clash-prelude: fully evaluates the first argument, before returning the second. Does not propagate s. clash-preludeReduce to weak head normal formEquivalent to \x ->  x ().Useful for defining z{# for types for which NF=WHNF holds. clash-prelude clash-prelude clash-preludeNB/: The documentation only shows instances up to 34-tuples. By default, instances up to and including 12!-tuples will exist. If the flag  large-tuples is set instances up to the GHC imposed limit will exist. The GHC imposed limit is either 62 or 64 depending on the GHC version. clash-preludeCall to  with default string clash-preludeSame as |}, but returns a bottom/undefined value that other Clash constructs are aware of. clash-preludeNB/: The documentation only shows instances up to 34-tuples. By default, instances up to and including 12!-tuples will exist. If the flag  large-tuples is set instances up to the GHC imposed limit will exist. The GHC imposed limit is either 62 or 64 depending on the GHC version.00000(C) 2022, QBayLogic B.V.BSD2 (see the file LICENSE)%QBayLogic B.V.  Safe-Inferred&/02356789;<  clash-prelude+Structure helping programmers to deal with  values. For safety reasons it can't be constructed directly, but should be constructed using either ! or <. After construction, it can be deconstructed using either  or . clash-preludeUpon construction, a evaluated to a non-bottom WHNF clash-preludeUpon construction, a evaluated to  clash-prelude Construct a  value. If a evaluates to , this function will return . Otherwise, it will return . clash-prelude Construct a  value. If  evaluates to M, this function will return . Otherwise, it will return . clash-prelude Deconstruct  into an a - the opposite of . Be careful when using this function, because it might return an  if the argument was . clash-prelude%Map functions over both constructors. clash-prelude Implements  accounting for X@X@@1@@0@@X@@X@@X@@0@@1@@X@@1@@0@@0@@0@@0@@0@ clash-prelude Implements  accounting for X@X@@1@@0@@X@@X@@1@@X@@1@@1@@1@@1@@0@@X@@1@@0@ clash-prelude Note that   and  are X-strict in their arguments. That is, if any of their inputs are , their outputs will be too. clash-prelude Note that 7 is X-strict in its argument. That is, if its input is , its output will be too.  32(C) 2013-2016, University of Twente, 2016 , Myrtle Software Ltd 2022 , QBayLogic B.V.BSD2 (see the file LICENSE)%QBayLogic B.V.  Trustworthy&'(/02356789;<5. clash-preludeBase-2 encoded natural numberNB-: The LSB is the left/outer-most constructor:NB: Not synthesizableB0 (B1 (B1 BT))b6 ConstructorsStarting/Terminating element: BT ::  0 Append a zero (0): B0 ::  n ->  (2 ~ n) Append a one (1): B1 ::  n ->  ((2 ~ n) ~ 1)  clash-prelude"Ordering relation between two Nats clash-prelude,Unary representation of a type-level naturalNB: Not synthesizable clash-prelude0Singleton value for a type-level natural number nClash.Promoted.Nat.Literals contains a list of predefined  literalsClash.Promoted.Nat.TH7 has functions to easily create large ranges of new  literals clash-prelude Create an  n from a proxy for n clash-prelude+Supply a function with a singleton natural n according to the context clash-preludeSame as  and 2, but doesn't take term arguments. Example usage:natToInteger @55 clash-preludeReify the type-level  n to it's term-level @ representation. clash-preludeSame as  and ~2, but doesn't take term arguments. Example usage:natToNatural @55 clash-preludeReify the type-level  n to it's term-level . clash-preludeSame as 1, but doesn't take term arguments. Example usage:natToNum @5 @Int5 clash-preludeReify the type-level  n to it's term-level +ber. clash-prelude>Convert a singleton natural number to its unary representationNB: Not synthesizable clash-preludeConvert a unary-encoded natural number to its singleton representationNB: Not synthesizable clash-prelude%Add two unary-encoded natural numbersNB: Not synthesizable clash-prelude*Multiply two unary-encoded natural numbersNB: Not synthesizable clash-prelude*Power of two unary-encoded natural numbersNB: Not synthesizable clash-prelude-Predecessor of a unary-encoded natural numberNB: Not synthesizable clash-prelude*Subtract two unary-encoded natural numbersNB: Not synthesizable clash-prelude)Predecessor of a singleton natural number clash-prelude'Successor of a singleton natural number clash-prelude!Add two singleton natural numbers clash-prelude&Subtract two singleton natural numbers clash-prelude&Multiply two singleton natural numbers clash-prelude&Power of two singleton natural numbers clash-prelude)Division of two singleton natural numbers clash-prelude'Modulo of two singleton natural numbers clash-prelude*Floor of the logarithm of a natural number clash-prelude,Ceiling of the logarithm of a natural number clash-prelude+Exact integer logarithm of a natural numberNB5: Only works when the argument is a power of the base clash-prelude*Power of two of a singleton natural number clash-prelude*Get an ordering relation between two SNats clash-prelude1Show a base-2 encoded natural as a binary literalNB(: The LSB is shown as the right-most bitd789d789 toBNat d789b789showBNat (toBNat d789)"0b1100010101"0b1100010101 :: Integer789 clash-prelude?Convert a singleton natural number to its base-2 representationNB: Not synthesizable clash-preludeConvert a base-2 encoded natural number to its singleton representationNB: Not synthesizable clash-prelude&Add two base-2 encoded natural numbersNB: Not synthesizable clash-prelude+Multiply two base-2 encoded natural numbersNB: Not synthesizable clash-prelude+Power of two base-2 encoded natural numbersNB: Not synthesizable clash-prelude,Successor of a base-2 encoded natural numberNB: Not synthesizable clash-prelude.Predecessor of a base-2 encoded natural numberNB: Not synthesizable clash-prelude+Divide a base-2 encoded natural number by 2NB: Not synthesizable clash-prelude:Subtract 1 and divide a base-2 encoded natural number by 2NB: Not synthesizable clash-prelude/Get the log2 of a base-2 encoded natural numberNB: Not synthesizable clash-preludeStrip non-contributing zero's from a base-2 encoded natural numberB1 (B0 (B0 (B0 BT)))b1showBNat (B1 (B0 (B0 (B0 BT))))"0b0001",showBNat (stripZeros (B1 (B0 (B0 (B0 BT)))))"0b1"!stripZeros (B1 (B0 (B0 (B0 BT))))b1NB: Not synthesizable clash-prelude/Change a function that has an argument with an  (n ~ (k + m))8 constraint to a function with an argument that has an (k <= n) constraint.Examples Example 1 =f :: Index (n+1) -> Index (n + 1) -> Bool g :: forall n. (1 ~* n) => Index n -> Index n -> Bool g a b =  @1 @n (f a b)  Example 2 4head :: Vec (n + 1) a -> a head' :: forall n a. (1 ~ n) => Vec n a -> a head' =  @1 @n head  clash-preludeSame as  with added  constraints clash-preludeBase clash-preludeBase clash-preludeBase clash-preludeContext with the  (n ~ (k + m)) constraint clash-preludeContext with the  (n ~ (k + m)) constraint88667877(C) 2013-2016, University of Twente, 2019 , Gerg rdi 2016-2019, Myrtle Software Ltd, 2021-2024, QBayLogic B.V. 2023 , Nadia ChambersBSD2 (see the file LICENSE)%QBayLogic B.V. Unsafe#&/02356789:; Maybe Bool decode $(bitPattern "00.._.110") = Just True decode $(bitPattern "10.._0001") = Just False decode $(bitPattern "aa.._b0b1") = Just (aa + bb > 1) decode _ = Nothing  clash-preludeNB: /& can cause unexpected truncation, as @3 is arbitrarily bounded during synthesis. Prefer op and the  class. clash-preludeNB: /& can cause unexpected truncation, as @3 is arbitrarily bounded during synthesis. Prefer op and the  class. clash-preludeThe functions:  ,  ,  , and  , are not synthesizable. clash-preludeunpack function(C) 2013-2016, University of Twente 2022-2024, Google Inc.BSD2 (see the file LICENSE)-Christiaan Baaij  Trustworthy&/02356789;<q clash-prelude&Shift in a bit from the MSB side of a . Equal to right shifting the < by one and replacing the MSB with the bit to be shifted in.!1 +>>. 0b1111_0000 :: BitVector 8 0b1111_1000!0 +>>. 0b1111_0000 :: BitVector 8 0b0111_1000 clash-prelude&Shift in a bit from the LSB side of a . Equal to left shifting the < by one and replacing the LSB with the bit to be shifted in.!0b1111_0000 .<<+ 0 :: BitVector 8 0b1110_0000!0b1111_0000 .<<+ 1 :: BitVector 8 0b1110_0001  44(C) 2013-2016, University of Twente, 2017-2019, Myrtle Software Ltd 2017-2022, Google Inc., 2021-2023, QBayLogic B.V.BSD2 (see the file LICENSE)%QBayLogic B.V. Unsafe'%&'(-/02356789:;<>?u] clash-preludeClock edge A produced clash-preludeClock edge B produced clash-preludeClock edges coincided clash-prelude,A reset signal belonging to a domain called dom.+The underlying representation of resets is ;. clash-preludeFemtoseconds expressed as an . Is a newtype to prevent accidental mixups with picoseconds - the unit used in . clash-prelude8A differential clock signal belonging to a domain named dom. The clock input of a design with such an input has two ports which are in antiphase. The first input is the positive phase, the second the negative phase. When using d', the names of the inputs will end in _p and _n respectively.=To create a differential clock in a test bench, you can use . clash-preludeThe negative or inverted phase of a differential clock signal. HDL generation will treat it the same as , except that no  create_clock( command is issued in the SDC file for  . Used in . clash-prelude+A clock signal belonging to a domain named dom. clash-prelude Domain associated with the clock clash-preludePeriods of the clock. This is an experimental feature used to simulate clock frequency correction mechanisms. Currently, all ways to contruct such a clock are hidden from the public API. clash-preludeA signal of booleans, indicating whether a component is enabled. No special meaning is implied, it's up to the component itself to decide how to respond to its enable line. It is used throughout Clash as a global enable signal. clash-preludeClash has synchronous s in the form of:  (dom :: ) a Where a! is the type of the value of the , for example Int or Bool, and dom is the clock- (and reset-9) domain to which the memory elements manipulating these  s belong.The type-parameter, dom, is of the kind 3 - a simple string. That string refers to a single synthesis domain. A synthesis domain describes the behavior of certain aspects of memory elements in it.NB: "Bad things"B happen when you actually use a clock period of 0, so do not do that!NB7: You should be judicious using a clock with period of 16 as you can never create a clock that goes any faster!NB: For the best compatibility make sure your period is divisible by 2, because some VHDL simulators don't support fractions of picoseconds.NB : Whether > has good defaults depends on your target platform. Check out  and  too!Signals have the https://downloads.haskell.org/ghc/latest/docs/html/users_guide/exts/roles.html type role :i Signal)type role Signal nominal representational...as it is safe to coerce the underlying value of a signal, but not safe to coerce a signal between different synthesis domains. See the module documentation of  Clash.Signal$ for more information about domains. clash-preludeThe constructor, (), is not synthesizable. clash-preludeSame as SDomainConfiguration but allows for easy updates through record update syntax. Should be used in combination with  and  . Example: createDomain (knownVDomain @System){vName="System10", vPeriod=10}$This duplicates the settings in the  domain, replaces the name and period, and creates an instance for it. As most users often want to update the system domain, a shortcut is available in the form: 2createDomain vSystem{vName="System10", vPeriod=10} clash-preludeCorresponds to  on  clash-preludeCorresponds to  on  clash-preludeCorresponds to  on  clash-preludeCorresponds to  on  clash-preludeCorresponds to  on  clash-preludeCorresponds to  on  clash-preludeA clock (and reset) dom with clocks running at 100 MHz. Memory elements respond to the rising edge of the clock, and synchronously to changes in reset signals. It has defined initial values, and active-high resets.See module documentation of Clash.Explicit.Signal for more information on how to create custom synthesis domains. clash-preludeA clock (and reset) dom with clocks running at 100 MHz. Memory elements respond to the rising edge of the clock, and asynchronously to changes in reset signals. It has defined initial values, and active-high resets.See module documentation of Clash.Explicit.Signal for more information on how to create custom synthesis domains. clash-preludeA clock (and reset) dom with clocks running at 100 MHz. Memory elements respond to the rising edge of the clock, and asynchronously to changes in reset signals. It has defined initial values, and active-high resets.See module documentation of Clash.Explicit.Signal for more information on how to create custom synthesis domains. clash-preludeA  constraint indicates that a circuit's behavior depends on some properties of a domain. See  for more information. clash-preludeReturns  corresponding to an instance's .Example usage:knownDomain @SystemSDomainConfiguration {sName = SSymbol @"System", sPeriod = SNat @10000, sActiveEdge = SRising, sResetKind = SAsynchronous, sInitBehavior = SDefined, sResetPolarity = SActiveHigh} clash-preludeSingleton version of  clash-prelude Domain name clash-preludePeriod of clock in ps clash-prelude.Active edge of the clock (not yet implemented) clash-preludeWhether resets are synchronous (edge-sensitive) or asynchronous (level-sensitive) clash-preludeWhether the initial (or "power up") value of memory elements is unknown/undefined, or configurable to a specific value clash-prelude,Whether resets are active high or active low clash-preludeConvenience type to help to extract the reset polarity from a domain. Example usage: myFunc :: (KnownDomain dom, DomainResetPolarity dom ~ 'ActiveHigh) => ...  clash-preludeConvenience type to constrain a domain to have initial values. Example usage: -myFunc :: HasDefinedInitialValues dom => ... Using this type implies .Note that there is no UnknownInitialValues dom as a component that works without initial values will also work if it does have them.(Clash.Explicit.Signal#g:conveniencetypesClick here for usage hints clash-preludeConvenience type to help to extract the initial value behavior from a domain. Example usage: myFunc :: (KnownDomain dom, DomainInitBehavior dom ~ 'Defined) => ...  clash-preludeConvenience type to constrain a domain to have asynchronous resets. Example usage: *myFunc :: HasAsynchronousReset dom => ... Using this type implies .(Clash.Explicit.Signal#g:conveniencetypesClick here for usage hints clash-preludeConvenience type to constrain a domain to have synchronous resets. Example usage: )myFunc :: HasSynchronousReset dom => ... Using this type implies .(Clash.Explicit.Signal#g:conveniencetypesClick here for usage hints clash-preludeConvenience type to help to extract the reset synchronicity from a domain. Example usage: myFunc :: (KnownDomain dom, DomainResetKind dom ~ 'Synchronous) => ...  clash-preludeConvenience type to help to extract the active edge from a domain. Example usage: myFunc :: (KnownDomain dom, DomainActiveEdge dom ~ 'Rising) => ...  clash-preludeConvenience type to help to extract a period from a domain. Example usage:  ...  clash-preludeHelper type family for  clash-preludeHelper type family for  clash-preludeHelper type family for  clash-preludeHelper type family for  clash-preludeHelper type family for  clash-preludeA domain with a name (Domain). Configures the behavior of various aspects of a circuits. See the documentation of this record's field types for more information on the options.See module documentation of Clash.Explicit.Signal for more information on how to create custom synthesis domains. clash-prelude Domain name clash-preludePeriod of clock in ps clash-preludeActive edge of the clock clash-preludeWhether resets are synchronous (edge-sensitive) or asynchronous (level-sensitive) clash-preludeWhether the initial (or "power up") value of memory elements is unknown/undefined, or configurable to a specific value clash-prelude,Whether resets are active high or active low clash-prelude%Power up value of memory elements is unknown. clash-preludeIf applicable, power up value of a memory element is defined. Applies to s for example, but not to W. clash-preludeSingleton version of  clash-preludeDetermines the value for which a reset line is considered "active" clash-prelude3Reset is considered active if underlying signal is L. clash-prelude3Reset is considered active if underlying signal is I. clash-preludeSingleton version of  clash-preludeElements respond asynchronously; to changes in their reset input. This means that they do not wait for the next active clock edge, but respond immediately instead. Common on Intel FPGA platforms. clash-preludeElements respond  synchronously to changes in their reset input. This means that changes in their reset input won't take effect until the next active clock edge. Common on Xilinx FPGA platforms. clash-preludeSingleton version of  clash-preludeDetermines clock edge memory elements are sensitive to. Not yet implemented. clash-preludeElements are sensitive to the rising edge (low-to-high) of the clock. clash-preludeElements are sensitive to the falling edge (high-to-low) of the clock. clash-prelude Version of  that takes a . For example:%knownDomainByName (SSymbol @"System")SDomainConfiguration {sName = SSymbol @"System", sPeriod = SNat @10000, sActiveEdge = SRising, sResetKind = SAsynchronous, sInitBehavior = SDefined, sResetPolarity = SActiveHigh} clash-preludeConvenience value to allow easy "subclassing" of System domain. Should be used in combination with . For example, if you just want to change the period but leave all other settings intact use: 2createDomain vSystem{vName="System10", vPeriod=10} clash-preludeConvenience value to allow easy "subclassing" of IntelSystem domain. Should be used in combination with . For example, if you just want to change the period but leave all other settings intact use: 6createDomain vIntelSystem{vName="Intel10", vPeriod=10} clash-preludeConvenience value to allow easy "subclassing" of XilinxSystem domain. Should be used in combination with . For example, if you just want to change the period but leave all other settings intact use: 8createDomain vXilinxSystem{vName="Xilinx10", vPeriod=10} clash-preludeConvert  to &. Should be used in combination with  only. clash-prelude=Convenience method to express new domains in terms of others. createDomain (knownVDomain @System){vName="System10", vPeriod=10}$This duplicates the settings in the System domain, replaces the name and period, and creates an instance for it. As most users often want to update the system domain, a shortcut is available in the form: 2createDomain vSystem{vName="System10", vPeriod=10}:The function will create two extra identifiers. The first: type System10 = ..You can use that as the dom to Clocks/Resets/Enables/Signals. For example: Signal System10 Int!. Additionally, it will create a % that you can use in later calls to : "vSystem10 = knownVDomain @System10It will also make System10 an instance of .If either identifier is already in scope it will not be generated a second time. Note: This can be useful for example when documenting a new domain: -- | Here is some documentation for CustomDomain type CustomDomain = ("CustomDomain" :: Domain) -- | Here is some documentation for vCustomDomain createDomain vSystem{vName="CustomDomain"} clash-preludeWe either get evidence that this function was instantiated with the same domains, or Nothing. clash-preludeWARNING: EXTREMELY EXPERIMENTALThe circuit semantics of this operation are unclear and/or non-existent. There is a good reason there is no ) instance for .Is currently treated as X by the Clash compiler. clash-preludeNB: Not synthesizableNB: In " f z s": The function f should be lazy in its second argument.The z element will never be used. clash-preludeConvert  construct to its underlying representation: a signal of bools. clash-prelude Convert a signal of bools to an  construct clash-prelude8Enable generator for some domain. Is simply always True. clash-prelude$Clock generator for simulations. Do not# use this clock generator for the  testBench function, use  instead.To be used like: clkSystem = clockGen @System See 6 for more information on how to use synthesis domains. clash-prelude"Clock generator to be used in the  testBench function.To be used like: %clkSystem en = tbClockGen @System en Example module Example where import Clash.Explicit.Prelude import Clash.Explicit.Testbench* -- Fast domain: twice as fast as "Slow" c c{vName="Fast", vPeriod=10} -- Slow domain: twice as slow as "Fast" c c+{vName="Slow", vPeriod=20} topEntity ::  "Fast" ->  "Fast" ->  "Fast" ->  "Slow" ->  "Fast" (Unsigned 8) ->  "Slow" (Unsigned 8, Unsigned 8) topEntity clk1 rst1 en1 clk2 i = let h = register clk1 rst1 en1 0 (register clk1 rst1 en1 0 i) l = register clk1 rst1 en1 0 i in unsafeSynchronizer clk1 clk2 (bundle (h, l)) testBench :: ; "Slow" Bool testBench = done where testInput =  clkA1 rstA1 $(5 [1::Unsigned 8,2,3,4,5,6,7,8]) expectedOutput =  clkB2 rstB2 $( [(0,0) :: (Unsigned 8, Unsigned 8),(1,2),(3,4),(5,6),(7,8)]) done = expectedOutput (topEntity clkA1 rstA1 enableGen clkB2 testInput) notDone = not <$> done clkA1 =  @"Fast" (unsafeSynchronizer clkB2 clkA1 notDone) clkB2 = & @"Slow" notDone rstA1 =  @"Fast" rstB2 =  @"Slow"  clash-preludeStrip newtype wrapper  clash-preludeMap  fields in  clash-preludeClock generator with dynamic clock periods for simulations. This is an experimental feature and hence not part of the public API.To be used like: $clkSystem = dynamicClockGen @System See 6 for more information on how to use synthesis domains. clash-preludeClock generator with dynamic clock periods for simulations. This is an experimental feature and hence not part of the public API. Like To be used like: $clkSystem = dynamicClockGen @System See 6 for more information on how to use synthesis domains. clash-preludeReset generator for simulation purposes. Asserts the reset for a single cycle.To be used like: rstSystem = resetGen @System See  for example usage.NB : While this can be used in the  testBench1 function, it cannot be synthesized to hardware. clash-preludeReset generator for simulation purposes. Asserts the reset for the first n cycles.To be used like: !rstSystem5 = resetGen @System d5 Example usage:5sampleN 7 (unsafeToActiveHigh (resetGenN @System d3))([True,True,True,False,False,False,False]NB : While this can be used in the  testBench1 function, it cannot be synthesized to hardware. clash-preludeConvert a reset to an active high reset. Has no effect if reset is already an active high reset. Is unsafe because it can introduce: (Clash-Explicit-Signal.html#metastabilitymeta-stabilityFor asynchronous resets it is unsafe because it can cause combinatorial loops. In case of synchronous resets it can lead to  (Clash-Explicit-Signal.html#metastabilitymeta-stability) in the presence of asynchronous resets. clash-preludeConvert a reset to an active high reset. Has no effect if reset is already an active high reset. Is unsafe because it can introduce: (Clash-Explicit-Signal.html#metastabilitymeta-stabilityFor asynchronous resets it is unsafe because it can cause combinatorial loops. In case of synchronous resets it can lead to  (Clash-Explicit-Signal.html#metastabilitymeta-stability) in the presence of asynchronous resets. clash-preludeConvert a reset to an active low reset. Has no effect if reset is already an active low reset. It is unsafe because it can introduce: (Clash-Explicit-Signal.html#metastabilitymeta-stabilityFor asynchronous resets it is unsafe because it can cause combinatorial loops. In case of synchronous resets it can lead to  (Clash-Explicit-Signal.html#metastabilitymeta-stability) in the presence of asynchronous resets. clash-preludeConvert a reset to an active low reset. Has no effect if reset is already an active low reset. It is unsafe because it can introduce: (Clash-Explicit-Signal.html#metastabilitymeta-stabilityFor asynchronous resets it is unsafe because it can cause combinatorial loops. In case of synchronous resets it can lead to  (Clash-Explicit-Signal.html#metastabilitymeta-stability) in the presence of asynchronous resets. clash-prelude$ is unsafe because it can introduce: (Clash-Explicit-Signal.html#metastabilitymeta-stabilityFor asynchronous resets it is unsafe because it can cause combinatorial loops. In case of synchronous resets it can lead to  (Clash-Explicit-Signal.html#metastabilitymeta-stability) in the presence of asynchronous resets.NB: You probably want to use  or . clash-prelude is unsafe. For asynchronous resets it is unsafe because it can introduce combinatorial loops. In case of synchronous resets it can lead to  (Clash-Explicit-Signal.html#metastabilitymeta-stability0 issues in the presence of asynchronous resets.NB: You probably want to use  or . clash-preludeInterpret a signal of bools as an active high reset and convert it to a reset signal corresponding to the domain's setting.For asynchronous resets it is unsafe because it can cause combinatorial loops. In case of synchronous resets it can lead to  (Clash-Explicit-Signal.html#metastabilitymeta-stability) in the presence of asynchronous resets. clash-preludeInterpret a signal of bools as an active high reset and convert it to a reset signal corresponding to the domain's setting.For asynchronous resets it is unsafe because it can cause combinatorial loops. In case of synchronous resets it can lead to  (Clash-Explicit-Signal.html#metastabilitymeta-stability) in the presence of asynchronous resets. clash-preludeInterpret a signal of bools as an active low reset and convert it to a reset signal corresponding to the domain's setting.For asynchronous resets it is unsafe because it can cause combinatorial loops. In case of synchronous resets it can lead to  (Clash-Explicit-Signal.html#metastabilitymeta-stability) in the presence of asynchronous resets. clash-preludeInterpret a signal of bools as an active low reset and convert it to a reset signal corresponding to the domain's setting.For asynchronous resets it is unsafe because it can cause combinatorial loops. In case of synchronous resets it can lead to  (Clash-Explicit-Signal.html#metastabilitymeta-stability) in the presence of asynchronous resets. clash-preludeInvert reset signal clash-prelude'The above type is a generalization for: (.||.) :: m ; -> m ; -> m ; It is a version of () that returns a m of ; clash-prelude'The above type is a generalization for: (.&&.) :: m ; -> m ; -> m ; It is a version of () that returns a m of ; clash-preludeA register with a power up and reset value. Power up values are not supported on all platforms, please consult the manual of your target platform and check the notes below.Xilinx: power up values and reset values MUST be the same. If they are not, the Xilinx tooling will ignore the reset value1 and use the power up value instead. Source: MIAIntel: power up values and reset values MUST be the same. If they are not, the Intel tooling will ignore the power up value+ and use the reset value instead. Source: https://www.intel.com/content/www/us/en/programmable/support/support-resources/knowledge-base/solutions/rd01072011_91.html clash-prelude Acts like X if given domain allows powerup values, but returns a value constructed with  otherwise. clash-prelude Version of  that simulates a register on an asynchronous domain. Is synthesizable. clash-prelude Version of  that simulates a register on a synchronous domain. Not synthesizable. clash-prelude'The above type is a generalization for: mux :: m ; -> m a -> m a -> m a A multiplexer. Given " b t f ", output t when b is L, and f when b is I. clash-prelude'The above type is a generalization for: (.==.) :: % a => m a -> m a -> m ; It is a version of () that returns a m of ; clash-prelude'The above type is a generalization for: (./=.) :: % a => m a -> m a -> m ; It is a version of (S) that returns a m of ; clash-prelude'The above type is a generalization for: (.<.) :: , a => m a -> m a -> m ; It is a version of () that returns a m of ; clash-prelude'The above type is a generalization for: (.<=.) :: , a => m a -> m a -> m ; It is a version of (~) that returns a m of ; clash-prelude'The above type is a generalization for: (.>.) :: , a => m a -> m a -> m ; It is a version of () that returns a m of ; clash-prelude'The above type is a generalization for: (.>=.) :: , a => m a -> m a -> m ; It is a version of () that returns a m of ; clash-prelude'The above type is a generalization for: testFor :: ? -> m Bool ->   testFor n s tests the signal s for n cycles.NB$: This function is not synthesizable clash-prelude'The above type is a generalization for: sample :: m a -> [a] 'Get an infinite list of samples from a m9The elements in the list correspond to the values of the m at consecutive clock cycles  sample s == [s0, s1, s2, s3, ...NB$: This function is not synthesizable clash-prelude'The above type is a generalization for: sampleN :: Int -> m a -> [a] Get a list of n samples from a m9The elements in the list correspond to the values of the m at consecutive clock cycles sampleN 3 s == [s0, s1, s2]NB$: This function is not synthesizable clash-prelude Create a m from a listEvery element in the list will correspond to a value of the signal for one clock cycle. sampleN 2 (fromList [1,2,3,4,5])[1,2]NB$: This function is not synthesizable clash-prelude Simulate a (m a -> m b,) function given a list of samples of type asimulate (register systemClockGen resetGen enableGen 8) [1, 1, 2, 3] [8,8,1,2,3......NB$: This function is not synthesizable clash-prelude'The above type is a generalization for: sample :: m a -> [a] 'Get an infinite list of samples from a m9The elements in the list correspond to the values of the m at consecutive clock cycles  sample s == [s0, s1, s2, s3, ...NB$: This function is not synthesizable clash-prelude'The above type is a generalization for: sampleN :: Int -> m a -> [a] Get a list of n samples from a m9The elements in the list correspond to the values of the m at consecutive clock cycles sampleN 3 s == [s0, s1, s2]NB$: This function is not synthesizable clash-prelude Create a m from a listEvery element in the list will correspond to a value of the signal for one clock cycle.5sampleN 2 (fromList [1,2,3,4,5] :: Signal System Int)[1,2]NB$: This function is not synthesizable clash-prelude Simulate a (m a -> m b,) function given a list of samples of type asimulate (register systemClockGen resetGen enableGen 8) [1, 1, 2, 3] [8,8,1,2,3......NB$: This function is not synthesizable clash-preludeCalculate the period in ps, given a frequency in HzI.e., to calculate the clock period for a circuit to run at 240 MHz we gethzToPeriod 240e64166 If the value  hzToPeriod" is applied to is not of the type  , you can use  hzToPeriod ( f). Note that if f is negative,  realToFrac will give an  :: 4 without a call stack, making debugging cumbersome.2Before Clash 1.8, this function always returned a . To get the old behavior of this function, use a type application:hzToPeriod @Natural 240e64166NB$: This function is not synthesizableNB : This function is lossy. I.e., periodToHz . hzToPeriod /= id. clash-preludeCalculate the period in fs, given a frequency in HzI.e., to calculate the clock period for a circuit to run at 240 MHz we get hzToFs 240e6Femtoseconds 4166666 If the value hzToFs" is applied to is not of the type  , you can use hzToFs ( f). Note that if f is negative,  realToFrac will give an  :: 4 without a call stack, making debugging cumbersome.NB$: This function is not synthesizableNB!: This function is lossy. I.e., fsToHz . hzToFs /= id. clash-preludeCalculate the frequency in Hz, given the period in psI.e., to calculate the clock frequency of a clock with a period of 5000 ps:periodToHz 50002.0e8 Note that if p in  periodToHz ( p) is negative,  fromIntegral will give an  :: 4 without a call stack, making debugging cumbersome.2Before Clash 1.8, this function always returned a  . To get the old behavior of this function, use a type application: periodToHz @(Ratio Natural) 5000 200000000 % 1NB$: This function is not synthesizable clash-preludeCalculate the frequency in Hz, given the period in fsI.e., to calculate the clock frequency of a clock with a period of 5000 fs:fsToHz (Femtoseconds 5000)2.0e11NB$: This function is not synthesizable clash-prelude Build an  from a function over s.NB%: Consumption of continuation of the  must be affine; that is, you can only apply the continuation associated with a particular element at most once. clash-preludeGiven two clocks, produce a list of clock ticks indicating which clock (or both) ticked. Can be used in components handling multiple clocks, such as unsafeSynchronizer or dual clock FIFOs.If your primitive does not care about coincided clock edges, it should - by convention - replace it by ClockB:ClockA:. clash-preludeGiven two clock periods, produce a list of clock ticks indicating which clock (or both) ticked. Can be used in components handling multiple clocks, such as unsafeSynchronizer or dual clock FIFOs.If your primitive does not care about coincided clock edges, it should - by convention - replace it by ClockB:ClockA:. clash-prelude1System instance with defaults set for Intel FPGAs clash-prelude2System instance with defaults set for Xilinx FPGAs clash-preludeA clock (and reset$) dom with clocks running at 100 MHz clash-preludeNB: Not synthesizableNB: In " f z s": The function f should be lazy in its second argument.The z element will never be used.  clash-preludeClock period in femtoseconds.NB: Beware that the periods are given in femtoseconds; this differs from the usual unit Clash uses to represent period length, picoseconds.NB: Beware that not all simulators support femtoseconds. For example, Vivado's XSIM will round down to nearest picoseconds.NB-: Beware that, by default, Clash will define `timescale 100fs/100fs in its generated Verilog. The latter will make simulators round time to 100fs. If you rely on more precision you should pass -fclash-timescale-precision 1fs to Clash. clash-preludeClock period in femtoseconds.NB: Beware that the periods are given in femtoseconds; this differs from the usual unit Clash uses to represent period length, picoseconds.NB: Beware that not all simulators support femtoseconds. For example, Vivado's XSIM will round down to nearest picoseconds.NB-: Beware that, by default, Clash will define `timescale 100fs/100fs in its generated Verilog. The latter will make simulators round time to 100fs. If you rely on more precision you should pass -fclash-timescale-precision 1fs to Clash. clash-prelude+Number of initial cycles to hold reset high clash-preludeReset signal that's L when active, and I when inactive. clash-preludeReset signal that's L when active, and I when inactive. clash-preludeReset signal that's I when active, and L when inactive. clash-preludeReset signal that's I when active, and L when inactive. clash-preludePower up value clash-prelude Reset value clash-prelude Clock signal clash-prelude Reset signal clash-prelude Enable signal clash-preludePower up value clash-prelude Reset value clash-prelude Clock signal clash-prelude Reset signal clash-prelude Enable signal clash-preludePower up value clash-prelude Reset value 523444444(C) 2019, Myrtle Software LtdBSD2 (see the file LICENSE)%QBayLogic B.V. None &/02356789;<>O clash-preludeAn AssertionValue is a bool-like value or stream that can be used in property specifications. Clash implements two: a stream of booleans (Signal dom Bool), and the result of a property expression (Assertion dom). clash-prelude$Convert given type into a Assertion. clash-preludeA result of some property. Besides carrying the actual boolean result, it carries some properties used to make reports. clash-prelude)Name of property belonging to this result clash-prelude3False whenever property is violated, True otherwise clash-preludeA property is a temporal or basic assertion that's specified to either used as an _assert_ or _cover_ statement. See   and  . clash-preludeInternal version of #. All user facing will instantiate a with (Maybe Text, Signal dom Bool)'. Blackboxes will instantiate it with (Maybe Text, Term) instead. clash-preludeInternal version of . clash-prelude"(Bootstrapping) signal of booleans clash-prelude7Tag to force a non-temporal assertion to a temporal one clash-preludeBoolean literal clash-prelude Logical not clash-prelude Logical and clash-prelude Logical or clash-preludeLogical implies clash-preludeMoves start point of assertion n cycles forward clash-preludeBefore  CvBefore a b is the same as CvAnd a (CvNext 1 b) clash-preludeTemporal implies CvTemporalImplies n a b:n | n == 0 -> same as  CvImplies a b | otherwise -> same as CvImplies a (CvNextN n b) clash-preludeAssertion should _always_ hold clash-prelude4Assertion should _never_ hold (not supported by SVA) clash-prelude"Assertion should _eventually_ hold clash-preludeRender target for HDL clash-preludeProperty Specification Language clash-preludeSystemVerilog Assertions clash-prelude)Use SVA for SystemVerilog, PSL for others clash-prelude=Yosys Formal Extensions for Verilog and SystemVerilog. See:  8https://symbiyosys.readthedocs.io/en/latest/verilog.html and 8https://symbiyosys.readthedocs.io/en/latest/verific.htmlFalls back to PSL for VHDL, however currently Clash's PSL syntax isn't suported by GHDL+SymbiYosys; clash-prelude"Result of a property specification clash-prelude.Stream of booleans, originating from a circuit''None%&/02356789;< clash-prelude/Get the clock period from a KnownDomain context clash-preludeGet + from a KnownDomain context. Example usage: f :: forall dom . KnownDomain dom => .... f a b c = case activeEdge @dom of SRising -> foo SFalling -> bar  clash-preludeGet + from a KnownDomain context. Example usage: f :: forall dom . KnownDomain dom => .... f a b c = case resetKind @dom of SAsynchronous -> foo SSynchronous -> bar  clash-preludeGet + from a KnownDomain context. Example usage: f :: forall dom . KnownDomain dom => .... f a b c = case initBehavior @dom of SDefined -> foo SUnknown -> bar  clash-preludeGet + from a KnownDomain context. Example usage: f :: forall dom . KnownDomain dom => .... f a b c = case resetPolarity @dom of SActiveHigh -> foo SActiveLow -> bar  clash-preludeLike 'knownDomain but yields a +. Should only be used in combination with .(C) 2024, QBayLogic B.V.BSD2 (see the file LICENSE)%QBayLogic B.V. None&/02356789;<v clash-prelude,Contruct all the tuple instances for Bundle. clash-preludeBundle clash-prelude Unbundled clash-preludebundle clash-preludeunbundle (C) 2019, Myrtle Software Ltd 2022, QBayLogic B.V.BSD2 (see the file LICENSE)%QBayLogic B.V. None&/02356789;<! clash-preludeConvert a signal to a cv expression with a name hint. Clash will try its best to use this name in the rendered assertion, but might run into collisions. You can skip using  altogether. Clash will then try its best to get a readable name from context. clash-prelude8For using a literal (either True or False) in assertions clash-preludeTruth table for : 5a | not a ------------ True | False False | True clash-preludeTruth table for : a | b | a `and` b --------------|---------- False | False | False False | True | False True | False | False True | True | True clash-preludeTruth table for : a | b | a `or` b --------------|--------- False | False | False False | True | True True | False | True True | True | True clash-preludeTruth table for : a | b | a `implies` b --------------|-------------- False | False | True False | True | True True | False | False True | True | True clash-preludeTruth table for : a[n] | a[n+1] | a `implies` next a ---------------|------------------- False | False | True False | True | True True | False | False True | True | True#where a[n] represents the value of a at cycle n and a[n+1] represents the value of a at cycle n+1 . Cycle n is an arbitrary cycle. clash-preludeTruth table for : a[n] | a[n+m] | a `implies` next m a ---------------|--------------------- False | False | True False | True | True True | False | False True | True | True#where a[n] represents the value of a at cycle n% and a[n+m] represents the value of a at cycle n+m . Cycle n is an arbitrary cycle. clash-preludeSame as  a && next b but with a nice syntax. E.g.,  a && next b could be written as a  b2. Might be read as "a happens one cycle before b". clash-preludeSame as a  next b but with a nice syntax. E.g., a  next b could be written as a  b:. Might be read as "a at cycle n implies b at cycle n+1". clash-preludeSame as  but strictly temporal. clash-prelude&Specify assertion should _always_ hold clash-prelude Trustworthy &'(/02356789;<  clash-prelude+A synchronized signal with samples of type a, synchronized to clock clk, that has accumulated delay( amount of samples delay along its path.DSignal has the https://downloads.haskell.org/ghc/latest/docs/html/users_guide/exts/roles.html type role :i DSignal2type role DSignal nominal nominal representational...as it is safe to coerce the values in the signal, but not safe to coerce the synthesis domain or delay in the signal.  clash-preludeStrip a   of its delay information.  clash-prelude Create a   from a listEvery element in the list will correspond to a value of the signal for one clock cycle.,sampleN 2 (toSignal (dfromList [1,2,3,4,5]))[1,2]NB$: This function is not synthesizable  clash-prelude Create a   from a listEvery element in the list will correspond to a value of the signal for one clock cycle.,sampleN 2 (toSignal (dfromList [1,2,3,4,5]))[1,2]NB$: This function is not synthesizable  clash-prelude8Feed the delayed result of a function back to its input: mac :: forall dom . KnownDomain dom => Clock dom -> Reset dom -> Enable dom ->   dom 0 Int ->   dom 0 Int ->   dom 0 Int mac clk rst en x y =  & (mac' x y) where mac' ::   dom 0 Int ->   dom 0 Int ->   dom 0 Int -> (  dom 0 Int,   dom 1 Int) mac' a b acc = let acc' = a * b + acc in (acc, = clk rst en 0 acc') sampleN 7 (toSignal (mac systemClockGen systemResetGen enableGen (dfromList [0..]) (dfromList [0..])))[0,0,1,5,14,30,55]  clash-preludes are not delayed  clash-prelude EXPERIMENTALUnsafely convert a  to a   with an arbitrary delay.NB: Should only be used to interface with functions specified in terms of .  clash-prelude EXPERIMENTAL Access a delayed signal from the future in the present. Often required When writing a circuit that requires feedback from itself. mac :: KnownDomain dom => Clock dom -> Reset dom -> Enable dom ->   dom 0 Int ->   dom 0 Int ->   dom 0 Int mac clk rst en x y = acc' where acc' = (x * y) +   d1 acc acc = = clk rst en 0 acc'  clash-prelude EXPERIMENTAL Access a delayed8 signal from the past in the present. In contrast with = and friends forward does not insert any logic. This means using this function violates the delay invariant of  . This is sometimes useful when combining unrelated delayed signals where inserting logic is not wanted or when abstracting over internal delayed signals where the internal delay information should not be leaked.For example, the circuit below returns a sequence of numbers as a pair but the internal delay information between the elements of the pair should not leak into the type. numbers :: forall dom . KnownDomain dom => Clock dom -> Reset dom -> Enable dom ->   dom 5 (Int, Int) numbers clk rst en = DB.bundle (forward d1 s1, s2) where s1 ::   dom 4 Int s1 = => clk rst en (100 :> 10 :> 5 :> 1 :> Nil) (pure 200) s2 ::   dom 5 Int s2 = fmap (2*) $ = d1 0 en clk s1 sampleN 8 (toSignal (numbers systemClockGen systemResetGen enableGen))[(1,0),(1,2),(5,2),(10,10),(100,20),(200,200),(200,400),(200,400)] "(C) 2015-2016, University of Twente 2022 , QBayLogic B.V.BSD2 (see the file LICENSE)%QBayLogic B.V. Unsafe&/02356789;<  clash-prelude!I hope you know what you're doing  ##(C) 2013-2016, University of TwenteBSD2 (see the file LICENSE)-Christiaan Baaij  Trustworthy&/02356789;<  clash-prelude Create an  literal $(decLiteralD 1111):t d1111d1111 :: SNat 1111  clash-preludeCreate a range of  literals $(decLiteralsD 1200 1202):t d1200d1200 :: SNat 1200:t d1201d1201 :: SNat 1201:t d1202d1202 :: SNat 1202  $#(C) 2013-2016, University of TwenteBSD2 (see the file LICENSE)-Christiaan Baaij  Trustworthy&/02356789;<t %(C) 2019, Myrtle Software LtdBSD2 (see the file LICENSE)-Christiaan Baaij  Safe-Inferred&/02356789;<L  &(C) 2019-2024, QBayLogic B.V.BSD2 (see the file LICENSE)%QBayLogic B.V. None&/02356789;<  clash-preludeContruct all the tuple (starting at size 3) instances for BitPack.  clash-preludeBitPack clash-preludeBitSize clash-preludepack clash-preludeunpack  '(C) 2013-2016, University of Twente, 2016-2017, Myrtle Software Ltd, 2021-2024 QBayLogic B.V., 2022, Google Inc.BSD2 (see the file LICENSE)%QBayLogic B.V.  Trustworthy&/02356789; a -> b f = unpack . go . pack where go :: BitVector (BitSize a) -> BitVector (BitSize b) go = _ -- A function on the underlying bit vector A type should only implement this class if it has a statically known size, as otherwise it is not possible to determine how many bits are needed to represent values. This means that types such as [a] cannot have BitPack instances, as even if a has a statically known size, the length of the list cannot be known in advance.It is not possible to give data a custom bit representation by providing a BitPack instance. A BitPack instance allows no creativity and should always accurately reflect the bit representation of the data in HDL. You should always derive (6 , BitPack) unless you use a custom data representation, in which case you should use ek(. Custom encodings can be created with #Clash.Annotations.BitRepresentation and ,Clash.Annotations.BitRepresentation.Deriving.If the BitPack instance does not accurately match the bit representation of the data in HDL, Clash designs will exhibit incorrect behavior in various places.Clash provides some generic functions on packable types in the prelude, such as indexing into packable stuctures (see Clash.Class.BitPack.BitIndex/) and bitwise reduction of packable data (see  Clash.Class.BitPack.BitReduction).  clash-prelude Number of )s needed to represents elements of type aCan be derived using rs: import Clash.Prelude import GHC.Generics data MyProductType = MyProductType { a :: Int, b :: Bool } deriving (Generic, BitPack)  clash-preludeConvert element of type a to a pack (-5 :: Signed 6) 0b11_1011  clash-prelude Convert a  to an element of type apack (-5 :: Signed 6) 0b11_1011let x = pack (-5 :: Signed 6)unpack x :: Unsigned 659pack (59 :: Unsigned 6) 0b11_1011  clash-preludePack both arguments to a  and use ; to compare them. This is a more lentiant comparison than , behaving more like (but not necessarily exactly the same as)  std_match in VHDL or casez in Verilog.Unlike , isLike is not symmetric. The reason for this is that a defined bit is said to be like an undefined bit, but not vice-versa:!isLike (12 :: Signed 8) undefinedTrue!isLike undefined (12 :: Signed 8)False8However, it is still trivially reflexive and transitive::set -XTemplateHaskelllet x1 = $(bLit "0010")let x2 = $(bLit "0.10")let x3 = $(bLit "0.1.") isLike x1 x1True isLike x1 x2True isLike x2 x3True isLike x1 x3TrueNB: Not synthesizable  clash-preludeCoerce a value from one type to another through its bit representation.pack (-5 :: Signed 6) 0b11_1011(bitCoerce (-5 :: Signed 6) :: Unsigned 659pack (59 :: Unsigned 6) 0b11_1011  clash-preludeMap a value by first coercing to another type through its bit representation.pack (-5 :: Signed 32))0b1111_1111_1111_1111_1111_1111_1111_1011bitCoerceMap @(Vec 4 (BitVector 8)) (replace 1 0) (-5 :: Signed 32) -16711685pack (-16711685 :: Signed 32))0b1111_1111_0000_0000_1111_1111_1111_1011  clash-preludeZero-extend a ;ean value to a  of the appropriate size.boolToBV True :: BitVector 6 0b00_0001boolToBV False :: BitVector 6 0b00_0000  clash-preludeConvert a Bool to a Bit  clash-preludeConvert a Bit to a Bool  clash-preludeNB/: The documentation only shows instances up to 34-tuples. By default, instances up to and including 12!-tuples will exist. If the flag  large-tuples is set instances up to the GHC imposed limit will exist. The GHC imposed limit is either 62 or 64 depending on the GHC version.  clash-preludeCurrent constructor clash-prelude Data to pack clash-prelude#(Constructor number, Packed fields)  clash-preludeConstruct with constructor n clash-preludeCurrent constructor clash-preludeBitVector containing fields clash-preludeUnpacked result  ((C) 2021-2024, QBayLogic B.V.BSD2 (see the file LICENSE)%QBayLogic B.V.  Trustworthy#$&'(/02356789;<  clash-prelude#Efficient storage of memory content It holds n words of  m.  clash-prelude Convert a   back to a listNB: Not synthesizable )(C) 2013-2016, University of Twente, 2021, QBayLogic B.V.BSD2 (see the file LICENSE)%QBayLogic B.V.  Trustworthy&/02356789; Trustworthy&/02356789;:...+ @ Couldn't match type @7 + i0@ with @6@% arising from a use of @slice@) The type variable @i0@ is ambiguous6 @ In the expression: slice d6 d4 (7 :: Unsigned 6) In an equation for @it@: it = slice d6 d4 (7 :: Unsigned 6)  clash-preludeSplit a value of a bit size m + n" into a tuple of values with size m and size n.pack (7 :: Unsigned 6) 0b00_01115split (7 :: Unsigned 6) :: (BitVector 2, BitVector 4) (0b00,0b0111)  clash-prelude"Set the bit at the specified indexNB: Bit indices are  DESCENDING.pack (-5 :: Signed 6) 0b11_1011replaceBit 4 0 (-5 :: Signed 6)-21pack (-21 :: Signed 6) 0b10_1011replaceBit 5 0 (-5 :: Signed 6)27pack (27 :: Signed 6) 0b01_1011replaceBit 6 0 (-5 :: Signed 6)3*** Exception: replaceBit: 6 is out of range [0..5]...  clash-preludeSet the bits between bit index m and bit index n.NB: Bit indices are  DESCENDING.pack (-5 :: Signed 6) 0b11_1011!setSlice d4 d3 0 (-5 :: Signed 6)-29pack (-29 :: Signed 6) 0b10_0011!setSlice d6 d5 0 (-5 :: Signed 6):...+ @ Couldn't match type @7 + i0@ with @6@( arising from a use of @setSlice@) The type variable @i0@ is ambiguous; @ In the expression: setSlice d6 d5 0 (- 5 :: Signed 6) In an equation for @it@: it = setSlice d6 d5 0 (- 5 :: Signed 6)  clash-preludeGet the most significant bit.pack (-4 :: Signed 6) 0b11_1100msb (-4 :: Signed 6)1pack (4 :: Signed 6) 0b00_0100msb (4 :: Signed 6)0  clash-preludeGet the least significant bit.pack (-9 :: Signed 6) 0b11_0111lsb (-9 :: Signed 6)1pack (-8 :: Signed 6) 0b11_1000lsb (-8 :: Signed 6)0  o(C) 2013-2016, University of Twente 2016-2017, Myrtle Software Ltd 2021, QBayLogic B.V.BSD2 (see the file LICENSE)%QBayLogic B.V. Safe&/02356789;<  +(C) 2019, QBayLogicBSD2 (see the file LICENSE)-Christiaan Baaij None&/02356789;Unsafe"&/02356789:;<  clash-prelude0Arbitrary-width unsigned integer represented by n bitsGiven n bits, an   n number has a range of: [0 .. 2^n-1]NB: The usual Haskell method of converting an integral numeric type to another, 6, is not well suited for Clash as it will go through @3 which is arbitrarily bounded in HDL. Instead use   and the  class.NB: The + operators perform  wrap-around on overflow. If you want saturation on overflow, check out the  class. maxBound :: Unsigned 37minBound :: Unsigned 302read (show (maxBound :: Unsigned 3)) :: Unsigned 371 + 2 :: Unsigned 332 + 6 :: Unsigned 301 - 3 :: Unsigned 362 * 3 :: Unsigned 362 * 4 :: Unsigned 307(2 :: Unsigned 3) `mul` (4 :: Unsigned 3) :: Unsigned 687(2 :: Unsigned 3) `add` (6 :: Unsigned 3) :: Unsigned 48%satAdd SatSymmetric 2 6 :: Unsigned 37%satSub SatSymmetric 2 3 :: Unsigned 30Unsigned has the https://downloads.haskell.org/ghc/latest/docs/html/users_guide/exts/roles.html type role :i Unsignedtype role Unsigned nominal...as it is not safe to coerce between different width Unsigned. To change the width, use the functions in the  class.  clash-preludeThe constructor,  , and the field,  , are not synthesizable.  clash-preludeNB: /& can cause unexpected truncation, as @3 is arbitrarily bounded during synthesis. Prefer   and the  class.  clash-preludeNB: /& can cause unexpected truncation, as @3 is arbitrarily bounded during synthesis. Prefer   and the  class.  clash-preludeThe functions:  ,  ,  , and  , are not synthesizable.  clash-prelude None of the -" class' methods are synthesizable., , ,#(C) 2013-2016, University of TwenteBSD2 (see the file LICENSE)-Christiaan Baaij  Trustworthy&/02356789;<v  /(C) 2013-2016, University of Twente, 2016 , Myrtle Software Ltd, 2021-2024, QBayLogic B.V.BSD2 (see the file LICENSE)%QBayLogic B.V. Unsafe"&/02356789:;<  clash-prelude.Arbitrary-width signed integer represented by n bits, including the sign bitUses standard 2-complements representation. Meaning that, given n bits, a   n number has a range of: [-(2^(n -1)) .. 2^(n -1)-1] for n > 0. When n = 0#, both the min and max bound are 0.NB: The usual Haskell method of converting an integral numeric type to another, 6, is not well suited for Clash as it will go through @3 which is arbitrarily bounded in HDL. Instead use op and the  class.NB: The + operators perform  wrap-around on overflow. If you want saturation on overflow, check out the  class. maxBound :: Signed 33minBound :: Signed 3-4.read (show (minBound :: Signed 3)) :: Signed 3-41 + 2 :: Signed 332 + 3 :: Signed 3-3(-2) + (-3) :: Signed 332 * 3 :: Signed 462 * 4 :: Signed 4-81(2 :: Signed 3) `mul` (4 :: Signed 4) :: Signed 781(2 :: Signed 3) `add` (3 :: Signed 3) :: Signed 453(-2 :: Signed 3) `add` (-3 :: Signed 3) :: Signed 4-5#satAdd SatSymmetric 2 3 :: Signed 33)satAdd SatSymmetric (-2) (-3) :: Signed 3-3Signed has the https://downloads.haskell.org/ghc/latest/docs/html/users_guide/exts/roles.html type role :i Signedtype role Signed nominal...as it is not safe to coerce between different width Signed. To change the width, use the functions in the  class.  clash-preludeThe constructor,  , and the field,  , are not synthesizable.  clash-preludeNB: /& can cause unexpected truncation, as @3 is arbitrarily bounded during synthesis. Prefer op and the  class.  clash-prelude Operators do  wrap-around on overflowNB: /& can cause unexpected truncation, as @3 is arbitrarily bounded during synthesis. Prefer op and the  class.  clash-preludeThe functions:  ,  ,  , and  , are not synthesizable.  clash-prelude None of the -" class' methods are synthesizable.- - .#(C) 2013-2016, University of TwenteBSD2 (see the file LICENSE)-Christiaan Baaij  Trustworthy&/02356789;<N  0(C) 2013-2016, University of Twente, 2021, QBayLogic B.V.,BSD2 (see the file LICENSE)%QBayLogic B.V.  Trustworthy#&-/02356789;   rep int2 frac2  int1 frac1 int2 frac2 for:   int1 frac1 ->   int2 frac2  rep int1 frac1 int2 frac2 for:   int1 frac1 ->   int2 frac2  clash-preludeConvert, at compile-time, a = constant to a  -point literal. The conversion saturates on overflow, and uses truncation as its rounding method.So when you type: n = $$(  pi) ::   4 4 The compiler sees: n =   (fromInteger 50) ::   4 4 Upon evaluation you see that the value is rounded / truncated in accordance to the fixed point representation:n3.125Further examples:sin 0.5 :: Double0.479425538604203 $$(fLit (sin 0.5)) :: SFixed 1 8 0.4765625atan 0.2 :: Double0.19739555984988078!$$(fLit (atan 0.2)) :: SFixed 1 8 0.1953125"$$(fLit (atan 0.2)) :: SFixed 1 200.19739532470703125  clash-preludeConvert, at run-time, a = to a  -point.NB: This function is not synthesizableCreating data-files creatingdatafilesAn example usage of this function is to convert a data file containing =s to a data file with ASCII-encoded binary numbers to be used by a synthesizable function like N . For example, consider a file Data.txt containing: #1.2 2.0 3.0 4.0 -1.0 -2.0 -3.5 -4.04which we want to put in a ROM, interpreting them as 8.8 signed fixed point numbers. What we do is that we first create a conversion utility,  createRomFile , which uses  :createRomFile.hs: module Main where import Clash.Prelude import Clash.Prelude.ROM.File import System.Environment import qualified Data.List as L createRomFile :: BitPack a => (Double -> a) -> FilePath -> FilePath -> IO () createRomFile convert fileR fileW = do f <- readFile fileR let ds :: [Double] ds = L.concat . (L.map . L.map) read . L.map words $ lines f fes = L.map convert ds writeFile fileW (N Nothing fes) toSFixed8_8 :: Double -> SFixed 8 8 toSFixed8_8 =   main :: IO () main = do [fileR,fileW] <- getArgs createRomFile toSFixed8_8 fileR fileW &We then compile this to an executable: $ clash --make createRomFile.hs,We can then use this utility to convert our Data.txt file which contains =s to a Data.bin file which will containing the desired ASCII-encoded binary data: #$ ./createRomFile Data.txt Data.binWhich results in a Data.bin file containing: 0000000100110011 0000001000000000 0000001100000000 0000010000000000 1111111100000000 1111111000000000 1111110010000000 1111110000000000We can then use this Data.bin file in for our ROM: romF :: Unsigned 3 -> Unsigned 3 -> SFixed 8 8 romF rowAddr colAddr =   $ N) d8 "Data.bin" ((rowAddr * 4) + colAddr) "And see that it works as expected:  >>> romF 1 2 -3.5  >>> romF 0 0 1.19921875 Using Template HaskellFor those of us who like to live on the edge, another option is to convert our Data.txt at compile-time using  https://downloads.haskell.org/ghc/latest/docs/html/users_guide/exts/template_haskell.htmlTemplate Haskell%. For this we first create a module CreateRomFileTH.hs: module CreateRomFileTH (romDataFromFile) where import Clash.Prelude import Clash.Prelude.ROM.File import qualified Data.List as L import Language.Haskell.TH (ExpQ, litE, stringL) import Language.Haskell.TH.Syntax (qRunIO) createRomFile :: BitPack a => (Double -> a) -> FilePath -> FilePath -> IO () createRomFile convert fileR fileW = do f <- readFile fileR let ds :: [Double] ds = L.concat . (L.map . L.map) read . L.map words $ lines f fes = L.map convert ds writeFile fileW (N Nothing fes) romDataFromFile :: BitPack a => (Double -> a) -> String -> ExpQ romDataFromFile convert fileR = do let fileW = fileR L.++ ".bin" qRunIO (createRomFile convert fileR fileW) litE (stringL fileW) Instead of first converting Data.txt to Data.bin, we will now use the romDataFromFile function to convert Data.txt to a new file in the proper format at compile-time of our new romF' function: import Clash.Prelude import CreateRomFileTH romF' :: Unsigned 3 -> Unsigned 3 -> SFixed 8 8 romF' rowAddr colAddr = unpack $ asyncRomFile d8 $(romDataFromFile (fLitR :: Double -> SFixed 8 8) "Data.txt") -- Template Haskell splice ((rowAddr * 4) + colAddr) $And see that it works just like the romF function from earlier:  >>> romF' 1 2 -3.5  >>> romF' 0 0 1.19921875  clash-preludeFixed point division7When used in a polymorphic setting, use the following  #constraintsynonymsConstraint synonyms" for less verbose type signatures:  rep int1 frac1 int2 frac2 for:   rep int1 frac1 ->   rep int2 frac2 ->  & rep (int1 + frac2 + 1) (int2 + frac1)  rep int1 frac1 int2 frac2 for:   int1 frac1 ->   int2 frac2 ->  " (int1 + frac2 + 1) (int2 + frac1)  rep int1 frac1 int2 frac2 for:   int1 frac1 ->   int2 frac2 ->  " (int1 + frac2 + 1) (int2 + frac1)  clash-prelude None of the -" class' methods are synthesizable.  clash-prelude7When used in a polymorphic setting, use the following  )Clash-Sized-Fixed.html#constraintsynonymsConstraint synonyms# for less verbose type signatures:  rep frac1 frac2 size1 size2 for:    int1 frac1 int2 frac2 for:    int1 frac1 int2 frac2 for:   clash-preludeThese behave similar to >, = and C. / add/subtract 1. See the  https://www.haskell.org/onlinereport/haskell2010/haskellch6.html#dx13-131001HaskellReport for full details..The rules set out there for instances of both $ and ## are also observed. In particular,  and  result in a runtime error if the result cannot be represented. See  and  for other options.  clash-preludeThe operators of this instance saturate on overflow, and use truncation as the rounding method.7When used in a polymorphic setting, use the following  )Clash-Sized-Fixed.html#constraintsynonymsConstraint synonyms# for less verbose type signatures:  frac rep size for:   frac rep size  int frac for:   int frac  int frac for:   int frac  clash-preludeThe operators of this instance saturate on overflow, and use truncation as the rounding method.7When used in a polymorphic setting, use the following  )Clash-Sized-Fixed.html#constraintsynonymsConstraint synonyms# for less verbose type signatures:  frac rep size for:   frac rep size  int frac for:   int frac  int frac for:   int frac  clash-prelude3Instance functions do not saturate. Meaning that "`shiftL` 1 ==   2'"  clash-preludePosition of the virtual point clash-preludeThe   integer  clash-preludePosition of the virtual point clash-preludeThe   integer  (C) 2013-2016, University of Twente, 2016-2019, Myrtle Software Ltd, 2021-2024, QBayLogic B.V.BSD2 (see the file LICENSE)%QBayLogic B.V. Unsafe"&/02356789:; Trustworthy&/02356789;<$  clash-prelude!An alternative implementation of o for the . data type; for when you know the size of the ( and want to determine the size of the .That is, the type of o is: unpack ::  ( 2 n) ->  n ,And is useful when you know the size of the ", and want to get a value from a  that is large enough (CLog 2 n) enough to hold an  . Note that o can fail at run-time when the value inside the  is higher than 'n-1'.  on the other hand will never fail at run-time, because the  argument determines the size.  (C) 2013-2016, University of Twente, 2017 , Myrtle Software Ltd 2022-2024, QBayLogic B.V.BSD2 (see the file LICENSE)%QBayLogic B.V.  Trustworthy%&'(/02356789;<>O clash-preludeFixed size vectors.-Lists with their length encoded in their typetor elements have an  ASCENDING, subscript starting from 0 and ending at   - 1. clash-prelude, applied to a binary operator, a starting value (typically the left-identity of the operator), and a vector, reduces the vector using the binary operator, from left to right: foldl f z (x1 :> x2 :> ... :> xn :> Nil) == (...((z `f` x1) `f` x2) `f`...) `f` xn foldl f z Nil == z%foldl (/) 1 (5 :> 4 :> 3 :> 2 :> Nil)8.333333333333333e-3" f z xs." corresponds to the following circuit layout: doc/foldl.svgNB: " f z xs" produces a linear structure, which has a depth, or delay, of O(  xs). Use   if your binary operator f is associative, as "  f xs"/ produces a structure with a depth of O(log_2(  xs)). clash-prelude, applied to a binary operator, a starting value (typically the right-identity of the operator), and a vector, reduces the vector using the binary operator, from right to left: foldr f z (x1 :> ... :> xn1 :> xn :> Nil) == x1 `f` (... (xn1 `f` (xn `f` z))...) foldr r z Nil == z%foldr (/) 1 (5 :> 4 :> 3 :> 2 :> Nil)1.875" f z xs." corresponds to the following circuit layout: doc/foldr.svgNB: " f z xs" produces a linear structure, which has a depth, or delay, of O(  xs). Use   if your binary operator f is associative, as "  f xs"/ produces a structure with a depth of O(log_2(  xs)). clash-prelude" f xs%" is the vector obtained by applying f to each element of xs, i.e., map f (x1 :> x2 :> ... :> xn :> Nil) == (f x1 :> f x2 :> ... :> f xn :> Nil)0and corresponds to the following circuit layout: doc/map.svg clash-prelude Convert a  to a  of s.let x = 6 :: BitVector 8x 0b0000_0110bv2v x+0 :> 0 :> 0 :> 0 :> 0 :> 1 :> 1 :> 0 :> Nil  clash-preludeTo be used as the motive p for   , when the f in "  p f" is a variation on ( ), e.g.: map' :: forall n a b . KnownNat n => (a -> b) -> Vec n a -> Vec n b map' f =   (Proxy @(  b)) (_ x xs -> f x :> xs)  clash-prelude'Add an element to the tail of a vector.(3:>4:>5:>Nil) :< 13 :> 4 :> 5 :> 1 :> Nillet x = (3:>4:>5:>Nil) :< 1:t xx :: Num a => Vec 4 aCan be used as a pattern:let f (_ :< y :< x) = y + x:t f&f :: Num a => Vec ((n + 1) + 1) a -> af (3:>4:>5:>6:>7:>Nil)13Also in conjunctions with ( ):0let g (a :> b :> (_ :< y :< x)) = a + b + x + y:t g2g :: Num a => Vec ((((n + 1) + 1) + 1) + 1) a -> ag (1:>2:>3:>4:>5:>Nil)12  clash-prelude'Add an element to the head of a vector. 3:>4:>5:>Nil3 :> 4 :> 5 :> Nillet x = 3:>4:>5:>Nil:t xx :: Num a => Vec 3 aCan be used as a pattern:let f (x :> y :> _) = x + y:t f&f :: Num a => Vec ((n + 1) + 1) a -> af (3:>4:>5:>6:>7:>Nil)7Also in conjunctions with ( ):0let g (a :> b :> (_ :< y :< x)) = a + b + x + y:t g2g :: Num a => Vec ((((n + 1) + 1) + 1) + 1) a -> ag (1:>2:>3:>4:>5:>Nil)12  clash-preludeCreate a vector of one element singleton 55 :> Nil  clash-prelude%Extract the first element of a vectorhead (1:>2:>3:>Nil)1head Nil:...& @ Couldn't match type @1@ with @0@" Expected type: Vec (0 + 1) a Actual type: Vec 0 a3 @ In the first argument of @head@, namely @Nil@! In the expression: head Nil, In an equation for @it@: it = head Nil  clash-prelude/Extract the elements after the head of a vectortail (1:>2:>3:>Nil) 2 :> 3 :> Niltail Nil:...& @ Couldn't match type @1@ with @0@" Expected type: Vec (0 + 1) a Actual type: Vec 0 a3 @ In the first argument of @tail@, namely @Nil@! In the expression: tail Nil, In an equation for @it@: it = tail Nil  clash-prelude$Extract the last element of a vectorlast (1:>2:>3:>Nil)3last Nil:...& @ Couldn't match type @1@ with @0@" Expected type: Vec (0 + 1) a Actual type: Vec 0 a3 @ In the first argument of @last@, namely @Nil@! In the expression: last Nil, In an equation for @it@: it = last Nil  clash-prelude2:>3:>Nil) 1 :> 2 :> Nilinit Nil:...& @ Couldn't match type @1@ with @0@" Expected type: Vec (0 + 1) a Actual type: Vec 0 a3 @ In the first argument of @init@, namely @Nil@! In the expression: init Nil, In an equation for @it@: it = init Nil  clash-preludeShift in elements to the head of a vector, bumping out elements at the tail. The result is a tuple containing:The new vectorThe shifted out elements7shiftInAt0 (1 :> 2 :> 3 :> 4 :> Nil) ((-1) :> 0 :> Nil)((-1 :> 0 :> 1 :> 2 :> Nil,3 :> 4 :> Nil)(shiftInAt0 (1 :> Nil) ((-1) :> 0 :> Nil)(-1 :> Nil,0 :> 1 :> Nil)  clash-preludeShift in element to the tail of a vector, bumping out elements at the head. The result is a tuple containing:The new vectorThe shifted out elements4shiftInAtN (1 :> 2 :> 3 :> 4 :> Nil) (5 :> 6 :> Nil)'(3 :> 4 :> 5 :> 6 :> Nil,1 :> 2 :> Nil)%shiftInAtN (1 :> Nil) (2 :> 3 :> Nil)(3 :> Nil,1 :> 2 :> Nil)  clash-preludeAdd an element to the head of a vector, and extract all but the last element.1 +>> (3:>4:>5:>Nil)1 :> 3 :> 4 :> Nil 1 +>> NilNil  clash-preludeAdd an element to the tail of a vector, and extract all but the first element.(3:>4:>5:>Nil) <<+ 14 :> 5 :> 1 :> Nil Nil <<+ 1Nil  clash-preludeShift m elements out from the head of a vector, filling up the tail with * values. The result is a tuple containing:The new vectorThe shifted out valuesshiftOutFrom0 d2 ((1 :> 2 :> 3 :> 4 :> 5 :> Nil) :: Vec 5 Integer),(3 :> 4 :> 5 :> 0 :> 0 :> Nil,1 :> 2 :> Nil)  clash-preludeShift m elements out from the tail of a vector, filling up the head with * values. The result is a tuple containing:The new vectorThe shifted out valuesshiftOutFromN d2 ((1 :> 2 :> 3 :> 4 :> 5 :> Nil) :: Vec 5 Integer),(0 :> 0 :> 1 :> 2 :> 3 :> Nil,4 :> 5 :> Nil)  clash-preludeAppend two vectors.(1:>2:>3:>Nil) ++ (7:>8:>Nil)1 :> 2 :> 3 :> 7 :> 8 :> Nil  clash-prelude3Split a vector into two vectors at the given point.-splitAt (SNat :: SNat 3) (1:>2:>3:>7:>8:>Nil)"(1 :> 2 :> 3 :> Nil,7 :> 8 :> Nil)splitAt d3 (1:>2:>3:>7:>8:>Nil)"(1 :> 2 :> 3 :> Nil,7 :> 8 :> Nil)  clash-preludeSplit a vector into two vectors where the length of the two is determined by the context.7splitAtI (1:>2:>3:>7:>8:>Nil) :: (Vec 2 Int, Vec 3 Int)"(1 :> 2 :> Nil,3 :> 7 :> 8 :> Nil)  clash-prelude Concatenate a vector of vectors.concat ((1:>2:>3:>Nil) :> (4:>5:>6:>Nil) :> (7:>8:>9:>Nil) :> (10:>11:>12:>Nil) :> Nil)1 :> 2 :> 3 :> 4 :> 5 :> 6 :> 7 :> 8 :> 9 :> 10 :> 11 :> 12 :> Nil  clash-preludeMap a function over all the elements of a vector and concatentate the resulting vectors.'concatMap (replicate d3) (1:>2:>3:>Nil)01 :> 1 :> 1 :> 2 :> 2 :> 2 :> 3 :> 3 :> 3 :> Nil  clash-preludeSplit a vector of (n * m) elements into a vector of "vectors of length m", where the length m is given.8unconcat d4 (1:>2:>3:>4:>5:>6:>7:>8:>9:>10:>11:>12:>Nil)(1 :> 2 :> 3 :> 4 :> Nil) :> (5 :> 6 :> 7 :> 8 :> Nil) :> (9 :> 10 :> 11 :> 12 :> Nil) :> Nil  clash-preludeSplit a vector of (n * m)/ elements into a vector of "vectors of length m", where the length m is determined by the context.unconcatI (1:>2:>3:>4:>5:>6:>7:>8:>9:>10:>11:>12:>Nil) :: Vec 2 (Vec 6 Int)(1 :> 2 :> 3 :> 4 :> 5 :> 6 :> Nil) :> (7 :> 8 :> 9 :> 10 :> 11 :> 12 :> Nil) :> Nil  clash-prelude4Merge two vectors, alternating their elements, i.e.,9merge (1 :> 2 :> 3 :> 4 :> Nil) (5 :> 6 :> 7 :> 8 :> Nil)+1 :> 5 :> 2 :> 6 :> 3 :> 7 :> 4 :> 8 :> Nil  clash-prelude*The elements in a vector in reverse order.reverse (1:>2:>3:>4:>Nil)4 :> 3 :> 2 :> 1 :> Nil  clash-prelude 2 :> 2 :> 2 :> Nil)5imap (+) (2 :> 2 :> 2 :> 2 :> Nil) :: Vec 4 (Index 4)"imap (+) (2 :> 2 :> 2 :> 2 :> Nil)2 :> 3 :> *** Exception: X: Clash.Sized.Index: result 4 is out of bounds: [0..3]...imap (\i a -> extend (bitCoerce i) + a) (2 :> 2 :> 2 :> 2 :> Nil) :: Vec 4 (Unsigned 8)2 :> 3 :> 4 :> 5 :> Nil"  f xs." corresponds to the following circuit layout: doc/imap.svg  clash-preludeZip two vectors with a functions that also takes the elements' indices.>izipWith (\i a b -> i + a + b) (2 :> 2 :> Nil) (3 :> 3:> Nil)*** Exception: X: Clash.Sized.Index: result 3 is out of bounds: [0..1]...izipWith (\i a b -> extend (bitCoerce i) + a + b) (2 :> 2 :> Nil) (3 :> 3 :> Nil) :: Vec 2 (Unsigned 8) 5 :> 6 :> Nil"  f xs." corresponds to the following circuit layout: doc/izipWith.svgNB:   is strict in its second argument, and lazy! in its third. This matters when  % is used in a recursive setting. See   for more information.  clash-prelude;Right fold (function applied to each element and its index)let findLeftmost x xs = ifoldr (\i a b -> if a == x then Just i else b) Nothing xs)findLeftmost 3 (1:>3:>2:>4:>3:>5:>6:>Nil)Just 1)findLeftmost 8 (1:>3:>2:>4:>3:>5:>6:>Nil)Nothing"  f z xs." corresponds to the following circuit layout: doc/ifoldr.svg  clash-prelude:Left fold (function applied to each element and its index)let findRightmost x xs = ifoldl (\a i b -> if b == x then Just i else a) Nothing xs*findRightmost 3 (1:>3:>2:>4:>3:>5:>6:>Nil)Just 4*findRightmost 8 (1:>3:>2:>4:>3:>5:>6:>Nil)Nothing"  f z xs." corresponds to the following circuit layout: doc/ifoldl.svg  clash-preludeGenerate a vector of indices. indices d40 :> 1 :> 2 :> 3 :> Nil  clash-preludeGenerate a vector of indices, where the length of the vector is determined by the context.indicesI :: Vec 4 (Index 4)0 :> 1 :> 2 :> 3 :> Nil  clash-prelude"  p xs" returns the index of the first element of xs satisfying the predicate p, or J if there is no such element.*findIndex (> 3) (1:>3:>2:>4:>3:>5:>6:>Nil)Just 3*findIndex (> 8) (1:>3:>2:>4:>3:>5:>6:>Nil)Nothing  clash-prelude"  a xs" returns the index of the first element which is equal (by ) to the query element a, or J if there is no such element.&elemIndex 3 (1:>3:>2:>4:>3:>5:>6:>Nil)Just 1&elemIndex 8 (1:>3:>2:>4:>3:>5:>6:>Nil)Nothing  clash-prelude  generalizes   by zipping with the function given as the first argument, instead of a tupling function. For example, "  (+)" applied to two vectors produces the vector of corresponding sums. zipWith f (x1 :> x2 :> ... xn :> Nil) (y1 :> y2 :> ... :> yn :> Nil) == (f x1 y1 :> f x2 y2 :> ... :> f xn yn :> Nil)"  f xs ys." corresponds to the following circuit layout: doc/zipWith.svgNB:   is strict in its second argument, and lazy" in its third. This matters when  & is used in a recursive setting. See   for more information.  clash-prelude  generalizes   by zipping with the function given as the first argument, instead of a tupling function. zipWith3 f (x1 :> x2 :> ... xn :> Nil) (y1 :> y2 :> ... :> yn :> Nil) (z1 :> z2 :> ... :> zn :> Nil) == (f x1 y1 z1 :> f x2 y2 z2 :> ... :> f xn yn zn :> Nil)"   f xs ys zs." corresponds to the following circuit layout: doc/zipWith3.svgNB:   is strict in its second argument, and lazy- in its third and fourth. This matters when  & is used in a recursive setting. See   for more information.  clash-prelude  is a variant of  that has no starting value argument, and thus must be applied to non-empty vectors. foldr1 f (x1 :> ... :> xn2 :> xn1 :> xn :> Nil) == x1 `f` (... (xn2 `f` (xn1 `f` xn))...) foldr1 f (x1 :> Nil) == x1 foldr1 f Nil == TYPE ERROR)foldr1 (/) (5 :> 4 :> 3 :> 2 :> 1 :> Nil)1.875"  f xs." corresponds to the following circuit layout: doc/foldr1.svgNB: "  f z xs" produces a linear structure, which has a depth, or delay, of O(  xs). Use   if your binary operator f is associative, as "  f xs"/ produces a structure with a depth of O(log_2(  xs)).  clash-prelude  is a variant of  that has no starting value argument, and thus must be applied to non-empty vectors. foldl1 f (x1 :> x2 :> x3 :> ... :> xn :> Nil) == (...((x1 `f` x2) `f` x3) `f`...) `f` xn foldl1 f (x1 :> Nil) == x1 foldl1 f Nil == TYPE ERROR)foldl1 (/) (1 :> 5 :> 4 :> 3 :> 2 :> Nil)8.333333333333333e-3"  f xs." corresponds to the following circuit layout: doc/foldl1.svgNB: "  f z xs" produces a linear structure, which has a depth, or delay, of O(  xs). Use   if your binary operator f is associative, as "  f xs"/ produces a structure with a depth of O(log_2(  xs)).  clash-prelude  is a variant of   and  , but instead of reducing from right to left, or left to right, it reduces a vector using a tree-like structure. The depth, or delay, of the structure produced by "  f xs ", is hence O(log_2(  xs)) , and not O(  xs).NB: The binary operator "f" in "  f xs" must be associative. fold f (x1 :> x2 :> ... :> xn1 :> xn :> Nil) == ((x1 `f` x2) `f` ...) `f` (... `f` (xn1 `f` xn)) fold f (x1 :> Nil) == x1 fold f Nil == TYPE ERROR'fold (+) (5 :> 4 :> 3 :> 2 :> 1 :> Nil)15"  f xs." corresponds to the following circuit layout: doc/fold.svg  clash-prelude  is similar to , but returns a vector of successive reduced values from the left: scanl f z (x1 :> x2 :> ... :> Nil) == z :> (z `f` x1) :> ((z `f` x1) `f` x2) :> ... :> Nil%scanl (+) 0 (5 :> 4 :> 3 :> 2 :> Nil)0 :> 5 :> 9 :> 12 :> 14 :> Nil"  f z xs." corresponds to the following circuit layout: doc/scanl.svgNB: #last (scanl f z xs) == foldl f z xsFor a different trade-off between circuit size and logic depth for associative operators, see Clash.Sized.RTree#scans  clash-prelude  with no seed value$scanl1 (-) (1 :> 2 :> 3 :> 4 :> Nil)1 :> -1 :> -4 :> -8 :> Nil  clash-prelude  with no seed value$scanr1 (-) (1 :> 2 :> 3 :> 4 :> Nil)-2 :> 3 :> -1 :> 4 :> Nil  clash-prelude  is a variant of  # where the first result is dropped: postscanl f z (x1 :> x2 :> ... :> Nil) == (z `f` x1) :> ((z `f` x1) `f` x2) :> ... :> Nil)postscanl (+) 0 (5 :> 4 :> 3 :> 2 :> Nil)5 :> 9 :> 12 :> 14 :> Nil"  f z xs." corresponds to the following circuit layout: doc/sscanl.svg  clash-prelude  is similar to , but returns a vector of successive reduced values from the right: scanr f z (... :> xn1 :> xn :> Nil) == ... :> (xn1 `f` (xn `f` z)) :> (xn `f` z) :> z :> Nil%scanr (+) 0 (5 :> 4 :> 3 :> 2 :> Nil)14 :> 9 :> 5 :> 2 :> 0 :> Nil"  f z xs." corresponds to the following circuit layout: doc/scanr.svgNB: #head (scanr f z xs) == foldr f z xsFor a different trade-off between circuit size and logic depth for associative operators, see Clash.Sized.RTree#scans  clash-prelude  is a variant of  ' that where the last result is dropped: postscanr f z (... :> xn1 :> xn :> Nil) == ... :> (xn1 `f` (xn `f` z)) :> (xn `f` z) :> Nil)postscanr (+) 0 (5 :> 4 :> 3 :> 2 :> Nil)14 :> 9 :> 5 :> 2 :> Nil"  f z xs." corresponds to the following circuit layout: doc/sscanr.svg  clash-preludeThe  ( function behaves like a combination of  and ; it applies a function to each element of a vector, passing an accumulating parameter from left to right, and returning a final value of this accumulator together with the new vector.mapAccumL (\acc x -> (acc + x,acc + 1)) 0 (1 :> 2 :> 3 :> 4 :> Nil)(10,1 :> 2 :> 4 :> 7 :> Nil)"  f acc xs." corresponds to the following circuit layout: doc/mapAccumL.svg  clash-preludeThe  ( function behaves like a combination of  and ; it applies a function to each element of a vector, passing an accumulating parameter from right to left, and returning a final value of this accumulator together with the new vector.mapAccumR (\acc x -> (acc + x,acc + 1)) 0 (1 :> 2 :> 3 :> 4 :> Nil)(10,10 :> 8 :> 5 :> 1 :> Nil)"  f acc xs." corresponds to the following circuit layout: doc/mapAccumR.svg  clash-prelude ? takes two vectors and returns a vector of corresponding pairs.'zip (1:>2:>3:>4:>Nil) (4:>3:>2:>1:>Nil)'(1,4) :> (2,3) :> (3,2) :> (4,1) :> Nil  clash-prelude  takes three vectors and returns a vector of corresponding triplets.:zip3 (1:>2:>3:>4:>Nil) (4:>3:>2:>1:>Nil) (5:>6:>7:>8:>Nil)/(1,4,5) :> (2,3,6) :> (3,2,7) :> (4,1,8) :> Nil  clash-prelude  takes four vectors and returns a list of quadruples, analogous to  .  clash-prelude  takes five vectors and returns a list of five-tuples, analogous to  .  clash-prelude  takes six vectors and returns a list of six-tuples, analogous to  .  clash-prelude  takes seven vectors and returns a list of seven-tuples, analogous to  .  clash-prelude  transforms a vector of pairs into a vector of first components and a vector of second components.'unzip ((1,4):>(2,3):>(3,2):>(4,1):>Nil)1(1 :> 2 :> 3 :> 4 :> Nil,4 :> 3 :> 2 :> 1 :> Nil)  clash-prelude  transforms a vector of triplets into a vector of first components, a vector of second components, and a vector of third components.0unzip3 ((1,4,5):>(2,3,6):>(3,2,7):>(4,1,8):>Nil)(1 :> 2 :> 3 :> 4 :> Nil,4 :> 3 :> 2 :> 1 :> Nil,5 :> 6 :> 7 :> 8 :> Nil)  clash-prelude  takes a vector of quadruples and returns four vectors, analogous to  .  clash-prelude  takes a vector of five-tuples and returns five vectors, analogous to  .  clash-prelude  takes a vector of six-tuples and returns six vectors, analogous to  .  clash-prelude  takes a vector of seven-tuples and returns seven vectors, analogous to  .  clash-prelude"xs   n" returns the n'th element of xs.NB: Vector elements have an  ASCENDING* subscript starting from 0 and ending at   - 1.(1:>2:>3:>4:>5:>Nil) !! 459(1:>2:>3:>4:>5:>Nil) !! (length (1:>2:>3:>4:>5:>Nil) - 1)5(1:>2:>3:>4:>5:>Nil) !! 12(1:>2:>3:>4:>5:>Nil) !! 14*** Exception: Clash.Sized.Vector.(!!): index 14 is larger than maximum index 4...  clash-preludeThe length of a  tor as an ? value.length (6 :> 7 :> 8 :> Nil)3  clash-prelude"  n a xs" returns the vector xs where the n'th element is replaced by a.NB: Vector elements have an  ASCENDING* subscript starting from 0 and ending at   - 1. replace 3 7 (1:>2:>3:>4:>5:>Nil)1 :> 2 :> 3 :> 7 :> 5 :> Nil replace 0 7 (1:>2:>3:>4:>5:>Nil)7 :> 2 :> 3 :> 4 :> 5 :> Nil replace 9 7 (1:>2:>3:>4:>5:>Nil)1 :> 2 :> 3 :> 4 :> 5 :> *** Exception: Clash.Sized.Vector.replace: index 9 is larger than maximum index 4...  clash-prelude"  n xs" returns the n-length prefix of xs.*take (SNat :: SNat 3) (1:>2:>3:>4:>5:>Nil)1 :> 2 :> 3 :> Nil*take d3 (1:>2:>3:>4:>5:>Nil)1 :> 2 :> 3 :> Nil!take d0 (1:>2:>Nil)Nil!take d4 (1:>2:>Nil) :...+ @ Couldn't match type @4 + n0@ with @2@# Expected type: Vec (4 + n0) a" Actual type: Vec (1 + 1) a) The type variable @n0@ is ambiguous @ In the second argument of @take@, namely @(1 :> 2 :> Nil)@0 In the expression: take d4 (1 :> 2 :> Nil); In an equation for @it@: it = take d4 (1 :> 2 :> Nil)  clash-prelude"  xs" returns the prefix of xs as demanded by the context.'takeI (1:>2:>3:>4:>5:>Nil) :: Vec 2 Int 1 :> 2 :> Nil  clash-prelude"  n xs" returns the suffix of xs after the first n elements.*drop (SNat :: SNat 3) (1:>2:>3:>4:>5:>Nil) 4 :> 5 :> Nil*drop d3 (1:>2:>3:>4:>5:>Nil) 4 :> 5 :> Nil!drop d0 (1:>2:>Nil) 1 :> 2 :> Nil!drop d4 (1:>2:>Nil):...: error:...& @ Couldn't match...type @4 + n0...) The type variable @n0@ is ambiguous3 @ In the first argument of @print@, namely @it@8 In a stmt of an interactive GHCi command: print it  clash-prelude"  xs" returns the suffix of xs as demanded by the context.'dropI (1:>2:>3:>4:>5:>Nil) :: Vec 2 Int 4 :> 5 :> Nil  clash-prelude"  n xs " returns n'th element of xsNB: Vector elements have an  ASCENDING* subscript starting from 0 and ending at   - 1.(at (SNat :: SNat 1) (1:>2:>3:>4:>5:>Nil)2(at d1 (1:>2:>3:>4:>5:>Nil)2  clash-prelude"  f s n xs " selects n elements with step-size s and offset f from xs.select (SNat :: SNat 1) (SNat :: SNat 2) (SNat :: SNat 3) (1:>2:>3:>4:>5:>6:>7:>8:>Nil)2 :> 4 :> 6 :> Nil-select d1 d2 d3 (1:>2:>3:>4:>5:>6:>7:>8:>Nil)2 :> 4 :> 6 :> Nil  clash-prelude"  f s xs" selects as many elements as demanded by the context with step-size s and offset f from xs.8selectI d1 d2 (1:>2:>3:>4:>5:>6:>7:>8:>Nil) :: Vec 2 Int 2 :> 4 :> Nil  clash-prelude"  n a" returns a vector that has n copies of a.replicate (SNat :: SNat 3) 66 :> 6 :> 6 :> Nilreplicate d3 66 :> 6 :> 6 :> Nil  clash-prelude"  a*" creates a vector with as many copies of a as demanded by the context.repeat 6 :: Vec 5 Int6 :> 6 :> 6 :> 6 :> 6 :> Nil  clash-prelude"  n f x!" returns a vector starting with x followed by n repeated applications of f to x. iterate (SNat :: SNat 4) f x == (x :> f x :> f (f x) :> f (f (f x)) :> Nil) iterate d4 f x == (x :> f x :> f (f x) :> f (f (f x)) :> Nil)iterate d4 (+1) 11 :> 2 :> 3 :> 4 :> Nil"  n f z." corresponds to the following circuit layout: doc/iterate.svg  clash-prelude"  f x!" returns a vector starting with x followed by n repeated applications of f to x, where n is determined by the context. 7iterateI f x :: Vec 3 a == (x :> f x :> f (f x) :> Nil)iterateI (+1) 1 :: Vec 3 Int1 :> 2 :> 3 :> Nil"  f z." corresponds to the following circuit layout: doc/iterate.svg  clash-prelude"  n f s" builds a vector of length n from a seed value s, where every element a# is created by successive calls of f on s . Unlike  from  Data.List the generating function f cannot dictate the length of the resulting vector, it must be statically known.a simple use of  :unfoldr d10 (\s -> (s,s-1)) 10610 :> 9 :> 8 :> 7 :> 6 :> 5 :> 4 :> 3 :> 2 :> 1 :> Nil  clash-prelude"  f s$" builds a vector from a seed value s, where every element a# is created by successive calls of f on s; the length of the vector is inferred from the context. Unlike  from  Data.List the generating function f cannot dictate the length of the resulting vector, it must be statically known.a simple use of  :)unfoldrI (\s -> (s,s-1)) 10 :: Vec 10 Int610 :> 9 :> 8 :> 7 :> 6 :> 5 :> 4 :> 3 :> 2 :> 1 :> Nil  clash-prelude"  n f x" returns a vector with n repeated applications of f to x. generate (SNat :: SNat 4) f x == (f x :> f (f x) :> f (f (f x)) :> f (f (f (f x))) :> Nil) generate d4 f x == (f x :> f (f x) :> f (f (f x)) :> f (f (f (f x))) :> Nil)generate d4 (+1) 12 :> 3 :> 4 :> 5 :> Nil"  n f z." corresponds to the following circuit layout: doc/generate.svg  clash-prelude"  f x" returns a vector with n repeated applications of f to x, where n is determined by the context. generateI f x :: Vec 3 a == (f x :> f (f x) :> f (f (f x)) :> Nil)generateI (+1) 1 :: Vec 3 Int2 :> 3 :> 4 :> Nil"  f z." corresponds to the following circuit layout: doc/generate.svg  clash-prelude5Transpose a matrix: go from row-major to column-major4let xss = (1:>2:>Nil):>(3:>4:>Nil):>(5:>6:>Nil):>Nilxss<(1 :> 2 :> Nil) :> (3 :> 4 :> Nil) :> (5 :> 6 :> Nil) :> Nil transpose xss3(1 :> 3 :> 5 :> Nil) :> (2 :> 4 :> 6 :> Nil) :> Nil  clash-prelude"1-dimensional stencil computations"  stX f xs ", where xs has stX + n, elements, applies the stencil computation f on: n + 1$ overlapping (1D) windows of length stX, drawn from xs. The resulting vector has n + 1 elements. let xs = (1:>2:>3:>4:>5:>6:>Nil):t xsxs :: Num a => Vec 6 a:t stencil1d d2 sum xs'stencil1d d2 sum xs :: Num b => Vec 5 bstencil1d d2 sum xs3 :> 5 :> 7 :> 9 :> 11 :> Nil  clash-prelude"2-dimensional stencil computations"   stY stX f xss ", where xss is a matrix of stY + m rows of stX + n+ elements, applies the stencil computation f on: (m + 1) * (n + 1) overlapping (2D) windows of stY rows of stX elements, drawn from xss. The result matrix has m + 1 rows of n + 1 elements.let xss = ((1:>2:>3:>4:>Nil):>(5:>6:>7:>8:>Nil):>(9:>10:>11:>12:>Nil):>(13:>14:>15:>16:>Nil):>Nil):t xssxss :: Num a => Vec 4 (Vec 4 a)&:t stencil2d d2 d2 (sum . map sum) xss?stencil2d d2 d2 (sum . map sum) xss :: Num b => Vec 3 (Vec 3 b)#stencil2d d2 d2 (sum . map sum) xss(14 :> 18 :> 22 :> Nil) :> (30 :> 34 :> 38 :> Nil) :> (46 :> 50 :> 54 :> Nil) :> Nil  clash-prelude"  stX xs", where the vector xs has stX + n elements, returns a vector of n + 1 overlapping (1D) windows of xs of length stX. let xs = (1:>2:>3:>4:>5:>6:>Nil):t xsxs :: Num a => Vec 6 a:t windows1d d2 xs+windows1d d2 xs :: Num a => Vec 5 (Vec 2 a)windows1d d2 xs(1 :> 2 :> Nil) :> (2 :> 3 :> Nil) :> (3 :> 4 :> Nil) :> (4 :> 5 :> Nil) :> (5 :> 6 :> Nil) :> Nil  clash-prelude"   stY stX xss", where matrix xss has stY + m rows of stX + n, returns a matrix of m+1 rows of n+1 elements. The elements of this new matrix are the overlapping (2D) windows of xss, where every window has stY rows of stX elements.let xss = ((1:>2:>3:>4:>Nil):>(5:>6:>7:>8:>Nil):>(9:>10:>11:>12:>Nil):>(13:>14:>15:>16:>Nil):>Nil):t xssxss :: Num a => Vec 4 (Vec 4 a):t windows2d d2 d2 xss?windows2d d2 d2 xss :: Num a => Vec 3 (Vec 3 (Vec 2 (Vec 2 a)))windows2d d2 d2 xss(((1 :> 2 :> Nil) :> (5 :> 6 :> Nil) :> Nil) :> ((2 :> 3 :> Nil) :> (6 :> 7 :> Nil) :> Nil) :> ((3 :> 4 :> Nil) :> (7 :> 8 :> Nil) :> Nil) :> Nil) :> (((5 :> 6 :> Nil) :> (9 :> 10 :> Nil) :> Nil) :> ((6 :> 7 :> Nil) :> (10 :> 11 :> Nil) :> Nil) :> ((7 :> 8 :> Nil) :> (11 :> 12 :> Nil) :> Nil) :> Nil) :> (((9 :> 10 :> Nil) :> (13 :> 14 :> Nil) :> Nil) :> ((10 :> 11 :> Nil) :> (14 :> 15 :> Nil) :> Nil) :> ((11 :> 12 :> Nil) :> (15 :> 16 :> Nil) :> Nil) :> Nil) :> Nil  clash-prelude3Forward permutation specified by an index mapping, ix;. The result vector is initialized by the given defaults, def, and an further values that are permuted into the result are added to the current value using the given combination function, f.!The combination function must be  associative and  commutative.  clash-prelude5Backwards permutation specified by an index mapping, is, from the destination vector specifying which element of the source vector xs to read."  xs is" is equivalent to " (xs  ) is". For example:*let input = 1:>9:>6:>4:>4:>2:>0:>1:>2:>Nil!let from = 1:>3:>7:>2:>5:>3:>Nilbackpermute input from!9 :> 4 :> 1 :> 6 :> 2 :> 4 :> Nil  clash-prelude&Copy elements from the source vector, xs;, to the destination vector according to an index mapping is/. This is a forward permute operation where a to vector encodes an input to output index mapping. Output elements for indices that are not mapped assume the value in the default vector def. For example:+let defVec = 0:>0:>0:>0:>0:>0:>0:>0:>0:>Nillet to = 1:>3:>7:>2:>5:>8:>Nil$let input = 1:>9:>6:>4:>4:>2:>5:>Nilscatter defVec to input00 :> 1 :> 4 :> 9 :> 0 :> 4 :> 0 :> 6 :> 2 :> NilNB: If the same index appears in the index mapping more than once, the latest mapping is chosen.  clash-prelude5Backwards permutation specified by an index mapping, is, from the destination vector specifying which element of the source vector xs to read."  xs is" is equivalent to " (xs  ) is". For example:*let input = 1:>9:>6:>4:>4:>2:>0:>1:>2:>Nil!let from = 1:>3:>7:>2:>5:>3:>Nilgather input from!9 :> 4 :> 1 :> 6 :> 2 :> 4 :> Nil  clash-prelude"  d xs" creates a vector: 9let xs = 1 :> 2 :> 3 :> 4 :> 5 :> 6 :> 7 :> 8 :> 9 :> Nilinterleave d3 xs01 :> 4 :> 7 :> 2 :> 5 :> 8 :> 3 :> 6 :> 9 :> Nil  clash-prelude Dynamically rotate a tor to the left: let xs = 1 :> 2 :> 3 :> 4 :> NilrotateLeft xs 12 :> 3 :> 4 :> 1 :> NilrotateLeft xs 23 :> 4 :> 1 :> 2 :> NilrotateLeft xs (-1)4 :> 1 :> 2 :> 3 :> NilNB: Use  ! if you want to rotate left by a static amount.  clash-prelude Dynamically rotate a tor to the right: let xs = 1 :> 2 :> 3 :> 4 :> NilrotateRight xs 14 :> 1 :> 2 :> 3 :> NilrotateRight xs 23 :> 4 :> 1 :> 2 :> NilrotateRight xs (-1)2 :> 3 :> 4 :> 1 :> NilNB: Use  " if you want to rotate right by a static amount.  clash-prelude Statically rotate a tor to the left: let xs = 1 :> 2 :> 3 :> 4 :> NilrotateLeftS xs d12 :> 3 :> 4 :> 1 :> NilNB: Use  ! if you want to rotate left by a dynamic amount.  clash-prelude Statically rotate a tor to the right: let xs = 1 :> 2 :> 3 :> 4 :> NilrotateRightS xs d14 :> 1 :> 2 :> 3 :> NilNB: Use  " if you want to rotate right by a dynamic amount.  clash-preludeConvert a vector to a list.toList (1:>2:>3:>Nil)[1,2,3]NB$: This function is not synthesizable  clash-preludeConvert a list to a vector. This function returns Nothing if the size of the list is not equal to the size of the resulting vector.-Vec.fromList [1,2,3,4,5] :: Maybe (Vec 5 Int)#Just (1 :> 2 :> 3 :> 4 :> 5 :> Nil)-Vec.fromList [1,2,3,4,5] :: Maybe (Vec 3 Int)Nothing.Vec.fromList [1,2,3,4,5] :: Maybe (Vec 10 Int)NothingNB: Use   if you want to make a statically known vectorNB$: This function is not synthesizable  clash-preludeConvert a list to a vector. This function always returns a vector of the desired length, by either truncating the list or padding the vector with undefined elements.+Vec.unsafeFromList [1,2,3,4,5] :: Vec 5 Int1 :> 2 :> 3 :> 4 :> 5 :> Nil+Vec.unsafeFromList [1,2,3,4,5] :: Vec 3 Int1 :> 2 :> 3 :> Nil,Vec.unsafeFromList [1,2,3,4,5] :: Vec 10 Int1 :> 2 :> 3 :> 4 :> 5 :> *** Exception: Clash.Sized.Vector.unsafeFromList: vector larger than list...NB: Use   if you want to make a statically known vectorNB$: This function is not synthesizable  clash-prelude,Create a vector literal from a list literal. $(listToVecTH [1::Signed 8,2,3,4,5]) == (8:>2:>3:>4:>5:>Nil) :: Vec 5 (Signed 8)[1 :: Signed 8,2,3,4,5] [1,2,3,4,5]$$(listToVecTH [1::Signed 8,2,3,4,5])1 :> 2 :> 3 :> 4 :> 5 :> Nil  clash-prelude tor as a  for   clash-prelude Length of a  tor as an  value  clash-preludeWhat you should use when your vector functions are too strict in their arguments.doctests setup5let compareSwapL a b = if a < b then (a,b) else (b,a):{let sortVL :: (Ord a, KnownNat (n + 1)) => Vec ((n + 1) + 1) a -> Vec ((n + 1) + 1) a5 sortVL xs = map fst sorted :< (snd (last sorted)) where1 lefts = head xs :> map snd (init sorted) rights = tail xs: sorted = zipWith compareSwapL (lazyV lefts) rights:}:{9let sortV_flip xs = map fst sorted :< (snd (last sorted)) where1 lefts = head xs :> map snd (init sorted) rights = tail xs9 sorted = zipWith (flip compareSwapL) rights lefts:} Example usage For example: *-- Bubble sort for 1 iteration sortV xs =  fst sorted   (snd (  sorted)) where lefts =   xs :>  snd (  sorted) rights =   xs sorted =   compareSwapL lefts rights -- Compare and swap compareSwapL a b = if a < b then (a,b) else (b,a) Will not terminate because  & is too strict in its second argument.In this case, adding   on  s second argument:  sortVL xs =  fst sorted   (snd (  sorted)) where lefts =   xs :> map snd (  sorted) rights =   xs sorted =   compareSwapL (  lefts) rights $Results in a successful computation: sortVL (4 :> 1 :> 2 :> 3 :> Nil)1 :> 2 :> 3 :> 4 :> NilNB!: There is also a solution using 6, but it slightly obfuscates the meaning of the code: sortV_flip xs =  fst sorted   (snd (  sorted)) where lefts =   xs :>  snd (  sorted) rights =   xs sorted =   ( compareSwapL) rights lefts $sortV_flip (4 :> 1 :> 2 :> 3 :> Nil)1 :> 2 :> 3 :> 4 :> Nil  clash-preludeA  dependently typed fold.doctests setup%:seti -fplugin GHC.TypeLits.Normalise1import Data.Singletons (Apply, Proxy (..), TyFun)data Append (m :: Nat) (a :: Type) (f :: TyFun Nat Type) :: Type2type instance Apply (Append m a) l = Vec (l + m) alet append' xs ys = dfold (Proxy :: Proxy (Append m a)) (const (:>)) ys xs Example usageUsing lists, we can define append (a.k.a.  Data.List.) in terms of  Data.List.:import qualified Data.List,let append xs ys = Data.List.foldr (:) ys xsappend [1,2] [3,4] [1,2,3,4](However, when we try to do the same for , by defining append' in terms of Clash.Sized.Vector.: append' xs ys =  (:>) ys xs we get a type error: (>>> let append' xs ys = foldr (:>) ys xs :... @ Occurs check: cannot construct the infinite type: ... ~ ... + 1 Expected type: a -> Vec ... a -> Vec ... a Actual type: a -> Vec ... a -> Vec (... + 1) a @ In the first argument of @foldr@, namely @(:>)@ In the expression: foldr (:>) ys xs In an equation for @append'@: append' xs ys = foldr (:>) ys xs @ Relevant bindings include ys :: Vec ... a (bound at ...) append' :: Vec n a -> Vec ... a -> Vec ... a (bound at ...) The reason is that the type of  is::t foldr+foldr :: (a -> b -> b) -> b -> Vec n a -> bWhile the type of ( ) is::t (:>)%(:>) :: a -> Vec n a -> Vec (n + 1) aWe thus need a fold4 function that can handle the growing vector type:  . Compared to ,  ' takes an extra parameter, called the motive, that allows the folded function to have an argument and result type that depends, on the current length of the vector. Using  , we can now correctly define append': import Data.Singletons import Data.Proxy data Append (m :: Nat) (a :: Type) (f :: ! Nat Type) :: Type type instance  (Append m a) l =  (l + m) a append' xs ys =  ' (Proxy :: Proxy (Append m a)) (const (  )) ys xs We now see that append' has the appropriate type: :t append' Vec k a -> Vec m a -> Vec (k + m) aAnd that it works:'append' (1 :> 2 :> Nil) (3 :> 4 :> Nil)1 :> 2 :> 3 :> 4 :> NilNB: "  m f z xs" creates a linear structure, which has a depth, or delay, of O(  xs ). Look at   for a  dependently? typed fold that produces a structure with a depth of O(log_2(  xs)).  clash-preludeA combination of   and  : a  dependently; typed fold that reduces a vector in a tree-like structure.doctests setup:seti -XUndecidableInstances1import Data.Singletons (Apply, Proxy (..), TyFun))data IIndex (f :: TyFun Nat Type) :: Type.type instance Apply IIndex l = Index ((2^l)+1):{let populationCount' :: (KnownNat k, KnownNat (2^k)) => BitVector (2^k) -> Index ((2^k)+1)0 populationCount' bv = dtfold (Proxy @IIndex)- fromIntegral4 (\_ x y -> add x y)* (bv2v bv):} Example usage,As an example of when you might want to use   we will build a population counter: a circuit that counts the number of bits set to '1' in a . Given a vector of n bits, we only need we need a data type that can represent the number n:  (n+1).  k has a range of  [0 .. k-1] (using  ceil(log2(k)) bits), hence we need  n+1$. As an initial attempt we will use r, because it gives a nice (log2(n)) tree-structure of adders: populationCount :: (KnownNat (n+1), KnownNat (n+2)) =>  (n+1) -> 2 (n+2) populationCount = sum . map fromIntegral .  The "problem" with this description is that all adders have the same bit-width, i.e. all adders are of the type: (+) ::  (n+2) ->  (n+2) ->  (n+2). This is a "problem" because we could have a more efficient structure: one where each layer of adders is  precisely wide enough to count the number of bits at that layer. That is, at height d! we want the adder to be of type:  ((2^d)+1) ->  ((2^d)+1) ->  ((2^(d+1))+1) )We have such an adder in the form of the  & function, as defined in the instance   instance of  . However, we cannot simply use   to create a tree-structure of  es::{8let populationCount' :: (KnownNat (n+1), KnownNat (n+2))6 => BitVector (n+1) -> Index (n+2)9 populationCount' = fold add . map fromIntegral . bv2v:}:... @ Couldn't match type @((n + 2) + (n + 2)) - 1@ with @n + 2@ Expected type: Index (n + 2) -> Index (n + 2) -> Index (n + 2)" Actual type: Index (n + 2) -> Index (n + 2) -> AResult (Index (n + 2)) (Index (n + 2))3 @ In the first argument of @fold@, namely @add@7 In the first argument of @(.)@, namely @fold add@; In the expression: fold add . map fromIntegral . bv2v @ Relevant bindings include> populationCount' :: BitVector (n + 1) -> Index (n + 2) (bound at ...)because   expects a function of type " a -> a -> a", i.e. a function where the arguments and result all have exactly the same type.(In order to accommodate the type of our  , where the result is larger than the arguments, we must use a dependently typed fold in the form of  : {-# LANGUAGE UndecidableInstances #-} import Data.Singletons import Data.Proxy data IIndex (f :: ! Nat Type) :: Type type instance  IIndex l =  ((2^l)+1) populationCount' :: (KnownNat k, KnownNat (2^k)) => BitVector (2^k) -> Index ((2^k)+1) populationCount' bv =   (Proxy @IIndex) fromIntegral (\_ x y ->  $ x y) ( bv) And we can test that it works:':t populationCount' (7 :: BitVector 16)0populationCount' (7 :: BitVector 16) :: Index 17$populationCount' (7 :: BitVector 16)3Some final remarks: By using   instead of  , we had to restrict our 5 argument to have bit-width that is a power of 2.Even though our original populationCount function specified a structure where all adders had the same width. Most VHDL/(System)Verilog synthesis tools will create a more efficient circuit, i.e. one where the adders have an increasing bit-width for every layer, from the VHDL/(System)Verilog produced by the Clash compiler.NB5: The depth, or delay, of the structure produced by "  m f g xs " is O(log_2(  xs)).  clash-preludeSpecialised version of  3 that builds a triangular computational structure.doctests setup4let compareSwap a b = if a > b then (a,b) else (b,a)let insert y xs = let (y',xs') = mapAccumL compareSwap y xs in xs' :< y'(let insertionSort = vfold (const insert) Example usage compareSwap a b = if a > b then (a,b) else (b,a) insert y xs = let (y',xs') =   compareSwap y xs in xs'   y' insertionSort =   (const insert) Builds a triangular structure of compare and swaps to sort a row.'insertionSort (7 :> 3 :> 9 :> 1 :> Nil)1 :> 3 :> 7 :> 9 :> NilThe circuit layout of  insertionSort, build using  , is: doc/csSort.svg  clash-prelude)The largest element of a non-empty vector  clash-prelude'The least element of a non-empty vector  clash-preludeApply a function to every element of a vector and the element's position (as an  value) in the vector.+let rotateMatrix = smap (flip rotateRightS)=let xss = (1:>2:>3:>Nil):>(1:>2:>3:>Nil):>(1:>2:>3:>Nil):>Nilxss(1 :> 2 :> 3 :> Nil) :> (1 :> 2 :> 3 :> Nil) :> (1 :> 2 :> 3 :> Nil) :> NilrotateMatrix xss(1 :> 2 :> 3 :> Nil) :> (3 :> 1 :> 2 :> Nil) :> (2 :> 3 :> 1 :> Nil) :> Nil  clash-prelude Convert a  of s to a .2let x = (0:>0:>0:>1:>0:>0:>1:>0:>Nil) :: Vec 8 Bitx+0 :> 0 :> 0 :> 1 :> 0 :> 0 :> 1 :> 0 :> Nilv2bv x 0b0001_0010  clash-preludeEvaluate all elements of a vector to WHNF, returning the second argument  clash-prelude)Evaluate all elements of a vector to WHNF  clash-preludeEvaluate all elements of a vector to WHNF, returning the second argument. Does not propagate s.  clash-prelude?Evaluate all elements of a vector to WHNF. Does not propagate s.  clash-preludeIn many cases, this Generic instance only allows generic functions/instances over vectors of at least size 1, due to the n-1 in the  Rep (Vec n a) definition.$We'll have to wait for things like  https://ryanglscott.github.io/2018/02/11/how-to-derive-generic-for-some-gadts/+ before we can work around this limitation  clash-preludeThe old vector clash-prelude$The elements to shift in at the head clash-prelude&(The new vector, shifted out elements)  clash-preludeThe old vector clash-prelude$The elements to shift in at the tail clash-prelude&(The new vector, shifted out elements)  clash-preludem%, the number of elements to shift out clash-preludeThe old vector clash-prelude&(The new vector, shifted out elements)  clash-preludem%, the number of elements to shift out clash-preludeThe old vector clash-prelude&(The new vector, shifted out elements)  clash-preludeWindows length stX, at least size 1 clash-preludeThe stencil (function)  clash-prelude Window hight stY, at least size 1 clash-prelude Window width stX, at least size 1 clash-preludeThe stencil (function)  clash-prelude%Length of the window, at least size 1  clash-prelude Window hight stY, at least size 1 clash-prelude Window width stX, at least size 1  clash-preludeCombination function, f clash-preludeDefault values, def clash-preludeIndex mapping, is clash-preludeVector to be permuted, xs  clash-preludeSource vector, xs clash-preludeIndex mapping, is  clash-preludeDefault values, def clash-preludeIndex mapping, is clash-preludeVector to be scattered, xs  clash-preludeSource vector, xs clash-preludeIndex mapping, is  clash-preludeInterleave step, d  clash-preludeThe motive clash-preludeFunction to fold.NB: The SNat l is not the index (see ( )) to the element a. SNat l7 is the number of elements that occur to the right of a. clash-preludeInitial element clash-preludeVector to fold over  clash-preludeThe motive clash-prelude"Function to apply to every element clash-preludeFunction to combine results.NB: The SNat l indicates the depth/height of the node in the tree that is created by applying this function. The leafs of the tree have depth/height 0&, and the root of the tree has height k. clash-preludeVector to fold over.NB*: Must have a length that is a power of 2.       5 5 5 4 4 5 0 0 Safe-Inferred&/02356789;<߷1(C) 2024, Google LLCBSD2 (see the file LICENSE)%QBayLogic B.V. None&/02356789;<>  clash-prelude#Given a vector with three elements:)myVec = (1 :> 2 :> 3 :> Nil) :: Vec 3 IntThe following would produce a warning even though we can be sure no other pattern can ever apply:(a :> b :> c :> Nil) = myVec ( can be used to work around the warning:(a, b, c) = vecToTuple myVecOf course, you will still get an error if you try to match a vector of the wrong length:(a, b, c, d) = vecToTuple myVec...* @ Couldn't match type: (Int, Int, Int) ^' with: (a, b, c, d)...  clash-preludeNB/: The documentation only shows instances up to 34-tuples. By default, instances up to and including 12!-tuples will exist. If the flag  large-tuples is set instances up to the GHC imposed limit will exist. The GHC imposed limit is either 62 or 64 depending on the GHC version.  2(C) 2019, Google Inc., 2022, QBayLogic B.V.BSD2 (see the file LICENSE)%QBayLogic B.V. None&'(/02356789; Int -> SimIO Int tbMachine (fileIn,fileOut) regOut = do eofFileOut <-   fileOut eofFileIn <-  2 fileIn when (eofFileIn || eofFileOut) $ do   "success"   0 goldenIn <-   fileIn goldenOut <-   fileOut res <- if regOut == fromEnum goldenOut then do return (fromEnum goldenIn) else do  1 "Output doesn't match golden output"   1 display ("Output matches golden output") return res tbInit :: (File,File) tbInit = do fileIn <-  ( "./goldenInput00.txt" "r" fileOut <-   "./goldenOutput00.txt" "r" return (fileIn,fileOut) topEntity :: Signal System Int topEntity = regOut where clk = systemClockGen rst = resetGen ena = enableGen regOut = register clk rst ena (fromEnum 'a') regIn regIn =   clk tbMachine tbInit regOut  clash-preludeString you want to display  clash-prelude=The exit code you want to return at the end of the simulation  clash-preludeThe starting value  clash-preludeThe mutable reference clash-prelude The new value  clash-prelude File to open clash-prelude File mode:"r": Open for reading"w": Create for writing "a": Append+"r+": Open for update (reading and writing)"w+": Create for update6"a+": Append, open or create for update at end-of-file  clash-preludeFile to read from  clash-preludeCharacter to insert clash-preludeBuffer to insert to  clash-preludeFile to read from clash-preludeVector to store the content  clash-preludeFile we want to inspect  clash-preludeFile to set the position for clash-preludePosition clash-preludeMode:!0: From the beginning of the file1: From the current position2: From the end of the file  clash-preludeFile we want to inspect  clash-prelude2Clock at which rate the I/O environment progresses clash-prelude-Transition function inside an I/O environment clash-prelude&I/O action to create the initial state  3(C) 2015-2016, University of Twente, 2017 , Google Inc. 2019 , Myrtle Software Ltd, 2021-2022, QBayLogic B.V.BSD2 (see the file LICENSE)%QBayLogic B.V.  Trustworthy&'(/02356789;<  clash-prelude5A ROM with a synchronous read port, with space for 2^n elementsNB": Read value is delayed by 1 cycleNB: Initial output value is  undefined, reading it will throw an  See also:See #Clash.Sized.Fixed#creatingdatafiles and !Clash.Explicit.BlockRam#usingrams( for ideas on how to use ROMs and RAMs.A large  for the content may be too inefficient, depending on how it is constructed. See > and C+ for different approaches that scale well.  clash-prelude3A ROM with a synchronous read port, with space for n elementsNB": Read value is delayed by 1 cycleNB: Initial output value is  undefined, reading it will throw an  See also:See #Clash.Sized.Fixed#creatingdatafiles and !Clash.Explicit.BlockRam#usingrams( for ideas on how to use ROMs and RAMs.A large  for the content may be too inefficient, depending on how it is constructed. See > and C* for different approaches that scale well.  clash-prelude ROM primitive  clash-prelude to synchronize to clash-prelude line clash-prelude ROM contentNB: MUST be a constant clash-prelude Read address r clash-prelude The value of the ROM at address r from the previous clock cycle  clash-prelude to synchronize to clash-prelude line clash-prelude'ROM content, also determines the size, n , of the ROMNB: MUST be a constant clash-prelude Read address r clash-prelude The value of the ROM at address r from the previous clock cycle  clash-prelude to synchronize to clash-prelude line clash-prelude'ROM content, also determines the size, n , of the ROMNB: MUST be a constant clash-prelude Read address rd clash-prelude The value of the ROM at address rd from the previous clock cycle  4(C) 2019, Myrtle Software LtdBSD2 (see the file LICENSE)-Christiaan Baaij None#&-./02356789;<>  clash-prelude1Type class that specifies that a certain domain, dom+, needs to be present in some other type, r. This is used to disambiguate what hidden clock, reset, and enable lines should be exposed in functions such as .+Functions in need of this class should use   though, to force Clash to display an error instead of letting it silently pass.  clash-preludeHelper function for HasSpecificDomain class (I don't really understand why this one is necessary. HasDomainWrapper _should_ check for stuckness and does so according to tests..  clash-prelude.Wrapper that checks for stuckness and returns  'NotFound if so  clash-preludeType family that searches a type and checks whether a specific domain is present. Will result in either "domain not found, and no others either", "domain not found, but found another", or "found domain".  clash-prelude"Check domain for equality. Return 'Found if so, return  'NotFound if not. The reason d'etre for this type family is that _open_ type families don't allow overlapping types. We therefore defer equality checking to a closed type family.  clash-prelude Merge two  +s according to the semantics of 'HasDomain.  clash-preludeNo domain found  clash-prelude0Found the specific domain caller was looking for  clash-preludeType that forces dom to be present in r at least once. Will resolve to a type error if it doesn't. It will always fail if given dom1 is completely polymorphic and can't be tied to r in any way.  6(C) 2018, Google Inc., 2021-2023, QBayLogic B.V.BSD2 (see the file LICENSE)%QBayLogic B.V. None&./02356789:;<  clash-preludeSynthesis attributes are directives passed to synthesis tools, such as Quartus. An example of such an attribute in VHDL: attribute chip_pin : string; attribute chip_pin of sel : signal is "C4"; attribute chip_pin of data : signal is "D1, D2, D3, D4";7This would instruct the synthesis tool to map the wire sel to pin C4 , and wire data to pins D1, D2, D3, and D4. To achieve this in Clash, Attr/s are used. An example of the same annotation: import Clash.Annotations.SynthesisAttributes (Attr (..), Annotate ) myFunc :: (Signal System Bool `Annotate` 'StringAttr "chip_pin" "C4") -> (Signal System Int4 `Annotate` 'StringAttr "chip_pin" "D1, D2, D3, D4") -> ... myFunc sel data = ... {-# NOINLINE myFunc #-} To ensure this function will be rendered as its own module, do not forget a NOINLINE pragma.Multiple attributes for the same9 argument can be specified by using a list. For example: Signal System Bool `Annotate` [ 'StringAttr "chip_pin" "C4" , 'BoolAttr "direct_enable" 'True , 'IntegerAttr "max_depth" 512 , 'Attr "keep" ] For Verilog see: https://www.intel.com/content/www/us/en/programmable/quartushelp/current/index.htm#hdl/vlog/vlog_file_dir.htmFor VHDL, see: https://www.intel.com/content/www/us/en/programmable/quartushelp/current/index.htm#hdl/vhdl/vhdl_file_dir.htmWarningsWhen using annotations, it is important that annotated arguments are not eta-reduced, as this may result in the annotation being stripped by GHC. For example f :: Signal System Bool `Annotate` 'StringAttr "chip_pin" "C4" -> Signal System Bool f x = id x -- Using a lambda, i.e. f = \x -> id x also works ;will reliably show the annotation in the generated HDL, but g :: Signal System Bool `Annotate` 'StringAttr "chip_pin" "C4" -> Signal System Bool g = id will not work.This is an experimental feature, please report any unexpected or broken behavior to Clash's GitHub page ( 3https://github.com/clash-lang/clash-compiler/issues).Use   if you wish to annotate an intermediate signal. Its use is preferred over type level annotations.  clash-prelude:Attribute which argument is rendered as a bool. Example: https://www.intel.com/content/www/us/en/programmable/quartushelp/current/index.htm#hdl/vlog/vlog_file_dir_direct_enable.htm  clash-prelude=Attribute which argument is rendered as a integer. Example: https://www.intel.com/content/www/us/en/programmable/quartushelp/current/index.htm#hdl/vlog/vlog_file_dir_max_depth.htm  clash-prelude Trustworthy!&'(/02356789;<4  clash-preludePerfect depth binary tree.)Only has elements at the leaf of the treeA tree of depth d has 2^d elements.  clash-preludeRBranch of a perfect depth treeBR (LR 1) (LR 2)<1,2>let x = BR (LR 1) (LR 2):t xx :: Num a => RTree 1 aCase be used a pattern:%let f (BR (LR a) (LR b)) = LR (a + b):t f$f :: Num a => RTree 1 a -> RTree 0 af (BR (LR 1) (LR 2))3  clash-preludeRLeaf of a perfect depth treeLR 11 let x = LR 1:t xx :: Num a => RTree 0 aCan be used as a pattern:let f (LR a) (LR b) = a + b:t f)f :: Num a => RTree 0 a -> RTree 0 a -> af (LR 1) (LR 2)3  clash-preludeA  dependently typed fold over trees.,As an example of when you might want to use   we will build a population counter: a circuit that counts the number of bits set to '1' in a . Given a vector of n bits, we only need we need a data type that can represent the number n:  (n+1).  k has a range of  [0 .. k-1] (using  ceil(log2(k)) bits), hence we need  n+1$. As an initial attempt we will use  , because it gives a nice (log2(n)) tree-structure of adders: populationCount :: (KnownNat (2^d), KnownNat d, KnownNat (2^d+1)) => BitVector (2^d) -> Index (2^d+1) populationCount = tfold (resize . bv2i . pack) (+) . v2t . bv2v The "problem" with this description is that all adders have the same bit-width, i.e. all adders are of the type: (+) ::  (2^d+1) ->  (2^d+1) ->  (2^d+1). This is a "problem" because we could have a more efficient structure: one where each layer of adders is  precisely wide enough to count the number of bits at that layer. That is, at height d! we want the adder to be of type:  ((2^d)+1) ->  ((2^d)+1) ->  ((2^(d+1))+1) )We have such an adder in the form of the  & function, as defined in the instance   instance of  . However, we cannot simply use  to create a tree-structure of  s::{let populationCount' :: (KnownNat (2^d), KnownNat d, KnownNat (2^d+1))8 => BitVector (2^d) -> Index (2^d+1) populationCount' = tfold (resize . bv2i . pack) add . v2t . bv2v:}:...? @ Couldn't match type @(((2 ^ d) + 1) + ((2 ^ d) + 1)) - 1@' with @(2 ^ d) + 1@( Expected type: Index ((2 ^ d) + 1) -> Index ((2 ^ d) + 1) -> Index ((2 ^ d) + 1)( Actual type: Index ((2 ^ d) + 1)+ -> Index ((2 ^ d) + 1) -> AResult (Index ((2 ^ d) + 1)) (Index ((2 ^ d) + 1))5 @ In the second argument of @tfold@, namely @add@, In the first argument of @(.)@, namely* @tfold (resize . bv2i . pack) add@ In the expression: tfold (resize . bv2i . pack) add . v2t . bv2v @ Relevant bindings include populationCount' :: BitVector (2 ^ d) -> Index ((2 ^ d) + 1) (bound at ...)because   expects a function of type " b -> b -> b", i.e. a function where the arguments and result all have exactly the same type.(In order to accommodate the type of our  , where the result is larger than the arguments, we must use a dependently typed fold in the form of  : {-# LANGUAGE UndecidableInstances #-} import Data.Singletons data IIndex (f :: ! Nat Type) :: Type type instance  IIndex l =  ((2^l)+1) populationCount' :: (KnownNat k, KnownNat (2^k)) => BitVector (2^k) -> Index ((2^k)+1) populationCount' bv =   (Proxy @IIndex) (resize . bv2i . pack) (\_ x y ->  $ x y) (  ( bv)) And we can test that it works:':t populationCount' (7 :: BitVector 16)0populationCount' (7 :: BitVector 16) :: Index 17$populationCount' (7 :: BitVector 16)3  clash-prelude!Reduce a tree to a single element  clash-prelude"  d a" returns a tree of depth d , and has 2^d copies of a.treplicate (SNat :: SNat 3) 6<<<6,6>,<6,6>>,<<6,6>,<6,6>>>treplicate d3 6<<<6,6>,<6,6>>,<<6,6>,<6,6>>>  clash-prelude"  a(" creates a tree with as many copies of a as demanded by the context.trepeat 6 :: RTree 2 Int <<6,6>,<6,6>>  clash-prelude"  f t " is the tree obtained by apply f to each element of t, i.e., 5tmap f (BR (LR a) (LR b)) == BR (LR (f a)) (LR (f b))  clash-preludeGenerate a tree of indices, where the depth of the tree is determined by the context.tindices :: RTree 3 (Index 8)<<<0,1>,<2,3>>,<<4,5>,<6,7>>>  clash-preludeConvert a vector with 2^d elements to a tree of depth d.v2t (1 :> 2 :> 3 :> 4:> Nil) <<1,2>,<3,4>>  clash-preludeConvert a tree of depth d to a vector of 2^d elements*(BR (BR (LR 1) (LR 2)) (BR (LR 3) (LR 4))) <<1,2>,<3,4>>.t2v (BR (BR (LR 1) (LR 2)) (BR (LR 3) (LR 4)))1 :> 2 :> 3 :> 4 :> Nil  clash-prelude"  t n" returns the n'th element of t.The bottom-left leaf had index 0', and the bottom-right leaf has index 2^d-1, where d is the depth of the tree6indexTree (BR (BR (LR 1) (LR 2)) (BR (LR 3) (LR 4))) 016indexTree (BR (BR (LR 1) (LR 2)) (BR (LR 3) (LR 4))) 237indexTree (BR (BR (LR 1) (LR 2)) (BR (LR 3) (LR 4))) 14*** Exception: Clash.Sized.Vector.(!!): index 14 is larger than maximum index 3...  clash-prelude"  n a t" returns the tree t where the n'th element is replaced by a.The bottom-left leaf had index 0', and the bottom-right leaf has index 2^d-1, where d is the depth of the tree:replaceTree 0 5 (BR (BR (LR 1) (LR 2)) (BR (LR 3) (LR 4))) <<5,2>,<3,4>>:replaceTree 2 7 (BR (BR (LR 1) (LR 2)) (BR (LR 3) (LR 4))) <<1,2>,<7,4>>:replaceTree 9 6 (BR (BR (LR 1) (LR 2)) (BR (LR 3) (LR 4)))<<1,2>,<3,*** Exception: Clash.Sized.Vector.replace: index 9 is larger than maximum index 3...  clash-prelude  generalizes   by zipping with the function given as the first argument, instead of a tupling function. For example, "tzipWith (+)" applied to two trees produces the tree of corresponding sums. tzipWith f (BR (LR a1) (LR b1)) (BR (LR a2) (LR b2)) == BR (LR (f a1 a2)) (LR (f b1 b2))  clash-prelude ; takes two trees and returns a tree of corresponding pairs.  clash-prelude  transforms a tree of pairs into a tree of first components and a tree of second components.  clash-preludeGiven a function f that is strict in its nth  % argument, make it lazy by applying   to this argument: "f x0 x1 .. (lazyT xn) .. xn_plus_k  clash-prelude#Extract the first element of a tree8The first element is defined to be the bottom-left leaf.0thead $ BR (BR (LR 1) (LR 2)) (BR (LR 3) (LR 4))1  clash-prelude"Extract the last element of a tree8The last element is defined to be the bottom-right leaf.0tlast $ BR (BR (LR 1) (LR 2)) (BR (LR 3) (LR 4))4  clash-prelude  applied to &scanlPar (+) (1 :> 2 :> 3 :> 4 :> Nil)1 :> 3 :> 6 :> 10 :> Nil  clash-prelude  applied to &scanrPar (+) (1 :> 2 :> 3 :> 4 :> Nil)10 :> 9 :> 7 :> 4 :> Nil  clash-preludeLow-depth left scan  is similar to , but returns a tree of successive reduced values from the left: tscanl f [x1, x2, x3, ...] == [x1, x1 `f` x2, x1 `f` x2 `f` x3, ...]*tscanl (+) (v2t (1 :> 2 :> 3 :> 4 :> Nil))<<1,3>,<6,10>> doc/scanlPar.svg  clash-preludeLow-depth right scan  is similar to , but returns a tree of successive reduced values from the left: tscanr f [..., xn2, xn1, xn] == [..., xn2 `f` xn1 `f` xn, xn1 `f` xn, xn]*tscanr (+) (v2t (1 :> 2 :> 3 :> 4 :> Nil))<<10,9>,<7,4>>  clash-preludeThe motive clash-prelude.Function to apply to the elements on the leafs clash-prelude#Function to fold the branches with.NB: SNat l& is the depth of the two sub-branches. clash-preludeTree to fold over.  clash-preludeFunction to apply to the leaves clash-preludeFunction to combine the results of the reduction of two branches clash-preludeTree to fold reduce  clash-preludeMust be associative  clash-preludeMust be associative  clash-preludeMust be associative  8(C) 2013-2016, University of Twente, 2017-2019, Myrtle Software Ltd, Google Inc. 2019,2022, QBayLogic B.V.BSD2 (see the file LICENSE)%QBayLogic B.V.  Trustworthy&/02356789;<A  clash-preludeIsomorphism between a m9 of a product type (e.g. a tuple) and a product type of ms. Instances of  ! must satisfy the following laws:   .   = X   .   = X  By default,   and  1, are defined as the identity, that is, writing: "data D = A | B instance Bundle D is the same as: /data D = A | B instance Bundle D where type   clk D =  clk D   s = s   s = s For custom product types you'll have to write the instance manually: data Pair a b = MkPair { getA :: a, getB :: b } instance Bundle (Pair a b) where type Unbundled dom (Pair a b) = Pair (Signal dom a) (Signal dom b) -- bundle :: Pair (Signal dom a) (Signal dom b) -> Signal dom (Pair a b) bundle (MkPair as bs) = MkPair  as   bs -- unbundle :: Signal dom (Pair a b) -> Pair (Signal dom a) (Signal dom b) unbundle pairs = MkPair (getA  pairs) (getB  pairs)  clash-preludeExample: bundle :: ( dom a,  dom b) ->  dom (a,b) However: bundle ::  dom  ->  dom   clash-preludeExample: unbundle ::  dom (a,b) -> ( dom a,  dom b) However: unbundle ::  dom  ->  dom   clash-preludeHelper type to emulate the "old" behavior of Bundle's unit instance. I.e., the instance for  Bundle () used to be defined as: class Bundle () where bundle :: () -> Signal dom () unbundle :: Signal dom () -> () .In order to have sensible type inference, the  , class specifies that the argument type of  ? should uniquely identify the result type, and vice versa for  =. The type signatures in the snippet above don't though, as ()= doesn't uniquely map to a specific domain. In other words, domain should occur in both the argument and result of both functions.7 tackles this by carrying the domain in its type. The   and   instance now looks like: class Bundle EmptyTuple where bundle :: TaggedEmptyTuple dom -> Signal dom EmptyTuple unbundle :: Signal dom EmptyTuple -> TaggedEmptyTuple dom dom8 is now mentioned both the argument and result for both   and  . clash-preludeSee  clash-preludeNB/: The documentation only shows instances up to 34-tuples. By default, instances up to and including 12!-tuples will exist. If the flag  large-tuples is set instances up to the GHC imposed limit will exist. The GHC imposed limit is either 62 or 64 depending on the GHC version. clash-preludeSee  https://github.com/clash-lang/clash-compiler/pull/539/commits/94b0bff5770aa4961e04ddce2515130df3fc7863commit 94b0bff5 and documentation for .  9(C) 2015-2016, University of Twente, 2017 , Google Inc., 2019 , Myrtle Software Ltd, 2021-2022, QBayLogic B.V.BSD2 (see the file LICENSE)%QBayLogic B.V. Unsafe&'(/02356789;<T clash-prelude$Create a block RAM with space for 2^n elementsNB": Read value is delayed by 1 cycleNB: Initial output value is  undefined, reading it will throw an NB: This function might not work for specific combinations of code-generation backends and hardware targets. Please check the support table below:VHDLVerilog SystemVerilogAltera/QuartusBrokenWorksWorks Xilinx/ISEWorksWorksWorksASICUntestedUntestedUntested See also:See  Clash.Prelude.BlockRam#usingrams1 for more information on how to use a block RAM.Use the adapter D6 for obtaining write-before-read semantics like this: D2 clk rst en (blockRamFilePow2' clk en file) rd wrM.See *Clash.Explicit.BlockRam.File#usingramfiles for more information on how to instantiate a block RAM with the contents of a data file.See % for creating a data file with Clash.See &Clash.Explicit.Fixed#creatingdatafiles6 for more ideas on how to create your own data files. clash-prelude"Create a block RAM with space for n elementsNB": Read value is delayed by 1 cycleNB: Initial output value is  undefined, reading it will throw an NB: This function might not work for specific combinations of code-generation backends and hardware targets. Please check the support table below:VHDLVerilog SystemVerilogAltera/QuartusBrokenWorksWorks Xilinx/ISEWorksWorksWorksASICUntestedUntestedUntested See also:See !Clash.Explicit.BlockRam#usingrams1 for more information on how to use a block RAM.Use the adapter D6 for obtaining write-before-read semantics like this: D clk rst en ( clk en size file) rd wrM.See *Clash.Explicit.BlockRam.File#usingramfiles for more information on how to instantiate a block RAM with the contents of a data file.See % for creating a data file with Clash.See #Clash.Sized.Fixed#creatingdatafiles6 for more ideas on how to create your own data files. clash-preludeConvert data to the R contents of a memory file.NB: Not synthesizableThe following document the several ways to instantiate components with files:)Clash.Prelude.BlockRam.File#usingramfiles$Clash.Prelude.ROM.File#usingromfiles*Clash.Explicit.BlockRam.File#usingramfiles%Clash.Explicit.ROM.File#usingromfilesSee #Clash.Sized.Fixed#creatingdatafiles6 for more ideas on how to create your own data files.ExampleThe Maybe datatype has don't care bits, where the actual value does not matter. But the bits need a defined value in the memory. Either 0 or 1 can be used, and both are valid representations of the data.3let es = [ Nothing, Just (7 :: Unsigned 8), Just 8]!mapM_ (putStrLn . show . pack) es 0b0_...._.... 0b1_0000_0111 0b1_0000_1000putStr (memFile (Just 0) es) 000000000 100000111 100001000putStr (memFile (Just 1) es) 011111111 100000111 100001000 clash-preludeblockRamFile primitive clash-preludeNB: Not synthesizable clash-prelude to synchronize to clash-prelude line clash-prelude/File describing the initial content of the BRAM clash-prelude Read address r clash-prelude(write address w, value to write) clash-preludeValue of the BRAM at address r from the previous clock cycle clash-prelude to synchronize to clash-prelude line clash-preludeSize of the BRAM clash-prelude/File describing the initial content of the BRAM clash-prelude Read address r clash-prelude(write address w, value to write) clash-preludeValue of the BRAM at address r from the previous clock cycle clash-prelude!Value to map don't care bits to. J- means throwing an error on don't care bits. clash-preludeValues to convert clash-preludeContents of the memory file  clash-prelude to synchronize to clash-prelude line clash-preludeSize of the BRAM clash-prelude/File describing the initial content of the BRAM clash-prelude Read address r clash-prelude Write enable clash-preludeWrite address w clash-preludeValue to write (at address w) clash-preludeValue of the BRAM at address r from the previous clock cycle:(C) 2023, QBayLogic B.V.BSD2 (see the file LICENSE)%QBayLogic B.V. None#$&'(/02356789;<_`  clash-prelude*Determine whether a write enable is active clash-prelude%Merge global enable with write enable clash-prelude$Update memory with a defined address clash-preludeHelper used in  clash-prelude Read/Write conflict for output A clash-prelude Read/Write conflict for output B clash-preludeWrite/Write conflict clash-preludeDetermines whether there was a write-write or read-write conflict. A conflict occurs when two ports tried to (potentially, in case of undefined values) access the same address and one or both tried to write to it. See documentation of  for more information. clash-preludeStep through a cycle of a TDP block RAM where only one clock is active. Like , it accounts for 6 in all values supplied by the user of the block RAM. clash-preludeStep through a cycle of a TDP block RAM where the clock edges of port A and port B coincided. Like , it accounts for 6 in all values supplied by the user of the block RAM. clash-preludeAccess a RAM and account for undefined values in the address, write enable, and data to write. Return read after write value. clash-preludeHaskell model for a true dual-port block RAM which is polymorphic in its write enables clash-prelude%Port A: enable, write enable, address clash-prelude%Port B: enable, write enable, address clash-preludeK5 if there is a (potential) write conflict, otherwise J clash-preludePrevious value clash-preludeMemory clash-prelude/Port: enable, address, write enable, write data clash-preludeUpdated memory, output value clash-preludePrevious value for port A clash-preludePrevious value for port B clash-preludeMemory clash-prelude1Port A: enable, address, write enable, write data clash-prelude1Port B: enable, address, write enable, write data clash-prelude.Updated memory, output value A, output value B clash-prelude*Determine whether a write enable is active clash-prelude$Update memory with a defined address clash-preludeAddress clash-prelude Byte enable clash-prelude Data to write clash-preludeMemory to write to clash-prelude$(Read after write value, new memory) clash-preludeEnable clash-preludeAddress clash-prelude Write enable clash-prelude Write data clash-preludeEnable clash-preludeAddress  clash-preludeWrite byte enable  clash-prelude Write data;(C) 2019, Myrtle Software Ltd 2022, QBayLogic B.V.BSD2 (see the file LICENSE)%QBayLogic B.V. None!&-./02356789;<>cS clash-preludeType family that searches a type and checks whether all subtypes that can contain a domain (for example, Signal) contain the same domain. Its associated type, GetDomain, will yield a type error if that doesn't hold OR if it can't check it. clash-preludeSame as Merge', but will insert a type error if Merge' got stuck. clash-prelude.Type family to resolve type conflicts (if any) clash-preludeType that forces dom# to be the same in all subtypes of r that might contain a domain. If given a polymorphic domain not tied to r, GHC will be allowed to infer that that domain is equal to the one in r on the condition that r contains just a single domain.5None&/02356789;<c    <(C) 2017, Google Inc. 2019, Myrtle Software Ltd 2022-2024, QBayLogic B.V.BSD2 (see the file LICENSE)%QBayLogic B.V. None$&'(/02356789;<>?m clash-preludeThe out part of an inout portWraps (multiple) writing signals. The semantics are such that only one of the signals may write at a single time step.BiSignalOut has the https://downloads.haskell.org/ghc/latest/docs/html/users_guide/exts/roles.html type role:i BiSignalOut-type role BiSignalOut nominal nominal nominal...as it is not safe to coerce the default behaviour, synthesis domain or width of the data in the signal. clash-preludeThe in part of an inout port. BiSignalIn has the https://downloads.haskell.org/ghc/latest/docs/html/users_guide/exts/roles.html type role :i BiSignalIn,type role BiSignalIn nominal nominal nominal...as it is not safe to coerce the default behaviour, synthesis domain or width of the data in the signal. clash-preludeType class for : can be used as a constraint and for obtaining the pull-up mode clash-preludeSingleton versions of  clash-preludeUsed to specify the default behavior of a "BiSignal" in Haskell simulation, i.e. what value is read when no value is being written to it. clash-preludeinout3 port behaves as if connected to a pull-up resistor clash-preludeinout5 port behaves as if connected to a pull-down resistor clash-preludeinout port behaves as if is floating . Reading a floating "BiSignal" value in simulation will yield an errorX (undefined value). clash-preludeRead the value from an inout port clash-preludeCombine several inout signals into one. clash-prelude Write to an inout port clash-prelude Converts the out part of a BiSignal to an in part. In simulation it checks whether multiple components are writing and will error accordingly. Make sure this is only called ONCE for every BiSignal. clash-prelude(Monoid instance to support concatenatingNB: Not synthesizable clash-preludeNB: Not synthesizable clash-preludeA + with a number of bits needed to represent a clash-preludeValue to writeJust a writes an a valueNothing puts the port in a high-impedance state(C) 2013-2016, University of Twente, 2016-2019, Myrtle Software, 2017-2022, Google Inc. 2020 , Ben Gamari, 2021-2023, QBayLogic B.V.BSD2 (see the file LICENSE)%QBayLogic B.V.  Trustworthy &'(/02356789;<> clash-preludeClock generator for the  clock domain.NB*: Should only be used for simulation, and not for the  testBench function. For the  testBench function, used  clash-prelude/Reset generator for use in simulation, for the 5 clock domain. Asserts the reset for a single cycle.NB : While this can be used in the  testBench1 function, it cannot be synthesized to hardware.Example topEntity :: Vec 2 (Vec 3 (Unsigned 8)) -> Vec 6 (Unsigned 8) topEntity = concat testBench :: Signal System Bool testBench = done where testInput = pure ((1 :> 2 :> 3 :> Nil) :> (4 :> 5 :> 6 :> Nil) :> Nil) expectedOutput = outputVerifier' ((1:>2:>3:>4:>5:>6:>Nil):>Nil) done = exposeClockResetEnable (expectedOutput (topEntity <$> testInput)) clk rst clk = tbSystemClockGen (not <$> done) rst =   clash-preludeThe  function is a primitive that must be used to connect one clock domain to the other, and will be synthesized to a (bundle of) wire(s) in the eventual circuit. This function should only be used as part of a proper synchronization component, such as the following dual flip-flop synchronizer: dualFlipFlop :: Clock domA -> Clock domB -> Enable domA -> Enable domB -> Bit -> Signal domA Bit -> Signal domB Bit dualFlipFlop clkA clkB enA enB dflt =  clkB enB dflt .  clkB enB dflt .  clkA clkB The * works in such a way that, given 2 clocks: 7createDomain vSystem{vName="Dom7", vPeriod=7} clk7 ::  Dom7 clk7 =  en7 ::  Dom7 en7 =  and 7createDomain vSystem{vName="Dom2", vPeriod=2} clk2 ::  Dom2 clk2 =  en2 ::  Dom2 en2 =  Oversampling followed by compression is the identity function plus 2 initial values:  clkB enB dflt $  clkA clkB $  clkA enA dflt $  clkB clkA $ # clkB enB s == dflt :- dflt :- s  Something we can easily observe: (oversampling clkA clkB enA enB dflt =  clkB enB dflt .  clkA clkB . 3 clkA enA dflt almostId clkA clkB enA enB dflt =  clkB enB dflt .  clkA clkB .  clkA enA dflt .  clkB clkA .  clkB enB dflt sampleN 37 (oversampling clk7 clk2 en7 en2 0 (fromList [(1::Int)..10]))[0,0,1,1,1,2,2,2,2,3,3,3,4,4,4,4,5,5,5,6,6,6,6,7,7,7,8,8,8,8,9,9,9,10,10,10,10]sampleN 12 (almostId clk2 clk7 en2 en7 0 (fromList [(1::Int)..10]))[0,0,1,2,3,4,5,6,7,8,9,10] clash-preludeSame as +, but with manually supplied clock periods.Note: this unsafeSynchronizer is defined to be consistent with the vhdl and verilog implementations however as only synchronous signals are represented in Clash this cannot be done precisely and can lead to odd behavior. For example, sample $ unsafeSynchronizer @Dom2 @Dom7 . unsafeSynchronizer @Dom7 @Dom2 $ fromList [0..10] > [0,4,4,4,7,7,7,7,11,11,11.. %is quite different from the identity, 6sample $ fromList [0..10] > [0,1,2,3,4,5,6,7,8,9,10.. (with values appearing from the "future". clash-preludeMerge enable signal with signal of bools by applying the boolean AND operation. clash-preludeSpecial version of  that doesn't take enable signals of any kind. Initial value will be undefined. clash-prelude" clk s" delays the values in  s) for once cycle, the value at time 0 is dflt.sampleN 3 (delay systemClockGen enableGen 0 (fromList [1,2,3,4]))[0,1,2] clash-prelude Version of 0 that only updates when its third argument is a K value.let input = fromList [Just 1, Just 2, Nothing, Nothing, Just 5, Just 6, Just (7::Int)]7sampleN 7 (delayMaybe systemClockGen enableGen 0 input)[0,1,2,2,2,5,6] clash-prelude Version of 7 that only updates when its third argument is asserted.)let input = fromList [1,2,3,4,5,6,7::Int] that only updates its content when its fourth argument is a K value. So given: &sometimes1 clk rst en = s where s =  clk rst en Nothing (switch  s) switch Nothing = Just 1 switch _ = Nothing countSometimes clk rst en = s where s =  clk rst en 0 (plusM (! ; s) (sometimes1 clk rst en)) plusM = liftA2 (liftA2 (+)) We get:8sampleN 9 (sometimes1 systemClockGen resetGen enableGen)[Nothing,Nothing,Just 1,Nothing,Just 1,Nothing,Just 1,Nothing,Just 1]3sampleN 9 (count systemClockGen resetGen enableGen)[0,0,0,1,1,2,2,3,3] clash-prelude Version of  that only updates its content when its fourth argument is asserted. So given: oscillate clk rst en = let s =  clk rst en False (not <$> s) in s count clk rst en = let s = 'regEn clk rst en 0 (oscillate clk rst en) (s + 1) in s We get:7sampleN 9 (oscillate systemClockGen resetGen enableGen)3[False,False,True,False,True,False,True,False,True]3sampleN 9 (count systemClockGen resetGen enableGen)[0,0,0,1,1,2,2,3,3] clash-preludeSame as ', but with the reset line asserted for n cycles. Similar to ,  will drop the output values produced while the reset is asserted. While the reset is asserted, the first value from [a] is fed to the circuit. clash-preludeSame as , but only sample the first Int output values. clash-prelude Simulate a (  a ->   b,) function given a list of samples of type asimulateB (unbundle . register systemClockGen resetGen enableGen (8,8) . bundle) [(1,1), (1,1), (2,2), (3,3)] :: [(Int,Int)]![(8,8),(8,8),(1,1),(2,2),(3,3)......NB$: This function is not synthesizable clash-preludeLazily simulate a (  a ->   b,) function given a list of samples of type asimulateB (unbundle . register systemClockGen resetGen enableGen (8,8) . bundle) [(1,1), (1,1), (2,2), (3,3)] :: [(Int,Int)]![(8,8),(8,8),(1,1),(2,2),(3,3)......NB$: This function is not synthesizable clash-preludeLike 4, but resets on reset and has a defined reset value.let rst = unsafeFromActiveHigh (fromList [True, True, False, False, True, False])let res = fromListWithReset @System rst Nothing [Just 'a', Just 'b', Just 'c'] sampleN 6 res4[Nothing,Nothing,Just 'a',Just 'b',Nothing,Just 'a']NB$: This function is not synthesizable clash-preludeGet a list of samples from a &, while asserting the reset line for n clock cycles.  does not return the first n+ cycles, i.e., when the reset is asserted.NB$: This function is not synthesizable clash-preludeGet a fine list of m samples from a &, while asserting the reset line for n clock cycles.  does not return the first n, cycles, i.e., while the reset is asserted.NB$: This function is not synthesizable clash-prelude1Simulate a component until it matches a conditionIt prints a message of the form )Signal sampled for N cycles until value XNB$: This function is not synthesizableExample with test bench+A common usage is with a test bench using .NB: Since this uses , when using clashi, read the note at &Clash.Explicit.Testbench#assert-clashi. import Clash.Prelude import Clash.Explicit.Testbench topEntity ::   Int ->  $ Int topEntity = id testBench ::  , Bool testBench = done where testInput =  clk rst $( * [1 :: Int .. 10]) expectedOutput =  clk rst $(  $ [1 :: Int .. 9] = [42]) done = expectedOutput $ topEntity testInput clk =  (not <$> done) rst =   > runUntil id testBench cycle(): 10, outputVerifier expected value: 42, not equal to actual value: 10 Signal sampled for 11 cycles until value True When you need to verify multiple test benches, the following invocations come in handy: > p* (runUntil id) [ testBenchA, testBenchB ] 8or when the test benches are in different clock domains: >testBenchA :: Signal DomA Bool testBenchB :: Signal DomB Bool > o4 [ runUntil id testBenchA, runUntil id testBenchB ]  clash-prelude of the incoming signal clash-prelude of the outgoing signal clash-preludePeriod of clock belonging to dom1. M if clock has a static period, N if periods are dynamic. clash-preludePeriod of clock belonging to dom2. M if clock has a static period, N if periods are dynamic. clash-preludeClock clash-prelude Global enable clash-prelude Initial value clash-preludeClock clash-prelude Global enable clash-prelude Initial value clash-preludeClock clash-prelude Global enable clash-prelude Initial value clash-preludeEnable clash-preludeclock clash-preludeReset, 1 outputs the reset value when the reset is active clash-prelude Global enable clash-preludeReset value. If the domain has initial values enabled, the reset value will also be the initial value. clash-preludeClock clash-preludeReset, 7 outputs the reset value when the reset value is active clash-prelude Global enable clash-preludeReset value. If the domain has initial values enabled, the reset value will also be the initial value. clash-preludeClock clash-preludeReset, 7 outputs the reset value when the reset value is active clash-prelude Global enable clash-preludeReset value. If the domain has initial values enabled, the reset value will also be the initial value. clash-prelude Enable signal clash-prelude$Number of cycles to assert the reset clash-prelude Reset value clash-preludeCircuit to simulate clash-prelude$Number of cycles to assert the reset clash-prelude Reset value clash-prelude=Number of cycles to simulate (excluding cycle spent in reset) clash-preludeCircuit to simulate clash-prelude The function we want to simulate clash-prelude Input samples clash-prelude The function we want to simulate clash-prelude Input samples clash-prelude$Number of cycles to assert the reset clash-prelude to sample clash-prelude$Number of cycles to assert the reset clash-preludeNumber of samples to produce clash-prelude to sample clash-prelude+Condition checking function, should return True to finish run clash-prelude$ we want to sample for the condition  =(C) 2013-2016, University of Twente, 2017 , Google Inc. 2019 , Myrtle Software Ltd 2021 , LUMI GUIDE FIETSDETECTIE B.V.BSD2 (see the file LICENSE)-Christiaan Baaij  Trustworthy&'(/02356789;< clash-preludeDelay a   for d periods. delay3 :: KnownDomain dom => Clock dom -> Reset dom -> Enable dom ->   dom n Int ->  % dom (n + 3) Int delay3 clk rst en =  clk rst en (-1   -1   -1    ) sampleN 7 (delay3 systemClockGen resetGen enableGen (dfromList [0..]))[-1,-1,-1,-1,1,2,3] clash-preludeDelay a   for d periods, where d is derived from the context. delay2 :: KnownDomain dom => Clock dom -> Reset dom -> Enable dom -> Int ->   dom n Int ->   dom (n + 2) Int delay2 =  sampleN 7 (delay2 systemClockGen resetGen enableGen (-1) (dfromList ([0..])))[-1,-1,-1,1,2,3,4]d. can also be specified using type application::t delayedI @3 delayedI @3 :: ... => Clock dom -> Reset dom -> Enable dom -> a -> DSignal dom n a -> DSignal dom (n + 3) a clash-preludeDelay a   for d% cycles, the value at time 0..d-1 is a.  delayN2 ::  dom => Int ->  dom ->  dom ->   dom n Int ->   dom (n + 2) Int delayN2 =  d2 printX $ sampleN 6 (delayN2 (-1) enableGen systemClockGen (dfromList [1..]))[-1,-1,1,2,3,4] clash-preludeDelay a   for d cycles, where d is derived from the context. The value at time 0..d-1 is a default value.  delayI2 ::  dom => Int ->  dom ->  dom ->   dom n Int ->   dom (n + 2) Int delayI2 =  sampleN 6 (delayI2 (-1) enableGen systemClockGen (dfromList [1..]))[-1,-1,1,2,3,4]1You can also use type application to do the same:sampleN 6 (delayI @2 (-1) enableGen systemClockGen (dfromList [1..]))[-1,-1,1,2,3,4] clash-preludeTree fold over a  of  /s with a combinatorial function, and delaying delay cycles after each application. Values at times 0..(delay*k)-1 are set to a default. countingSignals :: Vec 4 (DSignal dom 0 Int) countingSignals = repeat (dfromList [0..]) printX $ sampleN 6 (delayedFold d1 (-1) (+) enableGen systemClockGen countingSignals)[-1,-2,0,4,8,12]printX $ sampleN 8 (delayedFold d2 (-1) (*) enableGen systemClockGen countingSignals)[-1,-1,1,1,0,1,16,81] clash-preludeInitial values clash-prelude Initial value clash-prelude Initial value clash-prelude Initial value clash-preludeDelay applied after each step clash-prelude Initial value clash-preludeFold operation to apply clash-preludeVector input of size 2^k clash-prelude$Output Signal delayed by (delay * k)   >(C) 2015-2016, University of Twente, 2017 , Google Inc., 2019 , Myrtle Software Ltd., 2021-2022, QBayLogic B.V.BSD2 (see the file LICENSE)%QBayLogic B.V. Unsafe&/02356789; Trustworthy&/02356789;Safe&/02356789;< clash-preludeCreate a synchronous function from a combinational function describing a moore machine macT :: Int -- Current state -> (Int,Int) -- Input -> (Int,Int) -- Updated state macT s (x,y) = x * y + s mac ::  dom =>  dom ->  dom ->  dom ->  dom (Int, Int) ->  dom Int mac clk rst en =  clk rst en macT id 0 simulate (mac systemClockGen systemResetGen enableGen) [(0,0),(1,1),(2,2),(3,3),(4,4)][0,0,1,5,14......Synchronous sequential functions can be composed just like their combinational counterpart:  dualMac ::  dom =>  dom ->  dom ->  dom -> ( dom Int,  dom Int) -> ( dom Int,  dom Int) ->  dom Int dualMac clk rst en (a,b) (x,y) = s1 + s2 where s1 =  clk rst en macT id 0 (  (a,x)) s2 =  clk rst en macT id 0 (  (b,y))  clash-preludeCreate a synchronous function from a combinational function describing a moore machine without any output logic clash-prelude A version of  that does automatic  ingGiven a functions t and o of types: t :: Int -> (Bool, Int) -> Int o :: Int -> (Int, Bool) %When we want to make compositions of t and o in g using , we have to write: 6g clk rst en a b c = (b1,b2,i2) where (i1,b1) =   (moore clk rst en t o 0 (  (a,b))) (i2,b2) =   (moore clk rst en t o 3 (  (c,i1))) Using  however we can write: 6g clk rst en a b c = (b1,b2,i2) where (i1,b1) = & clk rst en t o 0 (a,b) (i2,b2) =  clk rst en t o 3 (c,i1)  clash-prelude A version of  that does automatic  ing clash-prelude to synchronize to clash-prelude)Transfer function in moore machine form: state -> input -> newstate clash-prelude'Output function in moore machine form: state -> output clash-prelude Initial state clash-preludeSynchronous sequential function with input and output matching that of the moore machine clash-prelude*Transfer function in moore machine form: state -> input -> newstate clash-prelude(Output function in moore machine form: state -> output clash-prelude Initial state clash-preludeSynchronous sequential function with input and output matching that of the moore machineA(C) 2013-2016, University of Twente, 2017 , Google Inc. 2019 , Myrtle Software Ltd 2023 , Alex MasonBSD2 (see the file LICENSE)-Christiaan Baaij Safe&/02356789;<َ clash-preludeCreate a synchronous function from a combinational function describing a mealy machine import qualified Data.List as L macT :: Int -- Current state -> (Int,Int) -- Input -> (Int,Int) -- (Updated state, output) macT s (x,y) = (s',s) where s' = x * y + s mac ::  dom =>  dom ->  dom ->  dom ->  dom (Int, Int) ->  dom Int mac clk rst en =  clk rst en macT 0 simulate (mac systemClockGen systemResetGen enableGen) [(0,0),(1,1),(2,2),(3,3),(4,4)][0,0,1,5,14......Synchronous sequential functions can be composed just like their combinational counterpart:  dualMac ::  dom =>  dom ->  dom ->  dom -> ( dom Int,  dom Int) -> ( dom Int,  dom Int) ->  dom Int dualMac clk rst en (a,b) (x,y) = s1 + s2 where s1 =  clk rst en macT 0 (  (a,x)) s2 =  clk rst en macT 0 (  (b,y))  clash-preludeCreate a synchronous function from a combinational function describing a mealy machine using the state monad. This can be particularly useful when combined with lenses or optics to replicate imperative algorithms. data DelayState = DelayState { _history :: Vec 4 Int , _untilValid :: Index 4 } deriving (Generic, NFDataX) makeLenses ''DelayState initialDelayState = DelayState (repeat 0) maxBound delayS :: Int -> State DelayState (Maybe Int) delayS n = do history %= (n +>>) remaining <- use untilValid if remaining > 0 then do untilValid -= 1 return Nothing else do out <- uses history last return (Just out) delayTop :: dom =>  dom ->  dom ->  dom -> ( dom Int -> ( dom (Maybe Int)) delayTop clk rst en = % clk rst en delayS initialDelayState L.take 7 $ simulate (delayTop systemClockGen systemResetGen enableGen) [-100,1,2,3,4,5,6,7,8]6[Nothing,Nothing,Nothing,Nothing,Just 1,Just 2,Just 3] clash-prelude A version of  that does automatic  ingGiven a function f of type: f* :: Int -> (Bool,Int) -> (Int,(Int,Bool)) %When we want to make compositions of f in g using , we have to write: 6g clk rst en a b c = (b1,b2,i2) where (i1,b1) =   (mealy clk rst en f 0 (  (a,b))) (i2,b2) =   (mealy clk rst en f 3 (  (c,i1))) Using  however we can write: 6g clk rst en a b c = (b1,b2,i2) where (i1,b1) = $ clk rst en f 0 (a,b) (i2,b2) =  clk rst en f 3 (c,i1)  clash-prelude A version of  that does automatic   ing, see  for details. clash-prelude to synchronize to clash-prelude Global enable clash-prelude)Transfer function in mealy machine form: #state -> input -> (newstate,output) clash-prelude Initial state clash-preludeSynchronous sequential function with input and output matching that of the mealy machine clash-prelude to synchronize to clash-prelude Global enable clash-prelude9Transfer function in mealy machine handling inputs using Control.Monad.Strict.State s. clash-prelude Initial state clash-preludeSynchronous sequential function with input and output matching that of the mealy machine clash-prelude)Transfer function in mealy machine form: #state -> input -> (newstate,output) clash-prelude Initial state clash-preludeSynchronous sequential function with input and output matching that of the mealy machine clash-prelude9Transfer function in mealy machine handling inputs using Control.Monad.Strict.State s. clash-prelude Initial state clash-preludeSynchronous sequential function with input and output matching that of the mealy machineB(C) 2021-2024, QBayLogic B.V.BSD2 (see the file LICENSE)%QBayLogic B.V.  Trustworthy&/02356789;< clash-prelude"Create a block RAM with space for n elementsNB": Read value is delayed by 1 cycleNB: Initial output value is  undefined, reading it will throw an  See also:See  Clash.Prelude.BlockRam#usingrams1 for more information on how to use a block RAM.Use the adapter D7 for obtaining write-before-read semantics like this: D clk rst en ( clk en content) rd wrM. clash-prelude$Create a block RAM with space for 2^n elementsNB": Read value is delayed by 1 cycleNB: Initial output value is  undefined, reading it will throw an  See also:See  Clash.Prelude.BlockRam#usingrams1 for more information on how to use a block RAM.Use the adapter D7 for obtaining write-before-read semantics like this: D clk rst en ( clk en content) rd wrM. clash-preludeblockRAMBlob primitive clash-prelude Create a   binding from a list of valuesSince this uses Template Haskell, nothing in the arguments given to 3 can refer to something defined in the same module.Example  "content" J( [15 :: Unsigned 8 .. 17] ram clk en =  clk en content The | datatype has don't care bits, where the actual value does not matter. But the bits need a defined value in the memory. Either 0 or 1 can be used, and both are valid representations of the data.import qualified Prelude as P4let es = [ Nothing, Just (7 :: Unsigned 8), Just 8 ]:{$createMemBlob "content0" (Just 0) es$createMemBlob "content1" (Just 1) esx = 1:} let pr = mapM_ (putStrLn . show)pr $ P.map pack es 0b0_...._.... 0b1_0000_0111 0b1_0000_1000pr $ unpackMemBlob content0 0b0_0000_0000 0b1_0000_0111 0b1_0000_1000pr $ unpackMemBlob content1 0b0_1111_1111 0b1_0000_0111 0b1_0000_1000:{#createMemBlob "contentN" Nothing esx = 1:}:...: error:... packBVs: cannot convert don't care values. Please specify a mapping to a definite value.Note how we hinted to clashi that our multi-line command was a list of declarations by including a dummy declaration x = 1. Without this trick, clashi would expect an expression and the Template Haskell would not work. clash-prelude Create a   from a list of valuesSince this uses Template Haskell, nothing in the arguments given to 3 can refer to something defined in the same module.Example  ram clk en = 6 clk en $(memBlobTH Nothing [15 :: Unsigned 8 .. 17]) The | datatype has don't care bits, where the actual value does not matter. But the bits need a defined value in the memory. Either 0 or 1 can be used, and both are valid representations of the data.import qualified Prelude as P4let es = [ Nothing, Just (7 :: Unsigned 8), Just 8 ]#content0 = $(memBlobTH (Just 0) es)#content1 = $(memBlobTH (Just 1) es) let pr = mapM_ (putStrLn . show)pr $ P.map pack es 0b0_...._.... 0b1_0000_0111 0b1_0000_1000pr $ unpackMemBlob content0 0b0_0000_0000 0b1_0000_0111 0b1_0000_1000pr $ unpackMemBlob content1 0b0_1111_1111 0b1_0000_0111 0b1_0000_1000$(memBlobTH Nothing es):...: error:... @ packBVs: cannot convert don't care values. Please specify a mapping to a definite value.4 @ In the untyped splice: $(memBlobTH Nothing es) clash-prelude to synchronize to clash-prelude line clash-prelude7Initial content of the BRAM, also determines the size, n , of the BRAMNB: MUST be a constant clash-prelude Read address r clash-prelude(write address w, value to write) clash-preludeValue of the BRAM at address r from the previous clock cycle clash-prelude to synchronize to clash-prelude line clash-prelude9Initial content of the BRAM, also determines the size, 2^n , of the BRAMNB: MUST be a constant clash-prelude Read address r clash-prelude(write address w, value to write) clash-preludeValue of the BRAM at address r from the previous clock cycle clash-prelude to synchronize to clash-prelude line clash-prelude7Initial content of the BRAM, also determines the size, n , of the BRAMNB: MUST be a constant clash-prelude Read address r clash-prelude Write enable clash-preludeWrite address w clash-preludeValue to write (at address w) clash-preludeValue of the BRAM at address r from the previous clock cycle clash-preludeName of the binding to generate clash-prelude!Value to map don't care bits to. J- means throwing an error on don't care bits. clash-preludeThe content for the   clash-prelude!Value to map don't care bits to. J- means throwing an error on don't care bits. clash-preludeThe content for the     C(C) 2021-2022, QBayLogic B.V.BSD2 (see the file LICENSE)%QBayLogic B.V.  Trustworthy&/02356789;<z clash-prelude3A ROM with a synchronous read port, with space for n elementsNB": Read value is delayed by 1 cycleNB: Initial output value is  undefined, reading it will throw an  See also:See #Clash.Sized.Fixed#creatingdatafiles and !Clash.Explicit.BlockRam#usingrams' for ideas on how to use ROMs and RAMs. clash-prelude5A ROM with a synchronous read port, with space for 2^n elementsNB": Read value is delayed by 1 cycleNB: Initial output value is  undefined, reading it will throw an  See also:See #Clash.Sized.Fixed#creatingdatafiles and !Clash.Explicit.BlockRam#usingrams' for ideas on how to use ROMs and RAMs. clash-prelude ROM primitive clash-prelude to synchronize to clash-prelude line clash-prelude'ROM content, also determines the size, n , of the ROMNB: MUST be a constant clash-prelude Read address r clash-prelude The value of the ROM at address r from the previous clock cycle clash-prelude to synchronize to clash-prelude line clash-prelude)ROM content, also determines the size, 2^n , of the ROMNB: MUST be a constant clash-prelude Read address r clash-prelude The value of the ROM at address r from the previous clock cycle clash-prelude to synchronize to clash-prelude line clash-prelude'ROM content, also determines the size, n , of the ROMNB: MUST be a constant clash-prelude Read address r clash-prelude The value of the ROM at address r from the previous clock cycle   D(C) 2013-2016, University of Twente, 2016-2017, Myrtle Software Ltd, 2017 , Google Inc., 2021-2023, QBayLogic B.V., 2022 , Google Inc.,BSD2 (see the file LICENSE)%QBayLogic B.V.  Trustworthy&'(/02356789:;< clash-preludePort operation clash-preludeRead from address clash-preludeWrite data to address clash-prelude No operation clash-prelude"Create a block RAM with space for n elementsNB": Read value is delayed by 1 cycleNB: Initial output value is  undefined, reading it will throw an  See also:See !Clash.Explicit.BlockRam#usingrams1 for more information on how to use a block RAM.Use the adapter 7 for obtaining write-before-read semantics like this:  clk rst en ( clk inits) rd wrM.A large  for the initial content may be too inefficient, depending on how it is constructed. See 9 and B+ for different approaches that scale well.Example  bram40 ::  dom ->  dom ->  dom (  6) ->  dom (Maybe (  6, )) ->  dom  bram40 clk en =  clk en (  d40 1)  clash-prelude$Create a block RAM with space for 2^n elementsNB": Read value is delayed by 1 cycleNB: Initial output value is  undefined, reading it will throw an  See also:See  Clash.Prelude.BlockRam#usingrams1 for more information on how to use a block RAM.Use the adapter 7 for obtaining write-before-read semantics like this:  clk rst en ( clk inits) rd wrM.A large  for the initial content may be too inefficient, depending on how it is constructed. See 9 and B+ for different approaches that scale well.Example  bram32 ::  dom ->  dom ->  dom (  5) ->  dom (Maybe (  5, )) ->  dom  bram32 clk en =  clk en (  d32 1)  clash-prelude A version of  that has no default values set. May be cleared to an arbitrary state using a reset function. clash-preludeblockRAMU primitive clash-prelude A version of  that is initialized with the same value on all memory positions clash-preludeblockRAM1 primitive clash-preludeblockRAM primitive clash-preludeCreate a read-after-write block RAM from a read-before-write one clash-preludeProduces vendor-agnostic HDL that will be inferred as a true dual-port block RAMAny value that is being written on a particular port is also the value that will be read on that port, i.e. the same-port read/write behavior is: WriteFirst. For mixed-port read/write, when port A writes to the address port B reads from, the output of port B is undefined, and vice versa. clash-preludePrimitive for   clash-prelude to synchronize to clash-prelude line clash-prelude7Initial content of the BRAM, also determines the size, n , of the BRAMNB: MUST be a constant clash-prelude Read address r clash-prelude(write address w, value to write) clash-preludeValue of the BRAM at address r from the previous clock cycle clash-prelude to synchronize to clash-prelude line clash-preludeInitial content of the BRAMNB: MUST be a constant clash-prelude Read address r clash-prelude(Write address w, value to write) clash-preludeValue of the BRAM at address r from the previous clock cycle  clash-prelude to synchronize to clash-prelude. line. This needs to be asserted for at least n cycles in order for the BRAM to be reset to its initial state. clash-prelude line clash-prelude)Whether to clear BRAM on asserted reset ( ) or not (/). The reset needs to be asserted for at least n cycles to clear the BRAM. clash-preludeNumber of elements in BRAM clash-preludeIf applicable (see * argument), reset BRAM using this function clash-prelude Read address r clash-prelude(write address w, value to write) clash-preludeValue of the BRAM at address r from the previous clock cycle clash-prelude to synchronize to clash-prelude line clash-preludeNumber of elements in BRAM clash-prelude Read address r clash-prelude Write enable clash-preludeWrite address w clash-preludeValue to write (at address w) clash-preludeValue of the BRAM at address r from the previous clock cycle  clash-prelude to synchronize to clash-prelude. line. This needs to be asserted for at least n cycles in order for the BRAM to be reset to its initial state. clash-prelude line clash-prelude)Whether to clear BRAM on asserted reset ( ) or not (/). The reset needs to be asserted for at least n cycles to clear the BRAM. clash-preludeNumber of elements in BRAM clash-prelude(Initial content of the BRAM (replicated n times) clash-prelude Read address r clash-prelude(write address w, value to write) clash-preludeValue of the BRAM at address r from the previous clock cycle  clash-prelude to synchronize to clash-prelude line clash-preludeNumber of elements in BRAM clash-prelude(Initial content of the BRAM (replicated n times) clash-prelude Read address r clash-prelude Write enable clash-preludeWrite address w clash-preludeValue to write (at address w) clash-preludeValue of the BRAM at address r from the previous clock cycle clash-prelude to synchronize to clash-prelude line clash-prelude7Initial content of the BRAM, also determines the size, n , of the BRAMNB: MUST be a constant clash-prelude Read address r clash-prelude Write enable clash-preludeWrite address w clash-preludeValue to write (at address w) clash-preludeValue of the BRAM at address r from the previous clock cycle clash-preludeThe BRAM component clash-prelude Read address r clash-prelude(Write address w, value to write) clash-preludeValue of the BRAM at address r from the previous clock cycle clash-preludeClock for port A clash-preludeClock for port B clash-preludeRAM operation for port A clash-preludeRAM operation for port B clash-preludeOutputs data on next cycle. When writing, the data written will be echoed. When reading, the read data is returned. clash-preludeEnable clash-prelude Write enable clash-preludeAddress clash-prelude Write data clash-preludeEnable clash-prelude Write enable clash-preludeAddress  clash-prelude Write dataE(C) 2015-2016, University of Twente, 2016-2019, Myrtle Software Ltd, 2017 , Google Inc., 2021-2022, QBayLogic B.V.BSD2 (see the file LICENSE)%QBayLogic B.V. Safe&/02356789;< clash-preludeNone&/02356789:;<>F  clash-preludeA reset that is never asserted clash-preludeOutput reset will be asserted when either one of the input resets is asserted clash-preludeOutput reset will be asserted when either one of the input resets is asserted. This function is considered unsafe because it can be used on domains with components with asynchronous resets, where use of this function can introduce glitches triggering a reset. clash-preludeOutput reset will be asserted when both input resets are asserted clash-preludeOutput reset will be asserted when both input resets are asserted. This function is considered unsafe because it can be used on domains with components with asynchronous resets, where use of this function can introduce glitches triggering a reset. clash-preludeThe resetSynchronizer will synchronize an incoming reset according to whether the domain is synchronous or asynchronous.For asynchronous resets this synchronizer ensures the reset will only be de-asserted synchronously but it can still be asserted asynchronously. The reset assert is immediate, but reset de-assertion is delayed by two cycles.Normally, asynchronous resets can be both asynchronously asserted and de-asserted. Asynchronous de-assertion can induce meta-stability in the component which is being reset. To ensure this doesn't happen,  ensures that de-assertion of a reset happens synchronously. Assertion of the reset remains asynchronous.Note that asynchronous assertion does not induce meta-stability in the component whose reset is asserted. However, when a component "A" in another clock or reset domain depends on the value of a component "B" being reset, then asynchronous assertion of the reset of component "B" can induce meta-stability in component "A". To prevent this from happening you need to use a proper synchronizer, for example one of the synchronizers in Clash.Explicit.Synchronizer.For synchronous resets this function ensures that the reset is asserted and de-asserted synchronously. Both the assertion and de-assertion of the reset are delayed by two cycles. Example 1The circuit below detects a rising bit (i.e., a transition from 0 to 1) in a given argument. It takes a reset that is not synchronized to any of the other incoming signals and synchronizes it using . topEntity :: Clock System -> Reset System -> Signal System Bit -> Signal System (BitVector 8) topEntity clk asyncRst key1 = withClockResetEnable clk rst enableGen leds where rst =  clk asyncRst key1R = isRising 1 key1 leds = mealy blinkerT (1, False, 0) key1R  Example 2 Similar to  Example 1 this circuit detects a rising bit (i.e., a transition from 0 to 1) in a given argument. It takes a clock that is not stable yet and a reset signal that is not synchronized to any other signals. It stabilizes the clock and then synchronizes the reset signal.Note that the function I provides this functionality in a convenient form, obviating the need for resetSynchronizer for this use case. topEntity :: Clock System -> Reset System -> Signal System Bit -> Signal System (BitVector 8) topEntity clk rst key1 = let (pllOut,pllStable) = unsafeAltpll clk rst rstSync =  pllOut (unsafeFromActiveLow pllStable) in exposeClockResetEnable leds pllOut rstSync enableGen where key1R = isRising 1 key1 leds = mealy blinkerT (1, False, 0) key1R Implementation details; implements the following circuit for asynchronous domains:  rst --------------------------------------+ | | +----v----+ +----v----+ deasserted | | | | ---------------> +-------> +--------> | | | | +---|> | +---|> | | | | | | | | +---------+ | +---------+ clk | | -----------------------------+!This corresponds to figure 3d at https://www.embedded.com/asynchronous-reset-synchronization-and-distribution-challenges-and-solutions/;For synchronous domains two sequential dflipflops are used:  +---------+ +---------+ rst | | | | ---------------> +-------> +--------> | | | | +---|> | +---|> | | | | | | | | +---------+ | +---------+ clk | | -----------------------------+ clash-preludeFilter glitches from reset signals by only triggering a reset after it has been asserted for glitchlessPeriod3 cycles. Similarly, it will stay asserted until a glitchlessPeriod1 number of deasserted cycles have been observed.This circuit can only be used on platforms supporting initial values. This restriction can be worked around by using  but this is not recommended.=On platforms without initial values, you should instead use ( with an additional power-on reset, or , if filtering is only needed on deassertion.At power-on, the reset will be asserted. If the filtered reset input remains unasserted, the output reset will deassert after glitchlessPeriod clock cycles.If resetGlitchFilter0 is used in a domain with asynchronous resets (), resetGlitchFilter. will first synchronize the reset input with . Example 13let sampleResetN n = sampleN n . unsafeToActiveHigh3let resetFromList = unsafeFromActiveHigh . fromListlet rst = resetFromList [True, True, False, False, True, False, False, True, True, False, True, True]sampleResetN 12 (resetGlitchFilter d2 (clockGen @XilinxSystem) rst)[True,True,True,True,False,False,False,False,False,True,True,True] clash-preludeFilter glitches from reset signals by only triggering a reset after it has been asserted for glitchlessPeriod3 cycles. Similarly, it will stay asserted until a glitchlessPeriod1 number of deasserted cycles have been observed.%On platforms without initial values (), $ cannot be used and you should use ( with an additional power-on reset, or , if filtering is only needed on deassertion.unsafeResetGlitchFilter allows breaking the requirement of initial values, but by doing so it is possible that the design starts up with a period of up to 2 * glitchlessPeriod clock cycles where the reset output is unasserted (or longer in the case of glitches on the filtered reset input). This can cause a number of problems. The outputs/tri-states of the design might output random things, including coherent but incorrect streams of data. This might have grave repercussions in the design's environment (sending network packets, overwriting non-volatile memory, in extreme cases destroying controlled equipment or causing harm to living beings, ...).2Without initial values, the synthesized result of unsafeResetGlitchFilter eventually correctly outputs a filtered version of the reset input. However, in simulation, it will indefinitely output an undefined value. This happens both in Clash simulation and in HDL simulation. Therefore, simulation should not include the unsafeResetGlitchFilter.If unsafeResetGlitchFilter0 is used in a domain with asynchronous resets (), unsafeResetGlitchFilter. will first synchronize the reset input with . clash-preludeFilter glitches from reset signals by only triggering a reset after it has been asserted for glitchlessPeriod3 cycles. Similarly, it will stay asserted until a glitchlessPeriod1 number of deasserted cycles have been observed. Compared to , this function adds an additional power-on reset input. As soon as the power-on reset asserts, the reset output will assert, and after the power-on reset deasserts, the reset output will stay asserted for another glitchlessPeriod. clock cycles. This is identical behavior to  where it concerns the power-on reset, and differs from the filtered reset, which will only cause an assertion after glitchlessPeriod cycles.If resetGlitchFilterWithReset0 is used in a domain with asynchronous resets (), resetGlitchFilterWithReset. will first synchronize the reset input with . clash-preludeHold reset for a number of cycles relative to an incoming reset signal.Example:4let sampleWithReset = sampleN 8 . unsafeToActiveHighsampleWithReset (holdReset @System clockGen enableGen (SNat @2) (resetGenN (SNat @3))),[True,True,True,True,True,False,False,False] holds the reset for an additional 2 clock cycles for a total of 5 clock cycles where the reset is asserted. < also works on intermediate assertions of the reset signal:let rst = fromList [True, False, False, False, True, False, False, False]sampleWithReset (holdReset @System clockGen enableGen (SNat @2) (unsafeFromActiveHigh rst))+[True,True,True,False,True,True,True,False] clash-preludeConvert between different types of reset, adding a synchronizer when the domains are not the same. See 2 for further details about reset synchronization.If domA has $ resets, a flip-flop is inserted in domA$ to filter glitches. This adds one domA clock cycle delay. clash-preludeConsider a reset signal to be properly asserted after having seen the reset asserted for glitchlessPeriod cycles straight. clash-preludeConsider a reset signal to be properly asserted after having seen the reset asserted for glitchlessPeriod cycles straight. clash-preludeConsider a reset signal to be properly asserted after having seen the reset asserted for glitchlessPeriod cycles straight. clash-prelude/The power-on reset for the glitch filter itself clash-preludeThe reset that will be filtered clash-prelude Global enable clash-prelude Hold for n cycles, counting from the moment the incoming reset signal becomes deasserted. clash-preludeReset to extend(C) 2018-2022, Google Inc 2019, Myrtle Software Ltd 2023, QBayLogic B.V.BSD2 (see the file LICENSE)%QBayLogic B.V. None&/02356789;<I clash-preludeNB/: The documentation only shows instances up to 3; output clocks. By default, instances up to and including 18 clocks will exist. clash-preludeNB/: The documentation only shows instances up to 3; output clocks. By default, instances up to and including 18 clocks will exist. G(C) 2018, Google Inc 2019, Myrtle Software Ltd 2023, QBayLogic B.V.BSD2 (see the file LICENSE)%QBayLogic B.V. None&-/02356789;<>?J  H<(C) 2017, Google Inc, 2023, QBayLogic B.V.BSD2 (see the file LICENSE)%QBayLogic B.V. None&'(/02356789;None&/02356789; Trustworthy &'(-/02356789; Vec 6 (Unsigned 8) topEntity = concat testBench :: Signal System Bool testBench = done where testInput = pure ((1 :> 2 :> 3 :> Nil) :> (4 :> 5 :> 6 :> Nil) :> Nil) expectedOutput = outputVerifier' ((1:>2:>3:>4:>5:>6:>Nil):>Nil) done = exposeClockResetEnable (expectedOutput (topEntity <$> testInput)) clk rst en clk = tbSystemClockGen (not <$> done) rst = systemResetGen en = enableGen  clash-prelude Hide the , , and = arguments of a component, so they can be routed implicitly. %Clash-Signal.html#hiddenclockandresetClick here to read more about hidden clocks, resets, and enables clash-preludeConnect an explicit , , and  to a function with a hidden , , and . %Clash-Signal.html#hiddenclockandresetClick here to read more about hidden clocks, resets, and enablesExample Usage with a  polymorphic domain:reg = register 5 (reg + 1):sig = withClockResetEnable clockGen resetGen enableGen regsampleN @System 10 sig[5,5,6,7,8,9,10,11,12,13]Force  to work on  (hence ' not needing an explicit domain later):reg = register 5 (reg + 1)sig = withClockResetEnable @System clockGen resetGen enableGen regsampleN 10 sig[5,5,6,7,8,9,10,11,12,13] clash-preludeSpecial version of  that doesn't take enable signals of any kind. Initial value will be undefined. clash-prelude dflt s delays the values in  s) for once cycle, the value at time 0 is dflt.0sampleN @System 3 (delay 0 (fromList [1,2,3,4]))[0,1,2] clash-prelude Version of 1 that only updates when its second argument is a K value.let input = fromList [Just 1, Just 2, Nothing, Nothing, Just 5, Just 6, Just (7::Int)]&sampleN @System 7 (delayMaybe 0 input)[0,1,2,2,2,5,6] clash-prelude Version of 8 that only updates when its second argument is asserted.)let input = fromList [1,2,3,4,5,6,7::Int] that only updates its content when its second argument is a K value. So given: sometimes1 = s where s =  Nothing (switch  s) switch Nothing = Just 1 switch _ = Nothing countSometimes = s where s =  0 (plusM (!  s) sometimes1) plusM =  (liftA2 (+)) We get:sampleN @System 9 sometimes1[Nothing,Nothing,Just 1,Nothing,Just 1,Nothing,Just 1,Nothing,Just 1] sampleN @System 9 countSometimes[0,0,0,1,1,2,2,3,3] clash-prelude Version of  that only updates its content when its second argument is asserted. So given:  oscillate =  False (  oscillate) count =  0 oscillate (count + 1) We get:sampleN @System 9 oscillate3[False,False,True,False,True,False,True,False,True]sampleN @System 9 count[0,0,0,1,1,2,2,3,3] clash-prelude'Get an infinite list of samples from a 9The elements in the list correspond to the values of the  at consecutive clock cycles  sample s == [s0, s1, s2, s3, ...If the given component has not yet been given a clock, reset, or enable line,  will supply them. The reset will be asserted for a single cycle.  will not drop the value produced by the circuit while the reset was asserted. If you want this, or if you want more than a single cycle reset, consider using .NB$: This function is not synthesizable clash-preludeGet a list of n samples from a 9The elements in the list correspond to the values of the  at consecutive clock cycles #sampleN @System 3 s == [s0, s1, s2]If the given component has not yet been given a clock, reset, or enable line,  will supply them. The reset will be asserted for a single cycle.  will not drop the value produced by the circuit while the reset was asserted. If you want this, or if you want more than a single cycle reset, consider using .NB$: This function is not synthesizable clash-prelude'Get an infinite list of samples from a &, while asserting the reset line for m clock cycles.  does not return the first m+ cycles, i.e., when the reset is asserted.NB$: This function is not synthesizable clash-preludeGet a list of n samples from a &, while asserting the reset line for m clock cycles.  does not return the first m, cycles, i.e., while the reset is asserted.NB$: This function is not synthesizable clash-preludeLazily( get an infinite list of samples from a 9The elements in the list correspond to the values of the  at consecutive clock cycles  sample s == [s0, s1, s2, s3, ...If the given component has not yet been given a clock, reset, or enable line,  will supply them. The reset will be asserted for a single cycle.  will not drop the value produced by the circuit while the reset was asserted.NB$: This function is not synthesizable clash-preludeLazily get a list of n samples from a 9The elements in the list correspond to the values of the  at consecutive clock cycles #sampleN @System 3 s == [s0, s1, s2]If the given component has not yet been given a clock, reset, or enable line,  will supply them. The reset will be asserted for a single cycle.  will not drop the value produced by the circuit while the reset was asserted.NB$: This function is not synthesizable clash-prelude Simulate a ( a ->  b,) function given a list of samples of type a'simulate @System (register 8) [1, 2, 3] [8,1,2,3......Where  denotes the domain to simulate on. The reset line is asserted for a single cycle. The first value is therefore supplied twice to the circuit: once while reset is high, and once directly after. The first output value (the value produced while the reset is asserted) is dropped.=If you only want to simulate a finite number of samples, see . If you need the reset line to be asserted for more than one cycle or if you need a custom reset value, see  and .NB$: This function is not synthesizable clash-preludeSame as , but only sample the first Int output values.NB$: This function is not synthesizable clash-preludeSame as ', but with the reset line asserted for n cycles. Similar to ,  will drop the output values produced while the reset is asserted. While the reset is asserted, the reset value a is supplied to the circuit. clash-preludeSame as , but only sample the first Int output values. clash-preludeLazily simulate a ( a ->  b,) function given a list of samples of type a'simulate @System (register 8) [1, 2, 3] [8,1,2,3......NB$: This function is not synthesizable clash-prelude Simulate a (  a ->   b,) function given a list of samples of type asimulateB @System (unbundle . register (8,8) . bundle) [(1,1), (2,2), (3,3)] :: [(Int,Int)][(8,8),(1,1),(2,2),(3,3)......NB$: This function is not synthesizable clash-preludeLazily simulate a (  a ->   b,) function given a list of samples of type asimulateB @System (unbundle . register (8,8) . bundle) [(1,1), (2,2), (3,3)] :: [(Int,Int)][(8,8),(1,1),(2,2),(3,3)......NB$: This function is not synthesizable clash-prelude1Simulate a component until it matches a conditionIf the given component has not yet been given a clock, reset, or enable line,  will supply them. The reset will be asserted for a single cycle.It prints a message of the form )Signal sampled for N cycles until value XNB$: This function is not synthesizableExample with test bench+A common usage is with a test bench using .NB: Since this uses , when using clashi, read the note at &Clash.Explicit.Testbench#assert-clashi. import Clash.Prelude import Clash.Explicit.Testbench topEntity ::   Int ->  $ Int topEntity = id testBench ::  , Bool testBench = done where testInput =  clk rst $(* [1 :: Int .. 10]) expectedOutput =  clk rst $( $ [1 :: Int .. 9] = [42]) done = expectedOutput $ topEntity testInput clk =  (not <$> done) rst =   > runUntil id testBench cycle(): 10, outputVerifier expected value: 42, not equal to actual value: 10 Signal sampled for 11 cycles until value True When you need to verify multiple test benches, the following invocations come in handy: > p* (runUntil id) [ testBenchA, testBenchB ] 8or when the test benches are in different clock domains: >testBenchA :: Signal DomA Bool testBenchB :: Signal DomB Bool > o4 [ runUntil id testBenchA, runUntil id testBenchB ]  clash-prelude testFor n s tests the signal s for n cycles.NB$: This function is not synthesizable clash-preludeHold reset for a number of cycles relative to an implicit reset signal.Example: