packages feed

clash-lib 1.10.3 → 1.10.4

raw patch · 30 files changed

+904/−92 lines, 30 filesdep ~asyncdep ~clash-preludePVP: major bump suggested

API removals or changes: PVP suggests a major version bump

Dependency ranges changed: async, clash-prelude

API changes (from Hackage documentation)

+ Clash.Core.Name: isIdentifierText :: Text -> Bool
+ Clash.Core.Name: unqualifiedOcc :: OccName -> OccName
+ Clash.Core.Util: renameIds :: VarEnv Id -> Term -> Term
+ Clash.Netlist.Util: literalToConName :: HWType -> Literal -> Maybe Text
+ Clash.Normalize: nameArgsAfterParams :: BindingMap -> [(Id, Term)] -> Term -> Term
+ Clash.Normalize.Transformations.Case: caseDataToTag :: Transformation
+ Clash.Normalize.Transformations.Case: caseDataToTagWorker :: HasCallStack => TransformContext -> Term -> Term -> Type -> [Alt] -> NormalizeSession Term
+ Clash.Normalize.Transformations.Specialize: zeroWidthTypeElem :: TyConMap -> Type -> Maybe Term
+ Clash.Primitives.Sized.BitVector: indexBitVectorCV :: BlackBoxFunction
+ Clash.Rewrite.Util: mkAltName :: TransformContext -> Pat -> TmName
+ Clash.Rewrite.Util: mkArgName :: TransformContext -> Term -> Int -> RewriteMonad extra TmName
+ Clash.Util.Exception: exceptionBacktrace :: SomeException -> String
+ Clash.Util.Exception: mapConcurrentlyWithBacktrace_ :: Foldable f => (a -> IO b) -> f a -> IO ()
- Clash.Rewrite.Types: bindings :: forall extra_a52V5. Lens' (RewriteState extra_a52V5) BindingMap
+ Clash.Rewrite.Types: bindings :: forall extra_a53Jy. Lens' (RewriteState extra_a53Jy) BindingMap
- Clash.Rewrite.Types: curFun :: forall extra_a52V5. Lens' (RewriteState extra_a52V5) (Id, SrcSpan)
+ Clash.Rewrite.Types: curFun :: forall extra_a53Jy. Lens' (RewriteState extra_a53Jy) (Id, SrcSpan)
- Clash.Rewrite.Types: extra :: forall extra_a52V5 extra_a536C. Lens (RewriteState extra_a52V5) (RewriteState extra_a536C) extra_a52V5 extra_a536C
+ Clash.Rewrite.Types: extra :: forall extra_a53Jy extra_a53V5. Lens (RewriteState extra_a53Jy) (RewriteState extra_a53V5) extra_a53Jy extra_a53V5
- Clash.Rewrite.Types: globalHeap :: forall extra_a52V5. Lens' (RewriteState extra_a52V5) PrimHeap
+ Clash.Rewrite.Types: globalHeap :: forall extra_a53Jy. Lens' (RewriteState extra_a53Jy) PrimHeap
- Clash.Rewrite.Types: hwTypeCache :: forall extra_a52V5. Lens' (RewriteState extra_a52V5) HWMap
+ Clash.Rewrite.Types: hwTypeCache :: forall extra_a53Jy. Lens' (RewriteState extra_a53Jy) HWMap
- Clash.Rewrite.Types: nameCounter :: forall extra_a52V5. Lens' (RewriteState extra_a52V5) Int
+ Clash.Rewrite.Types: nameCounter :: forall extra_a53Jy. Lens' (RewriteState extra_a53Jy) Int
- Clash.Rewrite.Types: transformAppliedCounters :: forall extra_a52V5. Lens' (RewriteState extra_a52V5) (HashMap Text Word)
+ Clash.Rewrite.Types: transformAppliedCounters :: forall extra_a53Jy. Lens' (RewriteState extra_a53Jy) (HashMap Text Word)
- Clash.Rewrite.Types: transformCounter :: forall extra_a52V5. Lens' (RewriteState extra_a52V5) Word
+ Clash.Rewrite.Types: transformCounter :: forall extra_a53Jy. Lens' (RewriteState extra_a53Jy) Word
- Clash.Rewrite.Types: transformTriedCounters :: forall extra_a52V5. Lens' (RewriteState extra_a52V5) (HashMap Text Word)
+ Clash.Rewrite.Types: transformTriedCounters :: forall extra_a53Jy. Lens' (RewriteState extra_a53Jy) (HashMap Text Word)
- Clash.Rewrite.Types: uniqSupply :: forall extra_a52V5. Lens' (RewriteState extra_a52V5) Supply
+ Clash.Rewrite.Types: uniqSupply :: forall extra_a53Jy. Lens' (RewriteState extra_a53Jy) Supply
- Clash.Rewrite.Types: workFreeBinders :: forall extra_a52V5. Lens' (RewriteState extra_a52V5) (VarEnv Bool)
+ Clash.Rewrite.Types: workFreeBinders :: forall extra_a53Jy. Lens' (RewriteState extra_a53Jy) (VarEnv Bool)

Files

CHANGELOG.md view
@@ -1,5 +1,67 @@ # Changelog for the Clash project +## 1.10.4 - *17 Nov, 2026*++### Changed:++- Clash now derives more names in the generated HDL from the source code:++  * Arguments of data constructors are named after the record field they are passed to, e.g. `c$baudCount` instead of `c$app_arg` for the second field of `Tx { txState, baudCount }`.+  * Arguments of functions are named after the function and its parameter, e.g. `c$txStep_s` for the state of `mealy txStep`.+  * Case alternatives are named after the constructor they match, e.g. `c$x_case_Idle` instead of `c$x_case_alt` for the alternative `Idle -> ...` of `x = case s of ...`.+  * Pattern bindings such as `(nextState, output) = ...` are named after their variables, e.g. `nextState_output` instead of `ds`.+  * Variables made up by GHC, such as `eta`, are named after the parameter of the user-defined function they're passed to. This also names ports of top entities without a `Synthesize` annotation.+  * User-written names are kept when they are aliases of variables Clash made up. For example, `dSCL` in `let dSCL = fst _dI2C` now names the register holding that field.++  [#3503](https://github.com/clash-lang/clash-compiler/pull/3503)+- Fields of SystemVerilog structs for records are now named after the record fields, e.g. `baudCount` instead of `Tx_sel1` for the field `baudCount` of a record `Tx`. When a record field isn't a valid SystemVerilog identifier, such as a keyword like `input` or a name with a `'`, the struct's fields are named like `Tx_sel1_baudCount` instead. Fields of tuples and other products without field names keep names like `Tuple2_sel0`.+  [#3503](https://github.com/clash-lang/clash-compiler/pull/3503)+- Removing unused declarations no longer shuffles the order of the remaining declarations in the generated HDL.+  [#3503](https://github.com/clash-lang/clash-compiler/pull/3503)+- Comparing constructors of enumerations with derived `==`, such as `mode == Done`, no longer produces an `Int`-wide signal named `c$case_scrut` in the HDL.+  [#3503](https://github.com/clash-lang/clash-compiler/pull/3503)+- Alternatives of case statements in the generated HDL now mention the constructor they match in a comment, e.g. `2'b00 : busy = 1'b0; // Idle`.+  [#3503](https://github.com/clash-lang/clash-compiler/pull/3503)+- Signals holding a record field that the HDL matches on are now named after the record and the field, e.g. `s_mode` for the field `mode` of a signal `s`.+  [#3503](https://github.com/clash-lang/clash-compiler/pull/3503)+- Clash now reports errors in the module it compiles directly, instead of wrapping them in a message about loading the module from both precompiled and local sources.+  [#2365](https://github.com/clash-lang/clash-compiler/issues/2365) [#2680](https://github.com/clash-lang/clash-compiler/issues/2680)+- Improved the documentation on converting between number types.+  [#3537](https://github.com/clash-lang/clash-compiler/pull/3537)+- The error for an inline primitive with a mismatched name now points at the annotated function.+  [#2365](https://github.com/clash-lang/clash-compiler/issues/2365)++### Fixed:++- Clash's internal `split#` unfolding now returns zero for zero-width halves, matching its Haskell counterpart.+  [#3490](https://github.com/clash-lang/clash-compiler/pull/3490)+- `GHC.Num.Integer.integerLogBase#` and `GHC.Num.Natural.naturalLogBase#` are now constant folded accurately, even in cases where these functions return errors.+  [#3492](https://github.com/clash-lang/clash-compiler/pull/3492)+- Unhandled `error` calls are reported with their `HasCallStack` backtrace again on GHC 9.12 and later.+  [#3449](https://github.com/clash-lang/clash-compiler/pull/3449)+- Errors raised while compiling top entities concurrently now report the backtrace they were thrown with, instead of one pointing into `async`.+  [#3449](https://github.com/clash-lang/clash-compiler/pull/3449)+- Clash no longer takes quadratic or exponential time to compile designs that use `iterateI` with a function that inspects its argument more than once, e.g. `iterateI (\(Just n) -> if n == maxBound then Nothing else Just (n + 1)) (Just 0)`, when the resulting vector is consumed by functions such as `takeI` or `foldr`.+  [#3477](https://github.com/clash-lang/clash-compiler/issues/3477) [#3539](https://github.com/clash-lang/clash-compiler/pull/3539)+- Clash now reports an error when `clash-lib`'s `mkFunInput` gets called with a local variable as its function input.+  [#3499](https://github.com/clash-lang/clash-compiler/pull/3499)+- The VHDL backend now generates valid VHDL for entities without ports, such as a top entity whose ports are all zero-width. This can be helpful when creating self-contained VHDL test benches.+  [#3500](https://github.com/clash-lang/clash-compiler/pull/3500)+- Clash's evaluator no longer produces an `SNat` newtype constructor when evaluating `withSomeSNat`.+  [#3491](https://github.com/clash-lang/clash-compiler/pull/3491)+- Clash no longer crashes on `iterateI` with functions such as `map f` or `resize`.+  [#3495](https://github.com/clash-lang/clash-compiler/issues/3495)+- Constant `BitVector` indices in Verilog and SystemVerilog are now rendered as plain integers, avoiding `64'sd` prefixes that caused warnings in tools such as Verilator.+  [#3056](https://github.com/clash-lang/clash-compiler/issues/3056)+- Clash no longer duplicates components whose result is projected out of more than once.+  [#3517](https://github.com/clash-lang/clash-compiler/issues/3517) [#3519](https://github.com/clash-lang/clash-compiler/pull/3519)+- Clash no longer duplicates components when applying a primitive to another instantiation of a primitive in certain situations.+  [#3516](https://github.com/clash-lang/clash-compiler/issues/3516) [#3518](https://github.com/clash-lang/clash-compiler/pull/3518)+- Clash now reports a clear error for functions returning a non-representable type that it can't inline away.+  [#3521](https://github.com/clash-lang/clash-compiler/issues/3521)+- Generating Verilog or SystemVerilog for `BitVector` indexing now uses the built-in blackbox function directly, avoiding unnecessary interpreter sessions that slowed compilation and could crash the compiler.+  [#3522](https://github.com/clash-lang/clash-compiler/pull/3522)+ ## 1.10.3 - *14 Oct, 2026*  ### Added:
clash-lib.cabal view
@@ -1,6 +1,6 @@ Cabal-version:        2.2 Name:                 clash-lib-Version:              1.10.3+Version:              1.10.4 Synopsis:             Clash: a functional hardware description language - As a library Description:   Clash is a functional hardware description language that borrows both its@@ -150,13 +150,13 @@                       aeson-pretty            >= 0.8      && < 0.9,                       ansi-terminal           >= 0.8.0.0  && < 1.2,                       array,-                      async                   >= 2.2.0    && < 2.3,+                      async                   >= 2.2.5    && < 2.3,                       attoparsec              >= 0.10.4.0 && < 0.15,                       base                    >= 4.18     && < 5,                       base16-bytestring       >= 0.1.1    && < 1.1,                       binary                  >= 0.8.5    && < 0.11,                       bytestring              >= 0.10.0.2 && < 0.13,-                      clash-prelude           == 1.10.3,+                      clash-prelude           == 1.10.4,                       containers              >= 0.6.7    && < 0.9,                       cryptohash-sha256       >= 0.11     && < 0.12,                       data-default            >= 0.7      && < 0.9,@@ -291,6 +291,7 @@                       Clash.Primitives.GHC.Word                       Clash.Primitives.Intel.ClockGen                       Clash.Primitives.Magic+                      Clash.Primitives.Sized.BitVector                       Clash.Primitives.Sized.ToInteger                       Clash.Primitives.Sized.Signed                       Clash.Primitives.Sized.Vector@@ -307,6 +308,7 @@                       Clash.Unique                       Clash.Util                       Clash.Util.Eq+                      Clash.Util.Exception                       Clash.Util.Graph                       Clash.Util.Interpolate                       Clash.Util.Supply@@ -437,8 +439,10 @@                  Clash.Tests.Core.Subst                  Clash.Tests.Core.TermLiteral                  Clash.Tests.Core.TermLiteral.Types+                 Clash.Tests.Core.Util                  Clash.Tests.Driver.Manifest                  Clash.Tests.Netlist.Id+                 Clash.Tests.Util.Exception                  Clash.Tests.Util.Interpolate                  Clash.Tests.Normalize.Transformations                  Clash.Tests.Rewrite.StrategyDSL
prims/commonverilog/Clash_Sized_Internal_BitVector.primitives.yaml view
@@ -178,15 +178,10 @@       m => BitVector n -> BitVector m -> BitVector (n + m)'     template: ~IF~AND[~SIZE[~TYP[1]],~SIZE[~TYP[2]]]~THEN{~ARG[1],~ARG[2]}~ELSE~IF~SIZE[~TYP[1]]~THEN~ARG[1]~ELSE~ARG[2]~FI~FI     workInfo: Never-- BlackBox:+- BlackBoxHaskell:     name: Clash.Sized.Internal.BitVector.index#-    kind: Expression-    type: |--      index# :: KnownNat n  -- ARG[0]-              => BitVector n -- ARG[1]-              -> Int         -- ARG[2]-              -> Bit-    template: ~VAR[bv][1][~ARG[2]]+    type: 'index# :: KnownNat n => BitVector n -> Int -> Bit'+    templateFunction: Clash.Primitives.Sized.BitVector.indexBitVectorCV - BlackBox:     name: Clash.Sized.Internal.BitVector.slice#     kind: Expression
prims/verilog/Clash_Sized_Vector.primitives.yaml view
@@ -212,6 +212,7 @@     workInfo: Never - BlackBoxHaskell:     name: Clash.Sized.Vector.index_int+    type: 'index_int :: KnownNat n => Vec n a -> Int -> a'     templateFunction: Clash.Primitives.Sized.Vector.indexIntVerilog - BlackBox:     name: Clash.Sized.Vector.replace_int
src/Clash/Backend/SystemVerilog.hs view
@@ -1,7 +1,7 @@ {-|   Copyright   :  (C) 2015-2016, University of Twente,                      2017-2018, Google Inc.,-                     2021-2024, QBayLogic B.V.,+                     2021-2026, QBayLogic B.V.,                      2022     , Google Inc.   License     :  BSD2 (see the file LICENSE)   Maintainer  :  QBayLogic B.V. <devops@qbaylogic.com>@@ -64,6 +64,8 @@ import           Clash.Netlist.BlackBox.Util   (extractLiterals, renderBlackBox, addFilePath) import qualified Clash.Netlist.Id                     as Id+import qualified Clash.Netlist.Id.SystemVerilog       as SystemVerilog+import qualified Clash.Netlist.Id.Verilog             as Verilog import           Clash.Netlist.Types                  hiding (intWidth, usages, _usages) import           Clash.Netlist.Util import           Clash.Signal.Internal                (ActiveEdge (..))@@ -397,7 +399,7 @@         Nothing -> pure Nothing         Just y' -> Just A.<$> (pure y' <+> x <> semi)     tName    = tyName ty-    selNames = map (\i -> tName <> "_sel" <> int i) [0..]+    selNames = map (verilogRecSel ty) [0..]  tyDec _ = pure Nothing @@ -689,12 +691,31 @@     Just Nothing  -> int (typeSize ty) <> "'d0 /* undefined */"     Just (Just x) -> braces (int (typeSize ty) <+> braces ("1'b" <> int x)) <+> "/* undefined */" +-- | Use record labels directly when all are valid SystemVerilog identifiers.+-- Otherwise use @Type_selN_sanitizedLabel@, or @Type_selN@ without a label. verilogRecSel   :: HWType   -> Int   -> SystemVerilogM Doc-verilogRecSel ty i = tyName ty <> "_sel" <> int i+verilogRecSel ty i = case ty of+  Product _ (Just labels) _+    | all SystemVerilog.parseBasic labels+    , (l:_) <- drop i labels+    -> PP.pretty l+    | (l:_) <- drop i labels+    , not (TextS.null l)+    -> byIndex <> "_" <> PP.pretty (TextS.map sanitize l)+  _ -> byIndex+ where+  byIndex = tyName ty <> "_sel" <> int i +  -- Haskell field names may contain characters that aren't allowed in+  -- (unescaped) SystemVerilog identifiers, such as @'@. The field index in the+  -- name keeps fields unique after replacing those.+  sanitize c+    | Verilog.isBasicChar c = c+    | otherwise = '_'+ decls :: [Declaration] -> SystemVerilogM Doc decls [] = emptyDoc decls ds = do@@ -788,6 +809,13 @@ patMod hwTy (NumLit i) = NumLit (i `mod` (2 ^ typeSize hwTy)) patMod _ l = l +-- | Comment saying which constructor an alternative of a case statement+-- matches, see 'literalToConName'.+conComment :: HWType -> Maybe Literal -> SystemVerilogM Doc+conComment ty lit = case lit >>= literalToConName ty of+  Just con -> " //" <+> stringS con+  Nothing -> emptyDoc+ -- | Helper function for inst_, handling CustomSP and CustomSum inst_' :: Identifier -> Expr -> HWType -> [(Maybe Literal, Expr)] -> SystemVerilogM (Maybe Doc) inst_' id_ scrut scrutTy es = fmap Just $@@ -804,10 +832,10 @@        conds :: [(Maybe Literal,Expr)] -> SystemVerilogM Doc       conds []                = error $ $(curLoc) ++ "Empty list of conditions invalid."-      conds [(_,e)]           = "default" <+> ":" <+> pretty id_ <+> "=" <+> expr_ False e <> ";"+      conds [(c,e)]           = "default" <+> ":" <+> pretty id_ <+> "=" <+> expr_ False e <> ";" <> conComment scrutTy c       conds ((Nothing,e):_)   = "default" <+> ":" <+> pretty id_ <+> "=" <+> expr_ False e <> ";"       conds ((Just c ,e):es') =-        mask' <+> ":" <+> pretty id_ <+> "=" <+> expr_ False e <> ";" <> line <> conds es'+        mask' <+> ":" <+> pretty id_ <+> "=" <+> expr_ False e <> ";" <> conComment scrutTy (Just c) <> line <> conds es'           where             mask' = patLitCustom scrutTy c @@ -863,23 +891,23 @@            ; verilogType ty <+> pretty regId <> semi <> line <>              "always_comb begin" <> line <>              indent 2 ("case" <> parens (expr_ True scrut) <> line <>-                         (indent 2 $ vcat $ punctuate semi (conds regId es)) <> semi <> line <>+                         (indent 2 $ vcat $ conds regId es) <> line <>                        "endcase") <> line <>              "end" <> line <>              "assign" <+> pretty id_ <+> equals <+> pretty regId <> semi            }          else "always_comb begin" <> line <>               indent 2 ("case" <> parens (expr_ True scrut) <> line <>-                          (indent 2 $ vcat $ punctuate semi (conds id_ es)) <> semi <> line <>+                          (indent 2 $ vcat $ conds id_ es) <> line <>                         "endcase") <> line <>               "end"     }   where     conds :: Identifier -> [(Maybe Literal,Expr)] -> SystemVerilogM [Doc]     conds _ []                = return []-    conds i [(_,e)]           = ("default" <+> colon <+> pretty i <+> equals <+> expr_ False e) <:> return []-    conds i ((Nothing,e):_)   = ("default" <+> colon <+> pretty i <+> equals <+> expr_ False e) <:> return []-    conds i ((Just c ,e):es') = (exprLitSV (Just (scrutTy,conSize scrutTy)) c <+> colon <+> pretty i <+> equals <+> expr_ False e) <:> conds i es'+    conds i [(c,e)]           = ("default" <+> colon <+> pretty i <+> equals <+> expr_ False e <> semi <> conComment scrutTy c) <:> return []+    conds i ((Nothing,e):_)   = ("default" <+> colon <+> pretty i <+> equals <+> expr_ False e <> semi) <:> return []+    conds i ((Just c ,e):es') = (exprLitSV (Just (scrutTy,conSize scrutTy)) c <+> colon <+> pretty i <+> equals <+> expr_ False e <> semi <> conComment scrutTy (Just c)) <:> conds i es'  inst_ (InstDecl _ _ attrs nm lbl ps pms0) = fmap Just $     attrs' <> nest 2 (pretty nm <> params <> pretty lbl <> line <> pms2 <> semi)@@ -981,8 +1009,8 @@         conds :: [(Maybe Literal,[Seq])] -> SystemVerilogM [Doc]         conds [] =           return []-        conds [(_,sq)] =-          ("default" <+> colon <+> "begin" <> line <>+        conds [(c,sq)] =+          ("default" <+> colon <+> "begin" <> conComment scrutTy c <> line <>             indent 2 (seqs sq) <> line <>           "end") <:> return []         conds ((Nothing,sq):_) =@@ -990,7 +1018,7 @@             indent 2 (seqs sq) <> line <>           "end") <:> return []         conds ((Just c ,sq):es') =-          (exprLitSV (Just (scrutTy,conSize scrutTy)) c <+> colon <+> "begin" <> line <>+          (exprLitSV (Just (scrutTy,conSize scrutTy)) c <+> colon <+> "begin" <> conComment scrutTy (Just c) <> line <>             indent 2 (seqs sq) <> line <>           "end") <:> conds es' @@ -1054,7 +1082,7 @@     end      = start - argSize + 1  expr_ _ (Identifier id_ (Just (Indexed (ty@(Product _ _ tys),_,fI)))) = do-  id'<- fmap (Text.toStrict . renderOneLine) (pretty id_ <> dot <> tyName ty <> "_sel" <> int fI)+  id'<- fmap (Text.toStrict . renderOneLine) (pretty id_ <> dot <> verilogRecSel ty fI)   simpleFromSLV (tys !! fI) id'  expr_ _ (Identifier id_ (Just (Indexed ((Vector _ elTy),1,0)))) = do
src/Clash/Backend/VHDL.hs view
@@ -948,7 +948,7 @@     rec (p,ls) <- fmap unzip (ports (maximum ls))     "entity" <+> pretty (componentName c) <+> "is" <> line <>       (case p of-         [] -> emptyDoc+         [] -> "end" <> semi          _  -> case syn of           -- See: [Note] Hack entity attributes in architecture           Other -> indent 2 (rports p <> if null attrs then emptyDoc else@@ -1526,6 +1526,25 @@     Just doc -> pure doc <> line <> line <> insts ds     _ -> insts ds +-- | Comment saying which constructor an alternative of a conditional+-- assignment matches, see 'literalToConName'. Patterns of enumerations+-- already mention the constructor, unless the alternative is rendered as+-- @others@.+conComment ::+  -- | Whether the alternative is rendered as @others@+  Bool ->+  HWType ->+  Maybe Literal ->+  VHDLM Doc+conComment isOthers ty lit = do+  RenderEnums enums <- Ap renderEnums+  case lit >>= literalToConName ty of+    Just con | isOthers || not (enums && isSum ty) -> " --" <+> pretty con+    _ -> emptyDoc+ where+  isSum Sum{} = True+  isSum _ = False+ -- | Helper function for inst_, handling CustomSP and CustomSum inst_'   :: Identifier@@ -1534,7 +1553,7 @@   -> [(Maybe Literal, Expr)]   -> VHDLM (Maybe Doc) inst_' id_ scrut scrutTy es = fmap Just $-  (pretty id_ <+> larrow <+> align (vcat (conds esNub) <> semi))+  (pretty id_ <+> larrow <+> align (vcat (conds esNub)))     where       esMod = map (first (fmap (patMod scrutTy))) es       esNub = nubBy ((==) `on` fst) esMod@@ -1542,11 +1561,12 @@        conds :: [(Maybe Literal,Expr)] -> VHDLM [Doc]       conds []                = return []-      conds [(_,e)]           = expr_ False e <:> return []-      conds ((Nothing,e):_)   = expr_ False e <:> return []+      conds [(c,e)]           = expr_ False e <> semi <> conComment True scrutTy c <:> return []+      conds ((Nothing,e):_)   = expr_ False e <> semi <:> return []       conds ((Just c ,e):es') = expr_ False e <+> "when"                                               <+> patLitCustom var scrutTy c                                               <+> "else"+                                              <> conComment False scrutTy (Just c)                                               <:> conds es'  -- | Turn a Netlist Declaration to a VHDL concurrent block@@ -1574,32 +1594,39 @@  inst_ (CondAssignment id_ _sig scrut scrutTy es) = fmap Just $     "with" <+> parens (expr_ True scrut) <+> "select" <> line <>-      indent 2 (pretty id_ <+> larrow <+> align (vcat (punctuate comma (conds esNub)) <> semi))+      indent 2 (pretty id_ <+> larrow <+> align (vcat (conds esNub)))   where     esMod = map (first (fmap (patMod scrutTy))) es     esNub = nubBy ((==) `on` fst) esMod      conds :: [(Maybe Literal,Expr)] -> VHDLM [Doc]     conds []                = return []-    conds [(_,e)]           = expr_ False e <+> "when" <+> "others" <:> return []-    conds ((Nothing,e):_)   = expr_ False e <+> "when" <+> "others" <:> return []-    conds ((Just c ,e):es') = expr_ False e <+> "when" <+> patLit scrutTy c <:> conds es'+    conds [(c,e)]           = expr_ False e <+> "when" <+> "others" <> semi <> conComment True scrutTy c <:> return []+    conds ((Nothing,e):_)   = expr_ False e <+> "when" <+> "others" <> semi <:> return []+    conds ((Just c ,e):es') = expr_ False e <+> "when" <+> patLit scrutTy c <> comma <> conComment False scrutTy (Just c) <:> conds es'  inst_ (InstDecl entOrComp libM _ nm lbl gens pms0) = do     maybe (return ()) (\lib -> Ap (libraries %= (T.fromStrict lib:))) libM     fmap Just $       nest 2 $ pretty lbl <+> colon <> entOrComp'-                <+> maybe emptyDoc ((<> ".") . pretty) libM <> pretty nm <> line <> gms <> pms2 <> semi+                <+> maybe emptyDoc ((<> ".") . pretty) libM <> pretty nm <> gms <> pms2 <> semi   where     gms | [] <- gens = emptyDoc         | otherwise =  do       rec (p,ls) <- fmap unzip $ sequence [ (,formalLength i) <$> fill (maximum ls) (expr_ False i) <+> "=>" <+> expr_ False e | (i,_,e) <- gens]-      nest 2 ("generic map" <> line <> tupled (pure p)) <> line-    pms2 = do+      line <> nest 2 ("generic map" <> line <> tupled (pure p))+    -- VHDL does not allow an empty port map, so omit it for an entity without+    -- ports+    pms2 | noPorts = emptyDoc+         | otherwise = do       rec (p,ls) <- case pms0 of                       NamedPortMap pms1 -> fmap unzip $ sequence [pm ls i e | (i,_,_,e) <- pms1]                       IndexedPortMap pms1 -> fmap unzip $ sequence [pmi e | (_,_,e) <- pms1]-      nest 2 $ "port map" <> line <> tupled (pure p)+      line <> nest 2 ("port map" <> line <> tupled (pure p))++    noPorts = case pms0 of+      NamedPortMap pms1 -> null pms1+      IndexedPortMap pms1 -> null pms1      pm ls i e = (,formalLength i) <$> fill (maximum ls) (expr_ False i) <+> "=>" <+> expr_ False e     pmi e = (,0) <$> expr_ False e
src/Clash/Backend/Verilog.hs view
@@ -524,6 +524,13 @@ patMod hwTy (NumLit i) = NumLit (i `mod` (2 ^ typeSize hwTy)) patMod _ l = l +-- | Comment saying which constructor an alternative of a case statement+-- matches, see 'literalToConName'.+conComment :: HWType -> Maybe Literal -> VerilogM Doc+conComment ty lit = case lit >>= literalToConName ty of+  Just con -> " //" <+> stringS con+  Nothing -> emptyDoc+ -- | Helper function for inst_, handling CustomSP and CustomSum inst_'   :: TextS.Text@@ -547,10 +554,10 @@        conds :: [(Maybe Literal,Expr)] -> VerilogM Doc       conds []                = error $ $(curLoc) ++ "Empty list of conditions invalid."-      conds [(_,e)]           = "default" <+> ":" <+> stringS id_ <+> "=" <+> expr_ False e <> ";"+      conds [(c,e)]           = "default" <+> ":" <+> stringS id_ <+> "=" <+> expr_ False e <> ";" <> conComment scrutTy c       conds ((Nothing,e):_)   = "default" <+> ":" <+> stringS id_ <+> "=" <+> expr_ False e <> ";"       conds ((Just c ,e):es') =-        mask' <+> ":" <+> stringS id_ <+> "=" <+> expr_ False e <> ";" <> line <> conds es'+        mask' <+> ":" <+> stringS id_ <+> "=" <+> expr_ False e <> ";" <> conComment scrutTy (Just c) <> line <> conds es'           where             mask' = patLitCustom scrutTy c @@ -583,15 +590,15 @@ inst_ (CondAssignment id_ _ scrut scrutTy es) = fmap Just $     "always @(*) begin" <> line <>     indent 2 ("case" <> parens (expr_ True scrut) <> line <>-                (indent 2 $ vcat $ punctuate semi (conds (Id.toText id_) es)) <> semi <> line <>+                (indent 2 $ vcat $ conds (Id.toText id_) es) <> line <>               "endcase") <> line <>     "end"   where     conds :: IdentifierText -> [(Maybe Literal,Expr)] -> VerilogM [Doc]     conds _ []                = return []-    conds i [(_,e)]           = ("default" <+> colon <+> stringS i <+> equals <+> expr_ False e) <:> return []-    conds i ((Nothing,e):_)   = ("default" <+> colon <+> stringS i <+> equals <+> expr_ False e) <:> return []-    conds i ((Just c ,e):es') = (exprLitV (Just (scrutTy,conSize scrutTy)) c <+> colon <+> stringS i <+> equals <+> expr_ False e) <:> conds i es'+    conds i [(c,e)]           = ("default" <+> colon <+> stringS i <+> equals <+> expr_ False e <> semi <> conComment scrutTy c) <:> return []+    conds i ((Nothing,e):_)   = ("default" <+> colon <+> stringS i <+> equals <+> expr_ False e <> semi) <:> return []+    conds i ((Just c ,e):es') = (exprLitV (Just (scrutTy,conSize scrutTy)) c <+> colon <+> stringS i <+> equals <+> expr_ False e <> semi <> conComment scrutTy (Just c)) <:> conds i es'  inst_ (InstDecl _ _ attrs nm lbl ps pms0) = fmap Just $     attrs' <> nest 2 (pretty nm <> params <> pretty lbl <> line <> pms2 <> semi)@@ -651,8 +658,8 @@     conds :: [(Maybe Literal,[Seq])] -> VerilogM [Doc]     conds [] =       return []-    conds [(_,sq)] =-      ("default" <+> colon <+> "begin" <> line <>+    conds [(c,sq)] =+      ("default" <+> colon <+> "begin" <> conComment scrutTy c <> line <>         indent 2 (seqs sq) <> line <>       "end") <:> return []     conds ((Nothing,sq):_) =@@ -660,7 +667,7 @@         indent 2 (seqs sq) <> line <>       "end") <:> return []     conds ((Just c ,sq):es') =-      (exprLitV (Just (scrutTy,conSize scrutTy)) c <+> colon <+> "begin" <> line <>+      (exprLitV (Just (scrutTy,conSize scrutTy)) c <+> colon <+> "begin" <> conComment scrutTy (Just c) <> line <>         indent 2 (seqs sq) <> line <>       "end") <:> conds es' 
src/Clash/Core/Name.hs view
@@ -1,5 +1,6 @@ {-|-  Copyright   :  (C) 2017, Google Inc.+  Copyright   :  (C) 2017, Google Inc.,+                     2026, QBayLogic B.V.   License     :  BSD2 (see the file LICENSE)   Maintainer  :  Christiaan Baaij <christiaan.baaij@gmail.com> @@ -20,9 +21,11 @@  import           Control.DeepSeq                        (NFData) import           Data.Binary                            (Binary)+import           Data.Char                              (isAlpha, isAlphaNum) import           Data.Function                          (on) import           Data.Hashable                          (Hashable (..)) import           Data.Text                              (Text, append)+import qualified Data.Text                              as Text import           GHC.BasicTypes.Extra                   () import           GHC.Generics                           (Generic) import           GHC.SrcLoc.Extra                       ()@@ -75,6 +78,20 @@   setUnique nm u = nm {nameUniq=u}  type OccName = Text++-- | Drop the module qualification of a name, e.g. @Clash.Sized.Vector.Cons@+-- becomes @Cons@.+unqualifiedOcc :: OccName -> OccName+unqualifiedOcc = snd . Text.breakOnEnd "."++-- | Whether text is a plain (Haskell) identifier, i.e., not an operator. These+-- can be used as (part of) names in HDL.+isIdentifierText :: Text -> Bool+isIdentifierText t = case Text.uncons t of+  Just (c, _) -> (isAlpha c || c == '_') && Text.all isIdChar t+  Nothing -> False+ where+  isIdChar c = isAlphaNum c || c == '_' || c == '\''  data NameSort   = User
src/Clash/Core/Util.hs view
@@ -1,6 +1,6 @@ {-|   Copyright   :  (C) 2012-2016, University of Twente,-                     2021-2024, QBayLogic B.V.,+                     2021-2026, QBayLogic B.V.,                      2022     , Google Inc.   License     :  BSD2 (see the file LICENSE)   Maintainer  :  QBayLogic B.V. <devops@qbaylogic.com>@@ -24,7 +24,7 @@ import Data.Bifunctor                          (first, second) import qualified Data.HashSet                  as HashSet import qualified Data.Graph                    as Graph-import Data.List                               (mapAccumR, uncons)+import Data.List                               (mapAccumL, mapAccumR, uncons) import Data.List.Extra                         (zipEqual) import Data.List.NonEmpty                      (NonEmpty (..), toList) import Data.Maybe@@ -62,6 +62,62 @@  import {-# SOURCE #-} qualified Clash.Normalize.Primitives as Primitives import Clash.XException (errorX)++-- | Change the names of variables, both at their binding sites and at the+-- occurrences referring to them, to the names of the variables with the same+-- unique in the given environment. Only the 'varName' of a variable changes,+-- its type and unique stay the same.+--+-- A binder with the same unique as a renamed binder it's in the scope of+-- shadows it, so it keeps its name, as do the occurrences referring to it. In:+--+-- > let x = 5 in (\x -> x + 1) x+--+-- where both binders of @x@ have the same unique, only the let-bound @x@ and+-- the @x@ the lambda is applied to are renamed. Occurrences of variables that+-- aren't bound in the term keep their names, so that they keep matching their+-- binding sites outside of it.+renameIds :: VarEnv Id -> Term -> Term+renameIds renames = go emptyVarEnv+ where+  -- 'env' holds the renames of the binders we're in the scope of+  go env tm = case tm of+    Var v -> Var (maybe v (rename v) (lookupVarEnv v env))+    Lam v e ->+      let (env1, v1) = bndr env v+       in Lam v1 (go env1 e)+    TyLam tv e -> TyLam tv (go env e)+    App f a -> App (go env f) (go env a)+    TyApp e ty -> TyApp (go env e) ty+    Let (NonRec v e) b ->+      let (env1, v1) = bndr env v+       in Let (NonRec v1 (go env e)) (go env1 b)+    Let (Rec bs) b ->+      let (env1, vs1) = mapAccumL bndr env (map fst bs)+       in Let (Rec (zip vs1 (map (go env1 . snd) bs))) (go env1 b)+    Case subj ty alts -> Case (go env subj) ty (map (goAlt env) alts)+    Cast e ty1 ty2 -> Cast (go env e) ty1 ty2+    Tick t e -> Tick (goTick env t) (go env e)+    Data{} -> tm+    Literal{} -> tm+    Prim{} -> tm++  bndr env v+    -- A binder shadowing a renamed binder keeps its name. Map it to itself, so+    -- that binders with the same unique in its scope shadow it too.+    | v `elemVarEnv` env = (extendVarEnv v v env, v)+    | Just v1 <- lookupVarEnv v renames = (extendVarEnv v v1 env, rename v v1)+    | otherwise = (env, v)++  rename v v1 = v {varName = varName v1}++  goAlt env (DataPat dc tvs ids, e) =+    let (env1, ids1) = mapAccumL bndr env ids+     in (DataPat dc tvs ids1, go env1 e)+  goAlt env (p, e) = (p, go env e)++  goTick env (Attributes ty e) = Attributes ty (go env e)+  goTick _ t = t  -- | Rebuild a let expression / let expressions by taking the SCCs of a list -- of bindings and remaking Let (NonRec ...) ... and Let (Rec ...) ...
src/Clash/Driver.hs view
@@ -24,7 +24,6 @@ module Clash.Driver where  import           Control.Concurrent               (MVar, modifyMVar, modifyMVar_, newMVar, withMVar)-import           Control.Concurrent.Async         (mapConcurrently_) import           Control.DeepSeq import           Control.Exception                (evaluate, throw, Exception) import qualified Control.Monad                    as Monad@@ -126,6 +125,7 @@ import           Clash.Normalize                  (checkNonRecursive, cleanupGraph,                                                    normalize, runNormalization) import           Clash.Normalize.Util             (callGraph, tvSubstWithTyEq)+import qualified Clash.Primitives.Sized.BitVector as P import qualified Clash.Primitives.Sized.Signed    as P import qualified Clash.Primitives.Sized.ToInteger as P import qualified Clash.Primitives.Sized.Vector    as P@@ -141,6 +141,7 @@ import           Clash.Util   (ClashException(..), reportTimeDiff,    wantedLanguageExtensions, unwantedLanguageExtensions, curLoc)+import           Clash.Util.Exception             (mapConcurrentlyWithBacktrace_) import           Clash.Util.Graph                 (reverseTopSort) import qualified Clash.Util.Interpolate           as I import qualified Clash.Util.Supply                as Supply@@ -349,7 +350,7 @@      let       maybeMapConcurrently_-        | opt_concurrentTopEntities opts = mapConcurrently_+        | opt_concurrentTopEntities opts = mapConcurrentlyWithBacktrace_         | otherwise = mapM_      maybeMapConcurrently_ (go compNames idSet edamFiles ioLock deps topEntityMap) tes@@ -701,6 +702,7 @@     , ('P.bvToIntegerVerilog, P.bvToIntegerVerilog)     , ('P.clashCompileErrorBBF, P.clashCompileErrorBBF)     , ('P.foldBBF, P.foldBBF)+    , ('P.indexBitVectorCV, P.indexBitVectorCV)     , ('P.indexIntVerilog, P.indexIntVerilog)     , ('P.indexToIntegerVerilog, P.indexToIntegerVerilog)     , ('P.indexToIntegerVHDL, P.indexToIntegerVHDL)
src/Clash/Netlist.hs view
@@ -58,7 +58,7 @@ import           Clash.Core.DataCon               (DataCon (..)) import           Clash.Core.HasType import           Clash.Core.Literal               (Literal (..))-import           Clash.Core.Name                  (Name(..))+import           Clash.Core.Name                  (Name(..), isIdentifierText) import           Clash.Core.Pretty                (showPpr) import           Clash.Core.Term   (IsMultiPrim (..), PrimInfo (..), mpi_resultTypes,  Alt, Pat (..), Term (..),@@ -981,9 +981,22 @@                ++ "Not in normal form: Unexpected pattern in case-projection:\n\n"                ++ showPpr e) Nothing)       let extractExpr = Identifier (maybe altVarId (const selId) modifier) modifier+          -- The record field the projection selects, if any+          fieldLabel = case pat of+            DataPat dc _ tms+              | Just i <- elemIndex varTm tms+              , (label:_) <- drop i (dcFieldLabels dc)+              , isIdentifierText label+              -> Just label+            _ -> Nothing       case bndr of         NetlistId scrutNm _ | mkDec -> do-          scrutNm' <- Id.next scrutNm+          -- Name a signal holding a record field after the signal it's+          -- projected out of and the field, e.g. @s_mode@ for the field+          -- @mode@ of a signal @s@+          scrutNm' <- case (modifier, fieldLabel) of+            (Just _, Just label) -> Id.suffix selId label+            _ -> Id.next scrutNm           scrutDecl <- mkInit declType assignTy scrutNm' vHwTy extractExpr           return (Identifier scrutNm' Nothing, scrutDecl ++ decls)         MultiId {} -> error "mkProjection: MultiId"
src/Clash/Netlist/BlackBox.hs view
@@ -90,7 +90,7 @@ import           Clash.Core.Util   (inverseTopSortLetBindings, splitShouldSplit) import           Clash.Core.Var                as V-  (Id, mkLocalId, modifyVarName, varType)+  (Id, isGlobalId, mkLocalId, modifyVarName, varType) import           Clash.Core.VarEnv   (extendInScopeSet, mkInScopeSet, lookupVarEnv, uniqAway, unitVarSet) import {-# SOURCE #-} Clash.Netlist@@ -1225,7 +1225,9 @@                                             ++ " This is a bug in Clash.")                  _ -> error $ $(curLoc) ++ "Cannot make function input for: " ++ showPpr e-            C.Var fun -> do+            -- A local variable can share its unique with a global binder, so+            -- check it's a global before looking it up by its unique+            C.Var fun | isGlobalId fun -> do               topAnns <- Lens.use topEntityAnns               case lookupVarEnv fun topAnns of                 Just _ ->
src/Clash/Netlist/Util.hs view
@@ -86,7 +86,7 @@ import           Clash.Core.HasType import qualified Clash.Core.Literal      as C import           Clash.Core.Name-  (Name (..), appendToName, mkUnsafeSystemName, nameOcc)+  (Name (..), appendToName, mkUnsafeSystemName, nameOcc, unqualifiedOcc) import           Clash.Core.PartialEval import           Clash.Core.Pretty       (showPpr) import           Clash.Core.Subst@@ -1086,6 +1086,22 @@ dcToLiteral Bool 1 = BoolLit False dcToLiteral Bool 2 = BoolLit True dcToLiteral _ i    = NumLit (toInteger i-1)++-- | Name of the constructor matched by the given literal, the inverse of+-- 'dcToLiteral'. Used to mention in the HDL which constructor an alternative of+-- a case-expression on a value of the given type matches.+literalToConName :: HWType -> Literal -> Maybe Text+literalToConName ty lit = case (ty, lit) of+  (Annotated _ ty1, _) -> literalToConName ty1 lit+  (Sum _ cons, NumLit i) -> unqualifiedOcc <$> index cons i+  (SP _ cons, NumLit i) -> unqualifiedOcc . fst <$> index cons i+  (CustomSum _ _ _ cons, NumLit i) -> unqualifiedOcc . snd <$> index cons i+  (CustomSP _ _ _ cons, NumLit i) -> (\(_, c, _) -> unqualifiedOcc c) <$> index cons i+  _ -> Nothing+ where+  index xs i+    | i < 0 = Nothing+    | otherwise = listToMaybe (drop (fromInteger i) xs)  -- * TopEntity Annotations 
src/Clash/Normalize.hs view
@@ -24,13 +24,14 @@ import           Control.Monad.IO.Class           (liftIO) import           Control.Monad.State.Strict       (State) import           Data.Default                     (def)-import           Data.Either                      (lefts,partitionEithers)+import           Data.Either                      (lefts,partitionEithers,rights) import qualified Data.IntMap                      as IntMap import qualified Data.IORef                       as IORef import           Clash.Data.UniqMap               (UniqMap) import qualified Clash.Data.UniqMap               as UniqMap import           Data.List   (intersect, mapAccumL)+import qualified Data.List                        as List import qualified Data.HashMap.Strict              as HashMap import qualified Data.Map                         as Map import qualified Data.Maybe                       as Maybe@@ -44,6 +45,7 @@ #endif  import           GHC.BasicTypes.Extra             (isNoInline)+import           GHC.Types.SrcLoc                 (isGoodSrcSpan)  import           Clash.Annotations.BitRepresentation.Internal   (CustomReprs)@@ -56,14 +58,17 @@ import           Clash.Core.Pretty                (PrettyOptions(..), showPpr, showPpr', ppr) import           Clash.Core.Subst   (extendGblSubstList, mkSubst, substTm)-import           Clash.Core.Term                  (Term (..), collectArgsTicks-                                                  ,mkApps, mkTicks)+import           Clash.Core.Name                  (Name (..), NameSort (..))+import           Clash.Core.Term+  (Term (..), collectArgs, collectArgsTicks, collectBndrs, mkApps, mkTicks,+   walkTerm) import           Clash.Core.Type                  (Type, splitCoreFunForallTy)+import           Clash.Core.Util                  (renameIds) import           Clash.Core.TyCon (TyConMap) import           Clash.Core.Type                  (isPolyTy)-import           Clash.Core.Var                   (Id, varName, varType)+import           Clash.Core.Var                   (Id, Var (..), isLocalId) import           Clash.Core.VarEnv-  (VarEnv, elemVarSet, eltsVarEnv, emptyInScopeSet, emptyVarEnv,+  (VarEnv, elemVarEnv, elemVarSet, eltsVarEnv, emptyInScopeSet, emptyVarEnv,    extendVarEnv, lookupVarEnv, mapVarEnv, mapMaybeVarEnv,    mkVarEnv, mkVarSet, notElemVarEnv, notElemVarSet, nullVarEnv, unionVarEnv) import           Clash.Debug                      (traceIf)@@ -200,7 +205,7 @@       -- check for unrepresentable result type       let (args,resTy) = splitCoreFunForallTy tcm ty1           isTopEnt = nm `elemVarSet` topEnts-          isFunction = not $ null $ lefts args+          isFunction = not $ null $ rights args       resTyRep <- not <$> isUntranslatableType False resTy       if resTyRep          then do@@ -221,7 +226,7 @@             -- Throw an error for unrepresentable topEntities and functions             when (isTopEnt || isFunction) $               let msg = $(curLoc) ++ [i|-                    This bndr has a non-representable return type and can't be normalized:+                    This binder has a non-representable return type and can't be normalized:                     #{showPpr' def{displayUniques=False\} nm'}                     |]               in throw (ClashException sp msg Nothing)@@ -273,6 +278,65 @@        return (mkVarEnv $ snd $ callTreeToList [] ctFlat) cleanupGraph _ norm = return norm +-- | Before inlining functions defined by the user, name variables made up by+-- GHC after the parameter of the function they are passed to. For example,+-- given:+--+-- > topEntity = \eta -> ... txStep s eta ...+-- > txStep = \s input -> ...+--+-- where GHC made up @eta@ when it eta-expanded @topEntity@, we rename @eta@ to+-- @input@. Once @txStep@ is inlined, @input@ would otherwise be gone from the+-- HDL. For top entities without a 'Clash.Annotations.TopEntity.Synthesize'+-- annotation this also names the ports.+--+-- Functions count as defined by the user when their binding has a source+-- location, i.e., when they were defined in a module compiled from source. We+-- don't take names from library functions: their parameters are often named+-- @x@ or @f@, which isn't an improvement over a name made up by GHC.+--+-- If a variable is passed to multiple user-defined functions, the first+-- application found determines its name.+nameArgsAfterParams ::+  -- | All bindings, used to find out which functions are defined by the user+  BindingMap ->+  -- | Functions that are about to be inlined, and their definitions+  [(Id, Term)] ->+  -- | Term the functions are inlined in+  Term ->+  Term+nameArgsAfterParams bndrs toInline tm+  | nullVarEnv renames = tm+  | otherwise = renameIds renames tm+ where+  userParams =+    mkVarEnv+      [ (f, lefts (fst (collectBndrs e)))+      | (f, e) <- toInline+      , Just b <- [lookupVarEnv f bndrs]+      , isGoodSrcSpan (bindingLoc b)+      ]++  renames = List.foldl' addRename emptyVarEnv (concat (walkTerm findArgs tm))++  addRename env (y, p)+    | y `elemVarEnv` env = env+    | otherwise = extendVarEnv y (rename y p) env++  findArgs t = case collectArgs t of+    (Var f, args) | Just params <- lookupVarEnv f userParams ->+      Just+        [ (y, p)+        | (Var y, p) <- zip (lefts args) params+        , isLocalId y+        , nameSort (varName y) == System+        , nameSort (varName p) == User+        ]+    _ -> Nothing++  rename y p =+    y {varName = (varName y) {nameOcc = nameOcc (varName p), nameSort = User}}+ -- | A tree of identifiers and their bindings, with branches containing -- additional bindings which are used. See "Clash.Driver.Types.Binding". --@@ -376,12 +440,14 @@   doFlatten = do    flattenedUsed   <- mapM (flattenCallTree cache) used    (newUsed,il_ct) <- partitionEithers <$> mapM flattenNode flattenedUsed+   bndrs <- Lens.use bindings    let (toInline,il_used) = unzip il_ct        subst = extendGblSubstList (mkSubst emptyInScopeSet) toInline    newExpr <- case toInline of      [] -> return tm      _  -> do-       let tm1 = substTm "flattenCallTree.flattenExpr" subst tm+       let tm0 = nameArgsAfterParams bndrs toInline tm+           tm1 = substTm "flattenCallTree.flattenExpr" subst tm0         -- NB: When -fclash-debug-history is on, emit binary data holding the recorded rewrite steps        opts <- Lens.view debugOpts
src/Clash/Normalize/Strategy/Spec.hs view
@@ -110,6 +110,7 @@       , caseLet       , caseCase       , caseCon+      , caseDataToTag       , elimExistentials       , caseEliminateNonReachable       , removeUnusedExpr
src/Clash/Normalize/Transformations/ANF.hs view
@@ -28,6 +28,7 @@ import Control.Monad.State (StateT, lift, modify, runStateT) import Control.Monad.Writer (listen) import Data.Bifunctor (second)+import Data.Either (lefts) import qualified Data.Monoid as Monoid (Any(..)) import qualified Data.Text.Extra as Text (showt) import GHC.Exts (State#)@@ -58,7 +59,7 @@ import Clash.Rewrite.Types   (Transform, TransformContext(..), tcCache) import Clash.Rewrite.Util-  (changed, isUntranslatable, mkDerivedName, mkTmBinderFor)+  (changed, isUntranslatable, mkAltName, mkArgName, mkDerivedName, mkTmBinderFor) import Clash.Rewrite.WorkFree (isConstant, isConstantNotClockReset) import Clash.Util (curLoc) @@ -258,7 +259,7 @@ --    depends on IO actions to be propagated down as far as possible. collectANF :: HasCallStack => NormRewriteW collectANF ctx e@(App appf arg)-  | (conVarPrim, _) <- collectArgs e+  | (conVarPrim, args) <- collectArgs e   , isCon conVarPrim || isPrim conVarPrim || isVar conVarPrim   = do     tcm <- Lens.view tcCache@@ -270,7 +271,8 @@       (False,False,False,_) -> do         -- See Note [ANF InScopeSet]         is1   <- Lens.use _2-        argId <- lift (mkTmBinderFor is1 tcm (mkDerivedName ctx "app_arg") arg)+        argNm <- lift (mkArgName ctx conVarPrim (length (lefts args) - 1))+        argId <- lift (mkTmBinderFor is1 tcm argNm arg)         -- See Note [ANF InScopeSet]         tellBinders [(argId,arg)]         return (App appf (Var argId))@@ -364,7 +366,7 @@           tcm <- Lens.view tcCache           -- See Note [ANF InScopeSet]           is1 <- Lens.use _2-          altId <- lift (mkTmBinderFor is1 tcm (mkDerivedName ctx "case_alt") altExpr)+          altId <- lift (mkTmBinderFor is1 tcm (mkAltName ctx (DataPat dc exts xs)) altExpr)           -- See Note [ANF InScopeSet]           tellBinders (patSels ++ [(altId,altExpr)])           return (DataPat dc exts xs,Var altId)@@ -379,7 +381,7 @@           tcm <- Lens.view tcCache           -- See Note [ANF InScopeSet]           is1 <- Lens.use _2-          altId <- lift (mkTmBinderFor is1 tcm (mkDerivedName ctx "case_alt") altExpr)+          altId <- lift (mkTmBinderFor is1 tcm (mkAltName ctx pat) altExpr)           tellBinders [(altId,altExpr)]           return (pat,Var altId) 
src/Clash/Normalize/Transformations/Case.hs view
@@ -17,11 +17,18 @@ {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TemplateHaskellQuotes #-} +-- 'dataToTagSmall#' and 'dataToTagLarge#' (used below in TH name quotes so that+-- Clash can match the primops by their canonical names across GHC versions) are+-- deprecated as of GHC 9.14 in favor of @dataToTag#@ from @GHC.Magic@.+{-# OPTIONS_GHC -Wno-deprecations #-}+ module Clash.Normalize.Transformations.Case   ( caseCase   , caseCaseWorker   , caseCon   , caseConWorker+  , caseDataToTag+  , caseDataToTagWorker   , caseEliminateNonReachable   , caseEliminateNonReachableWorker   , caseFlat@@ -49,6 +56,7 @@ import qualified Data.Primitive.ByteArray as BA import qualified Data.Text.Extra as Text (showt) import qualified GHC.Classes+import qualified GHC.Prim import GHC.Exts (Int(..)) import GHC.Stack (HasCallStack) @@ -70,13 +78,16 @@ import Clash.Core.Term   ( Alt, Pat(..), PrimInfo(..), Term(..), collectArgs, collectArgsTicks   , collectTicks, mkApps, mkTicks, patIds, stripTicks, Bind(..))-import Clash.Core.TyCon (TyConMap)-import Clash.Core.Type (LitTy(..), Type(..), TypeView(..), coreView1, tyView)+import Clash.Core.TyCon (TyConMap, tyConDataCons)+import Clash.Core.Type+  (LitTy(..), Type(..), TypeView(..), coreView, coreView1, tyView) import Clash.Core.TysPrim (integerIsDc, naturalNsDc)-import Clash.Core.Util (listToLets, mkInternalVar)+import Clash.Core.Util+  (dataConInstArgTysE, listToLets, mkInternalVar, mkWildValBinder) import Clash.Core.VarEnv   ( InScopeSet, elemVarSet, extendInScopeSet, extendInScopeSetList, mkVarSet   , unitVarSet, uniqAway)+import qualified Clash.Data.UniqMap as UniqMap import Clash.Debug (traceIf) import Clash.Driver.Types (DebugOpts(dbg_invariants)) import Clash.Netlist.Types (FilteredHWType(..), HWType(..))@@ -508,6 +519,77 @@     [] -> return case0     _  -> changed =<< caseOneAlt (Case scrut altsTy altsOther) {-# SCC caseEliminateNonReachableWorker #-}++-- | Turn a case-expression on the constructor tag of a value into a+-- case-expression on the value itself. For example, GHC derives '==' for+--+-- > data Mode = Idle | Counting | Done+--+-- by comparing the tags of the constructors, so that @mode == Done@ becomes:+--+-- > case dataToTag# mode of+-- >   2# -> True+-- >   _  -> False+--+-- which we rewrite to:+--+-- > case mode of+-- >   Done -> True+-- >   _    -> False+--+-- Without this, ANF binds the subject @dataToTag# mode@ to a new variable, so+-- the HDL holds the tag in a signal as wide as an 'Int', with a name like+-- @c$case_scrut@ that says nothing about the value it's the tag of.+-- After the rewrite, the HDL compares the value itself, and the alternatives of+-- the case-expression mention the constructors they match.+--+-- Fields of the matched constructors are bound to variables that the+-- alternatives don't reference.+caseDataToTag :: Transformation+caseDataToTag = toTransformation "caseDataToTag" (onCase 'caseDataToTagWorker)++-- | The 'Case' handler of 'caseDataToTag'.+caseDataToTagWorker ::+  HasCallStack =>+  TransformContext -> Term -> Term -> Type -> [Alt] -> NormalizeSession Term+caseDataToTagWorker (TransformContext is0 _) e subj ty alts = do+  tcm <- Lens.view tcCache+  case collectArgsTicks subj of+    (Prim pInfo, args, ticks)+      | primName pInfo `elem` dataToTagNames+      , [x] <- Either.lefts args+      , any (isLitPat . fst) alts+      , TyConApp tcNm tyArgs <- tyView (coreView tcm (inferCoreTypeOf tcm x))+      , Just tc <- UniqMap.lookup tcNm tcm+      , Just alts1 <- traverse (tagAlt tcm tyArgs (tyConDataCons tc)) alts+      -> do+        alts2 <- traverse (either pure conAlt) alts1+        changed (Case (mkTicks x ticks) ty alts2)+    _ -> return e+ where+#if MIN_VERSION_ghc(9,10,0)+  dataToTagNames =+    [Text.showt 'GHC.Prim.dataToTagSmall#, Text.showt 'GHC.Prim.dataToTagLarge#]+#else+  dataToTagNames = [Text.showt 'GHC.Prim.dataToTag#]+#endif++  isLitPat LitPat{} = True+  isLitPat _ = False++  -- The constructor an alternative matches and the types of its fields, or+  -- the alternative itself if it's the default alternative+  tagAlt _ _ _ alt@(DefaultPat, _) = Just (Left alt)+  tagAlt tcm tyArgs dcs (LitPat (IntLiteral i), altE) = do+    dc <- List.find ((== i) . toInteger . subtract 1 . dcTag) dcs+    fieldTys <- dataConInstArgTysE is0 tcm dc tyArgs+    Just (Right (dc, fieldTys, altE))+  tagAlt _ _ _ _ = Nothing++  conAlt (dc, fieldTys, altE) = do+    wilds <- mapM (mkWildValBinder is0) fieldTys+    pure (DataPat dc (dcExtTyVars dc) wilds, altE)+{-# SCC caseDataToTagWorker #-}  -- | Flatten ridiculous case-statements generated by GHC --
src/Clash/Normalize/Transformations/Inline.hs view
@@ -78,13 +78,13 @@ import Clash.Core.TermInfo (isLocalVar, termSizeSmallerThan) import Clash.Core.Type   (TypeView(..), isClassTy, isPolyFunCoreTy, tyView)-import Clash.Core.Util (isSignalType, primUCo)+import Clash.Core.Util (isSignalType, primUCo, renameIds) import Clash.Core.Var (Id, Var(..), isGlobalId, isLocalId) import Clash.Core.VarEnv   ( InScopeSet, VarEnv, VarSet, elemUniqInScopeSet, elemVarEnv, elemVarSet   , eltsVarEnv, emptyVarEnv, extendInScopeSetList, extendVarEnv-  , foldlWithUniqueVarEnv', lookupVarEnv, lookupVarEnvDirectly, mkVarEnv-  , notElemVarSet, unionVarEnv, unionVarEnvWith, unitVarSet)+  , foldlWithUniqueVarEnv', lookupVarEnv, lookupVarEnvDirectly, mkVarEnv, mkVarSet+  , notElemVarSet, nullVarEnv, unionVarEnv, unionVarEnvWith, unitVarSet) import Clash.Debug (trace) import Clash.Driver.Types (Binding(..)) import Clash.Primitives.Types@@ -126,6 +126,14 @@  -- | Inline let-bindings when the RHS is either a local variable reference or -- is constant (except clock or reset generators)+--+-- Inlining a local variable reference loses the name of its binder, even when+-- the user wrote it. For example, in @let b = a in ...@, where the user named+-- both @a@ and @b@, only @a@ ends up in the HDL. The same goes for a parameter+-- of an inlined function whose argument is a variable named by the user. We'd+-- like to keep such aliases, so that the HDL shows both names, e.g.+-- @assign b = a;@. However, keeping them would probably break constant+-- propagation, such as for the reset values of registers. bindConstantVar :: Transformation bindConstantVar =   toTransformation "bindConstantVar" (onLet 'bindConstantVarWorker)@@ -134,11 +142,43 @@ bindConstantVarWorker   :: HasCallStack   => TransformContext -> Term -> Bind Term -> Term -> NormalizeSession Term-bindConstantVarWorker = inlineBinders test+bindConstantVarWorker ctx node bind body+  | Term.Rec xes <- bind+  , renames <- userAliasRenames xes+  , not (nullVarEnv renames)+  = do+    -- See 'userAliasRenames'+    let node1 = renameIds renames node+    case node1 of+      Let bind1 body1 -> changed =<< inlineBinders test ctx node1 bind1 body1+      _ -> error "bindConstantVar: renaming changed the shape of a let-expression"+  | otherwise+  = inlineBinders test ctx node bind body   where+    TransformContext _ ctxFrames = ctx+    -- Variables bound by let-expressions enclosing this one+    enclosingLetBound = mkVarSet $ concat+      [ ids+      | frame <- ctxFrames+      , ids <- case frame of+          LetBinding _ siblings -> [siblings]+          LetBody bs -> [map fst bs]+          _ -> []+      ]+     test _ (i,stripTicks -> e) = case isLocalVar e of       -- Don't inline `let x = x in x`, it throws  us in an infinite loop-      True -> return (i `notElemFreeVars` e)+      True+        -- Don't inline a user-named alias of a compiler-named variable bound+        -- by an enclosing let-expression just yet: once 'flattenLet' has+        -- merged the let-expressions, 'userAliasRenames' can give the variable+        -- the user's name.+        | Var v <- e+        , nameSort (varName i) == User+        , nameSort (varName v) /= User+        , v `elemVarSet` enclosingLetBound+        -> return False+        | otherwise -> return (i `notElemFreeVars` e)       _    -> do         (fn,_) <- Lens.use curFun         -- Don't inline globally recursive calls, it prevents the@@ -156,6 +196,38 @@             _ -> return False {-# SCC bindConstantVarWorker #-} +-- | When 'bindConstantVar' inlines a user-named alias of a variable made up by+-- the compiler, e.g. @dSCL@ in:+--+-- > letrec+-- >   c$s_dSCL = register# ...+-- >   dSCL = c$s_dSCL+-- > in ...+--+-- the user's name would be lost. Instead, rename the variable to the user's+-- name first, so that we end up with:+--+-- > letrec+-- >   dSCL = register# ...+-- > in ...+--+-- We only rename variables bound in the same let-expression, as those are the+-- only binding sites we can see. When a variable has multiple user-named+-- aliases, the first one determines its name.+userAliasRenames :: [(Id, Term)] -> VarEnv Id+userAliasRenames xes =+  -- 'foldr', so that the first alias is inserted last and wins+  List.foldr (uncurry extendVarEnv) emptyVarEnv+  [ (v, v {varName = (varName v) {nameOcc = nameOcc (varName u), nameSort = User}})+  | (u, stripTicks -> Var v) <- xes+  , u /= v+  , nameSort (varName u) == User+  , nameSort (varName v) /= User+  , v `elemVarSet` bound+  ]+ where+  bound = mkVarSet (map fst xes)+ -- | Mark to track progress of 'reduceBindersCleanup' data Mark = Temp | Done | Rec @@ -382,7 +454,14 @@             -> True             | otherwise             -> primName pInfo `elem` ["Clash.Explicit.SimIO.bindSimIO#"]-          Case _ _ [_] -> True+          -- Projections out of a variable are work-free, so duplicating them+          -- is fine. Other subjects might do work, e.g. instantiate a+          -- component, so only inline those if they are used once.+          Case (stripTicks -> Var _) _ [_] -> True+          Case _ _ [_]+            | Just occ <- lookupVarEnv id_ allOccs+            , occ < 2+            -> True           Data _ -> True           Case _ aTy (_:_:_)             | TyConApp nm _ <- tyView aTy
src/Clash/Normalize/Transformations/Reduce.hs view
@@ -43,12 +43,13 @@   ( CoreContext(..), LetBinding, PrimInfo(..), Term(..), TickInfo(..)   , WorkInfo(..), collectArgs, collectArgsTicks, mkApps, mkTicks, mkTmApps) import Clash.Core.TyCon (TyCon(..), TyConMap, tyConDataCons)-import Clash.Core.Type (Type, TypeView(..), mkTyConApp, splitFunForallTy, tyView, coreView)+import Clash.Core.Type+  (Type, TypeView(..), mkTyConApp, splitFunForallTy, tyView, coreView, normalizeType) import Clash.Core.Util (mkVec, shouldSplit, tyNatSize, mkInternalVar) import Clash.Core.VarEnv (extendInScopeSet) import qualified Clash.Data.UniqMap as UniqMap import Clash.Normalize.PrimitiveReductions-import Clash.Normalize.Primitives (removedArg)+import Clash.Normalize.Transformations.Specialize (zeroWidthTypeElem) import Clash.Normalize.Types (NormalizeSession) import Clash.Normalize.Util (shouldReduce) import Clash.Rewrite.StrategyDSL (Transformation, onApp, toTransformation)@@ -736,28 +737,34 @@   | (tmArgs,[nTy,mTy]) <- Either.partitionEithers primArguments   = case (runExcept (tyNatSize tyConMap nTy), runExcept (tyNatSize tyConMap mTy), resultTypeView) of       (Right n, Right m, TyConApp tupTcNm [lTy,rTy])-        | n == 0 -> abstractOverMissingArgs primTicks tmArgs termType transformContext $+        -- XXX: This transformation is optimistic: it will return a defined value+        --      even if the input is a bottom, if one of its results is zero width.+        | n == 0+        , Just zeroWidthR <- zeroWidthTypeElem tyConMap (normalizeType tyConMap rTy)+        -> abstractOverMissingArgs primTicks tmArgs termType transformContext $             \(_kn :: Term) bvArg (_ctx :: TransformContext) -> do               let tup = mkApps (Data tupDc)                            [Right lTy                            ,Right rTy                            ,Left  bvArg-                           ,Left  (TyApp (Prim removedArg) rTy)+                           ,Left  zeroWidthR                            ]                (changed (mkTicks tup primTicks) :: NormalizeSession Term)-        | m == 0 -> abstractOverMissingArgs primTicks tmArgs termType transformContext $+        | m == 0+        , Just zeroWidthL <- zeroWidthTypeElem tyConMap (normalizeType tyConMap lTy)+        -> abstractOverMissingArgs primTicks tmArgs termType transformContext $             \(_kn :: Term) bvArg (_ctx :: TransformContext) -> do               let tup = mkApps (Data tupDc)                            [Right lTy                            ,Right rTy-                           ,Left  (TyApp (Prim removedArg) lTy)+                           ,Left  zeroWidthL                            ,Left  bvArg                            ]                (changed (mkTicks tup primTicks) :: NormalizeSession Term)        where-        tupDc = fromMaybe (error "reducePrim: faield to create tup DC") $ do+        tupDc = fromMaybe (error "reducePrim: failed to create tup DC") $ do                 tupTc <- UniqMap.lookup tupTcNm tyConMap                 listToMaybe (tyConDataCons tupTc)       _ -> return originalTerm
src/Clash/Normalize/Transformations/Specialize.hs view
@@ -30,6 +30,7 @@   , typeSpecWorker   , zeroWidthSpec   , zeroWidthSpecWorker+  , zeroWidthTypeElem   ) where  import Control.Arrow ((***), (&&&))
+ src/Clash/Primitives/Sized/BitVector.hs view
@@ -0,0 +1,37 @@+{-|+  Copyright   :  (C) 2026 QBayLogic B.V.+  License     :  BSD2 (see the file LICENSE)+  Maintainer  :  QBayLogic B.V. <devops@qbaylogic.com>++  Blackbox implementations for functions in "Clash.Sized.BitVector".+-}+{-# LANGUAGE OverloadedStrings #-}++module Clash.Primitives.Sized.BitVector (indexBitVectorCV) where++import Clash.Netlist.BlackBox (isLiteral)+import Clash.Netlist.BlackBox.Parser (runParse)+import Clash.Netlist.BlackBox.Types+  ( BlackBoxFunction+  , BlackBoxMeta (..)+  , TemplateKind (TExpr)+  , emptyBlackBoxMeta+  )+import Clash.Netlist.Types (BlackBox (BBTemplate))+import Text.Trifecta.Result (Result (Success))++-- index# :: KnownNat n => BitVector n -> Int -> Bit+indexBitVectorCV :: BlackBoxFunction+indexBitVectorCV _isD _primName args _ty =+  pure $ case runParse template of+    Success t -> Right (emptyBlackBoxMeta{bbKind = TExpr}, BBTemplate t)+    _ -> Left "indexBitVectorCV: could not parse index template"+ where+  -- Select the template before validation: a ~LIT inside a ~IF would also+  -- require a literal argument when that branch is not selected.+  template+    | [_nTy, _kn, _bv, Left ix] <- args+    , isLiteral ix+    = "~VAR[bv][1][~LIT[2]]"+    | otherwise+    = "~VAR[bv][1][~ARG[2]]"
src/Clash/Primitives/Sized/Vector.hs view
@@ -1,5 +1,5 @@ {-|-  Copyright   :  (C) 2020-2022 QBayLogic B.V.+  Copyright   :  (C) 2020-2026 QBayLogic B.V.                      2022     , Google Inc.   License     :  BSD2 (see the file LICENSE)   Maintainer  :  QBayLogic B.V. <devops@qbaylogic.com>@@ -89,7 +89,7 @@     , _hoFunction     , (a, aType)     ] <- tInputs bbCtx-  , let aTemplateType = [TypElem (Typ (Just 2))]+  , let aTemplateType = [Typ (Just 2)]   , let inst arg = instHO bbCtx 1 (aType, aTemplateType) [(arg, aTemplateType)]   = declarationReturn bbCtx "iterateI" (fmap pure . Prim.vec =<< iterateNM (fromInteger n) inst a)   | otherwise@@ -239,6 +239,7 @@ foldTF' args =   error $ "Unexpected number of arguments: " ++ show (length (bbInputs args)) +-- index_int :: KnownNat n => Vec n a -> Int -> a indexIntVerilog ::  BlackBoxFunction indexIntVerilog _isD _primName args _ty = return bb  where
src/Clash/Primitives/Util.hs view
@@ -243,6 +243,7 @@     -- primitives under index_int are fully unrolled.   fromIntForce     | nm == "Clash.Sized.Vector.index_int"                 = [2]+    | nm == "Clash.Sized.BitVector.index#"                 = [2]     | otherwise = [] constantArgs _ _ = Set.empty 
src/Clash/Rewrite/Util.hs view
@@ -54,6 +54,7 @@  import           GHC.Types.Basic             (InlineSpec (..)) +import           Clash.Core.DataCon          (DataCon (..)) import           Clash.Core.Evaluator.Types  (PureHeap, whnf') import           Clash.Core.FreeVars   (freeLocalVars, termFreeVars', freeLocalIds, globalIdOccursIn)@@ -67,10 +68,10 @@ import           Clash.Core.TyCon            (TyConMap) import           Clash.Core.Type             (Type (..), normalizeType) import           Clash.Core.Var-  (Id, IdScope (..), TyVar, Var (..), mkGlobalId, mkLocalId, mkTyVar)+  (Id, IdScope (..), TyVar, Var (..), isGlobalId, mkGlobalId, mkLocalId, mkTyVar) import           Clash.Core.VarEnv   (InScopeSet, extendInScopeSet, extendInScopeSetList, mkInScopeSet, notElemInScopeSet,-   uniqAway, uniqAway', mapVarEnv, eltsVarEnv, unitVarSet, emptyVarEnv,+   uniqAway, uniqAway', mapVarEnv, unitVarSet, emptyVarEnv,    mkVarEnv, eltsVarSet, elemVarEnv, lookupVarEnv, extendVarEnv, elemVarSet,    differenceVarEnv) import           Clash.Data.UniqMap (UniqMap)@@ -361,6 +362,69 @@   Just id_ -> appendToName (varName id_) ('_' `Text.cons` sf)   _ -> mkUnsafeInternalName sf 0 +-- | Name for a new binder for an argument of an application. Prefers names+-- derived from what the argument is passed to:+--+--   * The record field name, for arguments of a data constructor, e.g.+--     @c$baudCount@ for @n@ in @Tx { txState = st, baudCount = n }@+--+--   * The parameter name, for arguments of a global function, e.g.+--     @c$txStep_s@ for @st@ in @txStep st i@, given @txStep s input = ...@+--+-- Falls back to 'mkDerivedName' with suffix @app_arg@.+mkArgName ::+  TransformContext ->+  -- | Function part of the application+  Term ->+  -- | Index of the argument among the term arguments of the application+  Int ->+  RewriteMonad extra TmName+mkArgName ctx fun i = case fun of+  Data dc+    | (label:_) <- drop i (dcFieldLabels dc)+    , isIdentifierText label+    -> pure (mkDerivedName ctx label)+  Var f | isGlobalId f -> do+    bndrs <- Lens.use bindings+    pure $ case lookupVarEnv f bndrs of+      Just b+        | (param:_) <- drop i (lamIds (bindingTerm b))+        , nameSort (varName param) == User+        , let paramNm = nameOcc (varName param)+        , let funNm = unqualifiedOcc (nameOcc (varName f))+        , isIdentifierText paramNm+        , isIdentifierText funNm+        -> mkUnsafeInternalName (funNm <> "_" <> paramNm) 0+      _ -> fallback+  _ -> pure fallback+ where+  fallback = mkDerivedName ctx "app_arg"++  -- Term binders of the leading lambdas of a function+  lamIds = \case+    Lam x e -> x : lamIds e+    TyLam _ e -> lamIds e+    Tick _ e -> lamIds e+    _ -> []++-- | Name for a new binder for the right-hand side of a case alternative.+-- Includes the constructor matched by the alternative. For example, in:+--+-- > x = case s of+-- >   Idle -> ...+-- >   _ -> ...+--+-- the right-hand sides are named @c$x_case_Idle@ and @c$x_case_default@. Uses+-- @case_alt@ for literal patterns and constructors that are operators.+mkAltName :: TransformContext -> Pat -> TmName+mkAltName ctx = \case+  DataPat dc _ _+    | let con = unqualifiedOcc (nameOcc (dcName dc))+    , isIdentifierText con+    -> mkDerivedName ctx ("case_" <> con)+  DefaultPat -> mkDerivedName ctx "case_default"+  _ -> mkDerivedName ctx "case_alt"+ -- | Make a new binder and variable reference for a term mkTmBinderFor   :: (MonadUnique m)@@ -880,7 +944,9 @@    in if i `elemVarSet` bodyFVs then Nothing else Just body  removeUnusedBinders (Rec binds) body =-  case eltsVarEnv used of+  -- Filter 'binds' instead of taking the elements of 'used': those are ordered+  -- by 'Unique', which would scramble the order of declarations in the HDL.+  case filter ((`elemVarEnv` used) . fst) binds of     [] -> Just body     qqL | not (List.equalLength qqL binds)         -> Just (Letrec qqL body)
src/Clash/Rewrite/WorkFree.hs view
@@ -1,5 +1,5 @@ {-|-Copyright   : (C) 2020-2021, QBayLogic B.V.+Copyright   : (C) 2020-2026, QBayLogic B.V. License     : BSD2 (see the file LICENSE) Maintainer  : QBayLogic B.V. <devops@qaylogic.com> @@ -129,6 +129,8 @@ isConstant :: Term -> Bool isConstant e = case collectArgs e of   (Data _, args)   -> all (either isConstant (const True)) args+  (Prim (PrimInfo{primWorkInfo=WorkAlways}), _) -> False+  (Prim (PrimInfo{primWorkInfo=WorkConstant}), _) -> True   (Prim _, args) -> all (either isConstant (const True)) args   (Lam _ _, _)     -> isClosed e   (Literal _,_)    -> True
+ src/Clash/Util/Exception.hs view
@@ -0,0 +1,62 @@+{-# LANGUAGE CPP #-}++module Clash.Util.Exception+  ( mapConcurrentlyWithBacktrace_+  , exceptionBacktrace+  )+where++import qualified Control.Exception as Exception+#if MIN_VERSION_base(4,20,0)+import Control.Concurrent.Async (ConcurrentlyE(..))+import Data.Foldable (traverse_)+#else+import Control.Concurrent.Async (mapConcurrently_)+#endif+#if MIN_VERSION_base(4,21,0)+import Control.Exception.Context (displayExceptionContext)+#endif++-- | Like @mapConcurrently_@, preserving each exception's original type and+-- context. ConcurrentlyE carries failures as values and cancels siblings.+mapConcurrentlyWithBacktrace_ :: Foldable f => (a -> IO b) -> f a -> IO ()+#if MIN_VERSION_base(4,20,0)+mapConcurrentlyWithBacktrace_ f xs = do+  result <- runConcurrentlyE $ traverse_ (ConcurrentlyE . Exception.try . f) xs+  case result of+#if MIN_VERSION_base(4,21,0)+    Left original@(Exception.SomeException e) ->+      Exception.rethrowIO+        (Exception.ExceptionWithContext (Exception.someExceptionContext original) e)+#else+    Left original -> Exception.throwIO (RethrowException original)+#endif+    Right () -> pure ()+#else+-- Before base-4.20, ErrorCall stores the call stack in the exception value,+-- which survives async's rethrows without special handling.+mapConcurrentlyWithBacktrace_ = mapConcurrently_+#endif++#if MIN_VERSION_base(4,20,0) && !MIN_VERSION_base(4,21,0)+-- GHC 9.10's equivalent of rethrowIO: retain the saved type and context+-- without collecting another backtrace at the rethrow site.+newtype RethrowException = RethrowException Exception.SomeException++instance Show RethrowException where+  show (RethrowException e) = show e++instance Exception.Exception RethrowException where+  toException (RethrowException e) = e+  backtraceDesired _ = False+#endif++-- | Exception context to append to 'Exception.displayException'. Empty on+-- older versions of base, where displayException already includes it (GHC+-- 9.10), or ErrorCall stores its call stack in the exception value.+exceptionBacktrace :: Exception.SomeException -> String+#if MIN_VERSION_base(4,21,0)+exceptionBacktrace = displayExceptionContext . Exception.someExceptionContext+#else+exceptionBacktrace _ = ""+#endif
src/Data/List/Extra.hs view
@@ -110,7 +110,7 @@ countEq   :: Eq a   => a-  --  ^ Needle+  -- ^ Needle   -> [a]   -- ^ Haystack   -> Int
+ tests/Clash/Tests/Core/Util.hs view
@@ -0,0 +1,67 @@+{-# LANGUAGE OverloadedStrings #-}++module Clash.Tests.Core.Util (tests) where++import           Test.Tasty+import           Test.Tasty.HUnit++import           Clash.Core.Literal      (Literal(..))+import           Clash.Core.Name         (Name(..), NameSort(..), OccName)+import           Clash.Core.Term         (Bind(..), Term(..))+import           Clash.Core.Util         (renameIds)+import           Clash.Core.Var          (Id, Var(..))+import           Clash.Core.VarEnv       (unitVarEnv)++import           Test.Clash.Rewrite      (intTy, localId)++x, y :: Id+x = localId System "x" 1 intTy+-- | 'x', renamed+y = x {varName = (varName x) {nameOcc = "y"}}++nameOf :: Id -> OccName+nameOf = nameOcc . varName++-- | In @let x = 5 in (\x -> x) x@, where both binders of @x@ have the same+-- unique, only the outer @x@ and the occurrences referring to it are renamed.+renameIdsShadowing :: Assertion+renameIdsShadowing =+  case renameIds (unitVarEnv x y) tm of+    Let (NonRec b0 _) (App (Lam b1 (Var o1)) (Var o0)) ->+      map nameOf [b0, o0, b1, o1] @?= ["y", "y", "x", "x"]+    tm1 -> assertFailure ("Unexpected shape: " <> show tm1)+ where+  tm = Let (NonRec x (Literal (IntLiteral 5))) (App (Lam x (Var x)) (Var x))++-- | In @let x = 5 in (\x -> (\x -> x) x) x@, where all binders of @x@ have the+-- same unique, the innermost @x@ shadows a binder that shadows the renamed one,+-- so it keeps its name too.+renameIdsNestedShadowing :: Assertion+renameIdsNestedShadowing =+  case renameIds (unitVarEnv x y) tm of+    Let (NonRec b0 _) (App (Lam b1 (App (Lam b2 (Var o2)) (Var o1))) (Var o0)) ->+      map nameOf [b0, o0, b1, o1, b2, o2] @?= ["y", "y", "x", "x", "x", "x"]+    tm1 -> assertFailure ("Unexpected shape: " <> show tm1)+ where+  tm =+    Let+      (NonRec x (Literal (IntLiteral 5)))+      (App (Lam x (App (Lam x (Var x)) (Var x))) (Var x))++-- | Occurrences of variables that aren't bound in the term keep their names+renameIdsFree :: Assertion+renameIdsFree =+  case renameIds (unitVarEnv x y) (Var x) of+    Var o -> nameOf o @?= "x"+    tm1 -> assertFailure ("Unexpected shape: " <> show tm1)++tests :: TestTree+tests =+  testGroup+    "Clash.Tests.Core.Util"+    [ testGroup "renameIds"+      [ testCase "Shadowing" renameIdsShadowing+      , testCase "Nested shadowing" renameIdsNestedShadowing+      , testCase "Free variables" renameIdsFree+      ]+    ]
+ tests/Clash/Tests/Util/Exception.hs view
@@ -0,0 +1,104 @@+{-# LANGUAGE CPP #-}+{-# LANGUAGE TypeApplications #-}++module Clash.Tests.Util.Exception (tests) where++import Control.Concurrent (newEmptyMVar, putMVar, takeMVar)+import qualified Control.Exception as Exception+#if MIN_VERSION_base(4,20,0)+import Control.Exception.Annotation (ExceptionAnnotation(..))+import Data.List (isInfixOf, isPrefixOf)+import GHC.Stack (HasCallStack)+#endif+import System.Exit (ExitCode(..), exitWith)+import System.IO.Error (ioeGetErrorString)+import System.Timeout (timeout)+import Test.Tasty+import Test.Tasty.HUnit (assertBool, assertFailure, testCase, (@?=))++import Clash.Util.Exception++tests :: TestTree+tests = testGroup "Clash.Tests.Util.Exception"+  [ testCase "worker failures reach typed IOException handlers" $ do+      result <- Exception.try @Exception.IOException $+        mapConcurrentlyWithBacktrace_ (\() -> Exception.throwIO (userError "worker")) [(), ()]+      case result of+        Left e -> ioeGetErrorString e @?= "worker"+        Right () -> assertFailure "Expected an IOException"++  , testCase "worker failures reach typed ErrorCall handlers" $ do+      result <- Exception.try @Exception.ErrorCall $+        mapConcurrentlyWithBacktrace_ (\() -> Exception.evaluate (error "worker" :: ())) [(), ()]+      case result of+        Left (Exception.ErrorCall msg) -> msg @?= "worker"+        Right () -> assertFailure "Expected an ErrorCall"++  , testCase "nested concurrent actions preserve exception types" $ do+      mapConcurrentlyWithBacktrace_ (\() -> do+        result <- Exception.try @Exception.IOException $+          mapConcurrentlyWithBacktrace_ (\() -> Exception.throwIO (userError "nested worker")) [()]+        case result of+          Left e -> ioeGetErrorString e @?= "nested worker"+          Right () -> assertFailure "Expected an IOException") [(), ()]++  , testCase "ExitCode passes through" $ do+      result <- Exception.try @ExitCode $+        mapConcurrentlyWithBacktrace_ (\() -> exitWith (ExitFailure 17)) [()]+      result @?= Left (ExitFailure 17)++  , testCase "asynchronous exceptions pass through" $ do+      result <- Exception.try @Exception.AsyncException $+        mapConcurrentlyWithBacktrace_ (\() -> Exception.throwIO Exception.ThreadKilled) [()]+      result @?= Left Exception.ThreadKilled++  , testCase "a worker failure cancels its sibling" $ do+      started <- newEmptyMVar+      cancelled <- newEmptyMVar+      never <- newEmptyMVar+      let worker False = takeMVar started >> Exception.throwIO (userError "worker")+          worker True = Exception.finally+            (putMVar started () >> takeMVar never)+            (putMVar cancelled ())+      result <- timeout 5000000 $ Exception.try @Exception.IOException $+        mapConcurrentlyWithBacktrace_ worker [False, True]+      case result of+        Just (Left e) -> ioeGetErrorString e @?= "worker"+        _ -> assertFailure "Expected the worker failure without hanging"+      cleanup <- timeout 5000000 (takeMVar cancelled)+      assertBool "Sibling finished its cleanup" (cleanup == Just ())++#if MIN_VERSION_base(4,20,0)+  , testCase "the original worker backtrace is rendered once" $ do+      result <- Exception.try @Exception.SomeException $+        mapConcurrentlyWithBacktrace_ (\() -> throwOriginal) [()]+      case result of+        Left e -> do+          let rendered = Exception.displayException e ++ "\n" ++ exceptionBacktrace e+          length (filter (isPrefixOf "HasCallStack backtrace:") (lines rendered)) @?= 1+          assertBool "Original throw site is present" ("throwOriginal" `isInfixOf` rendered)+          assertBool "No backtrace from async's rethrow"+            (not ("Control.Concurrent.Async" `isInfixOf` rendered))+        Right () -> assertFailure "Expected an IOException"++  , testCase "the original exception annotations are preserved" $ do+      result <- Exception.try @Exception.SomeException $+        mapConcurrentlyWithBacktrace_+          (\() -> Exception.annotateIO OriginalContext throwOriginal) [()]+      case result of+        Left e -> do+          let rendered = Exception.displayException e ++ "\n" ++ exceptionBacktrace e+          length (filter (== "original worker context") (lines rendered)) @?= 1+        Right () -> assertFailure "Expected an IOException"+#endif+  ]++#if MIN_VERSION_base(4,20,0)+throwOriginal :: HasCallStack => IO ()+throwOriginal = Exception.throwIO (userError "original worker failure")++data OriginalContext = OriginalContext deriving Show++instance ExceptionAnnotation OriginalContext where+  displayExceptionAnnotation _ = "original worker context"+#endif
tests/unittests.hs view
@@ -8,10 +8,12 @@ import qualified Clash.Tests.Core.StructuralEquivalence import qualified Clash.Tests.Core.Subst import qualified Clash.Tests.Core.TermLiteral+import qualified Clash.Tests.Core.Util import qualified Clash.Tests.Driver.Manifest import qualified Clash.Tests.Netlist.Id import qualified Clash.Tests.Normalize.Transformations import qualified Clash.Tests.Rewrite.StrategyDSL+import qualified Clash.Tests.Util.Exception import qualified Clash.Tests.Util.Interpolate import qualified Test.Clash.Rewrite @@ -28,10 +30,12 @@   , Clash.Tests.Core.StructuralEquivalence.tests   , Clash.Tests.Core.Subst.tests   , Clash.Tests.Core.TermLiteral.tests+  , Clash.Tests.Core.Util.tests   , Clash.Tests.Driver.Manifest.tests   , Clash.Tests.Netlist.Id.tests   , Clash.Tests.Normalize.Transformations.tests   , Clash.Tests.Rewrite.StrategyDSL.tests+  , Clash.Tests.Util.Exception.tests   , Clash.Tests.Util.Interpolate.tests   , Test.Clash.Rewrite.tests   ]