Debian Codegraph @

src-ghc/Clash/GHC/GHC2Core.hs

raw
1 {-|
2 Copyright : (C) 2013-2016, University of Twente,
3 2016-2017, Myrtle Software Ltd,
4 2017-2022, Google Inc.
5 2021-2024, QBayLogic B.V.,
6 License : BSD2 (see the file LICENSE)
7 Maintainer : QBayLogic B.V. <[email protected]>
8 -}
9
10 {-# LANGUAGE CPP #-}
11 {-# LANGUAGE FlexibleContexts #-}
12 {-# LANGUAGE MagicHash #-}
13 {-# LANGUAGE MultiWayIf #-}
14 {-# LANGUAGE OverloadedStrings #-}
15 {-# LANGUAGE QuasiQuotes #-}
16 {-# LANGUAGE TemplateHaskell #-}
17
18 {-# OPTIONS_GHC -fno-warn-orphans #-}
19
20 module Clash.GHC.GHC2Core
21 ( C2C
22 , GHC2CoreState
23 , GHC2CoreEnv (..)
24 , srcSpan
25 , tyConMap
26 , coreToTerm
27 , coreToId
28 , coreToName
29 , modNameM
30 , qualifiedNameString
31 , qualifiedNameString'
32 , makeAllTyCons
33 , emptyGHC2CoreState
34 )
35 where
36
37 -- External Modules
38 import Control.Lens ((^.), (%~), (&), (%=), (.~), view, makeLenses)
39 import Control.Applicative ((<|>))
40 import Control.Monad.Extra (ifM, andM)
41 import Control.Monad.RWS.Strict (RWS)
42 import qualified Control.Monad.RWS.Strict as RWS
43 import Data.Bifunctor (second)
44 import Data.Binary.IEEE754 (doubleToWord, floatToWord)
45 import qualified Data.ByteString.Char8 as Char8
46 import Data.Char (isDigit)
47 import Data.Hashable (Hashable (..))
48 import Data.HashMap.Strict (HashMap)
49 import qualified Data.HashMap.Strict as HashMap
50 import Data.Maybe (catMaybes,fromMaybe,listToMaybe)
51 import Data.Text (Text, pack)
52 import qualified Data.Text as Text
53 import Data.Text.Encoding (decodeUtf8)
54 import qualified Data.Traversable as T
55 import Data.String.Interpolate (__i)
56 import qualified Text.Read as Text
57 #if MIN_VERSION_ghc(9,4,0)
58 import Data.Primitive.ByteArray (ByteArray(ByteArray))
59 import qualified GHC.Data.Strict as GHC
60 import GHC.Num.Integer (integerToBigNatClamp#)
61 #endif
62 #if MIN_VERSION_ghc(9,6,0)
63 import Language.Haskell.Syntax.Basic (FieldLabelString (..))
64 #endif
65
66 -- GHC API
67 #if MIN_VERSION_ghc(9,4,0)
68 import GHC.Core.Reduction (Reduction(Reduction))
69 #endif
70 #if MIN_VERSION_ghc(9,0,0)
71 import GHC.Builtin.Types (falseDataCon)
72 import GHC.Core.Coercion.Axiom
73 (CoAxiom (co_ax_branches), CoAxBranch (cab_lhs,cab_rhs), fromBranches)
74 import GHC.Core.Coercion (Role (Nominal), coercionType, coercionKind)
75 import GHC.Core.FVs (exprSomeFreeVars)
76 import GHC.Core
77 (AltCon (..), Bind (..), CoreExpr, Expr (..), Unfolding (..),
78 #if MIN_VERSION_ghc(9,2,0)
79 Alt(..),
80 #else
81 Tickish (..),
82 #endif
83 collectArgs, rhssOfAlts, unfoldingTemplate)
84 #if MIN_VERSION_ghc(9,2,0)
85 import GHC.Types.Tickish (GenTickish (..))
86 #endif
87 import GHC.Core.DataCon
88 (DataCon, dataConExTyCoVars, dataConName, dataConRepArgTys, dataConTag,
89 dataConTyCon, dataConUnivTyVars, dataConWorkId, dataConFieldLabels, flLabel,
90 HsImplBang(..), dataConImplBangs)
91 import GHC.Core.FamInstEnv
92 (FamInst (..), FamInstEnvs, familyInstances, normaliseType, emptyFamInstEnvs)
93 import GHC.Data.FastString (unpackFS, bytesFS)
94 import GHC.Types.Id (isDataConId_maybe)
95 import GHC.Types.Id.Info (IdDetails (..), unfoldingInfo)
96 import GHC.Types.Literal (Literal (..), LitNumType (..), literalType)
97 import GHC.Unit.Module (moduleName, moduleNameString)
98 import GHC.Types.Name
99 (Name, nameModule_maybe, nameOccName, nameUnique, getSrcSpan)
100 import GHC.Builtin.Names (integerTyConKey, naturalTyConKey)
101 import GHC.Types.Name.Occurrence (occNameString)
102 import GHC.Data.Pair (Pair (..))
103 import GHC.Types.SrcLoc (SrcSpan (..), isGoodSrcSpan)
104 import GHC.Core.TyCon
105 (AlgTyConRhs (..), TyCon, tyConName, algTyConRhs, isAlgTyCon, isFamilyTyCon,
106 isNewTyCon, isPrimTyCon, isTupleTyCon,
107 isClosedSynFamilyTyConWithAxiom_maybe, expandSynTyCon_maybe, tyConArity,
108 tyConDataCons, tyConKind, tyConName, tyConUnique, isClassTyCon, isPromotedDataCon_maybe)
109 #if MIN_VERSION_ghc(9,6,0)
110 import GHC.Core.TyCon (ExpandSynResult (..))
111 import GHC.Core.Type (tyConAppFunTy_maybe)
112 #else
113 import GHC.Core.TyCon (isFunTyCon)
114 #endif
115 import GHC.Core.Type (mkTvSubstPrs, substTy, coreView)
116 import GHC.Core.TyCo.Rep (Coercion (..), TyLit (..), Type (..), scaledThing)
117 import GHC.Types.Unique (Uniquable (..), Unique, getKey, hasKey)
118 import GHC.Types.Var
119 (Id, TyVar, Var, VarBndr (..), idDetails, isTyVar, varName, varType,
120 varUnique, idInfo, isGlobalId)
121 import GHC.Types.Var.Set (isEmptyVarSet)
122 #else
123 import CoAxiom (CoAxiom (co_ax_branches), CoAxBranch (cab_lhs,cab_rhs),
124 fromBranches, Role (Nominal))
125 import Coercion (coercionType,coercionKind)
126 import CoreFVs (exprSomeFreeVars)
127 import CoreSyn
128 (AltCon (..), Bind (..), CoreExpr, Expr (..), Unfolding (..), Tickish (..),
129 collectArgs, rhssOfAlts, unfoldingTemplate)
130 import TysWiredIn (falseDataCon)
131 import DataCon (DataCon, HsImplBang(..),
132 #if MIN_VERSION_ghc(8,8,0)
133 dataConExTyCoVars,
134 #else
135 dataConExTyVars,
136 #endif
137 dataConName, dataConRepArgTys,
138 dataConTag, dataConTyCon,
139 dataConUnivTyVars, dataConWorkId,
140 dataConFieldLabels, flLabel, dataConImplBangs)
141 import FamInstEnv (FamInst (..), FamInstEnvs,
142 familyInstances, normaliseType, emptyFamInstEnvs)
143
144 #if MIN_VERSION_ghc(8,10,0)
145 import FastString (unpackFS, bytesFS)
146 #else
147 import FastString (unpackFS, fastStringToByteString)
148 #endif
149
150 import Id (isDataConId_maybe)
151 import IdInfo (IdDetails (..), unfoldingInfo)
152 import Literal (Literal (..), LitNumType (..))
153 #if MIN_VERSION_ghc(8,8,0)
154 import Literal (literalType)
155 #endif
156 import Module (moduleName, moduleNameString)
157 import Name (Name, nameModule_maybe,
158 nameOccName, nameUnique, getSrcSpan)
159 import PrelNames (integerTyConKey, naturalTyConKey)
160 import OccName (occNameString)
161 import Pair (Pair (..))
162 import SrcLoc (SrcSpan (..), isGoodSrcSpan)
163 import TyCon (AlgTyConRhs (..), TyCon, tyConName,
164 algTyConRhs, isAlgTyCon, isFamilyTyCon,
165 isFunTyCon, isNewTyCon, isPromotedDataCon_maybe,
166 isPrimTyCon, isTupleTyCon,
167 isClosedSynFamilyTyConWithAxiom_maybe,
168 expandSynTyCon_maybe,
169 tyConArity,
170 tyConDataCons, tyConKind,
171 tyConName, tyConUnique, isClassTyCon)
172 import Type (mkTvSubstPrs, substTy, coreView)
173 import TyCoRep (Coercion (..), TyLit (..), Type (..))
174 import Unique (Uniquable (..), Unique, getKey, hasKey)
175 import Var (Id, TyVar, Var, idDetails,
176 isTyVar, varName, varType,
177 varUnique, idInfo, isGlobalId)
178 #if MIN_VERSION_ghc(8,8,0)
179 import Var (VarBndr (..))
180 #else
181 import Var (TyVarBndr (..))
182 #endif
183 import VarSet (isEmptyVarSet)
184 #endif
185
186 -- Local imports
187 import Clash.Annotations.Primitive (extractPrim)
188 import Clash.Annotations.SynthesisAttributes (Annotate, Attr(..))
189 import qualified Clash.Core.DataCon as C
190 import qualified Clash.Core.Literal as C
191 import qualified Clash.Core.Name as C
192 import qualified Clash.Core.Pretty as C
193 import qualified Clash.Core.Term as C
194 import qualified Clash.Core.TyCon as C
195 import qualified Clash.Core.Type as C
196 import qualified Clash.Core.Util as C (undefinedTy, undefinedXPrims)
197 import qualified Clash.Core.Var as C
198 import qualified Clash.Data.UniqMap as C
199 import Clash.Normalize.Primitives as C
200 import Clash.Primitives.Types hiding (name)
201 import Clash.Unique (fromGhcUnique)
202 import Clash.Util
203 import Clash.GHC.Util
204
205 instance Hashable Name where
206 hashWithSalt s = hashWithSalt s . getKey . nameUnique
207
208 data GHC2CoreState
209 = GHC2CoreState
210 { _tyConMap :: C.UniqMap TyCon
211 , _nameMap :: HashMap Name Text
212 }
213
214 makeLenses ''GHC2CoreState
215
216 data GHC2CoreEnv
217 = GHC2CoreEnv
218 { _srcSpan :: SrcSpan
219 , _famInstEnvs :: FamInstEnvs
220 }
221
222 makeLenses ''GHC2CoreEnv
223
224 emptyGHC2CoreState :: GHC2CoreState
225 emptyGHC2CoreState = GHC2CoreState mempty HashMap.empty
226
227 newtype SrcSpanRB = SrcSpanRB {unSrcSpanRB :: SrcSpan}
228
229 instance Semigroup SrcSpanRB where
230 (SrcSpanRB l) <> (SrcSpanRB r) =
231 if isGoodSrcSpan r
232 then SrcSpanRB r
233 else SrcSpanRB l
234
235 instance Monoid SrcSpanRB where
236 mempty = SrcSpanRB noSrcSpan
237
238 type C2C = RWS GHC2CoreEnv SrcSpanRB GHC2CoreState
239
240 makeAllTyCons
241 :: GHC2CoreState
242 -> FamInstEnvs
243 -> C.UniqMap C.TyCon
244 makeAllTyCons hm fiEnvs = go hm hm
245 where
246 go old new
247 | C.null (new ^. tyConMap) = mempty
248 | otherwise = tcm <> tcm'
249 where
250 (tcm,old', _) = RWS.runRWS (T.mapM makeTyCon (new ^. tyConMap))
251 (GHC2CoreEnv noSrcSpan fiEnvs)
252 old
253 tcm' = go old' (old' & tyConMap %~ (`C.difference` (old ^. tyConMap)))
254
255 makeTyCon :: TyCon
256 -> C2C C.TyCon
257 makeTyCon tc = tycon
258 where
259 tycon
260 | isFamilyTyCon tc = mkFunTyCon
261 | isTupleTyCon tc = mkTupleTyCon
262 | isAlgTyCon tc = mkAlgTyCon
263 | isPrimTyCon tc = mkPrimTyCon
264 | Just dc <- isPromotedDataCon_maybe tc = mkPromotedDataCon dc
265 | otherwise = mkVoidTyCon
266 where
267 tcArity = tyConArity tc
268
269 mkAlgTyCon = do
270 tcName <- coreToName tyConName tyConUnique qualifiedNameString tc
271 tcKind <- coreToType (tyConKind tc)
272 tcRhsM <- makeAlgTyConRhs $ algTyConRhs tc
273 case tcRhsM of
274 Just tcRhs ->
275 return
276 C.AlgTyCon
277 { C.tyConUniq = C.nameUniq tcName
278 , C.tyConName = tcName
279 , C.tyConKind = tcKind
280 , C.tyConArity = tcArity
281 , C.algTcRhs = tcRhs
282 , C.isClassTc = isClassTyCon tc
283 }
284 Nothing -> return (C.PrimTyCon (C.nameUniq tcName) tcName tcKind tcArity)
285
286 mkFunTyCon = do
287 tcName <- coreToName tyConName tyConUnique qualifiedNameString tc
288 tcKind <- coreToType (tyConKind tc)
289 substs <- case isClosedSynFamilyTyConWithAxiom_maybe tc of
290 Nothing -> do
291 instances <- familyInstances <$> view famInstEnvs <*> pure tc
292 mapM famInstToSubst instances
293 Just cx -> let bx = fromBranches (co_ax_branches cx)
294 in mapM (\b -> (,) <$> mapM coreToType (cab_lhs b)
295 <*> coreToType (cab_rhs b))
296 bx
297 return
298 C.FunTyCon
299 { C.tyConUniq = C.nameUniq tcName
300 , C.tyConName = tcName
301 , C.tyConKind = tcKind
302 , C.tyConArity = tcArity
303 , C.tyConSubst = substs
304 }
305
306 mkTupleTyCon = do
307 tcName <- coreToName tyConName tyConUnique qualifiedNameString tc
308 tcKind <- coreToType (tyConKind tc)
309 case tyConDataCons tc of
310 dc:_ -> do
311 tcDc <- fmap (C.DataTyCon . (:[])) (coreToDataCon dc)
312 return
313 C.AlgTyCon
314 { C.tyConUniq = C.nameUniq tcName
315 , C.tyConName = tcName
316 , C.tyConKind = tcKind
317 , C.tyConArity = tcArity
318 , C.algTcRhs = tcDc
319 , C.isClassTc = isClassTyCon tc
320 }
321 _ -> error "impossible"
322
323 mkPrimTyCon = do
324 tcName <- coreToName tyConName tyConUnique qualifiedNameString tc
325 tcKind <- coreToType (tyConKind tc)
326 return
327 C.PrimTyCon
328 { C.tyConUniq = C.nameUniq tcName
329 , C.tyConName = tcName
330 , C.tyConKind = tcKind
331 , C.tyConArity = tcArity
332 }
333
334 mkPromotedDataCon dc = do
335 tcName <- coreToName tyConName tyConUnique qualifiedNameString tc
336 tcKind <- coreToType (tyConKind tc)
337 tcData <- coreToDataCon dc
338
339 return
340 C.PromotedDataCon
341 { C.tyConUniq = C.nameUniq tcName
342 , C.tyConName = tcName
343 , C.tyConKind = tcKind
344 , C.tyConArity = tcArity
345 , C.tyConData = tcData
346 }
347
348 mkVoidTyCon = do
349 tcName <- coreToName tyConName tyConUnique qualifiedNameString tc
350 tcKind <- coreToType (tyConKind tc)
351 return (C.PrimTyCon (C.nameUniq tcName) tcName tcKind tcArity)
352
353 famInstToSubst :: FamInst -> C2C ([C.Type],C.Type)
354 famInstToSubst fi = do
355 tys <- mapM coreToType (fi_tys fi)
356 ty <- coreToType (fi_rhs fi)
357 return (tys,ty)
358
359 makeAlgTyConRhs :: AlgTyConRhs
360 -> C2C (Maybe C.AlgTyConRhs)
361 makeAlgTyConRhs algTcRhs = case algTcRhs of
362 DataTyCon {data_cons = dcs} -> Just <$> C.DataTyCon <$> mapM coreToDataCon dcs
363 SumTyCon dcs _ -> Just <$> C.DataTyCon <$> mapM coreToDataCon dcs
364
365 #if MIN_VERSION_ghc(8,10,0)
366 NewTyCon dc _ (rhsTvs,rhsEtad) _ _ ->
367 #else
368 NewTyCon dc _ (rhsTvs,rhsEtad) _ ->
369 #endif
370 Just <$> (C.NewTyCon <$> coreToDataCon dc
371 <*> ((,) <$> mapM coreToTyVar rhsTvs
372 <*> coreToType rhsEtad
373 )
374 )
375 AbstractTyCon {} -> return Nothing
376 TupleTyCon {} -> error "Cannot handle tuple tycons"
377
378 coreToTerm
379 :: CompiledPrimMap
380 -> [Var]
381 -> CoreExpr
382 -> C2C C.Term
383 coreToTerm primMap unlocs = term
384 where
385 term :: CoreExpr -> C2C C.Term
386 term e
387 | (Var x,args) <- collectArgs e
388 , let (nm, _) = RWS.evalRWS (qualifiedNameString (varName x))
389 (GHC2CoreEnv noSrcSpan emptyFamInstEnvs)
390 emptyGHC2CoreState
391 = go nm args
392 | otherwise
393 = term' e
394 where
395 -- Remove most Signal transformers
396 go "Clash.Signal.Internal.mapSignal#" args
397 | length args == 5
398 = term (App (args!!3) (args!!4))
399 go "Clash.Signal.Internal.signal#" args
400 | length args == 3
401 = term (args!!2)
402 go "Clash.Signal.Internal.appSignal#" args
403 | length args == 5
404 = term (App (args!!3) (args!!4))
405 go "Clash.Signal.Internal.joinSignal#" args
406 | length args == 3
407 = term (args!!2)
408 go "Clash.Signal.Bundle.vecBundle#" args
409 | length args == 4
410 = term (args!!3)
411 --- Remove `$`
412 go "GHC.Base.$" args
413 | length args == 5
414 = term (App (args!!3) (args!!4))
415 go "GHC.Magic.noinline" args -- noinline :: forall a. a -> a
416 | [_ty, x] <- args
417 = term x
418 -- Remove most CallStack logic
419 go "GHC.Stack.Types.PushCallStack" args = term (last args)
420 go "GHC.Stack.Types.FreezeCallStack" args = term (last args)
421 go "GHC.Stack.withFrozenCallStack" args
422 | length args == 3
423 = term (App (args!!2) (args!!1))
424 go "Clash.Sized.BitVector.Internal.checkUnpackUndef" args
425 | [_nTy,_aTy,_kn,_typ,f] <- args
426 = term f
427 go "Clash.Magic.prefixName" args
428 | [Type nmTy,_aTy,f] <- args
429 = C.Tick <$> (C.NameMod C.PrefixName <$> coreToType nmTy) <*> term f
430 go "Clash.Magic.suffixName" args
431 | [Type nmTy,_aTy,f] <- args
432 = C.Tick <$> (C.NameMod C.SuffixName <$> coreToType nmTy) <*> term f
433 go "Clash.Magic.suffixNameFromNat" args
434 | [Type nmTy,_aTy,f] <- args
435 = C.Tick <$> (C.NameMod C.SuffixName <$> coreToType nmTy) <*> term f
436 go "Clash.Magic.suffixNameP" args
437 | [Type nmTy,_aTy,f] <- args
438 = C.Tick <$> (C.NameMod C.SuffixNameP <$> coreToType nmTy) <*> term f
439 go "Clash.Magic.suffixNameFromNatP" args
440 | [Type nmTy,_aTy,f] <- args
441 = C.Tick <$> (C.NameMod C.SuffixNameP <$> coreToType nmTy) <*> term f
442 go "Clash.Magic.setName" args
443 | [Type nmTy,_aTy,f] <- args
444 = C.Tick <$> (C.NameMod C.SetName <$> coreToType nmTy) <*> term f
445 go "Clash.Magic.deDup" args
446 | [_aTy,f] <- args
447 = C.Tick C.DeDup <$> term f
448 go "Clash.Magic.noDeDup" args
449 | [_aTy,f] <- args
450 = C.Tick C.NoDeDup <$> term f
451 go "Clash.Magic.clashSimulation" _
452 = C.Data <$> coreToDataCon falseDataCon
453 go "Clash.XException.xToErrorCtx" args
454 -- xToErrorCtx :: forall a. String -> a -> a
455 | [_ty, _msg, x] <- args
456 = term x
457 go nm args
458 | Just n <- parseBundle "bundle" nm
459 -- length args = domain tyvar + signal arg + number of type vars
460 , length args == 2 + n
461 = term (last args)
462 go nm args
463 | Just n <- parseBundle "unbundle" nm
464 -- length args = domain tyvar + signal arg + number of type vars
465 , length args == 2 + n
466 = term (last args)
467 go _ _ = term' e
468
469 parseBundle :: Text -> Text -> Maybe Int
470 parseBundle fNm nm0 = do
471 nm1 <- Text.stripPrefix ("Clash.Signal.Bundle." <> fNm) nm0
472 nm2 <- Text.stripSuffix "#" nm1
473 Text.readMaybe (Text.unpack nm2)
474
475 term' (Var x) = var x
476 #if MIN_VERSION_ghc(8,8,0)
477 term' (Lit l@LitRubbish{}) = do
478 ty <- coreToType (literalType l)
479 return (C.Prim (C.PrimInfo (pack "_RUBBISH_")
480 ty
481 C.WorkNever
482 C.SingleResult
483 C.NoUnfolding))
484 #endif
485 term' (Lit l) = return $ C.Literal (coreToLiteral l)
486 term' (App eFun (Type tyArg)) = C.TyApp <$> term eFun <*> coreToType tyArg
487 term' (App eFun eArg) = C.App <$> term eFun <*> term eArg
488 term' (Lam x e)
489 | isTyVar x
490 = C.TyLam <$> coreToTyVar x <*> addUsefull (getSrcSpan x) (term e)
491 | otherwise
492 = do
493 (e',sp) <- termSP (getSrcSpan x) e
494 x' <- coreToIdSP sp x
495 return (C.Lam x' e')
496 term' (Let (NonRec x e1) e2) = do
497 (e1',sp) <- termSP (getSrcSpan x) e1
498 x' <- coreToIdSP sp x
499 e2' <- term e2
500 return (C.Let (C.NonRec x' e1') e2')
501
502 term' (Let (Rec xes) e) = do
503 xes' <- mapM go xes
504 e' <- term e
505 return (C.Let (C.Rec xes') e')
506 where
507 go (x,b) = do
508 (b',sp) <- termSP (getSrcSpan x) b
509 x' <- coreToIdSP sp x
510 return (x',b')
511
512 term' (Case s _ ty []) = do
513 s' <- term' s
514 ty' <- coreToType ty
515 case C.collectArgs s' of
516 (C.Prim p, _) | C.primName p `elem` C.undefinedXPrims ->
517 -- GHC translates things like:
518 --
519 -- xToBV (Index.pack# (errorX @TY "QQ"))
520 --
521 -- to
522 --
523 -- xToBV (case (errorX @TY "QQ") of {})
524 --
525 --
526 -- Here we then translate
527 --
528 -- case (errorX @TY "QQ") of {}
529 --
530 -- to
531 --
532 -- undefinedX @TY
533 --
534 -- So that the evaluator rule for 'xToBV' can recognize things that
535 -- would normally throw XException
536 return (C.TyApp (C.Prim C.undefinedX) ty')
537 _ ->
538 return (C.TyApp (C.Prim C.undefined) ty')
539
540 term' (Case e b ty alts) = do
541 let usesBndr = any ( not . isEmptyVarSet . exprSomeFreeVars (== b))
542 $ rhssOfAlts alts
543 (e',sp) <- termSP (getSrcSpan b) e
544 b' <- coreToIdSP sp b
545 ty' <- coreToType ty
546 let caseTerm v =
547 C.Case v ty' <$> mapM (addUsefull sp . alt sp) alts
548 if usesBndr
549 then do
550 ct <- caseTerm (C.Var b')
551 return (C.Let (C.NonRec b' e') ct)
552 else caseTerm e'
553
554 term' (Cast e co) = do
555 let (Pair ty1 ty2) = coercionKind co
556 hasPrimCoM <- hasPrimCo co
557 sizedCast <- isSizedCast ty1 ty2
558 case hasPrimCoM of
559 Just _ | sizedCast
560 -> C.Cast <$> term e <*> coreToType ty1 <*> coreToType ty2
561 _ -> term e
562 term' (Tick (SourceNote rsp _) e) =
563 #if MIN_VERSION_ghc(9,4,0)
564 C.Tick (C.SrcSpan (RealSrcSpan rsp GHC.Nothing)) <$>
565 addUsefull (RealSrcSpan rsp GHC.Nothing) (term e)
566 #elif MIN_VERSION_ghc(9,0,0)
567 C.Tick (C.SrcSpan (RealSrcSpan rsp Nothing)) <$>
568 addUsefull (RealSrcSpan rsp Nothing) (term e)
569 #else
570 C.Tick (C.SrcSpan (RealSrcSpan rsp)) <$> addUsefull (RealSrcSpan rsp) (term e)
571 #endif
572 term' (Tick _ e) = term e
573 term' (Type t) =
574 C.TyApp (C.Prim (C.PrimInfo (pack "_TY_") C.undefinedTy C.WorkNever C.SingleResult C.NoUnfolding))
575 <$> coreToType t
576 term' (Coercion co) =
577 C.TyApp (C.Prim (C.PrimInfo (pack "_CO_") C.undefinedTy C.WorkNever C.SingleResult C.NoUnfolding))
578 <$> coreToType (coercionType co)
579
580
581 termSP sp = fmap (second unSrcSpanRB) . RWS.listen . addUsefullR sp . term
582 coreToIdSP sp = RWS.local (\r@(GHC2CoreEnv _ e) ->
583 if isGoodSrcSpan sp then
584 GHC2CoreEnv sp e
585 else
586 r)
587 . coreToId
588
589
590 lookupPrim :: Text -> Maybe (Maybe CompiledPrimitive)
591 lookupPrim nm = extractPrim <$> HashMap.lookup nm primMap
592
593 var x = do
594 xPrim <- if isGlobalId x then coreToPrimVar x else coreToVar x
595 let xNameS = C.nameOcc xPrim
596 xType <- coreToType (varType x)
597 case isDataConId_maybe x of
598 Just dc -> case lookupPrim xNameS of
599 Just p ->
600 -- Primitive will be marked MultiResult in Transformations if it
601 -- is a multi result primitive.
602 return $ C.Prim (C.PrimInfo xNameS xType (maybe C.WorkVariable workInfo p) C.SingleResult C.NoUnfolding)
603 Nothing -> if isDataConWrapId x && not (isNewTyCon (dataConTyCon dc))
604 then let xInfo = idInfo x
605 unfolding = unfoldingInfo xInfo
606 in case unfolding of
607 CoreUnfolding {} -> do
608 sp <- view srcSpan
609 RWS.censor (const (SrcSpanRB sp)) (term (unfoldingTemplate unfolding))
610 NoUnfolding -> error ("No unfolding for DC wrapper: " ++ showPprUnsafe x)
611 _ -> error ("Unexpected unfolding for DC wrapper: " ++ showPprUnsafe x)
612 else C.Data <$> coreToDataCon dc
613 Nothing -> case lookupPrim xNameS of
614 Just (Just (Primitive f wi _))
615 | Just n <- parseBundle "bundle" f -> return (bundleUnbundleTerm (n+1) xType)
616 | Just n <- parseBundle "unbundle" f -> return (bundleUnbundleTerm (n+1) xType)
617 | f == "Clash.Signal.Internal.mapSignal#" -> return (mapSignalTerm xType)
618 | f == "Clash.Signal.Internal.signal#" -> return (signalTerm xType)
619 | f == "Clash.Signal.Internal.appSignal#" -> return (appSignalTerm xType)
620 | f == "Clash.Signal.Internal.traverse#" -> return (traverseTerm xType)
621 | f == "Clash.Signal.Internal.joinSignal#" -> return (joinTerm xType)
622 | f == "Clash.Signal.Bundle.vecBundle#" -> return (vecUnwrapTerm xType)
623 | f == "GHC.Base.$" -> return (dollarTerm xType)
624 | f == "GHC.Stack.withFrozenCallStack" -> return (withFrozenCallStackTerm xType)
625 | f == "GHC.Magic.noinline" -> return (idTerm xType)
626 | f == "GHC.Magic.lazy" -> return (idTerm xType)
627 | f == "GHC.Magic.nospec" -> return (idTerm xType)
628 | f == "GHC.Magic.runRW#" -> return (runRWTerm xType)
629 | f == "Clash.Sized.Internal.BitVector.checkUnpackUndef" -> return (checkUnpackUndefTerm xType)
630 | f == "Clash.Magic.prefixName"
631 -> return (nameModTerm C.PrefixName xType)
632 | f == "Clash.Magic.postfixName"
633 -> return (nameModTerm C.SuffixName xType)
634 | f == "Clash.Magic.setName"
635 -> return (nameModTerm C.SetName xType)
636 | f == "Clash.XException.xToErrorCtx"
637 -> return (xToErrorCtxTerm xType)
638 | x `elem` unlocs
639 -> return (C.Prim (C.PrimInfo xNameS xType wi C.SingleResult C.NoUnfolding))
640 | otherwise
641 -> do bndr <- coreToId x
642 return (C.Prim (C.PrimInfo xNameS xType wi C.SingleResult (C.Unfolding bndr)))
643 Just (Just (BlackBox {workInfo = wi}))
644 | x `elem` unlocs
645 -> return $ C.Prim (C.PrimInfo xNameS xType wi C.SingleResult C.NoUnfolding)
646 | otherwise
647 -> do bndr <- coreToId x
648 return (C.Prim (C.PrimInfo xNameS xType wi C.SingleResult (C.Unfolding bndr)))
649 Just (Just (BlackBoxHaskell {workInfo = wi}))
650 | x `elem` unlocs
651 -> return $ C.Prim (C.PrimInfo xNameS xType wi C.SingleResult C.NoUnfolding)
652 | otherwise
653 -> do bndr <- coreToId x
654 return $ C.Prim (C.PrimInfo xNameS xType wi C.SingleResult (C.Unfolding bndr))
655 Just Nothing ->
656 -- Was guarded by "DontTranslate". We don't know yet if Clash will
657 -- actually use it later on, so we don't err here.
658 return $ C.Prim (C.PrimInfo xNameS xType C.WorkVariable C.SingleResult C.NoUnfolding)
659 Nothing
660 | x `elem` unlocs
661 -> return (C.Prim (C.PrimInfo xNameS xType C.WorkVariable C.SingleResult C.NoUnfolding))
662 | otherwise
663 -> C.Var <$> coreToId x
664
665 #if MIN_VERSION_ghc(9,2,0)
666 alt _ (Alt DEFAULT _ e) = (C.DefaultPat,) <$> term e
667 alt _ (Alt (LitAlt l) _ e) = (C.LitPat (coreToLiteral l),) <$> term e
668 alt sp0 (Alt (DataAlt dc) xs e) = case span isTyVar xs of
669 #else
670 alt _ (DEFAULT , _ , e) = (C.DefaultPat,) <$> term e
671 alt _ (LitAlt l , _ , e) = (C.LitPat (coreToLiteral l),) <$> term e
672 alt sp0 (DataAlt dc, xs, e) = case span isTyVar xs of
673 #endif
674 (tyvs,tmvs) -> do
675 (e',sp1) <- termSP sp0 e
676 (,) <$> (C.DataPat <$> coreToDataCon dc
677 <*> mapM coreToTyVar tyvs
678 <*> mapM (coreToIdSP sp1) tmvs)
679 <*> pure e'
680
681 coreToLiteral :: Literal
682 -> C.Literal
683 coreToLiteral l = case l of
684 #if MIN_VERSION_ghc(8,8,0)
685 LitString fs -> C.StringLiteral (Char8.unpack fs)
686 LitChar c -> C.CharLiteral c
687 LitRubbish{} ->
688 error $ "coreToTerm: Encountered LibRubbish. This is a bug in Clash. "
689 ++ "Report on https://github.com/clash-lang/clash-compiler/issues."
690 #else
691 MachStr fs -> C.StringLiteral (Char8.unpack fs)
692 MachChar c -> C.CharLiteral c
693 #endif
694 #if MIN_VERSION_ghc(9,0,0)
695 LitNumber lt i -> case lt of
696 #else
697 LitNumber lt i _ -> case lt of
698 #endif
699 #if MIN_VERSION_ghc(9,4,0)
700 LitNumBigNat -> C.ByteArrayLiteral (ByteArray (integerToBigNatClamp# i))
701 #else
702 LitNumInteger -> C.IntegerLiteral i
703 LitNumNatural -> C.NaturalLiteral i
704 #endif
705 LitNumInt -> C.IntLiteral i
706 LitNumInt64 -> C.Int64Literal i
707 LitNumWord -> C.WordLiteral i
708 LitNumWord64 -> C.Word64Literal i
709 #if MIN_VERSION_ghc(9,2,0)
710 LitNumInt8 -> C.Int8Literal i
711 LitNumInt16 -> C.Int16Literal i
712 LitNumInt32 -> C.Int32Literal i
713 LitNumWord8 -> C.Word8Literal i
714 LitNumWord16 -> C.Word16Literal i
715 LitNumWord32 -> C.Word32Literal i
716 #endif
717 #if MIN_VERSION_ghc(8,8,0)
718 LitFloat r -> C.FloatLiteral . floatToWord $ fromRational r
719 LitDouble r -> C.DoubleLiteral . doubleToWord $ fromRational r
720 LitNullAddr -> C.StringLiteral []
721 LitLabel fs _ _ -> C.StringLiteral (unpackFS fs)
722 #else
723 MachFloat r -> C.FloatLiteral . floatToWord $ fromRational r
724 MachDouble r -> C.DoubleLiteral . doubleToWord $ fromRational r
725 MachNullAddr -> C.StringLiteral []
726 MachLabel fs _ _ -> C.StringLiteral (unpackFS fs)
727 #endif
728
729 addUsefull :: SrcSpan
730 -> C2C a
731 -> C2C a
732 addUsefull x m =
733 if isGoodSrcSpan x
734 then do a <- RWS.local (srcSpan .~ x) m
735 RWS.tell (SrcSpanRB x)
736 return a
737 else m
738
739 addUsefullR :: SrcSpan
740 -> C2C a
741 -> C2C a
742 addUsefullR x m =
743 if isGoodSrcSpan x
744 then RWS.local (srcSpan .~ x) m
745 else m
746
747 isSizedCast :: Type -> Type -> C2C Bool
748 isSizedCast (TyConApp tc1 _) (TyConApp tc2 _) = do
749 tc1Nm <- qualifiedNameString (tyConName tc1)
750 tc2Nm <- qualifiedNameString (tyConName tc2)
751 return
752 (or [tc1 `hasKey` integerTyConKey &&
753 or [tc2Nm == "Clash.Sized.Internal.Signed.Signed"
754 ,tc2Nm == "Clash.Sized.Internal.Index.Index"]
755 ,tc2 `hasKey` integerTyConKey &&
756 or [tc1Nm == "Clash.Sized.Internal.Signed.Signed"
757 ,tc1Nm == "Clash.Sized.Internal.Index.Index"]
758 ,tc1 `hasKey` naturalTyConKey &&
759 tc2Nm == "Clash.Sized.Internal.Unsigned.Unsigned"
760 ,tc2 `hasKey` naturalTyConKey &&
761 tc1Nm == "Clash.Sized.Internal.Unsigned.Unsigned"
762 ])
763 isSizedCast _ _ = return False
764
765 hasPrimCo :: Coercion -> C2C (Maybe Type)
766 hasPrimCo (TyConAppCo _ _ coers) = do
767 tcs <- catMaybes <$> mapM hasPrimCo coers
768 return (listToMaybe tcs)
769
770 hasPrimCo (AppCo co1 co2) = do
771 tc1M <- hasPrimCo co1
772 case tc1M of
773 Just _ -> return tc1M
774 _ -> hasPrimCo co2
775 #if MIN_VERSION_ghc(9,10,0)
776 hasPrimCo (ForAllCo {fco_body = co}) = hasPrimCo co
777 #else
778 hasPrimCo (ForAllCo _ _ co) = hasPrimCo co
779 #endif
780
781 hasPrimCo co@(AxiomInstCo _ _ coers) = do
782 let (Pair ty1 _) = coercionKind co
783 ty1PM <- isPrimTc ty1
784 if ty1PM
785 then return (Just ty1)
786 else do
787 tcs <- catMaybes <$> mapM hasPrimCo coers
788 return (listToMaybe tcs)
789 where
790 isPrimTc (TyConApp tc _) = do
791 tcNm <- qualifiedNameString (tyConName tc)
792 return (tcNm `elem` ["Clash.Sized.Internal.BitVector.Bit"
793 ,"Clash.Sized.Internal.BitVector.BitVector"
794 ,"Clash.Sized.Internal.Index.Index"
795 ,"Clash.Sized.Internal.Signed.Signed"
796 ,"Clash.Sized.Internal.Unsigned.Unsigned"
797 ])
798 isPrimTc _ = return False
799
800 hasPrimCo (SymCo co) = hasPrimCo co
801
802 hasPrimCo (TransCo co1 co2) = do
803 tc1M <- hasPrimCo co1
804 case tc1M of
805 Just _ -> return tc1M
806 _ -> hasPrimCo co2
807
808 hasPrimCo (AxiomRuleCo _ coers) = do
809 tcs <- catMaybes <$> mapM hasPrimCo coers
810 return (listToMaybe tcs)
811
812 #if MIN_VERSION_ghc(9,6,0)
813 hasPrimCo (SelCo _ co) = hasPrimCo co
814 #else
815 hasPrimCo (NthCo _ _ co) = hasPrimCo co
816 #endif
817 hasPrimCo (LRCo _ co) = hasPrimCo co
818 hasPrimCo (InstCo co _) = hasPrimCo co
819 hasPrimCo (SubCo co) = hasPrimCo co
820
821 hasPrimCo _ = return Nothing
822
823 coreToDataCon :: DataCon
824 -> C2C C.DataCon
825 coreToDataCon dc = do
826 #if MIN_VERSION_ghc(9,0,0)
827 repTys <- mapM (coreToType . scaledThing) (dataConRepArgTys dc)
828 #else
829 repTys <- mapM coreToType (dataConRepArgTys dc)
830 #endif
831 dcTy <- coreToType (varType $ dataConWorkId dc)
832 mkDc dcTy repTys
833 where
834 mkDc dcTy repTys = do
835 #if MIN_VERSION_ghc(9,6,0)
836 let decLabel = decodeUtf8 . bytesFS . field_label . flLabel
837 #elif MIN_VERSION_ghc(8,10,0)
838 let decLabel = decodeUtf8 . bytesFS . flLabel
839 #else
840 let decLabel = decodeUtf8 . fastStringToByteString . flLabel
841 #endif
842 let repBangs = fmap hsImplBangToBool (dataConImplBangs dc)
843 let fLabels = map decLabel (dataConFieldLabels dc)
844
845 nm <- coreToName dataConName getUnique qualifiedNameString dc
846 uTvs <- mapM coreToTyVar (dataConUnivTyVars dc)
847 #if MIN_VERSION_ghc(8,8,0)
848 eTvs <- mapM coreToTyVar (dataConExTyCoVars dc)
849 #else
850 eTvs <- mapM coreToTyVar (dataConExTyVars dc)
851 #endif
852 return $ C.MkData
853 { C.dcName = nm
854 , C.dcUniq = C.nameUniq nm
855 , C.dcTag = dataConTag dc
856 , C.dcType = dcTy
857 , C.dcArgTys = repTys
858 , C.dcArgStrict = repBangs
859 , C.dcUnivTyVars = uTvs
860 , C.dcExtTyVars = eTvs
861 , C.dcFieldLabels = fLabels
862 }
863
864 hsImplBangToBool :: HsImplBang -> C.DcStrictness
865 hsImplBangToBool HsLazy = C.Lazy
866 hsImplBangToBool HsStrict{} = C.Strict
867 hsImplBangToBool HsUnpack{} = C.Strict
868
869 typeConstructorToString
870 :: TyCon
871 -> C2C String
872 typeConstructorToString constructor =
873 Text.unpack . C.nameOcc <$> coreToName tyConName tyConUnique qualifiedNameString constructor
874
875 -- | Flatten a list type structure to a list of types.
876 listTypeToListOfTypes :: Type -> [Type]
877 -- TyConApp ': [kind, head, tail]
878 listTypeToListOfTypes (TyConApp _ [_, a, as]) = a : listTypeToListOfTypes as
879 listTypeToListOfTypes ty =
880 case coreView ty of
881 Nothing -> []
882 Just ty' -> listTypeToListOfTypes ty'
883
884 -- | Try to determine boolean value by looking at constructor name of type.
885 boolTypeToBool :: Type -> C2C Bool
886 boolTypeToBool (TyConApp constructor _args) = do
887 constructorName <- typeConstructorToString constructor
888 return $ case constructorName of
889 "GHC.Types.True" -> True
890 "GHC.Types.False" -> False
891 _ -> error $ "Expected boolean constructor, got:" ++ constructorName
892 boolTypeToBool s =
893 error $ unwords [ "Could not unpack given type to bool:"
894 , showPprUnsafe s ]
895
896 -- | Returns string of (LitTy (StrTyLit s)) construction.
897 tyLitToString :: Type -> String
898 tyLitToString (LitTy (StrTyLit s)) = unpackFS s
899 tyLitToString s = error $ unwords [ "Could not unpack given type to string:"
900 , showPprUnsafe s ]
901
902 -- | Returns string in Text form of (LitTy (StrTyLit s)) construction.
903 tyLitToText :: Type -> Text
904 tyLitToText = Text.pack . tyLitToString
905
906 -- | Returns integer of (LitTy (NumTyLit n)) construction.
907 tyLitToInteger :: Type -> Integer
908 tyLitToInteger (LitTy (NumTyLit n)) = n
909 tyLitToInteger s = error $ unwords [ "Could not unpack given type to integer:"
910 , showPprUnsafe s ]
911
912 -- | Try to interpret a Type as an Attr
913 coreToAttr :: Type -> C2C (Attr Text)
914 coreToAttr t0@(TyConApp ty args) = do
915 name <- typeConstructorToString ty
916 envs <- view famInstEnvs
917 let
918 -- XXX: This relies on 'value' not being evaluated if the constructor
919 -- doesn't have a second field.
920 key = args !! 1
921 value = args !! 2
922 #if MIN_VERSION_ghc(9,4,0)
923 let Reduction _ key1 = normaliseType envs Nominal key
924 Reduction _ value1 = normaliseType envs Nominal value
925 #else
926 let (_,key1) = normaliseType envs Nominal key
927 (_,value1) = normaliseType envs Nominal value
928 #endif
929 if
930 | name == show 'StringAttr ->
931 return $ StringAttr (tyLitToText key1) (tyLitToText value1)
932 | name == show 'IntegerAttr ->
933 return $ IntegerAttr (tyLitToText key1) (tyLitToInteger value1)
934 | name == show 'BoolAttr -> do
935 bool <- boolTypeToBool value1
936 return $ BoolAttr (tyLitToText key1) bool
937 | name == show 'Attr ->
938 return $ Attr (tyLitToText key1)
939 | otherwise ->
940 case coreView t0 of
941 Just t1 -> coreToAttr t1
942 Nothing -> error $ [__i|Expected constructor of Attr, got #{name}|]
943 coreToAttr t0 =
944 case coreView t0 of
945 Just t1 -> coreToAttr t1
946 Nothing -> error $ [__i|Expected constructor of Attr, got #{showPprUnsafe t0}|]
947
948 coreToAttrs' :: [Type] -> C2C [Attr Text]
949 coreToAttrs' [k, a, attrs] = do
950 -- We expect three type arguments:
951 --
952 -- k: either @Attr@ or @[Attr]@
953 -- a: type being annotated
954 -- attrs: attribute or list of attributes
955 --
956 attrs1 <- tryList
957 attrs2 <- tryAttr
958 case attrs1 <|> attrs2 of
959 Just theseAttrs -> do
960 subAttrs <- coreToAttrs a
961 pure (theseAttrs <> subAttrs)
962 Nothing ->
963 error [__i|
964 Expected either an attribute or a list of attributes, got:
965
966 #{showPprUnsafe k}
967 |]
968 where
969
970 isListTy = fmap (== show ''[]) . typeConstructorToString
971 isAttrTy = fmap (== show ''Attr) . typeConstructorToString
972
973 tryList = case k of
974 TyConApp ty0 [TyConApp ty1 _] -> do
975 ifM
976 (andM [isListTy ty0, isAttrTy ty1])
977 (Just <$> traverse coreToAttr (listTypeToListOfTypes attrs))
978 (pure Nothing)
979 _ -> pure Nothing
980
981 tryAttr = case k of
982 TyConApp ty _ -> do
983 ifM
984 (isAttrTy ty)
985 (Just <$> sequence [coreToAttr attrs])
986 (pure Nothing)
987 _ -> pure Nothing
988
989 coreToAttrs' illegal =
990 error $ "Unexpected type args to Annotate: " ++ show (map (showPprUnsafe) illegal)
991
992 -- | If this type has an annotate type synonym, return list of attributes.
993 coreToAttrs :: Type -> C2C [Attr Text]
994 coreToAttrs (TyConApp tycon kindsOrTypes) = do
995 name' <- typeConstructorToString tycon
996
997 if name' == show ''Annotate
998 then coreToAttrs' kindsOrTypes
999 else return []
1000
1001 coreToAttrs _ =
1002 return []
1003
1004 -- | Wrap given type in an annotation if it is annotated using the constructs
1005 -- defined in Clash.Annotations.SynthesisAttributes.
1006 annotateType
1007 :: Type
1008 -> C.Type
1009 -> C2C C.Type
1010 annotateType ty cty = do
1011 attrs <- coreToAttrs ty
1012 case attrs of
1013 [] -> return cty
1014 _ -> return $ C.AnnType attrs cty
1015
1016 -- | Converts GHC Type to a Clash Type. Strips newtypes and signals, with the
1017 -- exception of newtypes used as annotations (see: SynthesisAttributes).
1018 coreToType
1019 :: Type
1020 -> C2C C.Type
1021 coreToType ty = ty'' >>= annotateType ty
1022 where
1023 ty'' =
1024 case coreView ty of
1025 Just ty' -> coreToType ty'
1026 Nothing -> coreToType' ty
1027
1028 coreToType'
1029 :: Type
1030 -> C2C C.Type
1031 coreToType' (TyVarTy tv) = C.VarTy <$> coreToTyVar tv
1032 coreToType' (TyConApp tc args)
1033 #if MIN_VERSION_ghc(9,6,0)
1034 | Just (FunTy _ _ ty1 ty2) <- tyConAppFunTy_maybe tc args = C.mkFunTy <$> coreToType ty1 <*> coreToType ty2
1035 #else
1036 | isFunTyCon tc = foldl C.AppTy (C.ConstTy C.Arrow) <$> mapM coreToType args
1037 #endif
1038 | otherwise = case expandSynTyCon_maybe tc args of
1039 #if MIN_VERSION_ghc(9,6,0)
1040 ExpandsSyn substs synTy remArgs -> do
1041 #else
1042 Just (substs,synTy,remArgs) -> do
1043 #endif
1044 let substs' = mkTvSubstPrs substs
1045 synTy' = substTy substs' synTy
1046 foldl C.AppTy <$> coreToType synTy' <*> mapM coreToType remArgs
1047 _ -> do
1048 tcName <- coreToName tyConName tyConUnique qualifiedNameString tc
1049 tyConMap %= (C.insert tcName tc)
1050 C.mkTyConApp <$> (pure tcName) <*> mapM coreToType args
1051 #if MIN_VERSION_ghc(8,8,0)
1052 coreToType' (ForAllTy (Bndr tv _) ty) = C.ForAllTy <$> coreToTyVar tv <*> coreToType ty
1053 #else
1054 coreToType' (ForAllTy (TvBndr tv _) ty) = C.ForAllTy <$> coreToTyVar tv <*> coreToType ty
1055 #endif
1056 #if MIN_VERSION_ghc(8,10,0)
1057 -- TODO after we drop 8.8: save the distinction between => and ->
1058 #if MIN_VERSION_ghc(9,0,0)
1059 coreToType' (FunTy _ _ ty1 ty2) = C.mkFunTy <$> coreToType ty1 <*> coreToType ty2
1060 #else
1061 coreToType' (FunTy _ ty1 ty2) = C.mkFunTy <$> coreToType ty1 <*> coreToType ty2
1062 #endif
1063 #else
1064 coreToType' (FunTy ty1 ty2) = C.mkFunTy <$> coreToType ty1 <*> coreToType ty2
1065 #endif
1066 coreToType' (LitTy tyLit) = return $ C.LitTy (coreToTyLit tyLit)
1067 coreToType' (AppTy ty1 ty2) = C.AppTy <$> coreToType ty1 <*> coreToType' ty2
1068 coreToType' (CastTy t (Refl{})) = coreToType' t
1069 coreToType' t@(CastTy _ _) = error ("Cannot handle CastTy " ++ showPprUnsafe t)
1070 coreToType' t@(CoercionTy _) = error ("Cannot handle CoercionTy " ++ showPprUnsafe t)
1071
1072 coreToTyLit :: TyLit
1073 -> C.LitTy
1074 coreToTyLit (NumTyLit i) = C.NumTy (fromInteger i)
1075 coreToTyLit (StrTyLit s) = C.SymTy (unpackFS s)
1076 #if MIN_VERSION_ghc(9,2,0)
1077 coreToTyLit (CharTyLit c) = C.CharTy c
1078 #endif
1079
1080 coreToTyVar :: TyVar
1081 -> C2C C.TyVar
1082 coreToTyVar tv =
1083 C.mkTyVar <$> coreToType (varType tv) <*> coreToVar tv
1084
1085 coreToId :: Id
1086 -> C2C C.Id
1087 coreToId i = do
1088 C.mkId <$> coreToType (varType i) <*> pure scope <*> coreToVar i
1089 where
1090 scope = if isGlobalId i then C.GlobalId else C.LocalId
1091
1092 coreToVar :: Var
1093 -> C2C (C.Name a)
1094 coreToVar = coreToName varName varUnique qualifiedNameStringM
1095
1096 coreToPrimVar :: Var
1097 -> C2C (C.Name C.Term)
1098 coreToPrimVar = coreToName varName varUnique qualifiedNameString
1099
1100 coreToName
1101 :: (b -> Name)
1102 -> (b -> Unique)
1103 -> (Name -> C2C Text)
1104 -> b
1105 -> C2C (C.Name a)
1106 coreToName toName toUnique toString v = do
1107 ns <- toString (toName v)
1108 let key = fromGhcUnique (toUnique v)
1109 locI = getSrcSpan (toName v)
1110 -- Is it one of [ds,ds1,ds2,..]
1111 isDSX = maybe False (maybe True (isDigit . fst) . Text.uncons) . Text.stripPrefix "ds"
1112 sort | isDSX ns || Text.isPrefixOf "$" ns
1113 = C.System
1114 | otherwise
1115 = C.User
1116 locR <- view srcSpan
1117 let loc = if isGoodSrcSpan locI then locI else locR
1118 return (C.Name sort ns key loc)
1119
1120 qualifiedNameString'
1121 :: Name
1122 -> Text
1123 qualifiedNameString' n =
1124 fromMaybe "_INTERNAL_" (modNameM n) `Text.append` ('.' `Text.cons` occName)
1125 where
1126 occName = pack (occNameString (nameOccName n))
1127
1128 qualifiedNameString
1129 :: Name
1130 -> C2C Text
1131 qualifiedNameString n =
1132 makeCached n nameMap $
1133 return (fromMaybe "_INTERNAL_" (modNameM n) `Text.append` ('.' `Text.cons` occName))
1134 where
1135 occName = pack (occNameString (nameOccName n))
1136
1137 qualifiedNameStringM
1138 :: Name
1139 -> C2C Text
1140 qualifiedNameStringM n =
1141 makeCached n nameMap $
1142 return (maybe occName (\modName -> modName `Text.append` ('.' `Text.cons` occName)) (modNameM n))
1143 where
1144 occName = pack (occNameString (nameOccName n))
1145
1146 modNameM :: Name
1147 -> Maybe Text
1148 modNameM n = do
1149 module_ <- nameModule_maybe n
1150 let moduleNm = moduleName module_
1151 return (pack (moduleNameString moduleNm))
1152
1153 -- | Given the type:
1154 --
1155 -- @
1156 -- forall dom a0 a1 .. aN
1157 -- . Signal dom (a0, a1, .., aN)
1158 -- -> (Signal dom a0, Signal dom a1, .., Signal dom aN)
1159 -- @
1160 --
1161 -- or the type
1162 --
1163 -- @
1164 -- forall dom a0 a1 .. aN
1165 -- . (Signal dom a0, Signal dom a1, .., Signal dom aN)
1166 -- -> Signal dom (a0, a1, .., aN)
1167 -- @
1168 --
1169 -- Generate the term:
1170 --
1171 -- @/\dom. /\a0. /\a1. .. /\aN. \x -> x@
1172 --
1173 -- In other words: treat "bundle" and "unbundle" primitives as id.
1174 --
1175 bundleUnbundleTerm :: Int -> C.Type -> C.Term
1176 bundleUnbundleTerm nTyVarsExpected = go []
1177 where
1178 go :: [C.TyVar] -> C.Type -> C.Term
1179 go tvs (C.ForAllTy tv typ) = go (tv:tvs) typ
1180 go tvs (C.tyView -> C.FunTy argTy _resTy) =
1181 if length tvs /= nTyVarsExpected then
1182 -- Internal error: should never happen unless we change the type of
1183 -- bundle / unbundle.
1184 error $ $(curLoc) ++ show (length tvs) ++ " vs " ++ show nTyVarsExpected
1185 else
1186 let sigName = C.mkLocalId argTy (C.mkUnsafeSystemName "c$s" 0) in
1187 foldr C.TyLam (C.Lam sigName (C.Var sigName)) (reverse tvs)
1188 go tvs ty = error $ $(curLoc) ++ show ty ++ " " ++ show tvs
1189
1190
1191 -- | Given the type:
1192 --
1193 -- @forall a. forall b. forall clk. (a -> b) -> Signal clk a -> Signal clk b@
1194 --
1195 -- Generate the term:
1196 --
1197 -- @
1198 -- /\(a:*)./\(b:*)./\(clk:Clock).\(f : (Signal clk a -> Signal clk b)).
1199 -- \(x : Signal clk a).f x
1200 -- @
1201 mapSignalTerm :: C.Type
1202 -> C.Term
1203 mapSignalTerm (C.ForAllTy aTV (C.ForAllTy bTV (C.ForAllTy clkTV funTy)))
1204 | (C.FunTy _ funTy'') <- C.tyView funTy
1205 , (C.FunTy aTy bTy) <- C.tyView funTy''
1206 = let
1207 fName = C.mkUnsafeSystemName "f" 0
1208 xName = C.mkUnsafeSystemName "x" 1
1209 fTy = C.mkFunTy aTy bTy
1210 fId = C.mkLocalId fTy fName
1211 xId = C.mkLocalId aTy xName
1212 in
1213 C.TyLam aTV (
1214 C.TyLam bTV (
1215 C.TyLam clkTV (
1216 C.Lam fId (
1217 C.Lam xId (
1218 C.App (C.Var fId) (C.Var xId))))))
1219
1220 mapSignalTerm ty = error $ $(curLoc) ++ show ty
1221
1222 -- | Given the type:
1223 --
1224 -- @forall a. forall dom. a -> Signal dom a@
1225 --
1226 -- Generate the term
1227 --
1228 -- @/\(a:*)./\(dom:Domain).\(x:Signal dom a).x@
1229 signalTerm :: C.Type
1230 -> C.Term
1231 signalTerm (C.ForAllTy aTV (C.ForAllTy domTV funTy))
1232 | (C.FunTy _ saTy) <- C.tyView funTy
1233 = let
1234 xName = C.mkUnsafeSystemName "x" 0
1235 xId = C.mkLocalId saTy xName
1236 in
1237 C.TyLam aTV (
1238 C.TyLam domTV (
1239 C.Lam xId (
1240 C.Var xId)))
1241
1242 signalTerm ty = error $ $(curLoc) ++ show ty
1243
1244 -- | Given the type:
1245 --
1246 -- @
1247 -- forall dom. forall a. forall b. Signal dom (a -> b) -> Signal dom a ->
1248 -- Signal dom b
1249 -- @
1250 --
1251 -- Generate the term:
1252 --
1253 -- @
1254 -- /\(dom:Domain)./\(a:*)./\(b:*).\(f : (Signal dom a -> Signal dom b)).
1255 -- \(x : Signal dom a).f x
1256 -- @
1257 appSignalTerm :: C.Type
1258 -> C.Term
1259 appSignalTerm (C.ForAllTy domTV (C.ForAllTy aTV (C.ForAllTy bTV funTy)))
1260 | (C.FunTy _ funTy'') <- C.tyView funTy
1261 , (C.FunTy saTy sbTy) <- C.tyView funTy''
1262 = let
1263 fName = C.mkUnsafeSystemName "f" 0
1264 xName = C.mkUnsafeSystemName "x" 1
1265 fTy = C.mkFunTy saTy sbTy
1266 fId = C.mkLocalId fTy fName
1267 xId = C.mkLocalId saTy xName
1268 in
1269 C.TyLam domTV (
1270 C.TyLam aTV (
1271 C.TyLam bTV (
1272 C.Lam fId (
1273 C.Lam xId (
1274 C.App (C.Var fId) (C.Var xId))))))
1275
1276 appSignalTerm ty = error $ $(curLoc) ++ show ty
1277
1278 -- | Given the type:
1279 --
1280 -- @
1281 -- forall t.forall n.forall a.Vec n (Signal t a) ->
1282 -- Signal t (Vec n a)
1283 -- @
1284 --
1285 -- Generate the term:
1286 --
1287 -- @
1288 -- /\(t:Domain)./\(n:Nat)./\(a:*).\(vs:Signal t (Vec n a)).vs
1289 -- @
1290 vecUnwrapTerm :: C.Type
1291 -> C.Term
1292 vecUnwrapTerm (C.ForAllTy tTV (C.ForAllTy nTV (C.ForAllTy aTV funTy)))
1293 | (C.FunTy _ vsTy) <- C.tyView funTy
1294 = let
1295 vsName = C.mkUnsafeSystemName "vs" 0
1296 vsId = C.mkLocalId vsTy vsName
1297 in
1298 C.TyLam tTV (
1299 C.TyLam nTV (
1300 C.TyLam aTV (
1301 C.Lam vsId (
1302 C.Var vsId))))
1303
1304 vecUnwrapTerm ty = error $ $(curLoc) ++ show ty
1305
1306 -- | Given the type:
1307 --
1308 -- @
1309 -- forall f.forall a.forall b.forall dom.Applicative f => (a -> f b) ->
1310 -- Signal dom a -> f (Signal dom b)
1311 -- @
1312 --
1313 -- Generate the term:
1314 --
1315 -- @
1316 -- /\(f:* -> *)./\(a:*)./\(b:*)./\(dom:Clock).\(dict:Applicative f).
1317 -- \(g:a -> f b).\(x:Signal dom a).g x
1318 -- @
1319 traverseTerm :: C.Type
1320 -> C.Term
1321 traverseTerm (C.ForAllTy fTV (C.ForAllTy aTV (C.ForAllTy bTV (C.ForAllTy domTV funTy))))
1322 | (C.FunTy dictTy funTy1) <- C.tyView funTy
1323 , (C.FunTy gTy funTy2) <- C.tyView funTy1
1324 , (C.FunTy xTy _) <- C.tyView funTy2
1325 = let
1326 dictName = C.mkUnsafeSystemName "dict" 0
1327 gName = C.mkUnsafeSystemName "g" 1
1328 xName = C.mkUnsafeSystemName "x" 2
1329 dictId = C.mkLocalId dictTy dictName
1330 gId = C.mkLocalId gTy gName
1331 xId = C.mkLocalId xTy xName
1332 in
1333 C.TyLam fTV (
1334 C.TyLam aTV (
1335 C.TyLam bTV (
1336 C.TyLam domTV (
1337 C.Lam dictId (
1338 C.Lam gId (
1339 C.Lam xId (
1340 C.App (C.Var gId) (C.Var xId))))))))
1341
1342 traverseTerm ty = error $ $(curLoc) ++ show ty
1343
1344 -- ∀ (r :: GHC.Types.RuntimeRep)
1345 -- (a :: GHC.Prim.TYPE GHC.Types.PtrRepLifted)
1346 -- (b :: GHC.Prim.TYPE r).
1347 -- (a -> b) -> a -> b
1348
1349
1350 -- | Given the type:
1351 --
1352 -- @forall (r :: Rep) (a :: TYPE Lifted) (b :: TYPE r). (a -> b) -> a -> b@
1353 --
1354 -- Generate the term:
1355 --
1356 -- @/\(r:Rep)/\(a:TYPE Lifted)./\(b:TYPE r).\(f : (a -> b)).\(x : a).f x@
1357 dollarTerm :: C.Type
1358 -> C.Term
1359 #if MIN_VERSION_ghc(9,8,0)
1360 dollarTerm (C.ForAllTy raTV (C.ForAllTy rbTV (C.ForAllTy aTV (C.ForAllTy bTV funTy))))
1361 | (C.FunTy fTy funTy'') <- C.tyView funTy
1362 , (C.FunTy aTy _) <- C.tyView funTy''
1363 = let
1364 fName = C.mkUnsafeSystemName "f" 0
1365 xName = C.mkUnsafeSystemName "x" 1
1366 fId = C.mkLocalId fTy fName
1367 xId = C.mkLocalId aTy xName
1368 in
1369 C.TyLam raTV (
1370 C.TyLam rbTV (
1371 C.TyLam aTV (
1372 C.TyLam bTV (
1373 C.Lam fId (
1374 C.Lam xId (
1375 C.App (C.Var fId) (C.Var xId)))))))
1376 #else
1377 dollarTerm (C.ForAllTy rTV (C.ForAllTy aTV (C.ForAllTy bTV funTy)))
1378 | (C.FunTy fTy funTy'') <- C.tyView funTy
1379 , (C.FunTy aTy _) <- C.tyView funTy''
1380 = let
1381 fName = C.mkUnsafeSystemName "f" 0
1382 xName = C.mkUnsafeSystemName "x" 1
1383 fId = C.mkLocalId fTy fName
1384 xId = C.mkLocalId aTy xName
1385 in
1386 C.TyLam rTV (
1387 C.TyLam aTV (
1388 C.TyLam bTV (
1389 C.Lam fId (
1390 C.Lam xId (
1391 C.App (C.Var fId) (C.Var xId))))))
1392 #endif
1393
1394 dollarTerm ty = error $ $(curLoc) ++ C.showPpr ty
1395
1396 -- | Given the type:
1397 --
1398 -- @forall a. forall dom. Signal dom (Signal dom a) -> Signal dom a@
1399 --
1400 -- Generate the term
1401 --
1402 -- @/\(a:*)./\(dom:Domain).\(x:Signal dom a).x@
1403 joinTerm :: C.Type
1404 -> C.Term
1405 joinTerm ty@(C.ForAllTy {}) = signalTerm ty
1406 joinTerm ty = error $ $(curLoc) ++ show ty
1407
1408 -- | Given the type:
1409 --
1410 -- @forall a. CallStack -> (HasCallStack => a) -> a@
1411 --
1412 -- Generate the term
1413 --
1414 -- @/\(a:*)./\(callStack:CallStack).\(f:HasCallStack => a).f callStack@
1415 withFrozenCallStackTerm
1416 :: C.Type
1417 -> C.Term
1418 withFrozenCallStackTerm (C.ForAllTy aTV funTy)
1419 | (C.FunTy callStackTy fTy) <- C.tyView funTy
1420 = let
1421 callStackName = C.mkUnsafeSystemName "callStack" 0
1422 fName = C.mkUnsafeSystemName "f" 1
1423 callStackId = C.mkLocalId callStackTy callStackName
1424 fId = C.mkLocalId fTy fName
1425 in
1426 C.TyLam aTV (
1427 C.Lam callStackId (
1428 C.Lam fId (
1429 C.App (C.Var fId) (C.Var callStackId))))
1430
1431 withFrozenCallStackTerm ty = error $ $(curLoc) ++ show ty
1432
1433 -- | Given the type:
1434 --
1435 -- @forall a. a -> a@
1436 --
1437 -- Generate the term
1438 --
1439 -- @/\(a:*).\(x:a).x@
1440 idTerm
1441 :: C.Type
1442 -> C.Term
1443 idTerm (C.ForAllTy aTV funTy)
1444 | (C.FunTy xTy _) <- C.tyView funTy
1445 = let
1446 xName = C.mkUnsafeSystemName "x" 0
1447 xId = C.mkLocalId xTy xName
1448 in
1449 C.TyLam aTV (
1450 C.Lam xId (
1451 C.Var xId))
1452
1453 idTerm ty = error $ $(curLoc) ++ show ty
1454
1455 -- | Given type type:
1456 --
1457 -- @forall (r :: RuntimeRep) (o :: TYPE r).(State# RealWorld -> o) -> o@
1458 --
1459 -- Generate the term:
1460 --
1461 -- @/\(r:RuntimeRep)./\(o:TYPE r).\(f:State# RealWord -> o) -> f realWorld#@
1462 runRWTerm
1463 :: C.Type
1464 -> C.Term
1465 runRWTerm (C.ForAllTy rTV (C.ForAllTy oTV funTy))
1466 | (C.FunTy fTy _) <- C.tyView funTy
1467 , (C.FunTy rwTy _) <- C.tyView fTy
1468 = let
1469 fName = C.mkUnsafeSystemName "f" 0
1470 fId = C.mkLocalId fTy fName
1471 rwNm = pack "GHC.Prim.realWorld#"
1472 in
1473 C.TyLam rTV (
1474 C.TyLam oTV (
1475 C.Lam fId (
1476 (C.App (C.Var fId)
1477 (C.Prim (C.PrimInfo rwNm rwTy C.WorkNever C.SingleResult C.NoUnfolding))))))
1478
1479 runRWTerm ty = error $ $(curLoc) ++ show ty
1480
1481 -- | Given type type:
1482 --
1483 -- @forall (n :: Nat) (a :: Type) .Knownnat n => Typeable a => (BitVector n -> a) -> BitVector n -> a@
1484 --
1485 -- Generate the term:
1486 --
1487 -- @/\(n:Nat)./\(a:TYPE r).\(kn:KnownNat n).\(f:a -> BitVector n).f@
1488 checkUnpackUndefTerm
1489 :: C.Type
1490 -> C.Term
1491 checkUnpackUndefTerm (C.ForAllTy nTV (C.ForAllTy aTV funTy))
1492 | C.FunTy knTy r0Ty <- C.tyView funTy
1493 , C.FunTy tpTy r1Ty <- C.tyView r0Ty
1494 , C.FunTy fTy _ <- C.tyView r1Ty
1495 = let
1496 knName = C.mkUnsafeSystemName "kn" 0
1497 tpName = C.mkUnsafeSystemName "tp" 1
1498 fName = C.mkUnsafeSystemName "f" 2
1499 knId = C.mkLocalId knTy knName
1500 tpId = C.mkLocalId tpTy tpName
1501 fId = C.mkLocalId fTy fName
1502 in
1503 C.TyLam nTV (
1504 C.TyLam aTV (
1505 C.Lam knId (
1506 C.Lam tpId (
1507 C.Lam fId (
1508 C.Var fId)))))
1509
1510 checkUnpackUndefTerm ty = error $ $(curLoc) ++ show ty
1511
1512 -- | Given the type:
1513 --
1514 -- @forall (name :: Symbol) (a :: Type) . a -> (name ::: a)@
1515 --
1516 -- Generate the term:
1517 --
1518 -- @/\(name:Symbol)./\(a:Type).\(x:a) -> <TICK>x@
1519 nameModTerm
1520 :: C.NameMod
1521 -> C.Type
1522 -> C.Term
1523 nameModTerm sa (C.ForAllTy nmTV (C.ForAllTy aTV funTy))
1524 | (C.FunTy xTy _) <- C.tyView funTy
1525 = let
1526 -- Safe to use `mkUnsafeSystemName` here, because we're building the
1527 -- identity \x.x, so any shadowing of 'x' would be the desired behavior.
1528 xName = C.mkUnsafeSystemName "x" 0
1529 xId = C.mkLocalId xTy xName
1530 in
1531 C.TyLam nmTV (
1532 C.TyLam aTV (
1533 C.Lam xId (
1534 (C.Tick (C.NameMod sa (C.VarTy nmTV)) (C.Var xId)))))
1535
1536 nameModTerm _ ty = error $ $(curLoc) ++ show ty
1537
1538
1539 -- | Given the type:
1540 --
1541 -- @forall (a :: Type) . String -> a -> a@
1542 --
1543 -- Generate the term:
1544 --
1545 -- @/\(a:Type).\(ctx:String).\(x:a) -> x@
1546 xToErrorCtxTerm
1547 :: C.Type
1548 -> C.Term
1549 xToErrorCtxTerm (C.ForAllTy aTV funTy)
1550 | (C.FunTy ctxTy rTy) <- C.tyView funTy
1551 , (C.FunTy xTy _) <- C.tyView rTy
1552 = let
1553 -- Safe to use `mkUnsafeSystemName` here, because we're building the
1554 -- identity \_ x.x, so any shadowing of 'x' would be the desired behavior.
1555 ctxName = C.mkUnsafeSystemName "ctx" 0
1556 ctxId = C.mkLocalId ctxTy ctxName
1557 xName = C.mkUnsafeSystemName "x" 1
1558 xId = C.mkLocalId xTy xName
1559 in
1560 C.TyLam aTV (
1561 C.Lam ctxId (
1562 C.Lam xId (
1563 C.Var xId)))
1564
1565 xToErrorCtxTerm ty = error $ $(curLoc) ++ show ty
1566
1567 isDataConWrapId :: Id -> Bool
1568 isDataConWrapId v = case idDetails v of
1569 DataConWrapId {} -> True
1570 _ -> False