ghc-lib 0.20210228 → 0.20210331
raw patch · 205 files changed
+12958/−9810 lines, 205 filesdep ~basedep ~ghc-lib-parserPVP ok
version bump matches the API change (PVP)
Dependency ranges changed: base, ghc-lib-parser
API changes (from Hackage documentation)
- GHC: AnnBlockComment :: String -> AnnotationComment
- GHC: AnnDocCommentNamed :: String -> AnnotationComment
- GHC: AnnDocCommentNext :: String -> AnnotationComment
- GHC: AnnDocCommentPrev :: String -> AnnotationComment
- GHC: AnnDocOptions :: String -> AnnotationComment
- GHC: AnnDocSection :: Int -> String -> AnnotationComment
- GHC: AnnLineComment :: String -> AnnotationComment
- GHC: ApiAnns :: Map ApiAnnKey [RealSrcSpan] -> Maybe RealSrcSpan -> Map RealSrcSpan [RealLocated AnnotationComment] -> [RealLocated AnnotationComment] -> ApiAnns
- GHC: SevDump :: Severity
- GHC: SevFatal :: Severity
- GHC: SevInfo :: Severity
- GHC: SevInteractive :: Severity
- GHC: SevOutput :: Severity
- GHC: [apiAnnComments] :: ApiAnns -> Map RealSrcSpan [RealLocated AnnotationComment]
- GHC: [apiAnnEofPos] :: ApiAnns -> Maybe RealSrcSpan
- GHC: [apiAnnItems] :: ApiAnns -> Map ApiAnnKey [RealSrcSpan]
- GHC: [apiAnnRogueComments] :: ApiAnns -> [RealLocated AnnotationComment]
- GHC: [dirsToClean] :: DynFlags -> IORef (Map FilePath FilePath)
- GHC: [filesToClean] :: DynFlags -> IORef FilesToClean
- GHC: [nextTempSuffix] :: DynFlags -> IORef Int
- GHC: [pm_annotations] :: ParsedModule -> ApiAnns
- GHC: data AnnotationComment
- GHC: data ApiAnns
- GHC: getAndRemoveAnnotation :: ApiAnns -> RealSrcSpan -> AnnKeywordId -> ([RealSrcSpan], ApiAnns)
- GHC: getAndRemoveAnnotationComments :: ApiAnns -> RealSrcSpan -> ([RealLocated AnnotationComment], ApiAnns)
- GHC: getAnnotation :: ApiAnns -> RealSrcSpan -> AnnKeywordId -> [RealSrcSpan]
- GHC: getAnnotationComments :: ApiAnns -> RealSrcSpan -> [RealLocated AnnotationComment]
- GHC: type ApiAnnKey = (RealSrcSpan, AnnKeywordId)
- GHC: unicodeAnn :: AnnKeywordId -> AnnKeywordId
- GHC.Builtin.Types.Literals: typeNatLeqTyCon :: TyCon
- GHC.CmmToLlvm.Base: supportedLlvmVersion :: LlvmVersion
- GHC.CoreToByteCode: byteCodeGen :: HscEnv -> Module -> CoreProgram -> [TyCon] -> Maybe ModBreaks -> IO CompiledByteCode
- GHC.CoreToByteCode: coreExprToBCOs :: HscEnv -> Module -> CoreExpr -> IO UnlinkedBCO
- GHC.CoreToByteCode: data UnlinkedBCO
- GHC.CoreToByteCode: instance GHC.Base.Applicative GHC.CoreToByteCode.BcM
- GHC.CoreToByteCode: instance GHC.Base.Functor GHC.CoreToByteCode.BcM
- GHC.CoreToByteCode: instance GHC.Base.Monad GHC.CoreToByteCode.BcM
- GHC.CoreToByteCode: instance GHC.Classes.Eq GHC.CoreToByteCode.ByteOff
- GHC.CoreToByteCode: instance GHC.Classes.Eq GHC.CoreToByteCode.Discr
- GHC.CoreToByteCode: instance GHC.Classes.Eq GHC.CoreToByteCode.WordOff
- GHC.CoreToByteCode: instance GHC.Classes.Ord GHC.CoreToByteCode.ByteOff
- GHC.CoreToByteCode: instance GHC.Classes.Ord GHC.CoreToByteCode.Discr
- GHC.CoreToByteCode: instance GHC.Classes.Ord GHC.CoreToByteCode.WordOff
- GHC.CoreToByteCode: instance GHC.Driver.Session.HasDynFlags GHC.CoreToByteCode.BcM
- GHC.CoreToByteCode: instance GHC.Enum.Enum GHC.CoreToByteCode.ByteOff
- GHC.CoreToByteCode: instance GHC.Enum.Enum GHC.CoreToByteCode.WordOff
- GHC.CoreToByteCode: instance GHC.Num.Num GHC.CoreToByteCode.ByteOff
- GHC.CoreToByteCode: instance GHC.Num.Num GHC.CoreToByteCode.WordOff
- GHC.CoreToByteCode: instance GHC.Real.Integral GHC.CoreToByteCode.ByteOff
- GHC.CoreToByteCode: instance GHC.Real.Integral GHC.CoreToByteCode.WordOff
- GHC.CoreToByteCode: instance GHC.Real.Real GHC.CoreToByteCode.ByteOff
- GHC.CoreToByteCode: instance GHC.Real.Real GHC.CoreToByteCode.WordOff
- GHC.CoreToByteCode: instance GHC.Utils.Outputable.Outputable GHC.CoreToByteCode.Discr
- GHC.HsToCore.Monad: warnDs :: WarnReason -> SDoc -> DsM ()
- GHC.HsToCore.Pmc.Solver.Types: type CompleteMatch = UniqDSet ConLike
- GHC.Iface.Binary: readBinIface_ :: Profile -> CheckHiWay -> TraceBinIFace -> FilePath -> NameCacheUpdater -> IO ModIface
- GHC.Iface.Env: NCU :: (forall c. (NameCache -> (NameCache, c)) -> IO c) -> NameCacheUpdater
- GHC.Iface.Env: [updateNameCache] :: NameCacheUpdater -> forall c. (NameCache -> (NameCache, c)) -> IO c
- GHC.Iface.Env: extendNameCache :: OrigNameCache -> Module -> OccName -> Name -> OrigNameCache
- GHC.Iface.Env: mkNameCacheUpdater :: TcRnIf a b NameCacheUpdater
- GHC.Iface.Env: newtype NameCacheUpdater
- GHC.Iface.Env: updNameCache :: IORef NameCache -> (NameCache -> (NameCache, c)) -> IO c
- GHC.Iface.Env: updNameCacheTc :: Module -> OccName -> (NameCache -> (NameCache, c)) -> TcRnIf a b c
- GHC.Iface.Ext.Ast: instance (GHC.Iface.Ext.Ast.HiePass p, Data.Data.Data body, GHC.Iface.Ext.Ast.ToHie (GHC.Types.SrcLoc.Located body)) => GHC.Iface.Ext.Ast.ToHie (GHC.Types.SrcLoc.Located (Language.Haskell.Syntax.Expr.Match (GHC.Hs.Extension.GhcPass p) (GHC.Types.SrcLoc.Located body)))
- GHC.Iface.Ext.Ast: instance (GHC.Iface.Ext.Ast.HiePass p, GHC.Iface.Ext.Ast.ToHie (GHC.Types.SrcLoc.Located body), Data.Data.Data body) => GHC.Iface.Ext.Ast.ToHie (Language.Haskell.Syntax.Expr.MatchGroup (GHC.Hs.Extension.GhcPass p) (GHC.Types.SrcLoc.Located body))
- GHC.Iface.Ext.Ast: instance (GHC.Iface.Ext.Ast.ToHie (GHC.Iface.Ext.Ast.RFContext (GHC.Types.SrcLoc.Located label)), GHC.Iface.Ext.Ast.ToHie arg, GHC.Iface.Ext.Ast.HasLoc arg, Data.Data.Data arg, Data.Data.Data label) => GHC.Iface.Ext.Ast.ToHie (GHC.Iface.Ext.Ast.RContext (Language.Haskell.Syntax.Pat.LHsRecField' label arg))
- GHC.Iface.Ext.Ast: instance (GHC.Iface.Ext.Ast.ToHie (GHC.Types.SrcLoc.Located body), Data.Data.Data body, GHC.Iface.Ext.Ast.HiePass p) => GHC.Iface.Ext.Ast.ToHie (GHC.Iface.Ext.Ast.RScoped (GHC.Types.SrcLoc.Located (Language.Haskell.Syntax.Expr.Stmt (GHC.Hs.Extension.GhcPass p) (GHC.Types.SrcLoc.Located body))))
- GHC.Iface.Ext.Ast: instance (GHC.Iface.Ext.Ast.ToHie (GHC.Types.SrcLoc.Located body), GHC.Iface.Ext.Ast.HiePass a, Data.Data.Data body) => GHC.Iface.Ext.Ast.ToHie (GHC.Types.SrcLoc.Located (Language.Haskell.Syntax.Expr.GRHS (GHC.Hs.Extension.GhcPass a) (GHC.Types.SrcLoc.Located body)))
- GHC.Iface.Ext.Ast: instance (GHC.Iface.Ext.Ast.ToHie (GHC.Types.SrcLoc.Located body), GHC.Iface.Ext.Ast.HiePass p, Data.Data.Data body) => GHC.Iface.Ext.Ast.ToHie (Language.Haskell.Syntax.Expr.GRHSs (GHC.Hs.Extension.GhcPass p) (GHC.Types.SrcLoc.Located body))
- GHC.Iface.Ext.Ast: instance (GHC.Iface.Ext.Ast.ToHie rhs, GHC.Iface.Ext.Ast.HasLoc rhs) => GHC.Iface.Ext.Ast.ToHie (GHC.Iface.Ext.Ast.TScoped (Language.Haskell.Syntax.Decls.FamEqn GHC.Hs.Extension.GhcRn rhs))
- GHC.Iface.Ext.Ast: instance Data.Data.Data flag => GHC.Iface.Ext.Ast.ToHie (GHC.Iface.Ext.Ast.TVScoped (GHC.Types.SrcLoc.Located (Language.Haskell.Syntax.Type.HsTyVarBndr flag GHC.Hs.Extension.GhcRn)))
- GHC.Iface.Ext.Ast: instance GHC.Iface.Ext.Ast.HasLoc a => GHC.Iface.Ext.Ast.HasLoc (Language.Haskell.Syntax.Decls.FamEqn (GHC.Hs.Extension.GhcPass s) a)
- GHC.Iface.Ext.Ast: instance GHC.Iface.Ext.Ast.HiePass p => GHC.Iface.Ext.Ast.HasType (GHC.Types.SrcLoc.Located (Language.Haskell.Syntax.Binds.HsBind (GHC.Hs.Extension.GhcPass p)))
- GHC.Iface.Ext.Ast: instance GHC.Iface.Ext.Ast.HiePass p => GHC.Iface.Ext.Ast.HasType (GHC.Types.SrcLoc.Located (Language.Haskell.Syntax.Expr.HsExpr (GHC.Hs.Extension.GhcPass p)))
- GHC.Iface.Ext.Ast: instance GHC.Iface.Ext.Ast.HiePass p => GHC.Iface.Ext.Ast.HasType (GHC.Types.SrcLoc.Located (Language.Haskell.Syntax.Pat.Pat (GHC.Hs.Extension.GhcPass p)))
- GHC.Iface.Ext.Ast: instance GHC.Iface.Ext.Ast.HiePass p => GHC.Iface.Ext.Ast.ToHie (GHC.Iface.Ext.Ast.BindContext (GHC.Types.SrcLoc.Located (Language.Haskell.Syntax.Binds.HsBind (GHC.Hs.Extension.GhcPass p))))
- GHC.Iface.Ext.Ast: instance GHC.Iface.Ext.Ast.HiePass p => GHC.Iface.Ext.Ast.ToHie (GHC.Iface.Ext.Ast.PScoped (GHC.Types.SrcLoc.Located (Language.Haskell.Syntax.Pat.Pat (GHC.Hs.Extension.GhcPass p))))
- GHC.Iface.Ext.Ast: instance GHC.Iface.Ext.Ast.HiePass p => GHC.Iface.Ext.Ast.ToHie (GHC.Iface.Ext.Ast.RScoped (GHC.Types.SrcLoc.Located (Language.Haskell.Syntax.Binds.HsLocalBinds (GHC.Hs.Extension.GhcPass p))))
- GHC.Iface.Ext.Ast: instance GHC.Iface.Ext.Ast.HiePass p => GHC.Iface.Ext.Ast.ToHie (GHC.Iface.Ext.Ast.RScoped (GHC.Types.SrcLoc.Located (Language.Haskell.Syntax.Binds.IPBind (GHC.Hs.Extension.GhcPass p))))
- GHC.Iface.Ext.Ast: instance GHC.Iface.Ext.Ast.HiePass p => GHC.Iface.Ext.Ast.ToHie (GHC.Iface.Ext.Ast.SigContext (GHC.Types.SrcLoc.Located (Language.Haskell.Syntax.Binds.Sig (GHC.Hs.Extension.GhcPass p))))
- GHC.Iface.Ext.Ast: instance GHC.Iface.Ext.Ast.HiePass p => GHC.Iface.Ext.Ast.ToHie (GHC.Types.SrcLoc.Located (Language.Haskell.Syntax.Expr.HsCmd (GHC.Hs.Extension.GhcPass p)))
- GHC.Iface.Ext.Ast: instance GHC.Iface.Ext.Ast.HiePass p => GHC.Iface.Ext.Ast.ToHie (GHC.Types.SrcLoc.Located (Language.Haskell.Syntax.Expr.HsExpr (GHC.Hs.Extension.GhcPass p)))
- GHC.Iface.Ext.Ast: instance GHC.Iface.Ext.Ast.HiePass p => GHC.Iface.Ext.Ast.ToHie (GHC.Types.SrcLoc.Located (Language.Haskell.Syntax.Expr.HsSplice (GHC.Hs.Extension.GhcPass p)))
- GHC.Iface.Ext.Ast: instance GHC.Iface.Ext.Ast.HiePass p => GHC.Iface.Ext.Ast.ToHie (GHC.Types.SrcLoc.Located (Language.Haskell.Syntax.Expr.HsTupArg (GHC.Hs.Extension.GhcPass p)))
- GHC.Iface.Ext.Ast: instance GHC.Iface.Ext.Ast.ToHie (GHC.Data.BooleanFormula.LBooleanFormula (GHC.Types.SrcLoc.Located GHC.Types.Name.Name))
- GHC.Iface.Ext.Ast: instance GHC.Iface.Ext.Ast.ToHie (GHC.Iface.Ext.Ast.Context (GHC.Types.SrcLoc.Located a)) => GHC.Iface.Ext.Ast.ToHie (Language.Haskell.Syntax.Decls.AnnProvenance a)
- GHC.Iface.Ext.Ast: instance GHC.Iface.Ext.Ast.ToHie (GHC.Iface.Ext.Ast.EvBindContext (GHC.Types.SrcLoc.Located GHC.Tc.Types.Evidence.TcEvBinds))
- GHC.Iface.Ext.Ast: instance GHC.Iface.Ext.Ast.ToHie (GHC.Iface.Ext.Ast.IEContext (GHC.Types.SrcLoc.Located (GHC.Hs.ImpExp.IE GHC.Hs.Extension.GhcRn)))
- GHC.Iface.Ext.Ast: instance GHC.Iface.Ext.Ast.ToHie (GHC.Iface.Ext.Ast.TScoped (GHC.Types.SrcLoc.Located (Language.Haskell.Syntax.Type.HsSigType GHC.Hs.Extension.GhcRn)))
- GHC.Iface.Ext.Ast: instance GHC.Iface.Ext.Ast.ToHie (GHC.Iface.Ext.Ast.TScoped (Language.Haskell.Syntax.Type.HsWildCardBndrs GHC.Hs.Extension.GhcRn (GHC.Types.SrcLoc.Located (Language.Haskell.Syntax.Type.HsSigType GHC.Hs.Extension.GhcRn))))
- GHC.Iface.Ext.Ast: instance GHC.Iface.Ext.Ast.ToHie (GHC.Iface.Ext.Ast.TScoped (Language.Haskell.Syntax.Type.HsWildCardBndrs GHC.Hs.Extension.GhcRn (GHC.Types.SrcLoc.Located (Language.Haskell.Syntax.Type.HsType GHC.Hs.Extension.GhcRn))))
- GHC.Iface.Ext.Ast: instance GHC.Iface.Ext.Ast.ToHie (GHC.Types.SrcLoc.Located (GHC.Core.Class.FunDep (GHC.Types.SrcLoc.Located GHC.Types.Name.Name)))
- GHC.Iface.Ext.Ast: instance GHC.Iface.Ext.Ast.ToHie (GHC.Types.SrcLoc.Located (GHC.Hs.ImpExp.ImportDecl GHC.Hs.Extension.GhcRn))
- GHC.Iface.Ext.Ast: instance GHC.Iface.Ext.Ast.ToHie (GHC.Types.SrcLoc.Located (Language.Haskell.Syntax.Binds.FixitySig GHC.Hs.Extension.GhcRn))
- GHC.Iface.Ext.Ast: instance GHC.Iface.Ext.Ast.ToHie (GHC.Types.SrcLoc.Located (Language.Haskell.Syntax.Decls.AnnDecl GHC.Hs.Extension.GhcRn))
- GHC.Iface.Ext.Ast: instance GHC.Iface.Ext.Ast.ToHie (GHC.Types.SrcLoc.Located (Language.Haskell.Syntax.Decls.ClsInstDecl GHC.Hs.Extension.GhcRn))
- GHC.Iface.Ext.Ast: instance GHC.Iface.Ext.Ast.ToHie (GHC.Types.SrcLoc.Located (Language.Haskell.Syntax.Decls.ConDecl GHC.Hs.Extension.GhcRn))
- GHC.Iface.Ext.Ast: instance GHC.Iface.Ext.Ast.ToHie (GHC.Types.SrcLoc.Located (Language.Haskell.Syntax.Decls.DataFamInstDecl GHC.Hs.Extension.GhcRn))
- GHC.Iface.Ext.Ast: instance GHC.Iface.Ext.Ast.ToHie (GHC.Types.SrcLoc.Located (Language.Haskell.Syntax.Decls.DefaultDecl GHC.Hs.Extension.GhcRn))
- GHC.Iface.Ext.Ast: instance GHC.Iface.Ext.Ast.ToHie (GHC.Types.SrcLoc.Located (Language.Haskell.Syntax.Decls.DerivClauseTys GHC.Hs.Extension.GhcRn))
- GHC.Iface.Ext.Ast: instance GHC.Iface.Ext.Ast.ToHie (GHC.Types.SrcLoc.Located (Language.Haskell.Syntax.Decls.DerivDecl GHC.Hs.Extension.GhcRn))
- GHC.Iface.Ext.Ast: instance GHC.Iface.Ext.Ast.ToHie (GHC.Types.SrcLoc.Located (Language.Haskell.Syntax.Decls.FamilyDecl GHC.Hs.Extension.GhcRn))
- GHC.Iface.Ext.Ast: instance GHC.Iface.Ext.Ast.ToHie (GHC.Types.SrcLoc.Located (Language.Haskell.Syntax.Decls.ForeignDecl GHC.Hs.Extension.GhcRn))
- GHC.Iface.Ext.Ast: instance GHC.Iface.Ext.Ast.ToHie (GHC.Types.SrcLoc.Located (Language.Haskell.Syntax.Decls.InstDecl GHC.Hs.Extension.GhcRn))
- GHC.Iface.Ext.Ast: instance GHC.Iface.Ext.Ast.ToHie (GHC.Types.SrcLoc.Located (Language.Haskell.Syntax.Decls.RoleAnnotDecl GHC.Hs.Extension.GhcRn))
- GHC.Iface.Ext.Ast: instance GHC.Iface.Ext.Ast.ToHie (GHC.Types.SrcLoc.Located (Language.Haskell.Syntax.Decls.RuleDecl GHC.Hs.Extension.GhcRn))
- GHC.Iface.Ext.Ast: instance GHC.Iface.Ext.Ast.ToHie (GHC.Types.SrcLoc.Located (Language.Haskell.Syntax.Decls.RuleDecls GHC.Hs.Extension.GhcRn))
- GHC.Iface.Ext.Ast: instance GHC.Iface.Ext.Ast.ToHie (GHC.Types.SrcLoc.Located (Language.Haskell.Syntax.Decls.SpliceDecl GHC.Hs.Extension.GhcRn))
- GHC.Iface.Ext.Ast: instance GHC.Iface.Ext.Ast.ToHie (GHC.Types.SrcLoc.Located (Language.Haskell.Syntax.Decls.StandaloneKindSig GHC.Hs.Extension.GhcRn))
- GHC.Iface.Ext.Ast: instance GHC.Iface.Ext.Ast.ToHie (GHC.Types.SrcLoc.Located (Language.Haskell.Syntax.Decls.TyClDecl GHC.Hs.Extension.GhcRn))
- GHC.Iface.Ext.Ast: instance GHC.Iface.Ext.Ast.ToHie (GHC.Types.SrcLoc.Located (Language.Haskell.Syntax.Decls.TyFamInstDecl GHC.Hs.Extension.GhcRn))
- GHC.Iface.Ext.Ast: instance GHC.Iface.Ext.Ast.ToHie (GHC.Types.SrcLoc.Located (Language.Haskell.Syntax.Decls.WarnDecl GHC.Hs.Extension.GhcRn))
- GHC.Iface.Ext.Ast: instance GHC.Iface.Ext.Ast.ToHie (GHC.Types.SrcLoc.Located (Language.Haskell.Syntax.Decls.WarnDecls GHC.Hs.Extension.GhcRn))
- GHC.Iface.Ext.Ast: instance GHC.Iface.Ext.Ast.ToHie (GHC.Types.SrcLoc.Located (Language.Haskell.Syntax.Type.ConDeclField GHC.Hs.Extension.GhcRn))
- GHC.Iface.Ext.Ast: instance GHC.Iface.Ext.Ast.ToHie (GHC.Types.SrcLoc.Located (Language.Haskell.Syntax.Type.HsType GHC.Hs.Extension.GhcRn))
- GHC.Iface.Ext.Ast: instance GHC.Iface.Ext.Ast.ToHie (GHC.Types.SrcLoc.Located GHC.Tc.Types.Evidence.HsWrapper)
- GHC.Iface.Ext.Ast: instance GHC.Iface.Ext.Ast.ToHie (GHC.Types.SrcLoc.Located GHC.Types.Basic.OverlapMode)
- GHC.Iface.Ext.Ast: instance GHC.Iface.Ext.Ast.ToHie (GHC.Types.SrcLoc.Located [GHC.Types.SrcLoc.Located (Language.Haskell.Syntax.Type.ConDeclField GHC.Hs.Extension.GhcRn)])
- GHC.Iface.Ext.Ast: instance GHC.Iface.Ext.Ast.ToHie (GHC.Types.SrcLoc.Located [GHC.Types.SrcLoc.Located (Language.Haskell.Syntax.Type.HsType GHC.Hs.Extension.GhcRn)])
- GHC.Iface.Ext.Binary: NCU :: (forall c. (NameCache -> (NameCache, c)) -> IO c) -> NameCacheUpdater
- GHC.Iface.Ext.Binary: [updateNameCache] :: NameCacheUpdater -> forall c. (NameCache -> (NameCache, c)) -> IO c
- GHC.Iface.Ext.Binary: newtype NameCacheUpdater
- GHC.Plugins: idCprInfo :: Id -> CprSig
- GHC.Plugins: idStrictness :: Id -> StrictSig
- GHC.Plugins: setIdCprInfo :: Id -> CprSig -> Id
- GHC.Plugins: setIdStrictness :: Id -> StrictSig -> Id
- GHC.Plugins: zapIdStrictness :: Id -> Id
- GHC.Rename.Utils: extendTyVarEnvFVRn :: [Name] -> RnM (a, FreeVars) -> RnM (a, FreeVars)
- GHC.Runtime.Interpreter: [EnableBreakpoint] :: RemoteRef BreakArray -> Int -> Bool -> Message ()
- GHC.Runtime.Interpreter: enableBreakpoint :: HscEnv -> ForeignRef BreakArray -> Int -> Bool -> IO ()
- GHC.Runtime.Interpreter: iservCmd :: Binary a => HscEnv -> Message a -> IO a
- GHC.Runtime.Interpreter: withInterp :: HscEnv -> (Interp -> IO a) -> IO a
- GHC.StgToCmm.Env: getArgAmode :: NonVoid StgArg -> FCode CmmExpr
- GHC.StgToCmm.Env: getNonVoidArgAmodes :: [StgArg] -> FCode [CmmExpr]
- GHC.StgToCmm.Utils: cgLit :: Literal -> FCode CmmLit
- GHC.StgToCmm.Utils: mkSimpleLit :: Platform -> Literal -> CmmLit
- GHC.StgToCmm.Utils: newByteStringCLit :: ByteString -> FCode CmmLit
- GHC.StgToCmm.Utils: newStringCLit :: String -> FCode CmmLit
- GHC.StgToCmm.Utils: newTemp :: MonadUnique m => CmmType -> m LocalReg
- GHC.Tc.Errors: instance GHC.Utils.Outputable.Outputable GHC.Tc.Errors.HoleChoice
- GHC.Tc.Errors: instance GHC.Utils.Outputable.Outputable GHC.Tc.Errors.TypeErrorChoice
- GHC.Tc.Gen.Export: tcRnExports :: Bool -> Maybe (Located [LIE GhcPs]) -> TcGblEnv -> RnM TcGblEnv
- GHC.Tc.Gen.HsType: tcHsMbContext :: Maybe (LHsContext GhcRn) -> TcM [PredType]
- GHC.Tc.Solver: tcCheckSatisfiability :: InertSet -> Bag EvVar -> TcM (Maybe InertSet)
- GHC.Tc.Utils.Monad: addWarn :: WarnReason -> SDoc -> TcRn ()
- GHC.Tc.Utils.Monad: addWarnAt :: WarnReason -> SrcSpan -> SDoc -> TcRn ()
- GHC.Tc.Utils.Monad: addWarnTc :: WarnReason -> SDoc -> TcM ()
- GHC.Tc.Utils.Monad: addWarnTcM :: WarnReason -> (TidyEnv, SDoc) -> TcM ()
- GHC.Tc.Utils.Monad: add_warn :: WarnReason -> SDoc -> SDoc -> TcRn ()
- GHC.Tc.Utils.Monad: reportError :: MsgEnvelope DecoratedSDoc -> TcRn ()
- GHC.Tc.Utils.Monad: reportErrors :: [MsgEnvelope DecoratedSDoc] -> TcM ()
- GHC.Tc.Utils.Monad: reportWarning :: WarnReason -> MsgEnvelope DecoratedSDoc -> TcRn ()
- GHC.Tc.Utils.Monad: traceHiDiffs :: SDoc -> TcRnIf m n ()
- GHC.Tc.Utils.Monad: warnTc :: WarnReason -> Bool -> SDoc -> TcM ()
- GHC.Tc.Utils.Monad: warnTcM :: WarnReason -> Bool -> (TidyEnv, SDoc) -> TcM ()
- GHC.Tc.Utils.Monad: withDynamicNow :: TcRnIf gbl lcl a -> TcRnIf gbl lcl a
- GHC.Unit.Finder: type FinderCache = InstalledModuleEnv InstalledFindResult
+ GHC: AnnClosePH :: AnnKeywordId
+ GHC: AnnOpenPH :: AnnKeywordId
+ GHC: BreakInfo :: Module -> Int -> BreakInfo
+ GHC: EpaComment :: EpaCommentTok -> RealSrcSpan -> EpaComment
+ GHC: Opt_DistinctConstructorTables :: GeneralFlag
+ GHC: Opt_InfoTableMap :: GeneralFlag
+ GHC: [ac_prior_tok] :: EpaComment -> RealSrcSpan
+ GHC: [ac_tok] :: EpaComment -> EpaCommentTok
+ GHC: [breakInfo_module] :: BreakInfo -> Module
+ GHC: [breakInfo_number] :: BreakInfo -> Int
+ GHC: [targetUnitId] :: Target -> UnitId
+ GHC: data EpaComment
+ GHC: setupBreakpoint :: GhcMonad m => HscEnv -> BreakInfo -> Int -> m ()
+ GHC.Builtin.Types.Literals: typeCharToNatTyCon :: TyCon
+ GHC.Builtin.Types.Literals: typeNatToCharTyCon :: TyCon
+ GHC.ByteCode.Asm: mkTupleInfoLit :: Platform -> TupleInfo -> Literal
+ GHC.ByteCode.Instr: PUSH_ALTS_TUPLE :: ProtoBCO Name -> !TupleInfo -> ProtoBCO Name -> BCInstr
+ GHC.ByteCode.Instr: RETURN_TUPLE :: BCInstr
+ GHC.CmmToLlvm.Base: instance GHC.Classes.Eq GHC.CmmToLlvm.Base.LlvmVersion
+ GHC.CmmToLlvm.Base: instance GHC.Classes.Ord GHC.CmmToLlvm.Base.LlvmVersion
+ GHC.CmmToLlvm.Base: supportedLlvmVersionMax :: LlvmVersion
+ GHC.CmmToLlvm.Base: supportedLlvmVersionMin :: LlvmVersion
+ GHC.Core.Opt.CprAnal: instance GHC.Utils.Outputable.Outputable GHC.Core.Opt.CprAnal.SigEnv
+ GHC.Core.Opt.WorkWrap.Utils: StopUnboxing :: UnboxingDecision s
+ GHC.Core.Opt.WorkWrap.Utils: Unbox :: !DataConPatContext -> [s] -> UnboxingDecision s
+ GHC.Core.Opt.WorkWrap.Utils: data UnboxingDecision s
+ GHC.Data.Graph.UnVar: extendUnVarSet :: Var -> UnVarSet -> UnVarSet
+ GHC.Driver.CodeOutput: ipInitCode :: DynFlags -> Module -> [InfoProvEnt] -> CStub
+ GHC.HsToCore.Docs: extractTHDocs :: THDocs -> ExtractedTHDocs
+ GHC.HsToCore.Docs: unionArgMaps :: Map Name (IntMap b) -> Map Name (IntMap b) -> Map Name (IntMap b)
+ GHC.HsToCore.Monad: diagnosticDs :: DiagnosticReason -> SDoc -> DsM ()
+ GHC.HsToCore.Monad: putSrcSpanDsA :: SrcSpanAnn' ann -> DsM a -> DsM a
+ GHC.HsToCore.Pmc.Solver.Types: data CompleteMatch
+ GHC.HsToCore.Utils: mkFailExpr :: HsMatchContext GhcRn -> Type -> DsM CoreExpr
+ GHC.Iface.Env: trace_hi_diffs :: Logger -> DynFlags -> SDoc -> IO ()
+ GHC.Iface.Env: trace_if :: Logger -> DynFlags -> SDoc -> IO ()
+ GHC.Iface.Ext.Ast: instance (GHC.Iface.Ext.Ast.HasLoc a, GHC.Iface.Ext.Ast.HiePass p) => GHC.Iface.Ext.Ast.HasLoc (Language.Haskell.Syntax.Decls.FamEqn (GHC.Hs.Extension.GhcPass p) a)
+ GHC.Iface.Ext.Ast: instance (GHC.Iface.Ext.Ast.HiePass p, Data.Data.Data (body (GHC.Hs.Extension.GhcPass p)), GHC.Iface.Ext.Ast.AnnoBody p body, GHC.Iface.Ext.Ast.ToHie (GHC.Parser.Annotation.LocatedA (body (GHC.Hs.Extension.GhcPass p)))) => GHC.Iface.Ext.Ast.ToHie (GHC.Parser.Annotation.LocatedA (Language.Haskell.Syntax.Expr.Match (GHC.Hs.Extension.GhcPass p) (GHC.Parser.Annotation.LocatedA (body (GHC.Hs.Extension.GhcPass p)))))
+ GHC.Iface.Ext.Ast: instance (GHC.Iface.Ext.Ast.HiePass p, GHC.Iface.Ext.Ast.AnnoBody p body, GHC.Iface.Ext.Ast.ToHie (GHC.Parser.Annotation.LocatedA (body (GHC.Hs.Extension.GhcPass p)))) => GHC.Iface.Ext.Ast.ToHie (Language.Haskell.Syntax.Expr.MatchGroup (GHC.Hs.Extension.GhcPass p) (GHC.Parser.Annotation.LocatedA (body (GHC.Hs.Extension.GhcPass p))))
+ GHC.Iface.Ext.Ast: instance (GHC.Iface.Ext.Ast.ToHie (GHC.Iface.Ext.Ast.RFContext (GHC.Types.SrcLoc.Located label)), GHC.Iface.Ext.Ast.ToHie arg, GHC.Iface.Ext.Ast.HasLoc arg, Data.Data.Data arg, Data.Data.Data label) => GHC.Iface.Ext.Ast.ToHie (GHC.Iface.Ext.Ast.RContext (GHC.Parser.Annotation.LocatedA (Language.Haskell.Syntax.Pat.HsRecField' label arg)))
+ GHC.Iface.Ext.Ast: instance (GHC.Iface.Ext.Ast.ToHie (GHC.Parser.Annotation.LocatedA (body (GHC.Hs.Extension.GhcPass p))), GHC.Iface.Ext.Ast.AnnoBody p body, GHC.Iface.Ext.Ast.HiePass p) => GHC.Iface.Ext.Ast.ToHie (GHC.Iface.Ext.Ast.RScoped (GHC.Parser.Annotation.LocatedA (Language.Haskell.Syntax.Expr.Stmt (GHC.Hs.Extension.GhcPass p) (GHC.Parser.Annotation.LocatedA (body (GHC.Hs.Extension.GhcPass p))))))
+ GHC.Iface.Ext.Ast: instance (GHC.Iface.Ext.Ast.ToHie (GHC.Parser.Annotation.LocatedA (body (GHC.Hs.Extension.GhcPass p))), GHC.Iface.Ext.Ast.HiePass p, GHC.Iface.Ext.Ast.AnnoBody p body) => GHC.Iface.Ext.Ast.ToHie (GHC.Types.SrcLoc.Located (Language.Haskell.Syntax.Expr.GRHS (GHC.Hs.Extension.GhcPass p) (GHC.Parser.Annotation.LocatedA (body (GHC.Hs.Extension.GhcPass p)))))
+ GHC.Iface.Ext.Ast: instance (GHC.Iface.Ext.Ast.ToHie (GHC.Parser.Annotation.LocatedA (body (GHC.Hs.Extension.GhcPass p))), GHC.Iface.Ext.Ast.HiePass p, GHC.Iface.Ext.Ast.AnnoBody p body) => GHC.Iface.Ext.Ast.ToHie (Language.Haskell.Syntax.Expr.GRHSs (GHC.Hs.Extension.GhcPass p) (GHC.Parser.Annotation.LocatedA (body (GHC.Hs.Extension.GhcPass p))))
+ GHC.Iface.Ext.Ast: instance Data.Data.Data flag => GHC.Iface.Ext.Ast.ToHie (GHC.Iface.Ext.Ast.TVScoped (GHC.Parser.Annotation.LocatedA (Language.Haskell.Syntax.Type.HsTyVarBndr flag GHC.Hs.Extension.GhcRn)))
+ GHC.Iface.Ext.Ast: instance GHC.Iface.Ext.Ast.HasLoc (GHC.Parser.Annotation.LocatedA a)
+ GHC.Iface.Ext.Ast: instance GHC.Iface.Ext.Ast.HasLoc (GHC.Parser.Annotation.LocatedN a)
+ GHC.Iface.Ext.Ast: instance GHC.Iface.Ext.Ast.HiePass p => GHC.Iface.Ext.Ast.HasType (GHC.Parser.Annotation.LocatedA (Language.Haskell.Syntax.Binds.HsBind (GHC.Hs.Extension.GhcPass p)))
+ GHC.Iface.Ext.Ast: instance GHC.Iface.Ext.Ast.HiePass p => GHC.Iface.Ext.Ast.HasType (GHC.Parser.Annotation.LocatedA (Language.Haskell.Syntax.Expr.HsExpr (GHC.Hs.Extension.GhcPass p)))
+ GHC.Iface.Ext.Ast: instance GHC.Iface.Ext.Ast.HiePass p => GHC.Iface.Ext.Ast.HasType (GHC.Parser.Annotation.LocatedA (Language.Haskell.Syntax.Pat.Pat (GHC.Hs.Extension.GhcPass p)))
+ GHC.Iface.Ext.Ast: instance GHC.Iface.Ext.Ast.HiePass p => GHC.Iface.Ext.Ast.ToHie (GHC.Iface.Ext.Ast.BindContext (GHC.Parser.Annotation.LocatedA (Language.Haskell.Syntax.Binds.HsBind (GHC.Hs.Extension.GhcPass p))))
+ GHC.Iface.Ext.Ast: instance GHC.Iface.Ext.Ast.HiePass p => GHC.Iface.Ext.Ast.ToHie (GHC.Iface.Ext.Ast.PScoped (GHC.Parser.Annotation.LocatedA (Language.Haskell.Syntax.Pat.Pat (GHC.Hs.Extension.GhcPass p))))
+ GHC.Iface.Ext.Ast: instance GHC.Iface.Ext.Ast.HiePass p => GHC.Iface.Ext.Ast.ToHie (GHC.Iface.Ext.Ast.RScoped (GHC.Parser.Annotation.LocatedA (Language.Haskell.Syntax.Binds.IPBind (GHC.Hs.Extension.GhcPass p))))
+ GHC.Iface.Ext.Ast: instance GHC.Iface.Ext.Ast.HiePass p => GHC.Iface.Ext.Ast.ToHie (GHC.Iface.Ext.Ast.RScoped (Language.Haskell.Syntax.Binds.HsLocalBinds (GHC.Hs.Extension.GhcPass p)))
+ GHC.Iface.Ext.Ast: instance GHC.Iface.Ext.Ast.HiePass p => GHC.Iface.Ext.Ast.ToHie (GHC.Iface.Ext.Ast.SigContext (GHC.Parser.Annotation.LocatedA (Language.Haskell.Syntax.Binds.Sig (GHC.Hs.Extension.GhcPass p))))
+ GHC.Iface.Ext.Ast: instance GHC.Iface.Ext.Ast.HiePass p => GHC.Iface.Ext.Ast.ToHie (GHC.Parser.Annotation.LocatedA (Language.Haskell.Syntax.Expr.HsCmd (GHC.Hs.Extension.GhcPass p)))
+ GHC.Iface.Ext.Ast: instance GHC.Iface.Ext.Ast.HiePass p => GHC.Iface.Ext.Ast.ToHie (GHC.Parser.Annotation.LocatedA (Language.Haskell.Syntax.Expr.HsExpr (GHC.Hs.Extension.GhcPass p)))
+ GHC.Iface.Ext.Ast: instance GHC.Iface.Ext.Ast.HiePass p => GHC.Iface.Ext.Ast.ToHie (GHC.Parser.Annotation.LocatedA (Language.Haskell.Syntax.Expr.HsSplice (GHC.Hs.Extension.GhcPass p)))
+ GHC.Iface.Ext.Ast: instance GHC.Iface.Ext.Ast.HiePass p => GHC.Iface.Ext.Ast.ToHie (Language.Haskell.Syntax.Expr.HsTupArg (GHC.Hs.Extension.GhcPass p))
+ GHC.Iface.Ext.Ast: instance GHC.Iface.Ext.Ast.ToHie (GHC.Data.BooleanFormula.LBooleanFormula (GHC.Parser.Annotation.LocatedN GHC.Types.Name.Name))
+ GHC.Iface.Ext.Ast: instance GHC.Iface.Ext.Ast.ToHie (GHC.Iface.Ext.Ast.Context (GHC.Types.SrcLoc.Located a)) => GHC.Iface.Ext.Ast.ToHie (GHC.Iface.Ext.Ast.Context (GHC.Parser.Annotation.LocatedA a))
+ GHC.Iface.Ext.Ast: instance GHC.Iface.Ext.Ast.ToHie (GHC.Iface.Ext.Ast.Context (GHC.Types.SrcLoc.Located a)) => GHC.Iface.Ext.Ast.ToHie (GHC.Iface.Ext.Ast.Context (GHC.Parser.Annotation.LocatedN a))
+ GHC.Iface.Ext.Ast: instance GHC.Iface.Ext.Ast.ToHie (GHC.Iface.Ext.Ast.EvBindContext (GHC.Parser.Annotation.LocatedA GHC.Tc.Types.Evidence.TcEvBinds))
+ GHC.Iface.Ext.Ast: instance GHC.Iface.Ext.Ast.ToHie (GHC.Iface.Ext.Ast.IEContext (GHC.Parser.Annotation.LocatedA (GHC.Hs.ImpExp.IE GHC.Hs.Extension.GhcRn)))
+ GHC.Iface.Ext.Ast: instance GHC.Iface.Ext.Ast.ToHie (GHC.Iface.Ext.Ast.TScoped (GHC.Parser.Annotation.LocatedA (Language.Haskell.Syntax.Type.HsSigType GHC.Hs.Extension.GhcRn)))
+ GHC.Iface.Ext.Ast: instance GHC.Iface.Ext.Ast.ToHie (GHC.Iface.Ext.Ast.TScoped (Language.Haskell.Syntax.Decls.FamEqn GHC.Hs.Extension.GhcRn (GHC.Parser.Annotation.LocatedA (Language.Haskell.Syntax.Type.HsType GHC.Hs.Extension.GhcRn))))
+ GHC.Iface.Ext.Ast: instance GHC.Iface.Ext.Ast.ToHie (GHC.Iface.Ext.Ast.TScoped (Language.Haskell.Syntax.Decls.FamEqn GHC.Hs.Extension.GhcRn (Language.Haskell.Syntax.Decls.HsDataDefn GHC.Hs.Extension.GhcRn)))
+ GHC.Iface.Ext.Ast: instance GHC.Iface.Ext.Ast.ToHie (GHC.Iface.Ext.Ast.TScoped (Language.Haskell.Syntax.Type.HsWildCardBndrs GHC.Hs.Extension.GhcRn (GHC.Parser.Annotation.LocatedA (Language.Haskell.Syntax.Type.HsSigType GHC.Hs.Extension.GhcRn))))
+ GHC.Iface.Ext.Ast: instance GHC.Iface.Ext.Ast.ToHie (GHC.Iface.Ext.Ast.TScoped (Language.Haskell.Syntax.Type.HsWildCardBndrs GHC.Hs.Extension.GhcRn (GHC.Parser.Annotation.LocatedA (Language.Haskell.Syntax.Type.HsType GHC.Hs.Extension.GhcRn))))
+ GHC.Iface.Ext.Ast: instance GHC.Iface.Ext.Ast.ToHie (GHC.Parser.Annotation.LocatedA (GHC.Hs.ImpExp.ImportDecl GHC.Hs.Extension.GhcRn))
+ GHC.Iface.Ext.Ast: instance GHC.Iface.Ext.Ast.ToHie (GHC.Parser.Annotation.LocatedA (Language.Haskell.Syntax.Binds.FixitySig GHC.Hs.Extension.GhcRn))
+ GHC.Iface.Ext.Ast: instance GHC.Iface.Ext.Ast.ToHie (GHC.Parser.Annotation.LocatedA (Language.Haskell.Syntax.Decls.AnnDecl GHC.Hs.Extension.GhcRn))
+ GHC.Iface.Ext.Ast: instance GHC.Iface.Ext.Ast.ToHie (GHC.Parser.Annotation.LocatedA (Language.Haskell.Syntax.Decls.ClsInstDecl GHC.Hs.Extension.GhcRn))
+ GHC.Iface.Ext.Ast: instance GHC.Iface.Ext.Ast.ToHie (GHC.Parser.Annotation.LocatedA (Language.Haskell.Syntax.Decls.ConDecl GHC.Hs.Extension.GhcRn))
+ GHC.Iface.Ext.Ast: instance GHC.Iface.Ext.Ast.ToHie (GHC.Parser.Annotation.LocatedA (Language.Haskell.Syntax.Decls.DataFamInstDecl GHC.Hs.Extension.GhcRn))
+ GHC.Iface.Ext.Ast: instance GHC.Iface.Ext.Ast.ToHie (GHC.Parser.Annotation.LocatedA (Language.Haskell.Syntax.Decls.DefaultDecl GHC.Hs.Extension.GhcRn))
+ GHC.Iface.Ext.Ast: instance GHC.Iface.Ext.Ast.ToHie (GHC.Parser.Annotation.LocatedA (Language.Haskell.Syntax.Decls.DerivDecl GHC.Hs.Extension.GhcRn))
+ GHC.Iface.Ext.Ast: instance GHC.Iface.Ext.Ast.ToHie (GHC.Parser.Annotation.LocatedA (Language.Haskell.Syntax.Decls.FamilyDecl GHC.Hs.Extension.GhcRn))
+ GHC.Iface.Ext.Ast: instance GHC.Iface.Ext.Ast.ToHie (GHC.Parser.Annotation.LocatedA (Language.Haskell.Syntax.Decls.ForeignDecl GHC.Hs.Extension.GhcRn))
+ GHC.Iface.Ext.Ast: instance GHC.Iface.Ext.Ast.ToHie (GHC.Parser.Annotation.LocatedA (Language.Haskell.Syntax.Decls.FunDep GHC.Hs.Extension.GhcRn))
+ GHC.Iface.Ext.Ast: instance GHC.Iface.Ext.Ast.ToHie (GHC.Parser.Annotation.LocatedA (Language.Haskell.Syntax.Decls.InstDecl GHC.Hs.Extension.GhcRn))
+ GHC.Iface.Ext.Ast: instance GHC.Iface.Ext.Ast.ToHie (GHC.Parser.Annotation.LocatedA (Language.Haskell.Syntax.Decls.RoleAnnotDecl GHC.Hs.Extension.GhcRn))
+ GHC.Iface.Ext.Ast: instance GHC.Iface.Ext.Ast.ToHie (GHC.Parser.Annotation.LocatedA (Language.Haskell.Syntax.Decls.RuleDecl GHC.Hs.Extension.GhcRn))
+ GHC.Iface.Ext.Ast: instance GHC.Iface.Ext.Ast.ToHie (GHC.Parser.Annotation.LocatedA (Language.Haskell.Syntax.Decls.RuleDecls GHC.Hs.Extension.GhcRn))
+ GHC.Iface.Ext.Ast: instance GHC.Iface.Ext.Ast.ToHie (GHC.Parser.Annotation.LocatedA (Language.Haskell.Syntax.Decls.SpliceDecl GHC.Hs.Extension.GhcRn))
+ GHC.Iface.Ext.Ast: instance GHC.Iface.Ext.Ast.ToHie (GHC.Parser.Annotation.LocatedA (Language.Haskell.Syntax.Decls.StandaloneKindSig GHC.Hs.Extension.GhcRn))
+ GHC.Iface.Ext.Ast: instance GHC.Iface.Ext.Ast.ToHie (GHC.Parser.Annotation.LocatedA (Language.Haskell.Syntax.Decls.TyClDecl GHC.Hs.Extension.GhcRn))
+ GHC.Iface.Ext.Ast: instance GHC.Iface.Ext.Ast.ToHie (GHC.Parser.Annotation.LocatedA (Language.Haskell.Syntax.Decls.TyFamInstDecl GHC.Hs.Extension.GhcRn))
+ GHC.Iface.Ext.Ast: instance GHC.Iface.Ext.Ast.ToHie (GHC.Parser.Annotation.LocatedA (Language.Haskell.Syntax.Decls.WarnDecl GHC.Hs.Extension.GhcRn))
+ GHC.Iface.Ext.Ast: instance GHC.Iface.Ext.Ast.ToHie (GHC.Parser.Annotation.LocatedA (Language.Haskell.Syntax.Decls.WarnDecls GHC.Hs.Extension.GhcRn))
+ GHC.Iface.Ext.Ast: instance GHC.Iface.Ext.Ast.ToHie (GHC.Parser.Annotation.LocatedA (Language.Haskell.Syntax.Type.ConDeclField GHC.Hs.Extension.GhcRn))
+ GHC.Iface.Ext.Ast: instance GHC.Iface.Ext.Ast.ToHie (GHC.Parser.Annotation.LocatedA (Language.Haskell.Syntax.Type.HsType GHC.Hs.Extension.GhcRn))
+ GHC.Iface.Ext.Ast: instance GHC.Iface.Ext.Ast.ToHie (GHC.Parser.Annotation.LocatedA GHC.Tc.Types.Evidence.HsWrapper)
+ GHC.Iface.Ext.Ast: instance GHC.Iface.Ext.Ast.ToHie (GHC.Parser.Annotation.LocatedC (Language.Haskell.Syntax.Decls.DerivClauseTys GHC.Hs.Extension.GhcRn))
+ GHC.Iface.Ext.Ast: instance GHC.Iface.Ext.Ast.ToHie (GHC.Parser.Annotation.LocatedC [GHC.Parser.Annotation.LocatedA (Language.Haskell.Syntax.Type.HsType GHC.Hs.Extension.GhcRn)])
+ GHC.Iface.Ext.Ast: instance GHC.Iface.Ext.Ast.ToHie (GHC.Parser.Annotation.LocatedL [GHC.Parser.Annotation.LocatedA (Language.Haskell.Syntax.Type.ConDeclField GHC.Hs.Extension.GhcRn)])
+ GHC.Iface.Ext.Ast: instance GHC.Iface.Ext.Ast.ToHie (GHC.Parser.Annotation.LocatedP GHC.Types.Basic.OverlapMode)
+ GHC.Iface.Ext.Ast: instance GHC.Iface.Ext.Ast.ToHie (Language.Haskell.Syntax.Decls.AnnProvenance GHC.Hs.Extension.GhcRn)
+ GHC.Iface.Ext.Utils: makeNodeA :: (Monad m, Data a) => a -> SrcSpanAnn' ann -> ReaderT NodeOrigin m [HieAST b]
+ GHC.Iface.Ext.Utils: makeTypeNodeA :: (Monad m, Data a) => a -> SrcSpanAnnA -> Type -> ReaderT NodeOrigin m [HieAST Type]
+ GHC.Iface.Ext.Utils: mkLScopeA :: GenLocated (SrcSpanAnn' a) e -> Scope
+ GHC.Iface.Ext.Utils: mkLScopeN :: LocatedN a -> Scope
+ GHC.Iface.Ext.Utils: mkScopeA :: SrcSpanAnn' ann -> Scope
+ GHC.Plugins: idCprSig :: Id -> CprSig
+ GHC.Plugins: idDmdSig :: Id -> DmdSig
+ GHC.Plugins: isBoxedRuntimeRep :: Type -> Bool
+ GHC.Plugins: isBoxedType :: Type -> Bool
+ GHC.Plugins: isBoxedTypeKind :: Kind -> Bool
+ GHC.Plugins: isLevityTy :: Type -> Bool
+ GHC.Plugins: isLevityVar :: TyVar -> Bool
+ GHC.Plugins: isLiftedLevity :: Type -> Bool
+ GHC.Plugins: isUnliftedLevity :: Type -> Bool
+ GHC.Plugins: setIdCprSig :: Id -> CprSig -> Id
+ GHC.Plugins: setIdDmdSig :: Id -> DmdSig -> Id
+ GHC.Plugins: tYPE :: Type -> Type
+ GHC.Plugins: tcIsBoxedTypeKind :: Kind -> Bool
+ GHC.Plugins: unliftedTypeKind :: Kind
+ GHC.Plugins: zapIdDmdSig :: Id -> Id
+ GHC.Rename.Env: lookupLocatedTopBndrRnN :: LocatedN RdrName -> RnM (LocatedN Name)
+ GHC.Rename.Env: lookupSigCtxtOccRnN :: HsSigCtxt -> SDoc -> LocatedN RdrName -> RnM (LocatedN Name)
+ GHC.Rename.Env: lookupSigOccRnN :: HsSigCtxt -> Sig GhcPs -> LocatedN RdrName -> RnM (LocatedN Name)
+ GHC.Rename.Expr: type AnnoBody body = (Outputable (body GhcPs), Anno (StmtLR GhcPs GhcPs (LocatedA (body GhcPs))) ~ SrcSpanAnnA, Anno (StmtLR GhcRn GhcPs (LocatedA (body GhcPs))) ~ SrcSpanAnnA, Anno (StmtLR GhcRn GhcRn (LocatedA (body GhcRn))) ~ SrcSpanAnnA)
+ GHC.Rename.HsType: nubN :: Eq a => [LocatedN a] -> [LocatedN a]
+ GHC.Rename.Utils: checkDupRdrNamesN :: [LocatedN RdrName] -> RnM ()
+ GHC.Runtime.Eval: setupBreakpoint :: GhcMonad m => HscEnv -> BreakInfo -> Int -> m ()
+ GHC.Runtime.Interpreter: [SetupBreakpoint] :: RemoteRef BreakArray -> Int -> Int -> Message ()
+ GHC.Runtime.Interpreter: interpCmd :: Binary a => Interp -> Message a -> IO a
+ GHC.Runtime.Interpreter: storeBreakpoint :: Interp -> ForeignRef BreakArray -> Int -> Int -> IO ()
+ GHC.Stg.Debug: collectDebugInformation :: DynFlags -> ModLocation -> [StgTopBinding] -> ([StgTopBinding], InfoTableProvMap)
+ GHC.StgToByteCode: byteCodeGen :: HscEnv -> Module -> [StgTopBinding] -> [TyCon] -> Maybe ModBreaks -> IO CompiledByteCode
+ GHC.StgToByteCode: data UnlinkedBCO
+ GHC.StgToByteCode: instance GHC.Base.Applicative GHC.StgToByteCode.BcM
+ GHC.StgToByteCode: instance GHC.Base.Functor GHC.StgToByteCode.BcM
+ GHC.StgToByteCode: instance GHC.Base.Monad GHC.StgToByteCode.BcM
+ GHC.StgToByteCode: instance GHC.Classes.Eq GHC.StgToByteCode.Discr
+ GHC.StgToByteCode: instance GHC.Classes.Ord GHC.StgToByteCode.Discr
+ GHC.StgToByteCode: instance GHC.Driver.Session.HasDynFlags GHC.StgToByteCode.BcM
+ GHC.StgToByteCode: instance GHC.Utils.Outputable.Outputable GHC.StgToByteCode.Discr
+ GHC.StgToByteCode: stgExprToBCOs :: HscEnv -> Module -> Type -> StgRhs -> IO UnlinkedBCO
+ GHC.StgToCmm.Expr: cgLit :: Literal -> FCode CmmExpr
+ GHC.StgToCmm.Layout: getArgAmode :: NonVoid StgArg -> FCode CmmExpr
+ GHC.StgToCmm.Layout: getNonVoidArgAmodes :: [StgArg] -> FCode [CmmExpr]
+ GHC.StgToCmm.Lit: cgLit :: Literal -> FCode CmmExpr
+ GHC.StgToCmm.Lit: mkSimpleLit :: Platform -> Literal -> CmmLit
+ GHC.StgToCmm.Lit: newByteStringCLit :: ByteString -> FCode CmmLit
+ GHC.StgToCmm.Lit: newStringCLit :: String -> FCode CmmLit
+ GHC.StgToCmm.Monad: newTemp :: MonadUnique m => CmmType -> m LocalReg
+ GHC.StgToCmm.Prof: emitInfoTableProv :: InfoProvEnt -> FCode ()
+ GHC.StgToCmm.Prof: initInfoTableProv :: [CmmInfoTable] -> InfoTableProvMap -> Module -> FCode CStub
+ GHC.StgToCmm.Utils: cmmInfoTableToInfoProvEnt :: Module -> CmmInfoTable -> InfoProvEnt
+ GHC.StgToCmm.Utils: convertInfoProvMap :: DynFlags -> [CmmInfoTable] -> Module -> InfoTableProvMap -> [InfoProvEnt]
+ GHC.Tc.Gen.Export: rnExports :: Bool -> Maybe (LocatedL [LIE GhcPs]) -> RnM TcGblEnv
+ GHC.Tc.Solver: tcCheckGivens :: InertSet -> Bag EvVar -> TcM (Maybe InertSet)
+ GHC.Tc.Solver: tcCheckWanteds :: InertSet -> ThetaType -> TcM Bool
+ GHC.Tc.Utils.Monad: addDiagnostic :: DiagnosticReason -> SDoc -> TcRn ()
+ GHC.Tc.Utils.Monad: addDiagnosticAt :: DiagnosticReason -> SrcSpan -> SDoc -> TcRn ()
+ GHC.Tc.Utils.Monad: addDiagnosticTc :: DiagnosticReason -> SDoc -> TcM ()
+ GHC.Tc.Utils.Monad: addDiagnosticTcM :: DiagnosticReason -> (TidyEnv, SDoc) -> TcM ()
+ GHC.Tc.Utils.Monad: addLocMA :: (a -> TcM b) -> GenLocated (SrcSpanAnn' ann) a -> TcM b
+ GHC.Tc.Utils.Monad: add_diagnostic :: DiagnosticReason -> SDoc -> SDoc -> TcRn ()
+ GHC.Tc.Utils.Monad: diagnosticTc :: DiagnosticReason -> Bool -> SDoc -> TcM ()
+ GHC.Tc.Utils.Monad: diagnosticTcM :: DiagnosticReason -> Bool -> (TidyEnv, SDoc) -> TcM ()
+ GHC.Tc.Utils.Monad: reportDiagnostic :: MsgEnvelope DiagnosticMessage -> TcRn ()
+ GHC.Tc.Utils.Monad: reportDiagnostics :: [MsgEnvelope DiagnosticMessage] -> TcM ()
+ GHC.Tc.Utils.Monad: setSrcSpanA :: SrcSpanAnn' ann -> TcRn a -> TcRn a
+ GHC.Tc.Utils.Monad: wrapLocAM :: (a -> TcM b) -> LocatedAn an a -> TcM (Located b)
+ GHC.Tc.Utils.Monad: wrapLocFstMA :: (a -> TcM (b, c)) -> LocatedA a -> TcM (LocatedA b, c)
+ GHC.Tc.Utils.Monad: wrapLocMA :: (a -> TcM b) -> GenLocated (SrcSpanAnn' ann) a -> TcRn (GenLocated (SrcSpanAnn' ann) b)
+ GHC.Tc.Utils.Monad: wrapLocMA_ :: (a -> TcM ()) -> LocatedA a -> TcM ()
+ GHC.Tc.Utils.Monad: wrapLocSndMA :: (a -> TcM (b, c)) -> LocatedA a -> TcM (b, LocatedA c)
+ GHC.Tc.Utils.TcMType: newOpenBoxedTypeKind :: TcM TcKind
+ GHC.Tc.Utils.Unify: unifyExpectedType :: HsExpr GhcRn -> TcRhoType -> ExpRhoType -> TcM TcCoercionN
+ GHC.Unit.Finder: data FinderCache
+ GHC.Unit.Finder: initFinderCache :: IO FinderCache
- GHC: DynFlags :: GhcMode -> GhcLink -> !Backend -> {-# UNPACK #-} !GhcNameVersion -> {-# UNPACK #-} !FileSettings -> Platform -> {-# UNPACK #-} !ToolSettings -> {-# UNPACK #-} !PlatformMisc -> [(String, String)] -> LlvmConfig -> Int -> Int -> Int -> Int -> Int -> Maybe String -> Maybe String -> [Int] -> Maybe Int -> Bool -> Maybe Int -> Maybe Int -> Maybe Int -> Maybe Int -> Maybe Int -> Int -> Int -> Int -> Maybe Int -> Maybe Int -> Int -> Word -> Maybe Int -> Maybe Int -> Maybe Int -> Maybe Int -> Bool -> Maybe Int -> Int -> [FilePath] -> ModuleName -> Maybe String -> IntWithInf -> IntWithInf -> UnitId -> Maybe UnitId -> [(ModuleName, Module)] -> Ways -> Maybe (String, Int) -> Maybe String -> Maybe String -> Maybe String -> Maybe String -> Maybe String -> Maybe String -> String -> String -> String -> String -> IORef Bool -> String -> String -> Maybe String -> Maybe String -> Maybe String -> DynLibLoader -> !Bool -> Maybe FilePath -> Maybe FilePath -> [Option] -> IncludeSpecs -> [String] -> [String] -> [String] -> Maybe String -> RtsOptsEnabled -> Bool -> String -> [ModuleName] -> [(ModuleName, String)] -> [String] -> FilePath -> Bool -> Bool -> [ModuleName] -> [String] -> [PackageDBFlag] -> [IgnorePackageFlag] -> [PackageFlag] -> [PackageFlag] -> [TrustFlag] -> Maybe FilePath -> IORef FilesToClean -> IORef (Map FilePath FilePath) -> IORef Int -> EnumSet DumpFlag -> EnumSet GeneralFlag -> EnumSet WarningFlag -> EnumSet WarningFlag -> Maybe Language -> SafeHaskellMode -> Bool -> Bool -> SrcSpan -> SrcSpan -> SrcSpan -> SrcSpan -> SrcSpan -> SrcSpan -> SrcSpan -> SrcSpan -> [OnOff Extension] -> EnumSet Extension -> !UnfoldingOpts -> Int -> Int -> FlushOut -> FlushErr -> Maybe FilePath -> Maybe String -> [String] -> Int -> Int -> Bool -> OverridingBool -> Bool -> Scheme -> ProfAuto -> [CallerCcFilter] -> Maybe String -> IORef (ModuleEnv Int) -> Maybe SseVersion -> Maybe BmiVersion -> Bool -> Bool -> Bool -> Bool -> Bool -> Bool -> IORef (Maybe LinkerInfo) -> IORef (Maybe CompilerInfo) -> Int -> Int -> Int -> Bool -> Maybe Int -> Word -> Int -> Weights -> DynFlags
+ GHC: DynFlags :: GhcMode -> GhcLink -> !Backend -> {-# UNPACK #-} !GhcNameVersion -> {-# UNPACK #-} !FileSettings -> Platform -> {-# UNPACK #-} !ToolSettings -> {-# UNPACK #-} !PlatformMisc -> [(String, String)] -> LlvmConfig -> Int -> Int -> Int -> Int -> Int -> Maybe String -> Maybe String -> [Int] -> Maybe Int -> Bool -> Maybe Int -> Maybe Int -> Maybe Int -> Maybe Int -> Maybe Int -> Int -> Int -> Int -> Maybe Int -> Maybe Int -> Int -> Word -> Maybe Int -> Maybe Int -> Maybe Int -> Maybe Int -> Bool -> Maybe Int -> Int -> [FilePath] -> ModuleName -> Maybe String -> IntWithInf -> IntWithInf -> UnitId -> Maybe UnitId -> [(ModuleName, Module)] -> Ways -> Maybe (String, Int) -> Maybe String -> Maybe String -> Maybe String -> Maybe String -> Maybe String -> Maybe String -> String -> String -> String -> String -> IORef Bool -> String -> String -> Maybe String -> Maybe String -> Maybe String -> DynLibLoader -> !Bool -> Maybe FilePath -> Maybe FilePath -> [Option] -> IncludeSpecs -> [String] -> [String] -> [String] -> Maybe String -> RtsOptsEnabled -> Bool -> String -> [ModuleName] -> [(ModuleName, String)] -> [String] -> FilePath -> Bool -> Bool -> [ModuleName] -> [String] -> [PackageDBFlag] -> [IgnorePackageFlag] -> [PackageFlag] -> [PackageFlag] -> [TrustFlag] -> Maybe FilePath -> EnumSet DumpFlag -> EnumSet GeneralFlag -> EnumSet WarningFlag -> EnumSet WarningFlag -> Maybe Language -> SafeHaskellMode -> Bool -> Bool -> SrcSpan -> SrcSpan -> SrcSpan -> SrcSpan -> SrcSpan -> SrcSpan -> SrcSpan -> SrcSpan -> [OnOff Extension] -> EnumSet Extension -> !UnfoldingOpts -> Int -> Int -> FlushOut -> FlushErr -> Maybe FilePath -> Maybe String -> [String] -> Int -> Int -> Bool -> OverridingBool -> Bool -> Scheme -> ProfAuto -> [CallerCcFilter] -> Maybe String -> IORef (ModuleEnv Int) -> Maybe SseVersion -> Maybe BmiVersion -> Bool -> Bool -> Bool -> Bool -> Bool -> Bool -> IORef (Maybe LinkerInfo) -> IORef (Maybe CompilerInfo) -> Int -> Int -> Int -> Bool -> Maybe Int -> Word -> Int -> Weights -> DynFlags
- GHC: ParsedModule :: ModSummary -> ParsedSource -> [FilePath] -> ApiAnns -> ParsedModule
+ GHC: ParsedModule :: ModSummary -> ParsedSource -> [FilePath] -> ParsedModule
- GHC: Target :: TargetId -> Bool -> Maybe (InputFileBuffer, UTCTime) -> Target
+ GHC: Target :: TargetId -> Bool -> UnitId -> Maybe (InputFileBuffer, UTCTime) -> Target
- GHC: getDocs :: GhcMonad m => Name -> m (Either GetDocsFailure (Maybe HsDocString, Map Int HsDocString))
+ GHC: getDocs :: GhcMonad m => Name -> m (Either GetDocsFailure (Maybe HsDocString, IntMap HsDocString))
- GHC: getNameToInstancesIndex :: GhcMonad m => [Module] -> Maybe [Module] -> m (Messages DecoratedSDoc, Maybe (NameEnv ([ClsInst], [FamInst])))
+ GHC: getNameToInstancesIndex :: GhcMonad m => [Module] -> Maybe [Module] -> m (Messages DiagnosticMessage, Maybe (NameEnv ([ClsInst], [FamInst])))
- GHC: guessTarget :: GhcMonad m => String -> Maybe Phase -> m Target
+ GHC: guessTarget :: GhcMonad m => String -> Maybe UnitId -> Maybe Phase -> m Target
- GHC: putLogMsgM :: GhcMonad m => WarnReason -> Severity -> SrcSpan -> SDoc -> m ()
+ GHC: putLogMsgM :: GhcMonad m => MessageClass -> SrcSpan -> SDoc -> m ()
- GHC: resumeExec :: GhcMonad m => (SrcSpan -> Bool) -> SingleStep -> m ExecResult
+ GHC: resumeExec :: GhcMonad m => (SrcSpan -> Bool) -> SingleStep -> Maybe Int -> m ExecResult
- GHC: runTcInteractive :: HscEnv -> TcRn a -> IO (Messages DecoratedSDoc, Maybe a)
+ GHC: runTcInteractive :: HscEnv -> TcRn a -> IO (Messages DiagnosticMessage, Maybe a)
- GHC.ByteCode.Asm: assembleBCOs :: HscEnv -> [ProtoBCO Name] -> [TyCon] -> [RemotePtr ()] -> Maybe ModBreaks -> IO CompiledByteCode
+ GHC.ByteCode.Asm: assembleBCOs :: Interp -> Profile -> [ProtoBCO Name] -> [TyCon] -> [RemotePtr ()] -> Maybe ModBreaks -> IO CompiledByteCode
- GHC.ByteCode.Asm: assembleOneBCO :: HscEnv -> ProtoBCO Name -> IO UnlinkedBCO
+ GHC.ByteCode.Asm: assembleOneBCO :: Interp -> Profile -> ProtoBCO Name -> IO UnlinkedBCO
- GHC.ByteCode.InfoTable: mkITbls :: HscEnv -> [TyCon] -> IO ItblEnv
+ GHC.ByteCode.InfoTable: mkITbls :: Interp -> Profile -> [TyCon] -> IO ItblEnv
- GHC.ByteCode.Instr: ProtoBCO :: a -> [BCInstr] -> [StgWord] -> Word16 -> Int -> Either [AnnAlt Id DVarSet] (AnnExpr Id DVarSet) -> [FFIInfo] -> ProtoBCO a
+ GHC.ByteCode.Instr: ProtoBCO :: a -> [BCInstr] -> [StgWord] -> Word16 -> Int -> Either [CgStgAlt] CgStgRhs -> [FFIInfo] -> ProtoBCO a
- GHC.ByteCode.Instr: [protoBCOExpr] :: ProtoBCO a -> Either [AnnAlt Id DVarSet] (AnnExpr Id DVarSet)
+ GHC.ByteCode.Instr: [protoBCOExpr] :: ProtoBCO a -> Either [CgStgAlt] CgStgRhs
- GHC.ByteCode.Linker: linkBCO :: HscEnv -> ItblEnv -> ClosureEnv -> NameEnv Int -> RemoteRef BreakArray -> UnlinkedBCO -> IO ResolvedBCO
+ GHC.ByteCode.Linker: linkBCO :: Interp -> ItblEnv -> ClosureEnv -> NameEnv Int -> RemoteRef BreakArray -> UnlinkedBCO -> IO ResolvedBCO
- GHC.ByteCode.Linker: lookupIE :: HscEnv -> ItblEnv -> Name -> IO (Ptr ())
+ GHC.ByteCode.Linker: lookupIE :: Interp -> ItblEnv -> Name -> IO (Ptr ())
- GHC.ByteCode.Linker: lookupStaticPtr :: HscEnv -> FastString -> IO (Ptr ())
+ GHC.ByteCode.Linker: lookupStaticPtr :: Interp -> FastString -> IO (Ptr ())
- GHC.Cmm.Parser: parseCmmFile :: DynFlags -> HomeUnit -> FilePath -> IO (Bag PsWarning, Bag PsError, Maybe CmmGroup)
+ GHC.Cmm.Parser: parseCmmFile :: DynFlags -> Module -> HomeUnit -> FilePath -> IO (Bag PsWarning, Bag PsError, Maybe (CmmGroup, [InfoProvEnt]))
- GHC.Core.Opt.Simplify.Env: SimplEnv :: SimplMode -> TvSubstEnv -> CvSubstEnv -> SimplIdSubst -> InScopeSet -> !Int -> SimplEnv
+ GHC.Core.Opt.Simplify.Env: SimplEnv :: !SimplMode -> TvSubstEnv -> CvSubstEnv -> SimplIdSubst -> !InScopeSet -> !Int -> SimplEnv
- GHC.Core.Opt.Simplify.Env: [seInScope] :: SimplEnv -> InScopeSet
+ GHC.Core.Opt.Simplify.Env: [seInScope] :: SimplEnv -> !InScopeSet
- GHC.Core.Opt.Simplify.Env: [seMode] :: SimplEnv -> SimplMode
+ GHC.Core.Opt.Simplify.Env: [seMode] :: SimplEnv -> !SimplMode
- GHC.Core.Opt.Simplify.Utils: TickIt :: Tickish Id -> SimplCont -> SimplCont
+ GHC.Core.Opt.Simplify.Utils: TickIt :: CoreTickish -> SimplCont -> SimplCont
- GHC.Core.Opt.WorkWrap.Utils: mkWwBodies :: DynFlags -> FamInstEnvs -> VarSet -> Id -> [Demand] -> CprResult -> UniqSM (Maybe WwResult)
+ GHC.Core.Opt.WorkWrap.Utils: mkWwBodies :: DynFlags -> FamInstEnvs -> VarSet -> Id -> [Demand] -> Cpr -> UniqSM (Maybe WwResult)
- GHC.Core.Opt.WorkWrap.Utils: wantToUnbox :: FamInstEnvs -> Bool -> Type -> Demand -> Maybe ([Demand], DataConPatContext)
+ GHC.Core.Opt.WorkWrap.Utils: wantToUnbox :: FamInstEnvs -> Bool -> Type -> Demand -> UnboxingDecision Demand
- GHC.CoreToStg: coreToStg :: DynFlags -> Module -> CoreProgram -> ([StgTopBinding], CollectedCCs)
+ GHC.CoreToStg: coreToStg :: DynFlags -> Module -> ModLocation -> CoreProgram -> ([StgTopBinding], InfoTableProvMap, CollectedCCs)
- GHC.Driver.CodeOutput: codeOutput :: Logger -> DynFlags -> UnitState -> Module -> FilePath -> ModLocation -> ForeignStubs -> [(ForeignSrcLang, FilePath)] -> [UnitId] -> Stream IO RawCmmGroup a -> IO (FilePath, (Bool, Maybe FilePath), [(ForeignSrcLang, FilePath)], a)
+ GHC.Driver.CodeOutput: codeOutput :: Logger -> TmpFs -> DynFlags -> UnitState -> Module -> FilePath -> ModLocation -> (a -> ForeignStubs) -> [(ForeignSrcLang, FilePath)] -> [UnitId] -> Stream IO RawCmmGroup a -> IO (FilePath, (Bool, Maybe FilePath), [(ForeignSrcLang, FilePath)], a)
- GHC.Driver.CodeOutput: outputForeignStubs :: Logger -> DynFlags -> UnitState -> Module -> ModLocation -> ForeignStubs -> IO (Bool, Maybe FilePath)
+ GHC.Driver.CodeOutput: outputForeignStubs :: Logger -> TmpFs -> DynFlags -> UnitState -> Module -> ModLocation -> ForeignStubs -> IO (Bool, Maybe FilePath)
- GHC.Driver.CodeOutput: profilingInitCode :: Platform -> Module -> CollectedCCs -> SDoc
+ GHC.Driver.CodeOutput: profilingInitCode :: Platform -> Module -> CollectedCCs -> CStub
- GHC.Driver.Main: doCodeGen :: HscEnv -> Module -> [TyCon] -> CollectedCCs -> [StgTopBinding] -> HpcInfo -> IO (Stream IO CmmGroupSRTs CgInfos)
+ GHC.Driver.Main: doCodeGen :: HscEnv -> Module -> InfoTableProvMap -> [TyCon] -> CollectedCCs -> [StgTopBinding] -> HpcInfo -> IO (Stream IO CmmGroupSRTs CgInfos)
- GHC.Driver.Main: hscCompileCmmFile :: HscEnv -> FilePath -> FilePath -> IO ()
+ GHC.Driver.Main: hscCompileCmmFile :: HscEnv -> FilePath -> FilePath -> IO (Maybe FilePath)
- GHC.Driver.Main: hscParseIdentifier :: HscEnv -> String -> IO (Located RdrName)
+ GHC.Driver.Main: hscParseIdentifier :: HscEnv -> String -> IO (LocatedN RdrName)
- GHC.Driver.Main: hscTcRnLookupRdrName :: HscEnv -> Located RdrName -> IO [Name]
+ GHC.Driver.Main: hscTcRnLookupRdrName :: HscEnv -> LocatedN RdrName -> IO [Name]
- GHC.Driver.Main: ioMsgMaybe :: IO (Messages DecoratedSDoc, Maybe a) -> Hsc a
+ GHC.Driver.Main: ioMsgMaybe :: IO (Messages DiagnosticMessage, Maybe a) -> Hsc a
- GHC.Driver.Make: noModError :: HscEnv -> SrcSpan -> ModuleName -> FindResult -> MsgEnvelope DecoratedSDoc
+ GHC.Driver.Make: noModError :: HscEnv -> SrcSpan -> ModuleName -> FindResult -> MsgEnvelope DiagnosticMessage
- GHC.Driver.Pipeline: doCpp :: Logger -> DynFlags -> UnitEnv -> Bool -> FilePath -> FilePath -> IO ()
+ GHC.Driver.Pipeline: doCpp :: Logger -> TmpFs -> DynFlags -> UnitEnv -> Bool -> FilePath -> FilePath -> IO ()
- GHC.Driver.Pipeline: getOutputFilename :: Logger -> Phase -> PipelineOutput -> String -> DynFlags -> Phase -> Maybe ModLocation -> IO FilePath
+ GHC.Driver.Pipeline: getOutputFilename :: Logger -> TmpFs -> Phase -> PipelineOutput -> String -> DynFlags -> Phase -> Maybe ModLocation -> IO FilePath
- GHC.Driver.Pipeline: link :: GhcLink -> Logger -> Hooks -> DynFlags -> UnitEnv -> Bool -> HomePackageTable -> IO SuccessFlag
+ GHC.Driver.Pipeline: link :: GhcLink -> Logger -> TmpFs -> Hooks -> DynFlags -> UnitEnv -> Bool -> HomePackageTable -> IO SuccessFlag
- GHC.HsToCore: deSugar :: HscEnv -> ModLocation -> TcGblEnv -> IO (Messages DecoratedSDoc, Maybe ModGuts)
+ GHC.HsToCore: deSugar :: HscEnv -> ModLocation -> TcGblEnv -> IO (Messages DiagnosticMessage, Maybe ModGuts)
- GHC.HsToCore: deSugarExpr :: HscEnv -> LHsExpr GhcTc -> IO (Messages DecoratedSDoc, Maybe CoreExpr)
+ GHC.HsToCore: deSugarExpr :: HscEnv -> LHsExpr GhcTc -> IO (Messages DiagnosticMessage, Maybe CoreExpr)
- GHC.HsToCore.Coverage: hpcInitCode :: DynFlags -> Module -> HpcInfo -> SDoc
+ GHC.HsToCore.Coverage: hpcInitCode :: DynFlags -> Module -> HpcInfo -> CStub
- GHC.HsToCore.Docs: conArgDocs :: ConDecl GhcRn -> Map Int HsDocString
+ GHC.HsToCore.Docs: conArgDocs :: ConDecl GhcRn -> IntMap HsDocString
- GHC.HsToCore.Docs: con_arg_docs :: Int -> [HsType GhcRn] -> Map Int HsDocString
+ GHC.HsToCore.Docs: con_arg_docs :: Int -> [HsType GhcRn] -> IntMap HsDocString
- GHC.HsToCore.Docs: declTypeDocs :: HsDecl GhcRn -> Map Int HsDocString
+ GHC.HsToCore.Docs: declTypeDocs :: HsDecl GhcRn -> IntMap HsDocString
- GHC.HsToCore.Docs: extractDocs :: TcGblEnv -> (Maybe HsDocString, DeclDocMap, ArgDocMap)
+ GHC.HsToCore.Docs: extractDocs :: MonadIO m => TcGblEnv -> m (Maybe HsDocString, DeclDocMap, ArgDocMap)
- GHC.HsToCore.Docs: filterClasses :: forall p doc. (UnXRec p, MapXRec p) => [(LHsDecl p, doc)] -> [(LHsDecl p, doc)]
+ GHC.HsToCore.Docs: filterClasses :: forall p doc. IsPass p => [(LHsDecl (GhcPass p), doc)] -> [(LHsDecl (GhcPass p), doc)]
- GHC.HsToCore.Docs: gadtConArgDocs :: HsConDeclGADTDetails GhcRn -> HsType GhcRn -> Map Int HsDocString
+ GHC.HsToCore.Docs: gadtConArgDocs :: HsConDeclGADTDetails GhcRn -> HsType GhcRn -> IntMap HsDocString
- GHC.HsToCore.Docs: getInstLoc :: InstDecl (GhcPass p) -> SrcSpan
+ GHC.HsToCore.Docs: getInstLoc :: Anno (IdGhcP p) ~ SrcSpanAnnN => InstDecl (GhcPass p) -> SrcSpan
- GHC.HsToCore.Docs: getMainDeclBinder :: CollectPass (GhcPass p) => HsDecl (GhcPass p) -> [IdP (GhcPass p)]
+ GHC.HsToCore.Docs: getMainDeclBinder :: (Anno (IdGhcP p) ~ SrcSpanAnnN, CollectPass (GhcPass p)) => HsDecl (GhcPass p) -> [IdP (GhcPass p)]
- GHC.HsToCore.Docs: h98ConArgDocs :: HsConDeclH98Details GhcRn -> Map Int HsDocString
+ GHC.HsToCore.Docs: h98ConArgDocs :: HsConDeclH98Details GhcRn -> IntMap HsDocString
- GHC.HsToCore.Docs: mkDecls :: (struct -> [Located decl]) -> (decl -> hsDecl) -> struct -> [Located hsDecl]
+ GHC.HsToCore.Docs: mkDecls :: (struct -> [GenLocated l decl]) -> (decl -> hsDecl) -> struct -> [GenLocated l hsDecl]
- GHC.HsToCore.Docs: mkMaps :: [Name] -> [(LHsDecl GhcRn, [HsDocString])] -> (Map Name HsDocString, Map Name (Map Int HsDocString))
+ GHC.HsToCore.Docs: mkMaps :: [Name] -> [(LHsDecl GhcRn, [HsDocString])] -> (Map Name HsDocString, Map Name (IntMap HsDocString))
- GHC.HsToCore.Docs: sigTypeDocs :: HsSigType GhcRn -> Map Int HsDocString
+ GHC.HsToCore.Docs: sigTypeDocs :: HsSigType GhcRn -> IntMap HsDocString
- GHC.HsToCore.Docs: subordinates :: Map RealSrcSpan Name -> HsDecl GhcRn -> [(Name, [HsDocString], Map Int HsDocString)]
+ GHC.HsToCore.Docs: subordinates :: Map RealSrcSpan Name -> HsDecl GhcRn -> [(Name, [HsDocString], IntMap HsDocString)]
- GHC.HsToCore.Docs: typeDocs :: HsType GhcRn -> Map Int HsDocString
+ GHC.HsToCore.Docs: typeDocs :: HsType GhcRn -> IntMap HsDocString
- GHC.HsToCore.Expr: dsLocalBinds :: LHsLocalBinds GhcTc -> CoreExpr -> DsM CoreExpr
+ GHC.HsToCore.Expr: dsLocalBinds :: HsLocalBinds GhcTc -> CoreExpr -> DsM CoreExpr
- GHC.HsToCore.Match.Literal: warnAboutIdentities :: DynFlags -> CoreExpr -> Type -> DsM ()
+ GHC.HsToCore.Match.Literal: warnAboutIdentities :: DynFlags -> Id -> Type -> DsM ()
- GHC.HsToCore.Monad: initDs :: HscEnv -> TcGblEnv -> DsM a -> IO (Messages DecoratedSDoc, Maybe a)
+ GHC.HsToCore.Monad: initDs :: HscEnv -> TcGblEnv -> DsM a -> IO (Messages DiagnosticMessage, Maybe a)
- GHC.HsToCore.Monad: initDsWithModGuts :: HscEnv -> ModGuts -> DsM a -> IO (Messages DecoratedSDoc, Maybe a)
+ GHC.HsToCore.Monad: initDsWithModGuts :: HscEnv -> ModGuts -> DsM a -> IO (Messages DiagnosticMessage, Maybe a)
- GHC.HsToCore.Monad: initTcDsForSolver :: TcM a -> DsM (Messages DecoratedSDoc, Maybe a)
+ GHC.HsToCore.Monad: initTcDsForSolver :: TcM a -> DsM a
- GHC.HsToCore.Types: DsGblEnv :: Module -> FamInstEnv -> GlobalRdrEnv -> PrintUnqualified -> IORef (Messages DecoratedSDoc) -> (IfGblEnv, IfLclEnv) -> CompleteMatches -> IORef CostCentreState -> DsGblEnv
+ GHC.HsToCore.Types: DsGblEnv :: Module -> FamInstEnv -> GlobalRdrEnv -> PrintUnqualified -> IORef (Messages DiagnosticMessage) -> (IfGblEnv, IfLclEnv) -> CompleteMatches -> IORef CostCentreState -> DsGblEnv
- GHC.HsToCore.Types: [ds_msgs] :: DsGblEnv -> IORef (Messages DecoratedSDoc)
+ GHC.HsToCore.Types: [ds_msgs] :: DsGblEnv -> IORef (Messages DiagnosticMessage)
- GHC.HsToCore.Utils: mkOptTickBox :: [Tickish Id] -> CoreExpr -> CoreExpr
+ GHC.HsToCore.Utils: mkOptTickBox :: [CoreTickish] -> CoreExpr -> CoreExpr
- GHC.HsToCore.Utils: mkSelectorBinds :: [[Tickish Id]] -> LPat GhcTc -> CoreExpr -> DsM (Id, [(Id, CoreExpr)])
+ GHC.HsToCore.Utils: mkSelectorBinds :: [[CoreTickish]] -> LPat GhcTc -> CoreExpr -> DsM (Id, [(Id, CoreExpr)])
- GHC.Iface.Binary: getSymbolTable :: BinHandle -> NameCacheUpdater -> IO SymbolTable
+ GHC.Iface.Binary: getSymbolTable :: BinHandle -> NameCache -> IO SymbolTable
- GHC.Iface.Binary: getSymtabName :: NameCacheUpdater -> Dictionary -> SymbolTable -> BinHandle -> IO Name
+ GHC.Iface.Binary: getSymtabName :: NameCache -> Dictionary -> SymbolTable -> BinHandle -> IO Name
- GHC.Iface.Binary: getWithUserData :: Binary a => NameCacheUpdater -> BinHandle -> IO a
+ GHC.Iface.Binary: getWithUserData :: Binary a => NameCache -> BinHandle -> IO a
- GHC.Iface.Binary: readBinIface :: CheckHiWay -> TraceBinIFace -> FilePath -> TcRnIf a b ModIface
+ GHC.Iface.Binary: readBinIface :: Profile -> NameCache -> CheckHiWay -> TraceBinIFace -> FilePath -> IO ModIface
- GHC.Iface.Env: allocateGlobalBinder :: NameCache -> Module -> OccName -> SrcSpan -> (NameCache, Name)
+ GHC.Iface.Env: allocateGlobalBinder :: NameCache -> Module -> OccName -> SrcSpan -> IO Name
- GHC.Iface.Ext.Binary: readHieFile :: NameCacheUpdater -> FilePath -> IO HieFileResult
+ GHC.Iface.Ext.Binary: readHieFile :: NameCache -> FilePath -> IO HieFileResult
- GHC.Iface.Ext.Binary: readHieFileWithVersion :: (HieHeader -> Bool) -> NameCacheUpdater -> FilePath -> IO (Either HieHeader HieFileResult)
+ GHC.Iface.Ext.Binary: readHieFileWithVersion :: (HieHeader -> Bool) -> NameCache -> FilePath -> IO (Either HieHeader HieFileResult)
- GHC.Iface.Load: findAndReadIface :: SDoc -> InstalledModule -> Module -> IsBootInterface -> TcRnIf gbl lcl (MaybeErr SDoc (ModIface, FilePath))
+ GHC.Iface.Load: findAndReadIface :: Logger -> NameCache -> FinderCache -> Hooks -> UnitState -> HomeUnit -> DynFlags -> SDoc -> InstalledModule -> Module -> IsBootInterface -> IO (MaybeErr SDoc (ModIface, FilePath))
- GHC.Iface.Load: readIface :: Module -> FilePath -> TcRnIf gbl lcl (MaybeErr SDoc ModIface)
+ GHC.Iface.Load: readIface :: DynFlags -> NameCache -> Module -> FilePath -> IO (MaybeErr SDoc ModIface)
- GHC.Iface.Load: showIface :: HscEnv -> FilePath -> IO ()
+ GHC.Iface.Load: showIface :: Logger -> DynFlags -> UnitState -> NameCache -> FilePath -> IO ()
- GHC.Iface.Tidy.StaticPtrTable: sptModuleInitCode :: Platform -> Module -> [SptEntry] -> SDoc
+ GHC.Iface.Tidy.StaticPtrTable: sptModuleInitCode :: Platform -> Module -> [SptEntry] -> CStub
- GHC.Linker.Dynamic: linkDynLib :: Logger -> DynFlags -> UnitEnv -> [String] -> [UnitId] -> IO ()
+ GHC.Linker.Dynamic: linkDynLib :: Logger -> TmpFs -> DynFlags -> UnitEnv -> [String] -> [UnitId] -> IO ()
- GHC.Linker.ExtraObj: mkExtraObj :: Logger -> DynFlags -> UnitState -> Suffix -> String -> IO FilePath
+ GHC.Linker.ExtraObj: mkExtraObj :: Logger -> TmpFs -> DynFlags -> UnitState -> Suffix -> String -> IO FilePath
- GHC.Linker.ExtraObj: mkExtraObjToLinkIntoBinary :: Logger -> DynFlags -> UnitState -> IO (Maybe FilePath)
+ GHC.Linker.ExtraObj: mkExtraObjToLinkIntoBinary :: Logger -> TmpFs -> DynFlags -> UnitState -> IO (Maybe FilePath)
- GHC.Linker.ExtraObj: mkNoteObjsToLinkIntoBinary :: Logger -> DynFlags -> UnitEnv -> [UnitId] -> IO [FilePath]
+ GHC.Linker.ExtraObj: mkNoteObjsToLinkIntoBinary :: Logger -> TmpFs -> DynFlags -> UnitEnv -> [UnitId] -> IO [FilePath]
- GHC.Linker.Loader: deleteFromLoadedEnv :: Loader -> [Name] -> IO ()
+ GHC.Linker.Loader: deleteFromLoadedEnv :: Interp -> [Name] -> IO ()
- GHC.Linker.Loader: extendLoadedEnv :: Loader -> [(Name, ForeignHValue)] -> IO ()
+ GHC.Linker.Loader: extendLoadedEnv :: Interp -> [(Name, ForeignHValue)] -> IO ()
- GHC.Linker.Loader: extendLoadedPkgs :: Loader -> [UnitId] -> IO ()
+ GHC.Linker.Loader: extendLoadedPkgs :: Interp -> [UnitId] -> IO ()
- GHC.Linker.Loader: initLoaderState :: HscEnv -> IO ()
+ GHC.Linker.Loader: initLoaderState :: Interp -> HscEnv -> IO ()
- GHC.Linker.Loader: loadCmdLineLibs :: HscEnv -> IO ()
+ GHC.Linker.Loader: loadCmdLineLibs :: Interp -> HscEnv -> IO ()
- GHC.Linker.Loader: loadDecls :: HscEnv -> SrcSpan -> CompiledByteCode -> IO ()
+ GHC.Linker.Loader: loadDecls :: Interp -> HscEnv -> SrcSpan -> CompiledByteCode -> IO ()
- GHC.Linker.Loader: loadExpr :: HscEnv -> SrcSpan -> UnlinkedBCO -> IO ForeignHValue
+ GHC.Linker.Loader: loadExpr :: Interp -> HscEnv -> SrcSpan -> UnlinkedBCO -> IO ForeignHValue
- GHC.Linker.Loader: loadModule :: HscEnv -> Module -> IO ()
+ GHC.Linker.Loader: loadModule :: Interp -> HscEnv -> Module -> IO ()
- GHC.Linker.Loader: loadName :: HscEnv -> Name -> IO ForeignHValue
+ GHC.Linker.Loader: loadName :: Interp -> HscEnv -> Name -> IO ForeignHValue
- GHC.Linker.Loader: loadPackages :: HscEnv -> [UnitId] -> IO ()
+ GHC.Linker.Loader: loadPackages :: Interp -> HscEnv -> [UnitId] -> IO ()
- GHC.Linker.Loader: showLoaderState :: Loader -> IO SDoc
+ GHC.Linker.Loader: showLoaderState :: Interp -> IO SDoc
- GHC.Linker.Loader: unload :: HscEnv -> [Linkable] -> IO ()
+ GHC.Linker.Loader: unload :: Interp -> HscEnv -> [Linkable] -> IO ()
- GHC.Linker.Loader: withExtendedLoadedEnv :: ExceptionMonad m => Loader -> [(Name, ForeignHValue)] -> m a -> m a
+ GHC.Linker.Loader: withExtendedLoadedEnv :: ExceptionMonad m => Interp -> [(Name, ForeignHValue)] -> m a -> m a
- GHC.Linker.MacOS: loadFramework :: HscEnv -> [FilePath] -> FilePath -> IO (Maybe String)
+ GHC.Linker.MacOS: loadFramework :: Interp -> [FilePath] -> FilePath -> IO (Maybe String)
- GHC.Linker.Static: linkBinary :: Logger -> DynFlags -> UnitEnv -> [FilePath] -> [UnitId] -> IO ()
+ GHC.Linker.Static: linkBinary :: Logger -> TmpFs -> DynFlags -> UnitEnv -> [FilePath] -> [UnitId] -> IO ()
- GHC.Linker.Static: linkBinary' :: Bool -> Logger -> DynFlags -> UnitEnv -> [FilePath] -> [UnitId] -> IO ()
+ GHC.Linker.Static: linkBinary' :: Bool -> Logger -> TmpFs -> DynFlags -> UnitEnv -> [FilePath] -> [UnitId] -> IO ()
- GHC.Linker.Windows: maybeCreateManifest :: Logger -> DynFlags -> FilePath -> IO [FilePath]
+ GHC.Linker.Windows: maybeCreateManifest :: Logger -> TmpFs -> DynFlags -> FilePath -> IO [FilePath]
- GHC.Plugins: substTickish :: Subst -> Tickish Id -> Tickish Id
+ GHC.Plugins: substTickish :: Subst -> CoreTickish -> CoreTickish
- GHC.Rename.Bind: rnGRHS :: HsMatchContext GhcRn -> (Located (body GhcPs) -> RnM (Located (body GhcRn), FreeVars)) -> LGRHS GhcPs (Located (body GhcPs)) -> RnM (LGRHS GhcRn (Located (body GhcRn)), FreeVars)
+ GHC.Rename.Bind: rnGRHS :: AnnoBody body => HsMatchContext GhcRn -> (LocatedA (body GhcPs) -> RnM (LocatedA (body GhcRn), FreeVars)) -> LGRHS GhcPs (LocatedA (body GhcPs)) -> RnM (LGRHS GhcRn (LocatedA (body GhcRn)), FreeVars)
- GHC.Rename.Bind: rnGRHSs :: HsMatchContext GhcRn -> (Located (body GhcPs) -> RnM (Located (body GhcRn), FreeVars)) -> GRHSs GhcPs (Located (body GhcPs)) -> RnM (GRHSs GhcRn (Located (body GhcRn)), FreeVars)
+ GHC.Rename.Bind: rnGRHSs :: AnnoBody body => HsMatchContext GhcRn -> (LocatedA (body GhcPs) -> RnM (LocatedA (body GhcRn), FreeVars)) -> GRHSs GhcPs (LocatedA (body GhcPs)) -> RnM (GRHSs GhcRn (LocatedA (body GhcRn)), FreeVars)
- GHC.Rename.Bind: rnMatchGroup :: Outputable (body GhcPs) => HsMatchContext GhcRn -> (Located (body GhcPs) -> RnM (Located (body GhcRn), FreeVars)) -> MatchGroup GhcPs (Located (body GhcPs)) -> RnM (MatchGroup GhcRn (Located (body GhcRn)), FreeVars)
+ GHC.Rename.Bind: rnMatchGroup :: (Outputable (body GhcPs), AnnoBody body) => HsMatchContext GhcRn -> (LocatedA (body GhcPs) -> RnM (LocatedA (body GhcRn), FreeVars)) -> MatchGroup GhcPs (LocatedA (body GhcPs)) -> RnM (MatchGroup GhcRn (LocatedA (body GhcRn)), FreeVars)
- GHC.Rename.Env: lookupFamInstName :: Maybe Name -> Located RdrName -> RnM (Located Name)
+ GHC.Rename.Env: lookupFamInstName :: Maybe Name -> LocatedN RdrName -> RnM (LocatedN Name)
- GHC.Rename.Env: lookupLocatedOccRn :: Located RdrName -> RnM (Located Name)
+ GHC.Rename.Env: lookupLocatedOccRn :: GenLocated (SrcSpanAnn' ann) RdrName -> TcRn (GenLocated (SrcSpanAnn' ann) Name)
- GHC.Rename.Env: lookupSigCtxtOccRn :: HsSigCtxt -> SDoc -> Located RdrName -> RnM (Located Name)
+ GHC.Rename.Env: lookupSigCtxtOccRn :: HsSigCtxt -> SDoc -> LocatedA RdrName -> RnM (LocatedA Name)
- GHC.Rename.Env: lookupSigOccRn :: HsSigCtxt -> Sig GhcPs -> Located RdrName -> RnM (Located Name)
+ GHC.Rename.Env: lookupSigOccRn :: HsSigCtxt -> Sig GhcPs -> LocatedA RdrName -> RnM (LocatedA Name)
- GHC.Rename.Env: newTopSrcBinder :: Located RdrName -> RnM Name
+ GHC.Rename.Env: newTopSrcBinder :: LocatedN RdrName -> RnM Name
- GHC.Rename.Expr: rnStmts :: Outputable (body GhcPs) => HsStmtContext GhcRn -> (Located (body GhcPs) -> RnM (Located (body GhcRn), FreeVars)) -> [LStmt GhcPs (Located (body GhcPs))] -> ([Name] -> RnM (thing, FreeVars)) -> RnM (([LStmt GhcRn (Located (body GhcRn))], thing), FreeVars)
+ GHC.Rename.Expr: rnStmts :: AnnoBody body => HsStmtContext GhcRn -> (body GhcPs -> RnM (body GhcRn, FreeVars)) -> [LStmt GhcPs (LocatedA (body GhcPs))] -> ([Name] -> RnM (thing, FreeVars)) -> RnM (([LStmt GhcRn (LocatedA (body GhcRn))], thing), FreeVars)
- GHC.Rename.Fixity: lookupTyFixityRn :: Located Name -> RnM Fixity
+ GHC.Rename.Fixity: lookupTyFixityRn :: LocatedN Name -> RnM Fixity
- GHC.Rename.HsType: bindHsOuterTyVarBndrs :: OutputableBndrFlag flag => HsDocContext -> Maybe assoc -> FreeKiTyVars -> HsOuterTyVarBndrs flag GhcPs -> (HsOuterTyVarBndrs flag GhcRn -> RnM (a, FreeVars)) -> RnM (a, FreeVars)
+ GHC.Rename.HsType: bindHsOuterTyVarBndrs :: OutputableBndrFlag flag 'Renamed => HsDocContext -> Maybe assoc -> FreeKiTyVars -> HsOuterTyVarBndrs flag GhcPs -> (HsOuterTyVarBndrs flag GhcRn -> RnM (a, FreeVars)) -> RnM (a, FreeVars)
- GHC.Rename.HsType: bindLHsTyVarBndrs :: OutputableBndrFlag flag => HsDocContext -> WarnUnusedForalls -> Maybe a -> [LHsTyVarBndr flag GhcPs] -> ([LHsTyVarBndr flag GhcRn] -> RnM (b, FreeVars)) -> RnM (b, FreeVars)
+ GHC.Rename.HsType: bindLHsTyVarBndrs :: OutputableBndrFlag flag 'Renamed => HsDocContext -> WarnUnusedForalls -> Maybe a -> [LHsTyVarBndr flag GhcPs] -> ([LHsTyVarBndr flag GhcRn] -> RnM (b, FreeVars)) -> RnM (b, FreeVars)
- GHC.Rename.HsType: mkConOpPatRn :: Located Name -> Fixity -> LPat GhcRn -> LPat GhcRn -> RnM (Pat GhcRn)
+ GHC.Rename.HsType: mkConOpPatRn :: LocatedN Name -> Fixity -> LPat GhcRn -> LPat GhcRn -> RnM (Pat GhcRn)
- GHC.Rename.HsType: mkNegAppRn :: LHsExpr (GhcPass id) -> SyntaxExpr (GhcPass id) -> RnM (HsExpr (GhcPass id))
+ GHC.Rename.HsType: mkNegAppRn :: LHsExpr GhcRn -> SyntaxExpr GhcRn -> RnM (HsExpr GhcRn)
- GHC.Rename.HsType: newTyVarNameRn :: Maybe a -> Located RdrName -> RnM Name
+ GHC.Rename.HsType: newTyVarNameRn :: Maybe a -> LocatedN RdrName -> RnM Name
- GHC.Rename.HsType: nubL :: Eq a => [Located a] -> [Located a]
+ GHC.Rename.HsType: nubL :: Eq a => [GenLocated l a] -> [GenLocated l a]
- GHC.Rename.HsType: rnContext :: HsDocContext -> LHsContext GhcPs -> RnM (LHsContext GhcRn, FreeVars)
+ GHC.Rename.HsType: rnContext :: HsDocContext -> Maybe (LHsContext GhcPs) -> RnM (Maybe (LHsContext GhcRn), FreeVars)
- GHC.Rename.HsType: rnLTyVar :: Located RdrName -> RnM (Located Name)
+ GHC.Rename.HsType: rnLTyVar :: LocatedN RdrName -> RnM (LocatedN Name)
- GHC.Rename.HsType: type FreeKiTyVars = [Located RdrName]
+ GHC.Rename.HsType: type FreeKiTyVars = [LocatedN RdrName]
- GHC.Rename.Pat: applyNameMaker :: NameMaker -> Located RdrName -> RnM (Located Name)
+ GHC.Rename.Pat: applyNameMaker :: NameMaker -> LocatedN RdrName -> RnM (LocatedN Name)
- GHC.Rename.Pat: rnHsRecFields :: forall arg. HsRecFieldContext -> (SrcSpan -> RdrName -> arg) -> HsRecFields GhcPs (Located arg) -> RnM ([LHsRecField GhcRn (Located arg)], FreeVars)
+ GHC.Rename.Pat: rnHsRecFields :: forall arg. HsRecFieldContext -> (SrcSpan -> RdrName -> arg) -> HsRecFields GhcPs (LocatedA arg) -> RnM ([LHsRecField GhcRn (LocatedA arg)], FreeVars)
- GHC.Rename.Utils: ClassDeclCtx :: Located RdrName -> HsDocContext
+ GHC.Rename.Utils: ClassDeclCtx :: LocatedN RdrName -> HsDocContext
- GHC.Rename.Utils: ConDeclCtx :: [Located Name] -> HsDocContext
+ GHC.Rename.Utils: ConDeclCtx :: [LocatedN Name] -> HsDocContext
- GHC.Rename.Utils: FamPatCtx :: Located RdrName -> HsDocContext
+ GHC.Rename.Utils: FamPatCtx :: LocatedN RdrName -> HsDocContext
- GHC.Rename.Utils: ForeignDeclCtx :: Located RdrName -> HsDocContext
+ GHC.Rename.Utils: ForeignDeclCtx :: LocatedN RdrName -> HsDocContext
- GHC.Rename.Utils: TyDataCtx :: Located RdrName -> HsDocContext
+ GHC.Rename.Utils: TyDataCtx :: LocatedN RdrName -> HsDocContext
- GHC.Rename.Utils: TyFamilyCtx :: Located RdrName -> HsDocContext
+ GHC.Rename.Utils: TyFamilyCtx :: LocatedN RdrName -> HsDocContext
- GHC.Rename.Utils: TySynCtx :: Located RdrName -> HsDocContext
+ GHC.Rename.Utils: TySynCtx :: LocatedN RdrName -> HsDocContext
- GHC.Rename.Utils: checkDupRdrNames :: [Located RdrName] -> RnM ()
+ GHC.Rename.Utils: checkDupRdrNames :: [LocatedN RdrName] -> RnM ()
- GHC.Rename.Utils: checkShadowedRdrNames :: [Located RdrName] -> RnM ()
+ GHC.Rename.Utils: checkShadowedRdrNames :: [LocatedN RdrName] -> RnM ()
- GHC.Rename.Utils: newLocalBndrRn :: Located RdrName -> RnM Name
+ GHC.Rename.Utils: newLocalBndrRn :: LocatedN RdrName -> RnM Name
- GHC.Rename.Utils: newLocalBndrsRn :: [Located RdrName] -> RnM [Name]
+ GHC.Rename.Utils: newLocalBndrsRn :: [LocatedN RdrName] -> RnM [Name]
- GHC.Runtime.Eval: getDocs :: GhcMonad m => Name -> m (Either GetDocsFailure (Maybe HsDocString, Map Int HsDocString))
+ GHC.Runtime.Eval: getDocs :: GhcMonad m => Name -> m (Either GetDocsFailure (Maybe HsDocString, IntMap HsDocString))
- GHC.Runtime.Eval: resumeExec :: GhcMonad m => (SrcSpan -> Bool) -> SingleStep -> m ExecResult
+ GHC.Runtime.Eval: resumeExec :: GhcMonad m => (SrcSpan -> Bool) -> SingleStep -> Maybe Int -> m ExecResult
- GHC.Runtime.Interpreter: abandonStmt :: HscEnv -> ForeignRef (ResumeContext [HValueRef]) -> IO ()
+ GHC.Runtime.Interpreter: abandonStmt :: Interp -> ForeignRef (ResumeContext [HValueRef]) -> IO ()
- GHC.Runtime.Interpreter: addLibrarySearchPath :: HscEnv -> String -> IO (Ptr ())
+ GHC.Runtime.Interpreter: addLibrarySearchPath :: Interp -> String -> IO (Ptr ())
- GHC.Runtime.Interpreter: addSptEntry :: HscEnv -> Fingerprint -> ForeignHValue -> IO ()
+ GHC.Runtime.Interpreter: addSptEntry :: Interp -> Fingerprint -> ForeignHValue -> IO ()
- GHC.Runtime.Interpreter: breakpointStatus :: HscEnv -> ForeignRef BreakArray -> Int -> IO Bool
+ GHC.Runtime.Interpreter: breakpointStatus :: Interp -> ForeignRef BreakArray -> Int -> IO Bool
- GHC.Runtime.Interpreter: costCentreStackInfo :: HscEnv -> RemotePtr CostCentreStack -> IO [String]
+ GHC.Runtime.Interpreter: costCentreStackInfo :: Interp -> RemotePtr CostCentreStack -> IO [String]
- GHC.Runtime.Interpreter: createBCOs :: HscEnv -> [ResolvedBCO] -> IO [HValueRef]
+ GHC.Runtime.Interpreter: createBCOs :: Interp -> DynFlags -> [ResolvedBCO] -> IO [HValueRef]
- GHC.Runtime.Interpreter: evalIO :: HscEnv -> ForeignHValue -> IO ()
+ GHC.Runtime.Interpreter: evalIO :: Interp -> ForeignHValue -> IO ()
- GHC.Runtime.Interpreter: evalStmt :: HscEnv -> Bool -> EvalExpr ForeignHValue -> IO (EvalStatus_ [ForeignHValue] [HValueRef])
+ GHC.Runtime.Interpreter: evalStmt :: Interp -> DynFlags -> Bool -> EvalExpr ForeignHValue -> IO (EvalStatus_ [ForeignHValue] [HValueRef])
- GHC.Runtime.Interpreter: evalString :: HscEnv -> ForeignHValue -> IO String
+ GHC.Runtime.Interpreter: evalString :: Interp -> ForeignHValue -> IO String
- GHC.Runtime.Interpreter: evalStringToIOString :: HscEnv -> ForeignHValue -> String -> IO String
+ GHC.Runtime.Interpreter: evalStringToIOString :: Interp -> ForeignHValue -> String -> IO String
- GHC.Runtime.Interpreter: findSystemLibrary :: HscEnv -> String -> IO (Maybe String)
+ GHC.Runtime.Interpreter: findSystemLibrary :: Interp -> String -> IO (Maybe String)
- GHC.Runtime.Interpreter: freeHValueRefs :: HscEnv -> [HValueRef] -> IO ()
+ GHC.Runtime.Interpreter: freeHValueRefs :: Interp -> [HValueRef] -> IO ()
- GHC.Runtime.Interpreter: getBreakpointVar :: HscEnv -> ForeignHValue -> Int -> IO (Maybe ForeignHValue)
+ GHC.Runtime.Interpreter: getBreakpointVar :: Interp -> ForeignHValue -> Int -> IO (Maybe ForeignHValue)
- GHC.Runtime.Interpreter: getClosure :: HscEnv -> ForeignHValue -> IO (GenClosure ForeignHValue)
+ GHC.Runtime.Interpreter: getClosure :: Interp -> ForeignHValue -> IO (GenClosure ForeignHValue)
- GHC.Runtime.Interpreter: initObjLinker :: HscEnv -> IO ()
+ GHC.Runtime.Interpreter: initObjLinker :: Interp -> IO ()
- GHC.Runtime.Interpreter: loadArchive :: HscEnv -> String -> IO ()
+ GHC.Runtime.Interpreter: loadArchive :: Interp -> String -> IO ()
- GHC.Runtime.Interpreter: loadDLL :: HscEnv -> String -> IO (Maybe String)
+ GHC.Runtime.Interpreter: loadDLL :: Interp -> String -> IO (Maybe String)
- GHC.Runtime.Interpreter: loadObj :: HscEnv -> String -> IO ()
+ GHC.Runtime.Interpreter: loadObj :: Interp -> String -> IO ()
- GHC.Runtime.Interpreter: lookupClosure :: HscEnv -> String -> IO (Maybe HValueRef)
+ GHC.Runtime.Interpreter: lookupClosure :: Interp -> String -> IO (Maybe HValueRef)
- GHC.Runtime.Interpreter: lookupSymbol :: HscEnv -> FastString -> IO (Maybe (Ptr ()))
+ GHC.Runtime.Interpreter: lookupSymbol :: Interp -> FastString -> IO (Maybe (Ptr ()))
- GHC.Runtime.Interpreter: mallocData :: HscEnv -> ByteString -> IO (RemotePtr ())
+ GHC.Runtime.Interpreter: mallocData :: Interp -> ByteString -> IO (RemotePtr ())
- GHC.Runtime.Interpreter: mkCostCentres :: HscEnv -> String -> [(String, String)] -> IO [RemotePtr CostCentre]
+ GHC.Runtime.Interpreter: mkCostCentres :: Interp -> String -> [(String, String)] -> IO [RemotePtr CostCentre]
- GHC.Runtime.Interpreter: mkFinalizedHValue :: HscEnv -> RemoteRef a -> IO (ForeignRef a)
+ GHC.Runtime.Interpreter: mkFinalizedHValue :: Interp -> RemoteRef a -> IO (ForeignRef a)
- GHC.Runtime.Interpreter: newBreakArray :: HscEnv -> Int -> IO (ForeignRef BreakArray)
+ GHC.Runtime.Interpreter: newBreakArray :: Interp -> Int -> IO (ForeignRef BreakArray)
- GHC.Runtime.Interpreter: purgeLookupSymbolCache :: HscEnv -> IO ()
+ GHC.Runtime.Interpreter: purgeLookupSymbolCache :: Interp -> IO ()
- GHC.Runtime.Interpreter: removeLibrarySearchPath :: HscEnv -> Ptr () -> IO Bool
+ GHC.Runtime.Interpreter: removeLibrarySearchPath :: Interp -> Ptr () -> IO Bool
- GHC.Runtime.Interpreter: resolveObjs :: HscEnv -> IO SuccessFlag
+ GHC.Runtime.Interpreter: resolveObjs :: Interp -> IO SuccessFlag
- GHC.Runtime.Interpreter: resumeStmt :: HscEnv -> Bool -> ForeignRef (ResumeContext [HValueRef]) -> IO (EvalStatus_ [ForeignHValue] [HValueRef])
+ GHC.Runtime.Interpreter: resumeStmt :: Interp -> DynFlags -> Bool -> ForeignRef (ResumeContext [HValueRef]) -> IO (EvalStatus_ [ForeignHValue] [HValueRef])
- GHC.Runtime.Interpreter: seqHValue :: HscEnv -> ForeignHValue -> IO (EvalResult ())
+ GHC.Runtime.Interpreter: seqHValue :: Interp -> HscEnv -> ForeignHValue -> IO (EvalResult ())
- GHC.Runtime.Interpreter: stopInterp :: HscEnv -> IO ()
+ GHC.Runtime.Interpreter: stopInterp :: Interp -> IO ()
- GHC.Runtime.Interpreter: unloadObj :: HscEnv -> String -> IO ()
+ GHC.Runtime.Interpreter: unloadObj :: Interp -> String -> IO ()
- GHC.Runtime.Loader: getHValueSafely :: HscEnv -> Name -> Type -> IO (Maybe HValue)
+ GHC.Runtime.Loader: getHValueSafely :: Interp -> HscEnv -> Name -> Type -> IO (Maybe HValue)
- GHC.Stg.Lint: lintStgTopBindings :: forall a. (OutputablePass a, BinderP a ~ Id) => Logger -> DynFlags -> Module -> Bool -> String -> [GenStgTopBinding a] -> IO ()
+ GHC.Stg.Lint: lintStgTopBindings :: forall a. (OutputablePass a, BinderP a ~ Id) => Logger -> DynFlags -> InteractiveContext -> Module -> Bool -> String -> [GenStgTopBinding a] -> IO ()
- GHC.Stg.Pipeline: stg2stg :: Logger -> DynFlags -> Module -> [StgTopBinding] -> IO [StgTopBinding]
+ GHC.Stg.Pipeline: stg2stg :: Logger -> DynFlags -> InteractiveContext -> Module -> [StgTopBinding] -> IO [StgTopBinding]
- GHC.StgToCmm: codeGen :: Logger -> DynFlags -> Module -> [TyCon] -> CollectedCCs -> [CgStgTopBinding] -> HpcInfo -> Stream IO CmmGroup ModuleLFInfos
+ GHC.StgToCmm: codeGen :: Logger -> TmpFs -> DynFlags -> Module -> InfoTableProvMap -> [TyCon] -> CollectedCCs -> [CgStgTopBinding] -> HpcInfo -> Stream IO CmmGroup (CStub, ModuleLFInfos)
- GHC.StgToCmm.Closure: mkDataConInfoTable :: Profile -> DataCon -> Bool -> Int -> Int -> CmmInfoTable
+ GHC.StgToCmm.Closure: mkDataConInfoTable :: Profile -> DataCon -> ConInfoTableLocation -> Bool -> Int -> Int -> CmmInfoTable
- GHC.StgToCmm.DataCon: buildDynCon :: Id -> Bool -> CostCentreStack -> DataCon -> [NonVoid StgArg] -> FCode (CgIdInfo, FCode CmmAGraph)
+ GHC.StgToCmm.DataCon: buildDynCon :: Id -> ConstructorNumber -> Bool -> CostCentreStack -> DataCon -> [NonVoid StgArg] -> FCode (CgIdInfo, FCode CmmAGraph)
- GHC.StgToCmm.DataCon: cgTopRhsCon :: DynFlags -> Id -> DataCon -> [NonVoid StgArg] -> (CgIdInfo, FCode ())
+ GHC.StgToCmm.DataCon: cgTopRhsCon :: DynFlags -> Id -> DataCon -> ConstructorNumber -> [NonVoid StgArg] -> (CgIdInfo, FCode ())
- GHC.StgToCmm.Monad: getCmm :: FCode () -> FCode CmmGroup
+ GHC.StgToCmm.Monad: getCmm :: FCode a -> FCode (a, CmmGroup)
- GHC.SysTools.Process: runSomethingResponseFile :: Logger -> DynFlags -> (String -> String) -> String -> String -> [Option] -> Maybe [(String, String)] -> IO ()
+ GHC.SysTools.Process: runSomethingResponseFile :: Logger -> TmpFs -> DynFlags -> (String -> String) -> String -> String -> [Option] -> Maybe [(String, String)] -> IO ()
- GHC.SysTools.Tasks: runCc :: Maybe ForeignSrcLang -> Logger -> DynFlags -> [Option] -> IO ()
+ GHC.SysTools.Tasks: runCc :: Maybe ForeignSrcLang -> Logger -> TmpFs -> DynFlags -> [Option] -> IO ()
- GHC.SysTools.Tasks: runLink :: Logger -> DynFlags -> [Option] -> IO ()
+ GHC.SysTools.Tasks: runLink :: Logger -> TmpFs -> DynFlags -> [Option] -> IO ()
- GHC.SysTools.Tasks: runMergeObjects :: Logger -> DynFlags -> [Option] -> IO ()
+ GHC.SysTools.Tasks: runMergeObjects :: Logger -> TmpFs -> DynFlags -> [Option] -> IO ()
- GHC.Tc.Deriv.Generate: mkRdrFunBind :: Located RdrName -> [LMatch GhcPs (LHsExpr GhcPs)] -> LHsBind GhcPs
+ GHC.Tc.Deriv.Generate: mkRdrFunBind :: LocatedN RdrName -> [LMatch GhcPs (LHsExpr GhcPs)] -> LHsBind GhcPs
- GHC.Tc.Deriv.Generate: mkRdrFunBindEC :: Arity -> (LHsExpr GhcPs -> LHsExpr GhcPs) -> Located RdrName -> [LMatch GhcPs (LHsExpr GhcPs)] -> LHsBind GhcPs
+ GHC.Tc.Deriv.Generate: mkRdrFunBindEC :: Arity -> (LHsExpr GhcPs -> LHsExpr GhcPs) -> LocatedN RdrName -> [LMatch GhcPs (LHsExpr GhcPs)] -> LHsBind GhcPs
- GHC.Tc.Deriv.Generate: mkRdrFunBindSE :: Arity -> Located RdrName -> [LMatch GhcPs (LHsExpr GhcPs)] -> LHsBind GhcPs
+ GHC.Tc.Deriv.Generate: mkRdrFunBindSE :: Arity -> LocatedN RdrName -> [LMatch GhcPs (LHsExpr GhcPs)] -> LHsBind GhcPs
- GHC.Tc.Gen.Export: exports_from_avail :: Maybe (Located [LIE GhcPs]) -> GlobalRdrEnv -> ImportAvails -> Module -> RnM (Maybe [(LIE GhcRn, Avails)], Avails)
+ GHC.Tc.Gen.Export: exports_from_avail :: Maybe (LocatedL [LIE GhcPs]) -> GlobalRdrEnv -> ImportAvails -> Module -> RnM (Maybe [(LIE GhcRn, Avails)], Avails)
- GHC.Tc.Gen.Head: addFunResCtxt :: HsExpr GhcTc -> [HsExprArg 'TcpTc] -> TcType -> ExpRhoType -> TcM a -> TcM a
+ GHC.Tc.Gen.Head: addFunResCtxt :: HsExpr GhcRn -> [HsExprArg 'TcpRn] -> TcType -> ExpRhoType -> TcM a -> TcM a
- GHC.Tc.Gen.Head: insideExpansion :: [HsExprArg p] -> Bool
+ GHC.Tc.Gen.Head: insideExpansion :: AppCtxt -> Bool
- GHC.Tc.Gen.HsType: addSigCtxt :: Outputable hs_ty => UserTypeCtxt -> Located hs_ty -> TcM a -> TcM a
+ GHC.Tc.Gen.HsType: addSigCtxt :: Outputable hs_ty => UserTypeCtxt -> LocatedA hs_ty -> TcM a -> TcM a
- GHC.Tc.Gen.HsType: bindExplicitTKBndrs_Skol :: OutputableBndrFlag flag => [LHsTyVarBndr flag GhcRn] -> TcM a -> TcM ([VarBndr TyVar flag], a)
+ GHC.Tc.Gen.HsType: bindExplicitTKBndrs_Skol :: OutputableBndrFlag flag 'Renamed => [LHsTyVarBndr flag GhcRn] -> TcM a -> TcM ([VarBndr TyVar flag], a)
- GHC.Tc.Gen.HsType: bindExplicitTKBndrs_Tv :: OutputableBndrFlag flag => [LHsTyVarBndr flag GhcRn] -> TcM a -> TcM ([VarBndr TyVar flag], a)
+ GHC.Tc.Gen.HsType: bindExplicitTKBndrs_Tv :: OutputableBndrFlag flag 'Renamed => [LHsTyVarBndr flag GhcRn] -> TcM a -> TcM ([VarBndr TyVar flag], a)
- GHC.Tc.Gen.HsType: funsSigCtxt :: [Located Name] -> UserTypeCtxt
+ GHC.Tc.Gen.HsType: funsSigCtxt :: [LocatedN Name] -> UserTypeCtxt
- GHC.Tc.Gen.HsType: kcClassSigType :: [Located Name] -> LHsSigType GhcRn -> TcM ()
+ GHC.Tc.Gen.HsType: kcClassSigType :: [LocatedN Name] -> LHsSigType GhcRn -> TcM ()
- GHC.Tc.Gen.HsType: pprSigCtxt :: Outputable hs_ty => UserTypeCtxt -> Located hs_ty -> SDoc
+ GHC.Tc.Gen.HsType: pprSigCtxt :: Outputable hs_ty => UserTypeCtxt -> LocatedA hs_ty -> SDoc
- GHC.Tc.Gen.HsType: tcClassSigType :: [Located Name] -> LHsSigType GhcRn -> TcM Type
+ GHC.Tc.Gen.HsType: tcClassSigType :: [LocatedN Name] -> LHsSigType GhcRn -> TcM Type
- GHC.Tc.Gen.HsType: tcExplicitTKBndrs :: OutputableBndrFlag flag => [LHsTyVarBndr flag GhcRn] -> TcM a -> TcM ([VarBndr TyVar flag], a)
+ GHC.Tc.Gen.HsType: tcExplicitTKBndrs :: OutputableBndrFlag flag 'Renamed => [LHsTyVarBndr flag GhcRn] -> TcM a -> TcM ([VarBndr TyVar flag], a)
- GHC.Tc.Gen.HsType: tcHsContext :: LHsContext GhcRn -> TcM [PredType]
+ GHC.Tc.Gen.HsType: tcHsContext :: Maybe (LHsContext GhcRn) -> TcM [PredType]
- GHC.Tc.Gen.HsType: tcOuterTKBndrs :: OutputableBndrFlag flag => SkolemInfo -> HsOuterTyVarBndrs flag GhcRn -> TcM a -> TcM (HsOuterTyVarBndrs flag GhcTc, a)
+ GHC.Tc.Gen.HsType: tcOuterTKBndrs :: OutputableBndrFlag flag 'Renamed => SkolemInfo -> HsOuterTyVarBndrs flag GhcRn -> TcM a -> TcM (HsOuterTyVarBndrs flag GhcTc, a)
- GHC.Tc.Gen.Match: MC :: HsMatchContext GhcRn -> (Located (body GhcRn) -> ExpRhoType -> TcM (Located (body GhcTc))) -> TcMatchCtxt body
+ GHC.Tc.Gen.Match: MC :: HsMatchContext GhcRn -> (LocatedA (body GhcRn) -> ExpRhoType -> TcM (LocatedA (body GhcTc))) -> TcMatchCtxt body
- GHC.Tc.Gen.Match: [mc_body] :: TcMatchCtxt body -> Located (body GhcRn) -> ExpRhoType -> TcM (Located (body GhcTc))
+ GHC.Tc.Gen.Match: [mc_body] :: TcMatchCtxt body -> LocatedA (body GhcRn) -> ExpRhoType -> TcM (LocatedA (body GhcTc))
- GHC.Tc.Gen.Match: tcDoStmts :: HsStmtContext GhcRn -> Located [LStmt GhcRn (LHsExpr GhcRn)] -> ExpRhoType -> TcM (HsExpr GhcTc)
+ GHC.Tc.Gen.Match: tcDoStmts :: HsStmtContext GhcRn -> LocatedL [LStmt GhcRn (LHsExpr GhcRn)] -> ExpRhoType -> TcM (HsExpr GhcTc)
- GHC.Tc.Gen.Match: tcGRHS :: TcMatchCtxt body -> ExpRhoType -> GRHS GhcRn (Located (body GhcRn)) -> TcM (GRHS GhcTc (Located (body GhcTc)))
+ GHC.Tc.Gen.Match: tcGRHS :: TcMatchCtxt body -> ExpRhoType -> GRHS GhcRn (LocatedA (body GhcRn)) -> TcM (GRHS GhcTc (LocatedA (body GhcTc)))
- GHC.Tc.Gen.Match: tcMatchesCase :: Outputable (body GhcRn) => TcMatchCtxt body -> Scaled TcSigmaType -> MatchGroup GhcRn (Located (body GhcRn)) -> ExpRhoType -> TcM (MatchGroup GhcTc (Located (body GhcTc)))
+ GHC.Tc.Gen.Match: tcMatchesCase :: AnnoBody body => TcMatchCtxt body -> Scaled TcSigmaType -> MatchGroup GhcRn (LocatedA (body GhcRn)) -> ExpRhoType -> TcM (MatchGroup GhcTc (LocatedA (body GhcTc)))
- GHC.Tc.Gen.Match: tcMatchesFun :: Located Name -> MatchGroup GhcRn (LHsExpr GhcRn) -> ExpRhoType -> TcM (HsWrapper, MatchGroup GhcTc (LHsExpr GhcTc))
+ GHC.Tc.Gen.Match: tcMatchesFun :: LocatedN Name -> MatchGroup GhcRn (LHsExpr GhcRn) -> ExpRhoType -> TcM (HsWrapper, MatchGroup GhcTc (LHsExpr GhcTc))
- GHC.Tc.Gen.Match: tcStmts :: Outputable (body GhcRn) => HsStmtContext GhcRn -> TcStmtChecker body rho_type -> [LStmt GhcRn (Located (body GhcRn))] -> rho_type -> TcM [LStmt GhcTc (Located (body GhcTc))]
+ GHC.Tc.Gen.Match: tcStmts :: AnnoBody body => HsStmtContext GhcRn -> TcStmtChecker body rho_type -> [LStmt GhcRn (LocatedA (body GhcRn))] -> rho_type -> TcM [LStmt GhcTc (LocatedA (body GhcTc))]
- GHC.Tc.Gen.Match: tcStmtsAndThen :: Outputable (body GhcRn) => HsStmtContext GhcRn -> TcStmtChecker body rho_type -> [LStmt GhcRn (Located (body GhcRn))] -> rho_type -> (rho_type -> TcM thing) -> TcM ([LStmt GhcTc (Located (body GhcTc))], thing)
+ GHC.Tc.Gen.Match: tcStmtsAndThen :: AnnoBody body => HsStmtContext GhcRn -> TcStmtChecker body rho_type -> [LStmt GhcRn (LocatedA (body GhcRn))] -> rho_type -> (rho_type -> TcM thing) -> TcM ([LStmt GhcTc (LocatedA (body GhcTc))], thing)
- GHC.Tc.Gen.Match: type TcStmtChecker body rho_type = forall thing. HsStmtContext GhcRn -> Stmt GhcRn (Located (body GhcRn)) -> rho_type -> (rho_type -> TcM thing) -> TcM (Stmt GhcTc (Located (body GhcTc)), thing)
+ GHC.Tc.Gen.Match: type TcStmtChecker body rho_type = forall thing. HsStmtContext GhcRn -> Stmt GhcRn (LocatedA (body GhcRn)) -> rho_type -> (rho_type -> TcM thing) -> TcM (Stmt GhcTc (LocatedA (body GhcTc)), thing)
- GHC.Tc.Instance.FunDeps: improveFromInstEnv :: InstEnvs -> (PredType -> SrcSpan -> loc) -> PredType -> [FunDepEqn loc]
+ GHC.Tc.Instance.FunDeps: improveFromInstEnv :: InstEnvs -> (PredType -> SrcSpan -> loc) -> Class -> [Type] -> [FunDepEqn loc]
- GHC.Tc.Module: getModuleInterface :: HscEnv -> Module -> IO (Messages DecoratedSDoc, Maybe ModIface)
+ GHC.Tc.Module: getModuleInterface :: HscEnv -> Module -> IO (Messages DiagnosticMessage, Maybe ModIface)
- GHC.Tc.Module: isGHCiMonad :: HscEnv -> String -> IO (Messages DecoratedSDoc, Maybe Name)
+ GHC.Tc.Module: isGHCiMonad :: HscEnv -> String -> IO (Messages DiagnosticMessage, Maybe Name)
- GHC.Tc.Module: runTcInteractive :: HscEnv -> TcRn a -> IO (Messages DecoratedSDoc, Maybe a)
+ GHC.Tc.Module: runTcInteractive :: HscEnv -> TcRn a -> IO (Messages DiagnosticMessage, Maybe a)
- GHC.Tc.Module: tcRnDeclsi :: HscEnv -> [LHsDecl GhcPs] -> IO (Messages DecoratedSDoc, Maybe TcGblEnv)
+ GHC.Tc.Module: tcRnDeclsi :: HscEnv -> [LHsDecl GhcPs] -> IO (Messages DiagnosticMessage, Maybe TcGblEnv)
- GHC.Tc.Module: tcRnExpr :: HscEnv -> TcRnExprMode -> LHsExpr GhcPs -> IO (Messages DecoratedSDoc, Maybe Type)
+ GHC.Tc.Module: tcRnExpr :: HscEnv -> TcRnExprMode -> LHsExpr GhcPs -> IO (Messages DiagnosticMessage, Maybe Type)
- GHC.Tc.Module: tcRnGetInfo :: HscEnv -> Name -> IO (Messages DecoratedSDoc, Maybe (TyThing, Fixity, [ClsInst], [FamInst], SDoc))
+ GHC.Tc.Module: tcRnGetInfo :: HscEnv -> Name -> IO (Messages DiagnosticMessage, Maybe (TyThing, Fixity, [ClsInst], [FamInst], SDoc))
- GHC.Tc.Module: tcRnImportDecls :: HscEnv -> [LImportDecl GhcPs] -> IO (Messages DecoratedSDoc, Maybe GlobalRdrEnv)
+ GHC.Tc.Module: tcRnImportDecls :: HscEnv -> [LImportDecl GhcPs] -> IO (Messages DiagnosticMessage, Maybe GlobalRdrEnv)
- GHC.Tc.Module: tcRnInstantiateSignature :: HscEnv -> Module -> RealSrcSpan -> IO (Messages DecoratedSDoc, Maybe TcGblEnv)
+ GHC.Tc.Module: tcRnInstantiateSignature :: HscEnv -> Module -> RealSrcSpan -> IO (Messages DiagnosticMessage, Maybe TcGblEnv)
- GHC.Tc.Module: tcRnLookupName :: HscEnv -> Name -> IO (Messages DecoratedSDoc, Maybe TyThing)
+ GHC.Tc.Module: tcRnLookupName :: HscEnv -> Name -> IO (Messages DiagnosticMessage, Maybe TyThing)
- GHC.Tc.Module: tcRnLookupRdrName :: HscEnv -> Located RdrName -> IO (Messages DecoratedSDoc, Maybe [Name])
+ GHC.Tc.Module: tcRnLookupRdrName :: HscEnv -> LocatedN RdrName -> IO (Messages DiagnosticMessage, Maybe [Name])
- GHC.Tc.Module: tcRnMergeSignatures :: HscEnv -> HsParsedModule -> TcGblEnv -> ModIface -> IO (Messages DecoratedSDoc, Maybe TcGblEnv)
+ GHC.Tc.Module: tcRnMergeSignatures :: HscEnv -> HsParsedModule -> TcGblEnv -> ModIface -> IO (Messages DiagnosticMessage, Maybe TcGblEnv)
- GHC.Tc.Module: tcRnModule :: HscEnv -> ModSummary -> Bool -> HsParsedModule -> IO (Messages DecoratedSDoc, Maybe TcGblEnv)
+ GHC.Tc.Module: tcRnModule :: HscEnv -> ModSummary -> Bool -> HsParsedModule -> IO (Messages DiagnosticMessage, Maybe TcGblEnv)
- GHC.Tc.Module: tcRnStmt :: HscEnv -> GhciLStmt GhcPs -> IO (Messages DecoratedSDoc, Maybe ([Id], LHsExpr GhcTc, FixityEnv))
+ GHC.Tc.Module: tcRnStmt :: HscEnv -> GhciLStmt GhcPs -> IO (Messages DiagnosticMessage, Maybe ([Id], LHsExpr GhcTc, FixityEnv))
- GHC.Tc.Module: tcRnType :: HscEnv -> ZonkFlexi -> Bool -> LHsType GhcPs -> IO (Messages DecoratedSDoc, Maybe (Type, Kind))
+ GHC.Tc.Module: tcRnType :: HscEnv -> ZonkFlexi -> Bool -> LHsType GhcPs -> IO (Messages DiagnosticMessage, Maybe (Type, Kind))
- GHC.Tc.TyCl: dataDeclChecks :: Name -> NewOrData -> LHsContext GhcRn -> [LConDecl GhcRn] -> TcM Bool
+ GHC.Tc.TyCl: dataDeclChecks :: Name -> NewOrData -> Maybe (LHsContext GhcRn) -> [LConDecl GhcRn] -> TcM Bool
- GHC.Tc.Utils.Backpack: tcRnCheckUnit :: HscEnv -> Unit -> IO (Messages DecoratedSDoc, Maybe ())
+ GHC.Tc.Utils.Backpack: tcRnCheckUnit :: HscEnv -> Unit -> IO (Messages DiagnosticMessage, Maybe ())
- GHC.Tc.Utils.Backpack: tcRnInstantiateSignature :: HscEnv -> Module -> RealSrcSpan -> IO (Messages DecoratedSDoc, Maybe TcGblEnv)
+ GHC.Tc.Utils.Backpack: tcRnInstantiateSignature :: HscEnv -> Module -> RealSrcSpan -> IO (Messages DiagnosticMessage, Maybe TcGblEnv)
- GHC.Tc.Utils.Backpack: tcRnMergeSignatures :: HscEnv -> HsParsedModule -> TcGblEnv -> ModIface -> IO (Messages DecoratedSDoc, Maybe TcGblEnv)
+ GHC.Tc.Utils.Backpack: tcRnMergeSignatures :: HscEnv -> HsParsedModule -> TcGblEnv -> ModIface -> IO (Messages DiagnosticMessage, Maybe TcGblEnv)
- GHC.Tc.Utils.Env: newFamInstAxiomName :: Located Name -> [[Type]] -> TcM Name
+ GHC.Tc.Utils.Env: newFamInstAxiomName :: LocatedN Name -> [[Type]] -> TcM Name
- GHC.Tc.Utils.Env: newFamInstTyConName :: Located Name -> [Type] -> TcM Name
+ GHC.Tc.Utils.Env: newFamInstTyConName :: LocatedN Name -> [Type] -> TcM Name
- GHC.Tc.Utils.Env: tcLookupLocated :: Located Name -> TcM TcTyThing
+ GHC.Tc.Utils.Env: tcLookupLocated :: LocatedA Name -> TcM TcTyThing
- GHC.Tc.Utils.Env: tcLookupLocatedClass :: Located Name -> TcM Class
+ GHC.Tc.Utils.Env: tcLookupLocatedClass :: LocatedA Name -> TcM Class
- GHC.Tc.Utils.Env: tcLookupLocatedGlobal :: Located Name -> TcM TyThing
+ GHC.Tc.Utils.Env: tcLookupLocatedGlobal :: LocatedA Name -> TcM TyThing
- GHC.Tc.Utils.Env: tcLookupLocatedGlobalId :: Located Name -> TcM Id
+ GHC.Tc.Utils.Env: tcLookupLocatedGlobalId :: LocatedA Name -> TcM Id
- GHC.Tc.Utils.Env: tcLookupLocatedTyCon :: Located Name -> TcM TyCon
+ GHC.Tc.Utils.Env: tcLookupLocatedTyCon :: LocatedN Name -> TcM TyCon
- GHC.Tc.Utils.Monad: addMessages :: Messages DecoratedSDoc -> TcRn ()
+ GHC.Tc.Utils.Monad: addMessages :: Messages DiagnosticMessage -> TcRn ()
- GHC.Tc.Utils.Monad: getErrsVar :: TcRn (TcRef (Messages DecoratedSDoc))
+ GHC.Tc.Utils.Monad: getErrsVar :: TcRn (TcRef (Messages DiagnosticMessage))
- GHC.Tc.Utils.Monad: initTc :: HscEnv -> HscSource -> Bool -> Module -> RealSrcSpan -> TcM r -> IO (Messages DecoratedSDoc, Maybe r)
+ GHC.Tc.Utils.Monad: initTc :: HscEnv -> HscSource -> Bool -> Module -> RealSrcSpan -> TcM r -> IO (Messages DiagnosticMessage, Maybe r)
- GHC.Tc.Utils.Monad: initTcInteractive :: HscEnv -> TcM a -> IO (Messages DecoratedSDoc, Maybe a)
+ GHC.Tc.Utils.Monad: initTcInteractive :: HscEnv -> TcM a -> IO (Messages DiagnosticMessage, Maybe a)
- GHC.Tc.Utils.Monad: initTcWithGbl :: HscEnv -> TcGblEnv -> RealSrcSpan -> TcM r -> IO (Messages DecoratedSDoc, Maybe r)
+ GHC.Tc.Utils.Monad: initTcWithGbl :: HscEnv -> TcGblEnv -> RealSrcSpan -> TcM r -> IO (Messages DiagnosticMessage, Maybe r)
- GHC.Tc.Utils.Monad: mkDecoratedSDocAt :: SrcSpan -> SDoc -> SDoc -> SDoc -> TcRn (MsgEnvelope DecoratedSDoc)
+ GHC.Tc.Utils.Monad: mkDecoratedSDocAt :: DiagnosticReason -> SrcSpan -> SDoc -> SDoc -> SDoc -> TcRn (MsgEnvelope DiagnosticMessage)
- GHC.Tc.Utils.Monad: mkLongErrAt :: SrcSpan -> SDoc -> SDoc -> TcRn (MsgEnvelope DecoratedSDoc)
+ GHC.Tc.Utils.Monad: mkLongErrAt :: SrcSpan -> SDoc -> SDoc -> TcRn (MsgEnvelope DiagnosticMessage)
- GHC.Tc.Utils.Monad: setErrsVar :: TcRef (Messages DecoratedSDoc) -> TcRn a -> TcRn a
+ GHC.Tc.Utils.Monad: setErrsVar :: TcRef (Messages DiagnosticMessage) -> TcRn a -> TcRn a
- GHC.Tc.Utils.Monad: tryTc :: TcRn a -> TcRn (Maybe a, Messages DecoratedSDoc)
+ GHC.Tc.Utils.Monad: tryTc :: TcRn a -> TcRn (Maybe a, Messages DiagnosticMessage)
- GHC.Tc.Utils.Monad: withException :: TcRnIf gbl lcl (MaybeErr SDoc a) -> TcRnIf gbl lcl a
+ GHC.Tc.Utils.Monad: withException :: MonadIO m => DynFlags -> m (MaybeErr SDoc a) -> m a
- GHC.Tc.Utils.Zonk: mkHsCaseAlt :: forall (p :: Pass) body. LPat (GhcPass p) -> Located (body (GhcPass p)) -> LMatch (GhcPass p) (Located (body (GhcPass p)))
+ GHC.Tc.Utils.Zonk: mkHsCaseAlt :: forall (p :: Pass) body. (Anno (GRHS (GhcPass p) (LocatedA (body (GhcPass p)))) ~ SrcSpan, Anno (Match (GhcPass p) (LocatedA (body (GhcPass p)))) ~ SrcSpanAnnA) => LPat (GhcPass p) -> LocatedA (body (GhcPass p)) -> LMatch (GhcPass p) (LocatedA (body (GhcPass p)))
- GHC.Unit.Finder: addHomeModuleToFinder :: HscEnv -> ModuleName -> ModLocation -> IO Module
+ GHC.Unit.Finder: addHomeModuleToFinder :: FinderCache -> HomeUnit -> ModuleName -> ModLocation -> IO Module
- GHC.Unit.Finder: findExactModule :: HscEnv -> InstalledModule -> IO InstalledFindResult
+ GHC.Unit.Finder: findExactModule :: FinderCache -> DynFlags -> UnitState -> HomeUnit -> InstalledModule -> IO InstalledFindResult
- GHC.Unit.Finder: findExposedPackageModule :: HscEnv -> ModuleName -> Maybe FastString -> IO FindResult
+ GHC.Unit.Finder: findExposedPackageModule :: FinderCache -> UnitState -> DynFlags -> ModuleName -> Maybe FastString -> IO FindResult
- GHC.Unit.Finder: findHomeModule :: HscEnv -> ModuleName -> IO FindResult
+ GHC.Unit.Finder: findHomeModule :: FinderCache -> HomeUnit -> DynFlags -> ModuleName -> IO FindResult
- GHC.Unit.Finder: findImportedModule :: HscEnv -> ModuleName -> Maybe FastString -> IO FindResult
+ GHC.Unit.Finder: findImportedModule :: FinderCache -> UnitState -> HomeUnit -> DynFlags -> ModuleName -> Maybe FastString -> IO FindResult
- GHC.Unit.Finder: findPluginModule :: HscEnv -> ModuleName -> IO FindResult
+ GHC.Unit.Finder: findPluginModule :: FinderCache -> UnitState -> HomeUnit -> DynFlags -> ModuleName -> IO FindResult
- GHC.Unit.Finder: flushFinderCaches :: HscEnv -> IO ()
+ GHC.Unit.Finder: flushFinderCaches :: FinderCache -> HomeUnit -> IO ()
- GHC.Unit.Finder: uncacheModule :: HscEnv -> ModuleName -> IO ()
+ GHC.Unit.Finder: uncacheModule :: FinderCache -> HomeUnit -> ModuleName -> IO ()
Files
- compiler/GHC.hs +58/−41
- compiler/GHC/Builtin/Types/Literals.hs +96/−78
- compiler/GHC/ByteCode/Asm.hs +124/−18
- compiler/GHC/ByteCode/InfoTable.hs +12/−13
- compiler/GHC/ByteCode/Instr.hs +60/−32
- compiler/GHC/ByteCode/Linker.hs +71/−52
- compiler/GHC/Cmm/DebugBlock.hs +2/−2
- compiler/GHC/Cmm/LayoutStack.hs +2/−1
- compiler/GHC/Cmm/Parser.y +13/−6
- compiler/GHC/CmmToAsm.hs +9/−5
- compiler/GHC/CmmToAsm/Dwarf.hs +2/−2
- compiler/GHC/CmmToAsm/PPC/CodeGen.hs +27/−7
- compiler/GHC/CmmToAsm/Ppr.hs +6/−8
- compiler/GHC/CmmToAsm/Reg/Graph/TrivColorable.hs +3/−0
- compiler/GHC/CmmToAsm/Reg/Linear.hs +47/−53
- compiler/GHC/CmmToAsm/Reg/Linear/FreeRegs.hs +1/−0
- compiler/GHC/CmmToAsm/Reg/Linear/State.hs +22/−16
- compiler/GHC/CmmToAsm/Reg/Target.hs +5/−0
- compiler/GHC/CmmToAsm/X86/CodeGen.hs +1/−8
- compiler/GHC/CmmToC.hs +16/−5
- compiler/GHC/CmmToLlvm.hs +9/−2
- compiler/GHC/CmmToLlvm/Base.hs +8/−4
- compiler/GHC/Core/Map/Expr.hs +4/−3
- compiler/GHC/Core/Opt/CSE.hs +70/−16
- compiler/GHC/Core/Opt/CallArity.hs +1/−1
- compiler/GHC/Core/Opt/CprAnal.hs +145/−82
- compiler/GHC/Core/Opt/DmdAnal.hs +43/−64
- compiler/GHC/Core/Opt/FloatIn.hs +1/−0
- compiler/GHC/Core/Opt/FloatOut.hs +2/−1
- compiler/GHC/Core/Opt/Pipeline.hs +6/−5
- compiler/GHC/Core/Opt/SetLevels.hs +7/−6
- compiler/GHC/Core/Opt/Simplify.hs +92/−32
- compiler/GHC/Core/Opt/Simplify/Env.hs +46/−26
- compiler/GHC/Core/Opt/Simplify/Monad.hs +0/−1
- compiler/GHC/Core/Opt/Simplify/Utils.hs +11/−10
- compiler/GHC/Core/Opt/SpecConstr.hs +8/−8
- compiler/GHC/Core/Opt/Specialise.hs +8/−6
- compiler/GHC/Core/Opt/WorkWrap.hs +7/−7
- compiler/GHC/Core/Opt/WorkWrap/Utils.hs +430/−418
- compiler/GHC/Core/Rules.hs +1/−0
- compiler/GHC/Core/Tidy.hs +5/−3
- compiler/GHC/CoreToByteCode.hs +0/−2116
- compiler/GHC/CoreToStg.hs +77/−47
- compiler/GHC/CoreToStg/Prep.hs +26/−12
- compiler/GHC/Data/Graph/UnVar.hs +1/−1
- compiler/GHC/Driver/Backpack.hs +12/−7
- compiler/GHC/Driver/CodeOutput.hs +78/−32
- compiler/GHC/Driver/Main.hs +182/−111
- compiler/GHC/Driver/Make.hs +107/−121
- compiler/GHC/Driver/MakeFile.hs +26/−22
- compiler/GHC/Driver/Pipeline.hs +84/−49
- compiler/GHC/Hs/Stats.hs +1/−1
- compiler/GHC/HsToCore.hs +23/−22
- compiler/GHC/HsToCore/Arrows.hs +32/−29
- compiler/GHC/HsToCore/Binds.hs +9/−9
- compiler/GHC/HsToCore/Coverage.hs +74/−58
- compiler/GHC/HsToCore/Docs.hs +123/−43
- compiler/GHC/HsToCore/Expr.hs +141/−127
- compiler/GHC/HsToCore/Expr.hs-boot +2/−2
- compiler/GHC/HsToCore/Foreign/Decl.hs +20/−20
- compiler/GHC/HsToCore/ListComp.hs +3/−3
- compiler/GHC/HsToCore/Match.hs +9/−10
- compiler/GHC/HsToCore/Match.hs-boot +1/−1
- compiler/GHC/HsToCore/Match/Literal.hs +19/−18
- compiler/GHC/HsToCore/Monad.hs +24/−18
- compiler/GHC/HsToCore/Pmc.hs +13/−15
- compiler/GHC/HsToCore/Pmc/Check.hs +81/−0
- compiler/GHC/HsToCore/Pmc/Desugar.hs +6/−6
- compiler/GHC/HsToCore/Pmc/Solver.hs +227/−125
- compiler/GHC/HsToCore/Pmc/Solver/Types.hs +5/−5
- compiler/GHC/HsToCore/Quote.hs +92/−86
- compiler/GHC/HsToCore/Types.hs +2/−2
- compiler/GHC/HsToCore/Usage.hs +9/−2
- compiler/GHC/HsToCore/Utils.hs +62/−8
- compiler/GHC/Iface/Binary.hs +40/−67
- compiler/GHC/Iface/Env.hs +55/−96
- compiler/GHC/Iface/Ext/Ast.hs +297/−216
- compiler/GHC/Iface/Ext/Binary.hs +45/−44
- compiler/GHC/Iface/Ext/Utils.hs +27/−0
- compiler/GHC/Iface/Load.hs +198/−167
- compiler/GHC/Iface/Make.hs +4/−3
- compiler/GHC/Iface/Recomp.hs +154/−116
- compiler/GHC/Iface/Rename.hs +1/−1
- compiler/GHC/Iface/Tidy.hs +27/−34
- compiler/GHC/Iface/Tidy/StaticPtrTable.hs +4/−3
- compiler/GHC/IfaceToCore.hs +21/−8
- compiler/GHC/IfaceToCore.hs-boot +1/−1
- compiler/GHC/Linker/Dynamic.hs +6/−5
- compiler/GHC/Linker/ExtraObj.hs +12/−12
- compiler/GHC/Linker/Loader.hs +243/−230
- compiler/GHC/Linker/MacOS.hs +4/−5
- compiler/GHC/Linker/Static.hs +10/−10
- compiler/GHC/Linker/Windows.hs +5/−4
- compiler/GHC/Rename/Bind.hs +106/−88
- compiler/GHC/Rename/Env.hs +50/−29
- compiler/GHC/Rename/Expr.hs +313/−173
- compiler/GHC/Rename/Expr.hs-boot +15/−5
- compiler/GHC/Rename/Fixity.hs +1/−1
- compiler/GHC/Rename/HsType.hs +100/−76
- compiler/GHC/Rename/Module.hs +101/−95
- compiler/GHC/Rename/Names.hs +88/−60
- compiler/GHC/Rename/Pat.hs +55/−49
- compiler/GHC/Rename/Splice.hs +26/−18
- compiler/GHC/Rename/Utils.hs +35/−33
- compiler/GHC/Runtime/Debugger.hs +6/−6
- compiler/GHC/Runtime/Eval.hs +71/−43
- compiler/GHC/Runtime/Heap/Inspect.hs +9/−5
- compiler/GHC/Runtime/Interpreter.hs +156/−153
- compiler/GHC/Runtime/Loader.hs +19/−14
- compiler/GHC/Stg/CSE.hs +6/−6
- compiler/GHC/Stg/Debug.hs +240/−0
- compiler/GHC/Stg/DepAnal.hs +2/−2
- compiler/GHC/Stg/FVs.hs +7/−5
- compiler/GHC/Stg/Lift.hs +3/−3
- compiler/GHC/Stg/Lift/Analysis.hs +5/−5
- compiler/GHC/Stg/Lift/Monad.hs +2/−2
- compiler/GHC/Stg/Lint.hs +18/−11
- compiler/GHC/Stg/Pipeline.hs +4/−3
- compiler/GHC/Stg/Stats.hs +2/−2
- compiler/GHC/Stg/Unarise.hs +36/−8
- compiler/GHC/StgToByteCode.hs +2281/−0
- compiler/GHC/StgToCmm.hs +84/−56
- compiler/GHC/StgToCmm/ArgRep.hs +1/−1
- compiler/GHC/StgToCmm/Bind.hs +4/−3
- compiler/GHC/StgToCmm/Closure.hs +3/−3
- compiler/GHC/StgToCmm/DataCon.hs +23/−10
- compiler/GHC/StgToCmm/Env.hs +7/−24
- compiler/GHC/StgToCmm/Expr.hs +12/−10
- compiler/GHC/StgToCmm/Expr.hs-boot +7/−0
- compiler/GHC/StgToCmm/Foreign.hs +0/−1
- compiler/GHC/StgToCmm/Heap.hs +0/−1
- compiler/GHC/StgToCmm/Layout.hs +21/−1
- compiler/GHC/StgToCmm/Lit.hs +105/−0
- compiler/GHC/StgToCmm/Monad.hs +14/−10
- compiler/GHC/StgToCmm/Prim.hs +53/−55
- compiler/GHC/StgToCmm/Prof.hs +54/−2
- compiler/GHC/StgToCmm/Ticky.hs +1/−0
- compiler/GHC/StgToCmm/Utils.hs +51/−63
- compiler/GHC/SysTools/Process.hs +19/−14
- compiler/GHC/SysTools/Tasks.hs +27/−19
- compiler/GHC/Tc/Deriv.hs +12/−12
- compiler/GHC/Tc/Deriv/Functor.hs +12/−14
- compiler/GHC/Tc/Deriv/Generate.hs +87/−78
- compiler/GHC/Tc/Deriv/Generics.hs +16/−7
- compiler/GHC/Tc/Deriv/Utils.hs +3/−3
- compiler/GHC/Tc/Errors.hs +266/−208
- compiler/GHC/Tc/Errors/Hole.hs +2/−2
- compiler/GHC/Tc/Gen/Annotation.hs +3/−3
- compiler/GHC/Tc/Gen/App.hs +99/−69
- compiler/GHC/Tc/Gen/Arrow.hs +16/−11
- compiler/GHC/Tc/Gen/Bind.hs +35/−30
- compiler/GHC/Tc/Gen/Default.hs +5/−5
- compiler/GHC/Tc/Gen/Export.hs +49/−47
- compiler/GHC/Tc/Gen/Expr.hs +74/−45
- compiler/GHC/Tc/Gen/Foreign.hs +6/−6
- compiler/GHC/Tc/Gen/Head.hs +43/−35
- compiler/GHC/Tc/Gen/HsType.hs +203/−85
- compiler/GHC/Tc/Gen/Match.hs +61/−45
- compiler/GHC/Tc/Gen/Match.hs-boot +2/−2
- compiler/GHC/Tc/Gen/Pat.hs +12/−12
- compiler/GHC/Tc/Gen/Rule.hs +3/−3
- compiler/GHC/Tc/Gen/Sig.hs +19/−19
- compiler/GHC/Tc/Gen/Splice.hs +192/−29
- compiler/GHC/Tc/Instance/FunDeps.hs +8/−8
- compiler/GHC/Tc/Instance/Typeable.hs +20/−9
- compiler/GHC/Tc/Module.hs +360/−342
- compiler/GHC/Tc/Plugin.hs +5/−1
- compiler/GHC/Tc/Solver.hs +23/−9
- compiler/GHC/Tc/Solver/Canonical.hs +15/−8
- compiler/GHC/Tc/Solver/Interact.hs +182/−46
- compiler/GHC/Tc/Solver/Monad.hs +8/−3
- compiler/GHC/Tc/TyCl.hs +133/−62
- compiler/GHC/Tc/TyCl/Class.hs +28/−23
- compiler/GHC/Tc/TyCl/Instance.hs +45/−36
- compiler/GHC/Tc/TyCl/PatSyn.hs +38/−35
- compiler/GHC/Tc/TyCl/Utils.hs +20/−16
- compiler/GHC/Tc/Types/EvTerm.hs +6/−1
- compiler/GHC/Tc/Utils/Backpack.hs +47/−20
- compiler/GHC/Tc/Utils/Env.hs +15/−15
- compiler/GHC/Tc/Utils/Instantiate.hs +2/−2
- compiler/GHC/Tc/Utils/Monad.hs +113/−98
- compiler/GHC/Tc/Utils/TcMType.hs +23/−8
- compiler/GHC/Tc/Utils/Unify.hs +13/−6
- compiler/GHC/Tc/Utils/Zonk.hs +74/−57
- compiler/GHC/Tc/Validity.hs +7/−7
- compiler/GHC/ThToHs.hs +353/−321
- compiler/GHC/Types/Unique/SDFM.hs +2/−2
- compiler/GHC/Unit/Finder.hs +109/−113
- ghc-lib.cabal +11/−5
- ghc-lib/stage0/compiler/build/primop-data-decl.hs-incl +2/−0
- ghc-lib/stage0/compiler/build/primop-docs.hs-incl +2/−0
- ghc-lib/stage0/compiler/build/primop-list.hs-incl +2/−0
- ghc-lib/stage0/compiler/build/primop-out-of-line.hs-incl +1/−0
- ghc-lib/stage0/compiler/build/primop-primop-info.hs-incl +110/−108
- ghc-lib/stage0/compiler/build/primop-strictness.hs-incl +13/−13
- ghc-lib/stage0/compiler/build/primop-tag.hs-incl +1285/−1283
- ghc-lib/stage0/lib/DerivedConstants.h +13/−13
- ghc-lib/stage0/lib/ghcautoconf.h +5/−2
- ghc-lib/stage0/lib/llvm-targets +3/−1
- includes/CodeGen.Platform.hs +69/−1
- includes/stg/MachRegs.h +80/−2
- libraries/ghci/GHCi/CreateBCO.hs +6/−0
- libraries/ghci/GHCi/InfoTable.hsc +32/−0
- libraries/ghci/GHCi/Run.hs +4/−4
- libraries/ghci/GHCi/TH.hs +2/−0
compiler/GHC.hs view
@@ -159,9 +159,10 @@ GHC.obtainTermFromId, GHC.obtainTermFromVal, reconstructType, modInfoModBreaks, ModBreaks(..), BreakIndex,- BreakInfo(breakInfo_number, breakInfo_module),+ BreakInfo(..), GHC.Runtime.Eval.back, GHC.Runtime.Eval.forward,+ GHC.Runtime.Eval.setupBreakpoint, -- * Abstract syntax elements @@ -282,10 +283,7 @@ parser, -- * API Annotations- ApiAnns(..),AnnKeywordId(..),AnnotationComment(..), ApiAnnKey,- getAnnotation, getAndRemoveAnnotation,- getAnnotationComments, getAndRemoveAnnotationComments,- unicodeAnn,+ AnnKeywordId(..),EpaComment(..), -- * Miscellaneous --sessionHscEnv,@@ -310,7 +308,8 @@ import GHC.Driver.Env import GHC.Driver.Errors import GHC.Driver.CmdLine-import GHC.Driver.Session hiding (WarnReason(..))+import GHC.Driver.Session+import qualified GHC.Driver.Session as Session import GHC.Driver.Backend import GHC.Driver.Config import GHC.Driver.Main@@ -321,11 +320,11 @@ import GHC.Driver.Ppr import GHC.ByteCode.Types+import qualified GHC.Linker.Loader as Loader import GHC.Runtime.Loader import GHC.Runtime.Eval import GHC.Runtime.Eval.Types import GHC.Runtime.Interpreter-import GHC.Runtime.Interpreter.Types import GHC.Runtime.Context import GHCi.RemoteTypes @@ -351,7 +350,7 @@ import GHC.Tc.Utils.Instantiate import GHC.Tc.Instance.Family -import GHC.SysTools.FileCleanup+import GHC.Utils.TmpFs import GHC.SysTools import GHC.SysTools.BaseDir @@ -391,6 +390,7 @@ import GHC.Types.Name.Ppr import GHC.Types.TypeEnv import GHC.Types.SourceFile+import GHC.Types.Error ( DiagnosticMessage ) import GHC.Unit import GHC.Unit.Env@@ -533,10 +533,11 @@ hsc_env <- getSession let dflags = hsc_dflags hsc_env let logger = hsc_logger hsc_env+ let tmpfs = hsc_tmpfs hsc_env liftIO $ do- cleanTempFiles logger dflags- cleanTempDirs logger dflags- stopInterp hsc_env -- shut down the IServ+ cleanTempFiles logger tmpfs dflags+ cleanTempDirs logger tmpfs dflags+ traverse_ stopInterp (hsc_interp hsc_env) -- exceptions will be blocked while we clean the temporary files, -- so there shouldn't be any difficulty if we receive further -- signals.@@ -643,7 +644,7 @@ (dbs,unit_state,home_unit) <- liftIO $ initUnits logger dflags (hsc_unit_dbs hsc_env) -- Interpreter- interp <- if gopt Opt_ExternalInterpreter dflags+ interp <- if gopt Opt_ExternalInterpreter dflags then do let prog = pgm_i dflags ++ flavour@@ -667,10 +668,13 @@ , iservConfTrace = tr } s <- liftIO $ newMVar IServPending- return (Just (ExternalInterp conf (IServ s)))+ loader <- liftIO Loader.uninitializedLoader+ return (Just (Interp (ExternalInterp conf (IServ s)) loader)) else #if defined(HAVE_INTERNAL_INTERPRETER)- return (Just InternalInterp)+ do+ loader <- liftIO Loader.uninitializedLoader+ return (Just (Interp InternalInterp loader)) #else return Nothing #endif@@ -897,7 +901,7 @@ -- the REPL. See #12356. if xopt LangExt.StaticPointers dflags0 then do liftIO $ printOrThrowWarnings logger dflags0 $ listToBag- [mkPlainWarnMsg interactiveSrcSpan+ [mkPlainMsgEnvelope Session.WarningWithoutFlag interactiveSrcSpan $ text "StaticPointers is not supported in GHCi interactive expressions."] return $ xopt_unset dflags0 LangExt.StaticPointers else return dflags0@@ -933,7 +937,7 @@ removeTarget target_id = modifySession (\h -> h{ hsc_targets = filter (hsc_targets h) }) where- filter targets = [ t | t@(Target id _ _) <- targets, id /= target_id ]+ filter targets = [ t | t@Target { targetId = id } <- targets, id /= target_id ] -- | Attempts to guess what Target a string refers to. This function -- implements the @--make@/GHCi command-line syntax for filenames:@@ -946,23 +950,25 @@ -- -- - otherwise interpret the string as a module name ---guessTarget :: GhcMonad m => String -> Maybe Phase -> m Target-guessTarget str (Just phase)- = return (Target (TargetFile str (Just phase)) True Nothing)-guessTarget str Nothing+guessTarget :: GhcMonad m => String -> Maybe UnitId -> Maybe Phase -> m Target+guessTarget str mUnitId (Just phase)+ = do+ tuid <- unitIdOrHomeUnit mUnitId+ return (Target (TargetFile str (Just phase)) True tuid Nothing)+guessTarget str mUnitId Nothing | isHaskellSrcFilename file- = return (target (TargetFile file Nothing))+ = target (TargetFile file Nothing) | otherwise = do exists <- liftIO $ doesFileExist hs_file if exists- then return (target (TargetFile hs_file Nothing))+ then target (TargetFile hs_file Nothing) else do exists <- liftIO $ doesFileExist lhs_file if exists- then return (target (TargetFile lhs_file Nothing))+ then target (TargetFile lhs_file Nothing) else do if looksLikeModuleName file- then return (target (TargetModule (mkModuleName file)))+ then target (TargetModule (mkModuleName file)) else do dflags <- getDynFlags liftIO $ throwGhcExceptionIO@@ -977,8 +983,16 @@ hs_file = file <.> "hs" lhs_file = file <.> "lhs" - target tid = Target tid obj_allowed Nothing+ target tid = do+ tuid <- unitIdOrHomeUnit mUnitId+ pure $ Target tid obj_allowed tuid Nothing +-- | Unwrap 'UnitId' or retrieve the 'UnitId'+-- of the current 'HomeUnit'.+unitIdOrHomeUnit :: GhcMonad m => Maybe UnitId -> m UnitId+unitIdOrHomeUnit mUnitId = do+ currentHomeUnitId <- homeUnitId . ue_home_unit . hsc_unit_env <$> getSession+ pure (fromMaybe currentHomeUnitId mUnitId) -- | Inform GHC that the working directory has changed. GHC will flush -- its cache of module locations, since it may no longer be valid.@@ -988,7 +1002,9 @@ -- you should also unload the current program (set targets to empty, -- followed by load). workingDirectoryChanged :: GhcMonad m => m ()-workingDirectoryChanged = withSession $ (liftIO . flushFinderCaches)+workingDirectoryChanged = do+ hsc_env <- getSession+ liftIO $ flushFinderCaches (hsc_FC hsc_env) (hsc_home_unit hsc_env) -- %************************************************************************@@ -1019,9 +1035,7 @@ data ParsedModule = ParsedModule { pm_mod_summary :: ModSummary , pm_parsed_source :: ParsedSource- , pm_extra_src_files :: [FilePath]- , pm_annotations :: ApiAnns }- -- See Note [Api annotations] in GHC.Parser.Annotation+ , pm_extra_src_files :: [FilePath] } instance ParsedMod ParsedModule where modSummary m = pm_mod_summary m@@ -1113,9 +1127,8 @@ hsc_env <- getSession let hsc_env_tmp = hsc_env { hsc_dflags = ms_hspp_opts ms } hpm <- liftIO $ hscParse hsc_env_tmp ms- return (ParsedModule ms (hpm_module hpm) (hpm_src_files hpm)- (hpm_annotations hpm))- -- See Note [Api annotations] in GHC.Parser.Annotation+ return (ParsedModule ms (hpm_module hpm) (hpm_src_files hpm))+ -- See Note [exact print annotations] in GHC.Parser.Annotation -- | Typecheck and rename a parsed module. --@@ -1128,8 +1141,7 @@ (tc_gbl_env, rn_info) <- liftIO $ hscTypecheckRename hsc_env_tmp ms $ HsParsedModule { hpm_module = parsedSource pmod,- hpm_src_files = pm_extra_src_files pmod,- hpm_annotations = pm_annotations pmod }+ hpm_src_files = pm_extra_src_files pmod } details <- liftIO $ makeSimpleDetails hsc_env_tmp tc_gbl_env safe <- liftIO $ finalSafeMode (ms_hspp_opts ms) tc_gbl_env @@ -1243,7 +1255,7 @@ compileCore :: GhcMonad m => Bool -> FilePath -> m CoreModule compileCore simplify fn = do -- First, set the target to the desired filename- target <- guessTarget fn Nothing+ target <- guessTarget fn Nothing Nothing addTarget target _ <- load LoadAllTargets -- Then find dependencies@@ -1481,7 +1493,7 @@ -- if it is visible from at least one module in the list. -> Maybe [Module] -- ^ modules to load. If this is not specified, we load -- modules for everything that is in scope unqualified.- -> m (Messages DecoratedSDoc, Maybe (NameEnv ([ClsInst], [FamInst])))+ -> m (Messages DiagnosticMessage, Maybe (NameEnv ([ClsInst], [FamInst]))) getNameToInstancesIndex visible_mods mods_to_load = do hsc_env <- getSession liftIO $ runTcInteractive hsc_env $@@ -1654,11 +1666,13 @@ -- using the algorithm that is used for an @import@ declaration. findModule :: GhcMonad m => ModuleName -> Maybe FastString -> m Module findModule mod_name maybe_pkg = withSession $ \hsc_env -> do- let dflags = hsc_dflags hsc_env- home_unit = hsc_home_unit hsc_env+ let fc = hsc_FC hsc_env+ let home_unit = hsc_home_unit hsc_env+ let units = hsc_units hsc_env+ let dflags = hsc_dflags hsc_env case maybe_pkg of Just pkg | not (isHomeUnit home_unit (fsToUnit pkg)) && pkg /= fsLit "this" -> liftIO $ do- res <- findImportedModule hsc_env mod_name maybe_pkg+ res <- findImportedModule fc units home_unit dflags mod_name maybe_pkg case res of Found _ m -> return m err -> throwOneError $ noModError hsc_env noSrcSpan mod_name err@@ -1667,7 +1681,7 @@ case home of Just m -> return m Nothing -> liftIO $ do- res <- findImportedModule hsc_env mod_name maybe_pkg+ res <- findImportedModule fc units home_unit dflags mod_name maybe_pkg case res of Found loc m | not (isHomeModule home_unit m) -> return m | otherwise -> modNotLoadedError dflags m loc@@ -1693,7 +1707,10 @@ case home of Just m -> return m Nothing -> liftIO $ do- res <- findExposedPackageModule hsc_env mod_name Nothing+ let fc = hsc_FC hsc_env+ let units = hsc_units hsc_env+ let dflags = hsc_dflags hsc_env+ res <- findExposedPackageModule fc units dflags mod_name Nothing case res of Found _ m -> return m err -> throwOneError $ noModError hsc_env noSrcSpan mod_name err
compiler/GHC/Builtin/Types/Literals.hs view
@@ -11,7 +11,6 @@ , typeNatAddTyCon , typeNatMulTyCon , typeNatExpTyCon- , typeNatLeqTyCon , typeNatSubTyCon , typeNatDivTyCon , typeNatModTyCon@@ -22,6 +21,8 @@ , typeCharCmpTyCon , typeConsSymbolTyCon , typeUnconsSymbolTyCon+ , typeCharToNatTyCon+ , typeNatToCharTyCon ) where import GHC.Prelude@@ -40,11 +41,12 @@ import GHC.Builtin.Types.Prim ( mkTemplateAnonTyConBinders ) import GHC.Builtin.Names ( gHC_TYPELITS+ , gHC_TYPELITS_INTERNAL , gHC_TYPENATS+ , gHC_TYPENATS_INTERNAL , typeNatAddTyFamNameKey , typeNatMulTyFamNameKey , typeNatExpTyFamNameKey- , typeNatLeqTyFamNameKey , typeNatSubTyFamNameKey , typeNatDivTyFamNameKey , typeNatModTyFamNameKey@@ -55,11 +57,13 @@ , typeCharCmpTyFamNameKey , typeConsSymbolTyFamNameKey , typeUnconsSymbolTyFamNameKey+ , typeCharToNatTyFamNameKey+ , typeNatToCharTyFamNameKey ) import GHC.Data.FastString-import Data.Maybe ( isJust ) import Control.Monad ( guard ) import Data.List ( isPrefixOf, isSuffixOf )+import qualified Data.Char as Char {- Note [Type-level literals]@@ -146,7 +150,6 @@ [ typeNatAddTyCon , typeNatMulTyCon , typeNatExpTyCon- , typeNatLeqTyCon , typeNatSubTyCon , typeNatDivTyCon , typeNatModTyCon@@ -157,6 +160,8 @@ , typeCharCmpTyCon , typeConsSymbolTyCon , typeUnconsSymbolTyCon+ , typeCharToNatTyCon+ , typeNatToCharTyCon ] typeNatAddTyCon :: TyCon@@ -236,24 +241,7 @@ name = mkWiredInTyConName UserSyntax gHC_TYPENATS (fsLit "Log2") typeNatLogTyFamNameKey typeNatLogTyCon -typeNatLeqTyCon :: TyCon-typeNatLeqTyCon =- mkFamilyTyCon name- (mkTemplateAnonTyConBinders [ naturalTy, naturalTy ])- boolTy- Nothing- (BuiltInSynFamTyCon ops)- Nothing- NotInjective - where- name = mkWiredInTyConName UserSyntax gHC_TYPENATS (fsLit "<=?")- typeNatLeqTyFamNameKey typeNatLeqTyCon- ops = BuiltInSynFamily- { sfMatchFam = matchFamLeq- , sfInteractTop = interactTopLeq- , sfInteractInert = interactInertLeq- } typeNatCmpTyCon :: TyCon typeNatCmpTyCon =@@ -266,7 +254,7 @@ NotInjective where- name = mkWiredInTyConName UserSyntax gHC_TYPENATS (fsLit "CmpNat")+ name = mkWiredInTyConName UserSyntax gHC_TYPENATS_INTERNAL (fsLit "CmpNat") typeNatCmpTyFamNameKey typeNatCmpTyCon ops = BuiltInSynFamily { sfMatchFam = matchFamCmpNat@@ -285,7 +273,7 @@ NotInjective where- name = mkWiredInTyConName UserSyntax gHC_TYPELITS (fsLit "CmpSymbol")+ name = mkWiredInTyConName UserSyntax gHC_TYPELITS_INTERNAL (fsLit "CmpSymbol") typeSymbolCmpTyFamNameKey typeSymbolCmpTyCon ops = BuiltInSynFamily { sfMatchFam = matchFamCmpSymbol@@ -340,6 +328,43 @@ , sfInteractInert = interactInertUnconsSymbol } +typeCharToNatTyCon :: TyCon+typeCharToNatTyCon =+ mkFamilyTyCon name+ (mkTemplateAnonTyConBinders [ charTy ])+ naturalTy+ Nothing+ (BuiltInSynFamTyCon ops)+ Nothing+ (Injective [True])+ where+ name = mkWiredInTyConName UserSyntax gHC_TYPELITS (fsLit "CharToNat")+ typeCharToNatTyFamNameKey typeCharToNatTyCon+ ops = BuiltInSynFamily+ { sfMatchFam = matchFamCharToNat+ , sfInteractTop = interactTopCharToNat+ , sfInteractInert = \_ _ _ _ -> []+ }+++typeNatToCharTyCon :: TyCon+typeNatToCharTyCon =+ mkFamilyTyCon name+ (mkTemplateAnonTyConBinders [ naturalTy ])+ charTy+ Nothing+ (BuiltInSynFamTyCon ops)+ Nothing+ (Injective [True])+ where+ name = mkWiredInTyConName UserSyntax gHC_TYPELITS (fsLit "NatToChar")+ typeNatToCharTyFamNameKey typeNatToCharTyCon+ ops = BuiltInSynFamily+ { sfMatchFam = matchFamNatToChar+ , sfInteractTop = interactTopNatToChar+ , sfInteractInert = \_ _ _ _ -> []+ }+ -- Make a unary built-in constructor of kind: Nat -> Nat mkTypeNatFunTyCon1 :: Name -> BuiltInSynFamily -> TyCon mkTypeNatFunTyCon1 op tcb =@@ -383,12 +408,13 @@ axAddDef , axMulDef , axExpDef- , axLeqDef , axCmpNatDef , axCmpSymbolDef , axAppendSymbolDef , axConsSymbolDef , axUnconsSymbolDef+ , axCharToNatDef+ , axNatToCharDef , axAdd0L , axAdd0R , axMul0L@@ -398,10 +424,8 @@ , axExp1L , axExp0R , axExp1R- , axLeqRefl , axCmpNatRefl , axCmpSymbolRefl- , axLeq0L , axSubDef , axSub0R , axAppendSymbol0R@@ -422,9 +446,6 @@ axExpDef = mkBinAxiom "ExpDef" typeNatExpTyCon isNumLitTy isNumLitTy $ \x y -> Just $ num (x ^ y) -axLeqDef = mkBinAxiom "LeqDef" typeNatLeqTyCon isNumLitTy isNumLitTy $- \x y -> Just $ bool (x <= y)- axCmpNatDef = mkBinAxiom "CmpNatDef" typeNatCmpTyCon isNumLitTy isNumLitTy $ \x y -> Just $ ordering (compare x y) @@ -461,6 +482,14 @@ \str -> Just $ mkPromotedMaybeTy charSymbolPairKind (fmap reifyCharSymbolPairTy (unconsFS str)) +axCharToNatDef =+ mkUnAxiom "CharToNatDef" typeCharToNatTyCon isCharLitTy $+ \c -> Just $ num (charToInteger c)++axNatToCharDef =+ mkUnAxiom "NatToCharDef" typeNatToCharTyCon isNumLitTy $+ \n -> fmap mkCharLitTy (integerToChar n)+ axSubDef = mkBinAxiom "SubDef" typeNatSubTyCon isNumLitTy isNumLitTy $ \x y -> fmap num (minus x y) @@ -489,12 +518,10 @@ axExp1L = mkAxiom1 "Exp1L" $ \(Pair s _) -> (num 1 .^. s) === num 1 axExp0R = mkAxiom1 "Exp0R" $ \(Pair s _) -> (s .^. num 0) === num 1 axExp1R = mkAxiom1 "Exp1R" $ \(Pair s t) -> (s .^. num 1) === t-axLeqRefl = mkAxiom1 "LeqRefl" $ \(Pair s _) -> (s <== s) === bool True axCmpNatRefl = mkAxiom1 "CmpNatRefl" $ \(Pair s _) -> (cmpNat s s) === ordering EQ axCmpSymbolRefl = mkAxiom1 "CmpSymbolRefl" $ \(Pair s _) -> (cmpSymbol s s) === ordering EQ-axLeq0L = mkAxiom1 "Leq0L" $ \(Pair s _) -> (num 0 <== s) === bool True axAppendSymbol0R = mkAxiom1 "Concat0R" $ \(Pair s t) -> (mkStrLitTy nilFS `appendSymbol` s) === t axAppendSymbol0L = mkAxiom1 "Concat0L"@@ -508,7 +535,6 @@ [ axAddDef , axMulDef , axExpDef- , axLeqDef , axCmpNatDef , axCmpSymbolDef , axCmpCharDef@@ -524,11 +550,9 @@ , axExp1L , axExp0R , axExp1R- , axLeqRefl , axCmpNatRefl , axCmpSymbolRefl , axCmpCharRefl- , axLeq0L , axSubDef , axSub0R , axAppendSymbol0R@@ -564,9 +588,6 @@ (.^.) :: Type -> Type -> Type s .^. t = mkTyConApp typeNatExpTyCon [s,t] -(<==) :: Type -> Type -> Type-s <== t = mkTyConApp typeNatLeqTyCon [s,t]- cmpNat :: Type -> Type -> Type cmpNat s t = mkTyConApp typeNatCmpTyCon [s,t] @@ -582,24 +603,12 @@ num :: Integer -> Type num = mkNumLitTy -bool :: Bool -> Type-bool b = if b then mkTyConApp promotedTrueDataCon []- else mkTyConApp promotedFalseDataCon []- charSymbolPair :: Type -> Type -> Type charSymbolPair = mkPromotedPairTy charTy typeSymbolKind charSymbolPairKind :: Kind charSymbolPairKind = mkTyConApp pairTyCon [charTy, typeSymbolKind] -isBoolLitTy :: Type -> Maybe Bool-isBoolLitTy tc =- do (tc,[]) <- splitTyConApp_maybe tc- case () of- _ | tc == promotedFalseDataCon -> return False- | tc == promotedTrueDataCon -> return True- | otherwise -> Nothing- orderingKind :: Kind orderingKind = mkTyConApp orderingTyCon [] @@ -734,15 +743,6 @@ where mbX = isNumLitTy s matchFamLog _ = Nothing -matchFamLeq :: [Type] -> Maybe (CoAxiomRule, [Type], Type)-matchFamLeq [s,t]- | Just 0 <- mbX = Just (axLeq0L, [t], bool True)- | Just x <- mbX, Just y <- mbY =- Just (axLeqDef, [s,t], bool (x <= y))- | tcEqType s t = Just (axLeqRefl, [s], bool True)- where mbX = isNumLitTy s- mbY = isNumLitTy t-matchFamLeq _ = Nothing matchFamCmpNat :: [Type] -> Maybe (CoAxiomRule, [Type], Type) matchFamCmpNat [s,t]@@ -794,6 +794,29 @@ mbX = isStrLitTy s matchFamUnconsSymbol _ = Nothing +matchFamCharToNat :: [Type] -> Maybe (CoAxiomRule, [Type], Type)+matchFamCharToNat [c]+ | Just c' <- isCharLitTy c, n <- charToInteger c'+ = Just (axCharToNatDef, [c], mkNumLitTy n)+ | otherwise = Nothing+matchFamCharToNat _ = Nothing++matchFamNatToChar :: [Type] -> Maybe (CoAxiomRule, [Type], Type)+matchFamNatToChar [n]+ | Just n' <- isNumLitTy n, Just c <- integerToChar n'+ = Just (axNatToCharDef, [n], mkCharLitTy c)+ | otherwise = Nothing+matchFamNatToChar _ = Nothing++charToInteger :: Char -> Integer+charToInteger c = fromIntegral (Char.ord c)++integerToChar :: Integer -> Maybe Char+integerToChar n | inBounds = Just (Char.chr (fromInteger n))+ where inBounds = n >= charToInteger minBound &&+ n <= charToInteger maxBound+integerToChar _ = Nothing+ {------------------------------------------------------------------------------- Interact with axioms -------------------------------------------------------------------------------}@@ -883,13 +906,6 @@ interactTopLog _ _ = [] -- I can't think of anything... -interactTopLeq :: [Xi] -> Xi -> [Pair Type]-interactTopLeq [s,t] r- | Just 0 <- mbY, Just True <- mbZ = [ s === num 0 ] -- (s <= 0) => (s ~ 0)- where- mbY = isNumLitTy t- mbZ = isBoolLitTy r-interactTopLeq _ _ = [] interactTopCmpNat :: [Xi] -> Xi -> [Pair Type] interactTopCmpNat [s,t] r@@ -948,7 +964,21 @@ interactTopUnconsSymbol _ _ = [] +interactTopCharToNat :: [Xi] -> Xi -> [Pair Type]+interactTopCharToNat [s] r+ -- (CharToNat c ~ 122) => (c ~ 'z')+ | Just n <- isNumLitTy r+ , Just c <- integerToChar n+ = [ s === mkCharLitTy c ]+interactTopCharToNat _ _ = [] +interactTopNatToChar :: [Xi] -> Xi -> [Pair Type]+interactTopNatToChar [s] r+ -- (NatToChar n ~ 'z') => (n ~ 122)+ | Just c <- isCharLitTy r+ = [ s === mkNumLitTy (charToInteger c) ]+interactTopNatToChar _ _ = []+ {------------------------------------------------------------------------------- Interaction with inerts -------------------------------------------------------------------------------}@@ -993,18 +1023,6 @@ interactInertLog _ _ _ _ = [] -interactInertLeq :: [Xi] -> Xi -> [Xi] -> Xi -> [Pair Type]-interactInertLeq [x1,y1] z1 [x2,y2] z2- | bothTrue && tcEqType x1 y2 && tcEqType y1 x2 = [ x1 === y1 ]- | bothTrue && tcEqType y1 x2 = [ (x1 <== y2) === bool True ]- | bothTrue && tcEqType y2 x1 = [ (x2 <== y1) === bool True ]- where bothTrue = isJust $ do True <- isBoolLitTy z1- True <- isBoolLitTy z2- return ()--interactInertLeq _ _ _ _ = []-- interactInertAppendSymbol :: [Xi] -> Xi -> [Xi] -> Xi -> [Pair Type] interactInertAppendSymbol [x1,y1] z1 [x2,y2] z2 | sameZ && tcEqType x1 x2 = [ y1 === y2 ]@@ -1110,7 +1128,7 @@ Nothing NotInjective where- name = mkWiredInTyConName UserSyntax gHC_TYPELITS (fsLit "CmpChar")+ name = mkWiredInTyConName UserSyntax gHC_TYPELITS_INTERNAL (fsLit "CmpChar") typeCharCmpTyFamNameKey typeCharCmpTyCon ops = BuiltInSynFamily { sfMatchFam = matchFamCmpChar
compiler/GHC/ByteCode/Asm.hs view
@@ -9,25 +9,22 @@ -- | Bytecode assembler and linker module GHC.ByteCode.Asm ( assembleBCOs, assembleOneBCO,- bcoFreeNames, SizedSeq, sizeSS, ssElts,- iNTERP_STACK_CHECK_THRESH+ iNTERP_STACK_CHECK_THRESH,+ mkTupleInfoLit ) where #include "GhclibHsVersions.h" import GHC.Prelude -import GHC.Driver.Env-import GHC.Driver.Session- import GHC.ByteCode.Instr import GHC.ByteCode.InfoTable import GHC.ByteCode.Types import GHCi.RemoteTypes import GHC.Runtime.Interpreter-import GHC.Runtime.Heap.Layout+import GHC.Runtime.Heap.Layout hiding ( WordOff ) import GHC.Types.Name import GHC.Types.Name.Set@@ -45,6 +42,7 @@ import GHC.StgToCmm.Layout ( ArgRep(..) ) import GHC.Platform+import GHC.Platform.Profile import Control.Monad import Control.Monad.ST ( runST )@@ -96,13 +94,19 @@ -- Top level assembler fn. assembleBCOs- :: HscEnv -> [ProtoBCO Name] -> [TyCon] -> [RemotePtr ()]+ :: Interp+ -> Profile+ -> [ProtoBCO Name]+ -> [TyCon]+ -> [RemotePtr ()] -> Maybe ModBreaks -> IO CompiledByteCode-assembleBCOs hsc_env proto_bcos tycons top_strs modbreaks = do- itblenv <- mkITbls hsc_env tycons- bcos <- mapM (assembleBCO (targetPlatform (hsc_dflags hsc_env))) proto_bcos- (bcos',ptrs) <- mallocStrings hsc_env bcos+assembleBCOs interp profile proto_bcos tycons top_strs modbreaks = do+ -- TODO: the profile should be bundled with the interpreter: the rts ways are+ -- fixed for an interpreter+ itblenv <- mkITbls interp profile tycons+ bcos <- mapM (assembleBCO (profilePlatform profile)) proto_bcos+ (bcos',ptrs) <- mallocStrings interp bcos return CompiledByteCode { bc_bcos = bcos' , bc_itbls = itblenv@@ -118,10 +122,10 @@ -- b) For -fexternal-interpreter It's more efficient to malloc the strings -- as a single batch message, especially when compiling in parallel. ---mallocStrings :: HscEnv -> [UnlinkedBCO] -> IO ([UnlinkedBCO], [RemotePtr ()])-mallocStrings hsc_env ulbcos = do+mallocStrings :: Interp -> [UnlinkedBCO] -> IO ([UnlinkedBCO], [RemotePtr ()])+mallocStrings interp ulbcos = do let bytestrings = reverse (execState (mapM_ collect ulbcos) [])- ptrs <- iservCmd hsc_env (MallocStrings bytestrings)+ ptrs <- interpCmd interp (MallocStrings bytestrings) return (evalState (mapM splice ulbcos) ptrs, ptrs) where splice bco@UnlinkedBCO{..} = do@@ -154,10 +158,12 @@ collectPtr _ = return () -assembleOneBCO :: HscEnv -> ProtoBCO Name -> IO UnlinkedBCO-assembleOneBCO hsc_env pbco = do- ubco <- assembleBCO (targetPlatform (hsc_dflags hsc_env)) pbco- ([ubco'], _ptrs) <- mallocStrings hsc_env [ubco]+assembleOneBCO :: Interp -> Profile -> ProtoBCO Name -> IO UnlinkedBCO+assembleOneBCO interp profile pbco = do+ -- TODO: the profile should be bundled with the interpreter: the rts ways are+ -- fixed for an interpreter+ ubco <- assembleBCO (profilePlatform profile) pbco+ ([ubco'], _ptrs) <- mallocStrings interp [ubco] return ubco' assembleBCO :: Platform -> ProtoBCO Name -> IO UnlinkedBCO@@ -335,7 +341,12 @@ -- Bring in all the bci_ bytecode constants. #include "rts/Bytecodes.h"+#if __GLASGOW_HASKELL__ <= 901+# define bci_RETURN_T 69+# define bci_PUSH_ALTS_T 70+#endif + largeArgInstr :: Word16 -> Word16 largeArgInstr bci = bci_FLAG_LARGE_ARGS .|. bci @@ -381,6 +392,16 @@ -> do let ul_bco = assembleBCO platform proto p <- ioptr (liftM BCOPtrBCO ul_bco) emit (push_alts pk) [Op p]+ PUSH_ALTS_TUPLE proto tuple_info tuple_proto+ -> do let ul_bco = assembleBCO platform proto+ ul_tuple_bco = assembleBCO platform+ tuple_proto+ p <- ioptr (liftM BCOPtrBCO ul_bco)+ p_tup <- ioptr (liftM BCOPtrBCO ul_tuple_bco)+ info <- int (fromIntegral $+ mkTupleInfoSig tuple_info)+ emit bci_PUSH_ALTS_T+ [Op p, Op info, Op p_tup] PUSH_PAD8 -> emit bci_PUSH_PAD8 [] PUSH_PAD16 -> emit bci_PUSH_PAD16 [] PUSH_PAD32 -> emit bci_PUSH_PAD32 []@@ -439,6 +460,7 @@ ENTER -> emit bci_ENTER [] RETURN -> emit bci_RETURN [] RETURN_UBX rep -> emit (return_ubx rep) []+ RETURN_TUPLE -> emit bci_RETURN_T [] CCALL off m_addr i -> do np <- addr m_addr emit bci_CCALL [SmallOp off, Op np, SmallOp i] BRK_FUN index uniq cc -> do p1 <- ptr BCOPtrBreakArray@@ -515,6 +537,90 @@ return_ubx V16 = error "return_ubx: vector" return_ubx V32 = error "return_ubx: vector" return_ubx V64 = error "return_ubx: vector"++{-+ we can only handle up to a fixed number of words on the stack,+ because we need a stg_ctoi_tN stack frame for each size N. See+ Note [unboxed tuple bytecodes and tuple_BCO].++ If needed, you can support larger tuples by adding more in+ StgMiscClosures.cmm, Interpreter.c and MiscClosures.h and+ raising this limit.++ Note that the limit is the number of words passed on the stack.+ If the calling convention passes part of the tuple in registers, the+ maximum number of tuple elements may be larger. Elements can also+ take multiple words on the stack (for example Double# on a 32 bit+ platform).++ -}+maxTupleNativeStackSize :: WordOff+maxTupleNativeStackSize = 62++{-+ Maximum number of supported registers for returning tuples.++ If GHC uses more more than these (because of a change in the calling+ convention or a new platform) mkTupleInfoSig will panic.++ You can raise the limits after modifying stg_ctoi_t and stg_ret_t+ (StgMiscClosures.cmm) to save and restore the additional registers.+ -}+maxTupleVanillaRegs, maxTupleFloatRegs, maxTupleDoubleRegs,+ maxTupleLongRegs :: Int+maxTupleVanillaRegs = 6+maxTupleFloatRegs = 6+maxTupleDoubleRegs = 6+maxTupleLongRegs = 1++{-+ Construct the tuple_info word that stg_ctoi_t and stg_ret_t use+ to convert a tuple between the native calling convention and the+ interpreter.++ See Note [GHCi tuple layout] for more information.+ -}+mkTupleInfoSig :: TupleInfo -> Word32+mkTupleInfoSig ti@TupleInfo{..}+ | tupleNativeStackSize > maxTupleNativeStackSize =+ pprPanic "mkTupleInfoSig: tuple too big for the bytecode compiler"+ (ppr tupleNativeStackSize <+> text "stack words." <+>+ text "Use -fobject-code to get around this limit"+ )+ | tupleVanillaRegs `shiftR` maxTupleVanillaRegs /= 0 =+ pprPanic "mkTupleInfoSig: too many vanilla registers" (ppr tupleVanillaRegs)+ | tupleLongRegs `shiftR` maxTupleLongRegs /= 0 =+ pprPanic "mkTupleInfoSig: too many long registers" (ppr tupleLongRegs)+ | tupleFloatRegs `shiftR` maxTupleFloatRegs /= 0 =+ pprPanic "mkTupleInfoSig: too many float registers" (ppr tupleFloatRegs)+ | tupleDoubleRegs `shiftR` maxTupleDoubleRegs /= 0 =+ pprPanic "mkTupleInfoSig: too many double registers" (ppr tupleDoubleRegs)+ {-+ Check that we can pack the register counts/bitmaps and stack size+ in the information word. In particular we check that each component+ fits in the bits we have reserved for it.++ This overlaps with some of the above checks. It's likely that if the+ number of registers changes, the number of bits will also need to be+ updated.+ -}+ | tupleNativeStackSize < 16384 && -- 14 bits stack usage+ tupleDoubleRegs < 64 && -- 6 bit bitmap (these can be shared with float)+ tupleFloatRegs < 64 && -- 6 bit bitmap (these can be shared with double)+ tupleLongRegs < 4 && -- 2 bit bitmap+ tupleVanillaRegs < 65536 && -- 4 bit count (tupleVanillaRegs is still a bitmap)+ -- check that there are no "holes", i.e. that R1..Rn are all in use+ tupleVanillaRegs .&. (tupleVanillaRegs + 1) == 0+ = fromIntegral tupleNativeStackSize .|.+ unRegBitmap (tupleLongRegs `shiftL` 14) .|.+ unRegBitmap (tupleDoubleRegs `shiftL` 16) .|.+ unRegBitmap (tupleFloatRegs `shiftL` 22) .|.+ fromIntegral (countTrailingZeros (1 + tupleVanillaRegs) `shiftL` 28)+ | otherwise = pprPanic "mkTupleInfoSig: unsupported tuple shape" (ppr ti)++mkTupleInfoLit :: Platform -> TupleInfo -> Literal+mkTupleInfoLit platform tuple_info =+ mkLitWord platform . fromIntegral $ mkTupleInfoSig tuple_info -- Make lists of host-sized words for literals, so that when the -- words are placed in memory at increasing addresses, the
compiler/GHC/ByteCode/InfoTable.hs view
@@ -13,7 +13,6 @@ import GHC.Prelude import GHC.Driver.Session-import GHC.Driver.Env import GHC.Platform import GHC.Platform.Profile@@ -40,30 +39,30 @@ -} -- Make info tables for the data decls in this module-mkITbls :: HscEnv -> [TyCon] -> IO ItblEnv-mkITbls hsc_env tcs =+mkITbls :: Interp -> Profile -> [TyCon] -> IO ItblEnv+mkITbls interp profile tcs = foldr plusNameEnv emptyNameEnv <$>- mapM (mkITbl hsc_env) (filter isDataTyCon tcs)+ mapM mkITbl (filter isDataTyCon tcs) where- mkITbl :: HscEnv -> TyCon -> IO ItblEnv- mkITbl hsc_env tc+ mkITbl :: TyCon -> IO ItblEnv+ mkITbl tc | dcs `lengthIs` n -- paranoia; this is an assertion.- = make_constr_itbls hsc_env dcs+ = make_constr_itbls interp profile dcs where dcs = tyConDataCons tc n = tyConFamilySize tc- mkITbl _ _ = panic "mkITbl"+ mkITbl _ = panic "mkITbl" mkItblEnv :: [(Name,ItblPtr)] -> ItblEnv mkItblEnv pairs = mkNameEnv [(n, (n,p)) | (n,p) <- pairs] -- Assumes constructors are numbered from zero, not one-make_constr_itbls :: HscEnv -> [DataCon] -> IO ItblEnv-make_constr_itbls hsc_env cons =+make_constr_itbls :: Interp -> Profile -> [DataCon] -> IO ItblEnv+make_constr_itbls interp profile cons =+ -- TODO: the profile should be bundled with the interpreter: the rts ways are+ -- fixed for an interpreter mkItblEnv <$> mapM (uncurry mk_itbl) (zip cons [0..]) where- profile = targetProfile (hsc_dflags hsc_env)- mk_itbl :: DataCon -> Int -> IO (Name,ItblPtr) mk_itbl dcon conNo = do let rep_args = [ NonVoid prim_rep@@ -85,6 +84,6 @@ constants = platformConstants platform tables_next_to_code = platformTablesNextToCode platform - r <- iservCmd hsc_env (MkConInfoTable tables_next_to_code ptrs' nptrs_really+ r <- interpCmd interp (MkConInfoTable tables_next_to_code ptrs' nptrs_really conNo (tagForCon platform dcon) descr) return (getName dcon, ItblPtr r)
compiler/GHC/ByteCode/Instr.hs view
@@ -1,4 +1,5 @@-{-# LANGUAGE CPP #-}+{-# LANGUAGE CPP #-}+{-# LANGUAGE FlexibleContexts #-} {-# OPTIONS_GHC -funbox-strict-fields #-} -- -- (c) The University of Glasgow 2002-2006@@ -17,22 +18,19 @@ import GHCi.RemoteTypes import GHCi.FFI (C_ffi_cif) import GHC.StgToCmm.Layout ( ArgRep(..) )-import GHC.Core.Ppr import GHC.Utils.Outputable-import GHC.Data.FastString import GHC.Types.Name import GHC.Types.Unique-import GHC.Types.Id-import GHC.Core import GHC.Types.Literal import GHC.Core.DataCon-import GHC.Types.Var.Set import GHC.Builtin.PrimOps import GHC.Runtime.Heap.Layout import Data.Word import GHC.Stack.CCS (CostCentre) +import GHC.Stg.Syntax+ -- ---------------------------------------------------------------------------- -- Bytecode instructions @@ -45,7 +43,7 @@ protoBCOBitmapSize :: Word16, protoBCOArity :: Int, -- what the BCO came from, for debugging only- protoBCOExpr :: Either [AnnAlt Id DVarSet] (AnnExpr Id DVarSet),+ protoBCOExpr :: Either [CgStgAlt] CgStgRhs, -- malloc'd pointers protoBCOFFIs :: [FFIInfo] }@@ -91,6 +89,9 @@ -- Push an alt continuation | PUSH_ALTS (ProtoBCO Name) | PUSH_ALTS_UNLIFTED (ProtoBCO Name) ArgRep+ | PUSH_ALTS_TUPLE (ProtoBCO Name) -- continuation+ !TupleInfo+ (ProtoBCO Name) -- tuple return BCO -- Pushing 8, 16 and 32 bits of padding (for constructors). | PUSH_PAD8@@ -173,8 +174,9 @@ -- To Infinity And Beyond | ENTER- | RETURN -- return a lifted value+ | RETURN -- return a lifted value | RETURN_UBX ArgRep -- return an unlifted value, here's its rep+ | RETURN_TUPLE -- return an unboxed tuple (info already on stack) -- Breakpoints | BRK_FUN Word16 Unique (RemotePtr CostCentre)@@ -193,37 +195,46 @@ = (text "ProtoBCO" <+> ppr name <> char '#' <> int arity <+> text (show ffis) <> colon) $$ nest 3 (case origin of- Left alts -> vcat (zipWith (<+>) (char '{' : repeat (char ';'))- (map (pprCoreAltShort.deAnnAlt) alts)) <+> char '}'- Right rhs -> pprCoreExprShort (deAnnotate rhs))+ Left alts ->+ vcat (zipWith (<+>) (char '{' : repeat (char ';'))+ (map (pprStgAltShort shortStgPprOpts) alts))+ Right rhs ->+ pprStgRhsShort shortStgPprOpts rhs+ ) $$ nest 3 (text "bitmap: " <+> text (show bsize) <+> ppr bitmap) $$ nest 3 (vcat (map ppr instrs)) --- Print enough of the Core expression to enable the reader to find--- the expression in the -ddump-prep output. That is, we need to+-- Print enough of the STG expression to enable the reader to find+-- the expression in the -ddump-stg output. That is, we need to -- include at least a binder. -pprCoreExprShort :: CoreExpr -> SDoc-pprCoreExprShort expr@(Lam _ _)- = let- (bndrs, _) = collectBinders expr- in- char '\\' <+> sep (map (pprBndr LambdaBind) bndrs) <+> arrow <+> text "..."+pprStgExprShort :: OutputablePass pass => StgPprOpts -> GenStgExpr pass -> SDoc+pprStgExprShort _ (StgCase _expr var _ty _alts) =+ text "case of" <+> ppr var+pprStgExprShort _ (StgLet _ bnd _) =+ text "let" <+> pprStgBindShort bnd <+> text "in ..."+pprStgExprShort _ (StgLetNoEscape _ bnd _) =+ text "let-no-escape" <+> pprStgBindShort bnd <+> text "in ..."+pprStgExprShort opts (StgTick t e) = ppr t <+> pprStgExprShort opts e+pprStgExprShort opts e = pprStgExpr opts e -pprCoreExprShort (Case _expr var _ty _alts)- = text "case of" <+> ppr var+pprStgBindShort :: OutputablePass pass => GenStgBinding pass -> SDoc+pprStgBindShort (StgNonRec x _) =+ ppr x <+> text "= ..."+pprStgBindShort (StgRec bs) =+ char '{' <+> ppr (fst (head bs)) <+> text "= ...; ... }" -pprCoreExprShort (Let (NonRec x _) _) = text "let" <+> ppr x <+> ptext (sLit ("= ... in ..."))-pprCoreExprShort (Let (Rec bs) _) = text "let {" <+> ppr (fst (head bs)) <+> ptext (sLit ("= ...; ... } in ..."))+pprStgAltShort :: OutputablePass pass => StgPprOpts -> GenStgAlt pass -> SDoc+pprStgAltShort opts (con, args, expr) =+ ppr con <+> sep (map ppr args) <+> text "->" <+> pprStgExprShort opts expr -pprCoreExprShort (Tick t e) = ppr t <+> pprCoreExprShort e-pprCoreExprShort (Cast e _) = pprCoreExprShort e <+> text "`cast` T"+pprStgRhsShort :: OutputablePass pass => StgPprOpts -> GenStgRhs pass -> SDoc+pprStgRhsShort opts (StgRhsClosure _ext _cc upd_flag args body) =+ hang (hsep [ char '\\' <> ppr upd_flag, brackets (interppSP args) ])+ 4 (pprStgExprShort opts body)+pprStgRhsShort opts rhs = pprStgRhs opts rhs -pprCoreExprShort e = pprCoreExpr e -pprCoreAltShort :: CoreAlt -> SDoc-pprCoreAltShort (Alt con args expr) = ppr con <+> sep (map ppr args) <+> text "->" <+> pprCoreExprShort expr- instance Outputable BCInstr where ppr (STKCHECK n) = text "STKCHECK" <+> ppr n ppr (PUSH_L offset) = text "PUSH_L " <+> ppr offset@@ -239,8 +250,13 @@ ppr (PUSH_PRIMOP op) = text "PUSH_G " <+> text "GHC.PrimopWrappers." <> ppr op ppr (PUSH_BCO bco) = hang (text "PUSH_BCO") 2 (ppr bco)+ ppr (PUSH_ALTS bco) = hang (text "PUSH_ALTS") 2 (ppr bco) ppr (PUSH_ALTS_UNLIFTED bco pk) = hang (text "PUSH_ALTS_UNLIFTED" <+> ppr pk) 2 (ppr bco)+ ppr (PUSH_ALTS_TUPLE bco tuple_info tuple_bco) =+ hang (text "PUSH_ALTS_TUPLE" <+> ppr tuple_info)+ 2+ (ppr tuple_bco $+$ ppr bco) ppr PUSH_PAD8 = text "PUSH_PAD8" ppr PUSH_PAD16 = text "PUSH_PAD16"@@ -297,8 +313,11 @@ ppr ENTER = text "ENTER" ppr RETURN = text "RETURN" ppr (RETURN_UBX pk) = text "RETURN_UBX " <+> ppr pk+ ppr (RETURN_TUPLE) = text "RETURN_TUPLE" ppr (BRK_FUN index uniq _cc) = text "BRK_FUN" <+> ppr index <+> ppr uniq <+> text "<cc>" ++ -- ----------------------------------------------------------------------------- -- The stack use, in words, of each bytecode insn. These _must_ be -- correct, or overestimates of reality, to be safe.@@ -326,8 +345,16 @@ bciStackUse PUSH_G{} = 1 bciStackUse PUSH_PRIMOP{} = 1 bciStackUse PUSH_BCO{} = 1-bciStackUse (PUSH_ALTS bco) = 2 + protoBCOStackUse bco-bciStackUse (PUSH_ALTS_UNLIFTED bco _) = 2 + protoBCOStackUse bco+bciStackUse (PUSH_ALTS bco) = 2 {- profiling only, restore CCCS -} ++ 3 + protoBCOStackUse bco+bciStackUse (PUSH_ALTS_UNLIFTED bco _) = 2 {- profiling only, restore CCCS -} ++ 4 + protoBCOStackUse bco+bciStackUse (PUSH_ALTS_TUPLE bco info _) =+ -- (tuple_bco, tuple_info word, cont_bco, stg_ctoi_t)+ -- tuple+ -- (tuple_info, tuple_bco, stg_ret_t)+ 1 {- profiling only -} ++ 7 + fromIntegral (tupleSize info) + protoBCOStackUse bco bciStackUse (PUSH_PAD8) = 1 -- overapproximation bciStackUse (PUSH_PAD16) = 1 -- overapproximation bciStackUse (PUSH_PAD32) = 1 -- overapproximation on 64bit arch@@ -365,7 +392,8 @@ bciStackUse JMP{} = 0 bciStackUse ENTER{} = 0 bciStackUse RETURN{} = 0-bciStackUse RETURN_UBX{} = 1+bciStackUse RETURN_UBX{} = 1 -- pushes stg_ret_X for some X+bciStackUse RETURN_TUPLE{} = 1 -- pushes stg_ret_t header bciStackUse CCALL{} = 0 bciStackUse SWIZZLE{} = 0 bciStackUse BRK_FUN{} = 0
compiler/GHC/ByteCode/Linker.hs view
@@ -8,19 +8,22 @@ -- -- | Bytecode assembler and linker-module GHC.ByteCode.Linker (- ClosureEnv, emptyClosureEnv, extendClosureEnv,- linkBCO, lookupStaticPtr,- lookupIE,- nameToCLabel, linkFail- ) where+module GHC.ByteCode.Linker+ ( ClosureEnv+ , emptyClosureEnv+ , extendClosureEnv+ , linkBCO+ , lookupStaticPtr+ , lookupIE+ , nameToCLabel+ , linkFail+ )+where #include "GhclibHsVersions.h" import GHC.Prelude -import GHC.Driver.Env- import GHC.Runtime.Interpreter import GHC.ByteCode.Types import GHCi.RemoteTypes@@ -65,88 +68,104 @@ -} linkBCO- :: HscEnv -> ItblEnv -> ClosureEnv -> NameEnv Int -> RemoteRef BreakArray+ :: Interp+ -> ItblEnv+ -> ClosureEnv+ -> NameEnv Int+ -> RemoteRef BreakArray -> UnlinkedBCO -> IO ResolvedBCO-linkBCO hsc_env ie ce bco_ix breakarray+linkBCO interp ie ce bco_ix breakarray (UnlinkedBCO _ arity insns bitmap lits0 ptrs0) = do -- fromIntegral Word -> Word64 should be a no op if Word is Word64 -- otherwise it will result in a cast to longlong on 32bit systems.- lits <- mapM (fmap fromIntegral . lookupLiteral hsc_env ie) (ssElts lits0)- ptrs <- mapM (resolvePtr hsc_env ie ce bco_ix breakarray) (ssElts ptrs0)+ lits <- mapM (fmap fromIntegral . lookupLiteral interp ie) (ssElts lits0)+ ptrs <- mapM (resolvePtr interp ie ce bco_ix breakarray) (ssElts ptrs0) return (ResolvedBCO isLittleEndian arity insns bitmap (listArray (0, fromIntegral (sizeSS lits0)-1) lits) (addListToSS emptySS ptrs)) -lookupLiteral :: HscEnv -> ItblEnv -> BCONPtr -> IO Word-lookupLiteral _ _ (BCONPtrWord lit) = return lit-lookupLiteral hsc_env _ (BCONPtrLbl sym) = do- Ptr a# <- lookupStaticPtr hsc_env sym- return (W# (int2Word# (addr2Int# a#)))-lookupLiteral hsc_env ie (BCONPtrItbl nm) = do- Ptr a# <- lookupIE hsc_env ie nm- return (W# (int2Word# (addr2Int# a#)))-lookupLiteral _ _ (BCONPtrStr _) =- -- should be eliminated during assembleBCOs- panic "lookupLiteral: BCONPtrStr"+lookupLiteral :: Interp -> ItblEnv -> BCONPtr -> IO Word+lookupLiteral interp ie ptr = case ptr of+ BCONPtrWord lit -> return lit+ BCONPtrLbl sym -> do+ Ptr a# <- lookupStaticPtr interp sym+ return (W# (int2Word# (addr2Int# a#)))+ BCONPtrItbl nm -> do+ Ptr a# <- lookupIE interp ie nm+ return (W# (int2Word# (addr2Int# a#)))+ BCONPtrStr _ ->+ -- should be eliminated during assembleBCOs+ panic "lookupLiteral: BCONPtrStr" -lookupStaticPtr :: HscEnv -> FastString -> IO (Ptr ())-lookupStaticPtr hsc_env addr_of_label_string = do- m <- lookupSymbol hsc_env addr_of_label_string+lookupStaticPtr :: Interp -> FastString -> IO (Ptr ())+lookupStaticPtr interp addr_of_label_string = do+ m <- lookupSymbol interp addr_of_label_string case m of Just ptr -> return ptr Nothing -> linkFail "GHC.ByteCode.Linker: can't find label" (unpackFS addr_of_label_string) -lookupIE :: HscEnv -> ItblEnv -> Name -> IO (Ptr ())-lookupIE hsc_env ie con_nm =+lookupIE :: Interp -> ItblEnv -> Name -> IO (Ptr ())+lookupIE interp ie con_nm = case lookupNameEnv ie con_nm of Just (_, ItblPtr a) -> return (fromRemotePtr (castRemotePtr a)) Nothing -> do -- try looking up in the object files. let sym_to_find1 = nameToCLabel con_nm "con_info"- m <- lookupSymbol hsc_env sym_to_find1+ m <- lookupSymbol interp sym_to_find1 case m of Just addr -> return addr Nothing -> do -- perhaps a nullary constructor? let sym_to_find2 = nameToCLabel con_nm "static_info"- n <- lookupSymbol hsc_env sym_to_find2+ n <- lookupSymbol interp sym_to_find2 case n of Just addr -> return addr Nothing -> linkFail "GHC.ByteCode.Linker.lookupIE" (unpackFS sym_to_find1 ++ " or " ++ unpackFS sym_to_find2) -lookupPrimOp :: HscEnv -> PrimOp -> IO (RemotePtr ())-lookupPrimOp hsc_env primop = do+lookupPrimOp :: Interp -> PrimOp -> IO (RemotePtr ())+lookupPrimOp interp primop = do let sym_to_find = primopToCLabel primop "closure"- m <- lookupSymbol hsc_env (mkFastString sym_to_find)+ m <- lookupSymbol interp (mkFastString sym_to_find) case m of Just p -> return (toRemotePtr p) Nothing -> linkFail "GHC.ByteCode.Linker.lookupCE(primop)" sym_to_find resolvePtr- :: HscEnv -> ItblEnv -> ClosureEnv -> NameEnv Int -> RemoteRef BreakArray+ :: Interp+ -> ItblEnv+ -> ClosureEnv+ -> NameEnv Int+ -> RemoteRef BreakArray -> BCOPtr -> IO ResolvedBCOPtr-resolvePtr hsc_env _ie ce bco_ix _ (BCOPtrName nm)- | Just ix <- lookupNameEnv bco_ix nm =- return (ResolvedBCORef ix) -- ref to another BCO in this group- | Just (_, rhv) <- lookupNameEnv ce nm =- return (ResolvedBCOPtr (unsafeForeignRefToRemoteRef rhv))- | otherwise =- ASSERT2(isExternalName nm, ppr nm)- do let sym_to_find = nameToCLabel nm "closure"- m <- lookupSymbol hsc_env sym_to_find- case m of- Just p -> return (ResolvedBCOStaticPtr (toRemotePtr p))- Nothing -> linkFail "GHC.ByteCode.Linker.lookupCE" (unpackFS sym_to_find)-resolvePtr hsc_env _ _ _ _ (BCOPtrPrimOp op) =- ResolvedBCOStaticPtr <$> lookupPrimOp hsc_env op-resolvePtr hsc_env ie ce bco_ix breakarray (BCOPtrBCO bco) =- ResolvedBCOPtrBCO <$> linkBCO hsc_env ie ce bco_ix breakarray bco-resolvePtr _ _ _ _ breakarray BCOPtrBreakArray =- return (ResolvedBCOPtrBreakArray breakarray)+resolvePtr interp ie ce bco_ix breakarray ptr = case ptr of+ BCOPtrName nm+ | Just ix <- lookupNameEnv bco_ix nm+ -> return (ResolvedBCORef ix) -- ref to another BCO in this group++ | Just (_, rhv) <- lookupNameEnv ce nm+ -> return (ResolvedBCOPtr (unsafeForeignRefToRemoteRef rhv))++ | otherwise+ -> ASSERT2(isExternalName nm, ppr nm)+ do+ let sym_to_find = nameToCLabel nm "closure"+ m <- lookupSymbol interp sym_to_find+ case m of+ Just p -> return (ResolvedBCOStaticPtr (toRemotePtr p))+ Nothing -> linkFail "GHC.ByteCode.Linker.lookupCE" (unpackFS sym_to_find)++ BCOPtrPrimOp op+ -> ResolvedBCOStaticPtr <$> lookupPrimOp interp op++ BCOPtrBCO bco+ -> ResolvedBCOPtrBCO <$> linkBCO interp ie ce bco_ix breakarray bco++ BCOPtrBreakArray+ -> return (ResolvedBCOPtrBreakArray breakarray) linkFail :: String -> String -> IO a linkFail who what
compiler/GHC/Cmm/DebugBlock.hs view
@@ -39,13 +39,13 @@ import GHC.Cmm.CLabel import GHC.Cmm import GHC.Cmm.Utils-import GHC.Core import GHC.Data.FastString ( nilFS, mkFastString ) import GHC.Unit.Module import GHC.Utils.Outputable import GHC.Utils.Panic import GHC.Cmm.Ppr.Expr ( pprExpr ) import GHC.Types.SrcLoc+import GHC.Types.Tickish import GHC.Utils.Misc ( seqList ) import GHC.Cmm.Dataflow.Block@@ -118,7 +118,7 @@ -- recover by copying ticks below. scp' | SubScope _ scp' <- scp = scp' | CombinedScope scp' _ <- scp = scp'-#if __GLASGOW_HASKELL__ <= 810+#if __GLASGOW_HASKELL__ < 901 | otherwise = panic "findP impossible" #endif
compiler/GHC/Cmm/LayoutStack.hs view
@@ -8,7 +8,8 @@ import GHC.Platform import GHC.Platform.Profile -import GHC.StgToCmm.Utils ( callerSaveVolatileRegs, newTemp ) -- XXX layering violation+import GHC.StgToCmm.Monad ( newTemp ) -- XXX layering violation+import GHC.StgToCmm.Utils ( callerSaveVolatileRegs ) -- XXX layering violation import GHC.StgToCmm.Foreign ( saveThreadState, loadThreadState ) -- XXX layering violation import GHC.Types.Basic
compiler/GHC/Cmm/Parser.y view
@@ -218,13 +218,13 @@ import GHC.StgToCmm.Utils import GHC.StgToCmm.Foreign import GHC.StgToCmm.Expr+import GHC.StgToCmm.Lit import GHC.StgToCmm.Closure import GHC.StgToCmm.Layout hiding (ArgRep(..)) import GHC.StgToCmm.Ticky+import GHC.StgToCmm.Prof import GHC.StgToCmm.Bind ( emitBlackHoleCode, emitUpdateFrame ) -import GHC.Core ( Tickish(SourceNote) )- import GHC.Cmm.Opt import GHC.Cmm.Graph import GHC.Cmm@@ -249,6 +249,7 @@ import GHC.Types.Unique import GHC.Types.Unique.FM import GHC.Types.SrcLoc+import GHC.Types.Tickish ( GenTickish(SourceNote) ) import GHC.Driver.Session import GHC.Driver.Ppr import GHC.Driver.Config@@ -1448,8 +1449,9 @@ ] where platform = profilePlatform profile -parseCmmFile :: DynFlags -> HomeUnit -> FilePath -> IO (Bag PsWarning, Bag PsError, Maybe CmmGroup)-parseCmmFile dflags home_unit filename = do++parseCmmFile :: DynFlags -> Module -> HomeUnit -> FilePath -> IO (Bag PsWarning, Bag PsError, Maybe (CmmGroup, [InfoProvEnt]))+parseCmmFile dflags this_mod home_unit filename = do buf <- hGetStringBuffer filename let init_loc = mkRealSrcLoc (mkFastString filename) 1 1@@ -1463,8 +1465,13 @@ return (warnings, errors, Nothing) POk pst code -> do st <- initC- let fcode = getCmm $ unEC code "global" (initEnv (targetProfile dflags)) [] >> return ()- (cmm,_) = runC dflags no_module st fcode+ let fcode = do+ ((), cmm) <- getCmm $ unEC code "global" (initEnv (targetProfile dflags)) [] >> return ()+ let used_info = map (cmmInfoTableToInfoProvEnt this_mod)+ (mapMaybe topInfoTable cmm)+ ((), cmm2) <- getCmm $ mapM_ emitInfoTableProv used_info+ return (cmm ++ cmm2, used_info)+ (cmm, _) = runC dflags no_module st fcode (warnings,errors) = getMessages pst if not (isEmptyBag errors) then return (warnings, errors, Nothing)
compiler/GHC/CmmToAsm.hs view
@@ -5,13 +5,16 @@ -- -- ----------------------------------------------------------------------------- -{-# LANGUAGE BangPatterns, CPP, GADTs, ScopedTypeVariables, PatternSynonyms,- DeriveFunctor #-}-{-# LANGUAGE MultiParamTypeClasses #-}-{-# LANGUAGE FlexibleInstances #-}+{-# LANGUAGE BangPatterns #-}+{-# LANGUAGE CPP #-}+{-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE FlexibleContexts #-}-{-# LANGUAGE UnboxedTuples #-}+{-# LANGUAGE FlexibleInstances #-}+{-# LANGUAGE GADTs #-}+{-# LANGUAGE MultiParamTypeClasses #-}+{-# LANGUAGE PatternSynonyms #-} {-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE UnboxedTuples #-} {-# OPTIONS_GHC -Wno-incomplete-record-updates #-} @@ -168,6 +171,7 @@ ArchAlpha -> panic "nativeCodeGen: No NCG for Alpha" ArchMipseb -> panic "nativeCodeGen: No NCG for mipseb" ArchMipsel -> panic "nativeCodeGen: No NCG for mipsel"+ ArchRISCV64 -> panic "nativeCodeGen: No NCG for RISCV64" ArchUnknown -> panic "nativeCodeGen: No NCG for unknown arch" ArchJavaScript-> panic "nativeCodeGen: No NCG for JavaScript"
compiler/GHC/CmmToAsm/Dwarf.hs view
@@ -7,7 +7,7 @@ import GHC.Cmm.CLabel import GHC.Cmm.Expr ( GlobalReg(..) ) import GHC.Settings.Config ( cProjectName, cProjectVersion )-import GHC.Core ( Tickish(..) )+import GHC.Types.Tickish ( CmmTickish, GenTickish(..) ) import GHC.Cmm.DebugBlock import GHC.Unit.Module import GHC.Utils.Outputable@@ -210,7 +210,7 @@ | Just _ <- dblPosition blk = Just $ mkAsmTempLabel $ dblLabel blk | otherwise = Nothing -- block was optimized out -tickToDwarf :: Tickish () -> [DwarfInfo]+tickToDwarf :: CmmTickish -> [DwarfInfo] tickToDwarf (SourceNote ss _) = [DwarfSrcNote ss] tickToDwarf _ = []
compiler/GHC/CmmToAsm/PPC/CodeGen.hs view
@@ -57,7 +57,7 @@ import GHC.Cmm.CLabel import GHC.Cmm.Dataflow.Block import GHC.Cmm.Dataflow.Graph-import GHC.Core ( Tickish(..) )+import GHC.Types.Tickish ( GenTickish(..) ) import GHC.Types.SrcLoc ( srcSpanFile, srcSpanStartLine, srcSpanStartCol ) -- The rest:@@ -2381,6 +2381,10 @@ coerceInt2FP' (ArchPPC_64 _) fromRep toRep x = do (src, code) <- getSomeReg x platform <- getPlatform+ upper <- getNewRegNat II64+ lower <- getNewRegNat II64+ l1 <- getBlockIdNat+ l2 <- getBlockIdNat let code' dst = code `appOL` maybe_exts `appOL` toOL [ ST II64 src (spRel platform 3),@@ -2388,12 +2392,28 @@ FCFID dst dst ] `appOL` maybe_frsp dst - maybe_exts = case fromRep of- W8 -> unitOL $ EXTS II8 src src- W16 -> unitOL $ EXTS II16 src src- W32 -> unitOL $ EXTS II32 src src- W64 -> nilOL- _ -> panic "PPC.CodeGen.coerceInt2FP: no match"+ maybe_exts+ = case fromRep of+ W8 -> unitOL $ EXTS II8 src src+ W16 -> unitOL $ EXTS II16 src src+ W32 -> unitOL $ EXTS II32 src src+ W64 -> case toRep of+ W32 -> toOL [ SRA II64 upper src (RIImm (ImmInt 53))+ , CLRLI II64 lower src 53+ , ADD upper upper (RIImm (ImmInt 1))+ , ADD lower lower (RIImm (ImmInt 2047))+ , CMPL II64 upper (RIImm (ImmInt 2))+ , OR lower lower (RIReg src)+ , CLRRI II64 lower lower 11+ , BCC LTT l2 Nothing+ , BCC ALWAYS l1 Nothing+ , NEWBLOCK l1+ , MR src lower+ , BCC ALWAYS l2 Nothing+ , NEWBLOCK l2+ ]+ _ -> nilOL+ _ -> panic "PPC.CodeGen.coerceInt2FP: no match" maybe_frsp dst = case toRep of
compiler/GHC/CmmToAsm/Ppr.hs view
@@ -38,15 +38,13 @@ import Data.Bits import Data.ByteString (ByteString) import qualified Data.ByteString as BS-import GHC.Exts hiding (extendWord8#)+import GHC.Exts import GHC.Word -#if MIN_VERSION_base(4,16,0)-import GHC.Base (extendWord8#)-#else-extendWord8# :: Word# -> Word#-extendWord8# w = w-{-# INLINE extendWord8# #-}+#if !MIN_VERSION_base(4,16,0)+word8ToWord# :: Word# -> Word#+word8ToWord# w = w+{-# INLINE word8ToWord# #-} #endif -- -----------------------------------------------------------------------------@@ -111,7 +109,7 @@ -- we know that the Chars we create are in the ASCII range -- so we bypass the check in "chr" chr' :: Word8 -> Char- chr' (W8# w#) = C# (chr# (word2Int# (extendWord8# w#)))+ chr' (W8# w#) = C# (chr# (word2Int# (word8ToWord# w#))) octal :: Word8 -> String octal w = [ chr' (ord0 + (w `unsafeShiftR` 6) .&. 0x07)
compiler/GHC/CmmToAsm/Reg/Graph/TrivColorable.hs view
@@ -120,6 +120,7 @@ ArchMipseb -> panic "trivColorable ArchMipseb" ArchMipsel -> panic "trivColorable ArchMipsel" ArchS390X -> panic "trivColorable ArchS390X"+ ArchRISCV64 -> panic "trivColorable ArchRISCV64" ArchJavaScript-> panic "trivColorable ArchJavaScript" ArchUnknown -> panic "trivColorable ArchUnknown") , count2 <- accSqueeze 0 cALLOCATABLE_REGS_INTEGER@@ -151,6 +152,7 @@ ArchMipseb -> panic "trivColorable ArchMipseb" ArchMipsel -> panic "trivColorable ArchMipsel" ArchS390X -> panic "trivColorable ArchS390X"+ ArchRISCV64 -> panic "trivColorable ArchRISCV64" ArchJavaScript-> panic "trivColorable ArchJavaScript" ArchUnknown -> panic "trivColorable ArchUnknown") , count2 <- accSqueeze 0 cALLOCATABLE_REGS_FLOAT@@ -184,6 +186,7 @@ ArchMipseb -> panic "trivColorable ArchMipseb" ArchMipsel -> panic "trivColorable ArchMipsel" ArchS390X -> panic "trivColorable ArchS390X"+ ArchRISCV64 -> panic "trivColorable ArchRISCV64" ArchJavaScript-> panic "trivColorable ArchJavaScript" ArchUnknown -> panic "trivColorable ArchUnknown") , count2 <- accSqueeze 0 cALLOCATABLE_REGS_DOUBLE
compiler/GHC/CmmToAsm/Reg/Linear.hs view
@@ -172,18 +172,18 @@ | LiveInfo info entry_ids@(first_id:_) block_live _ <- static = do -- do register allocation on each component.- (final_blocks, stats, stack_use)+ !(!final_blocks, !stats, !stack_use) <- linearRegAlloc config entry_ids block_live sccs -- make sure the block that was first in the input list -- stays at the front of the output- let ((first':_), rest')+ let !(!(!first':_), !rest') = partition ((== first_id) . blockId) final_blocks let max_spill_slots = maxSpillSlots config extra_stack | stack_use > max_spill_slots- = Just (stack_use - max_spill_slots)+ = Just $! stack_use - max_spill_slots | otherwise = Nothing @@ -228,6 +228,7 @@ ArchAlpha -> panic "linearRegAlloc ArchAlpha" ArchMipseb -> panic "linearRegAlloc ArchMipseb" ArchMipsel -> panic "linearRegAlloc ArchMipsel"+ ArchRISCV64 -> panic "linearRegAlloc ArchRISCV64" ArchJavaScript -> panic "linearRegAlloc ArchJavaScript" ArchUnknown -> panic "linearRegAlloc ArchUnknown" where@@ -252,7 +253,7 @@ linearRegAlloc' config initFreeRegs entry_ids block_live sccs = do us <- getUniqueSupplyM- let (_, stack, stats, blocks) =+ let !(_, !stack, !stats, !blocks) = runR config mapEmpty initFreeRegs emptyRegMap emptyStackMap us $ linearRA_SCCs entry_ids block_live [] sccs return (blocks, stats, getStackUse stack)@@ -276,7 +277,7 @@ linearRA_SCCs entry_ids block_live blocksAcc (CyclicSCC blocks : sccs) = do- blockss' <- process entry_ids block_live blocks [] (return []) False+ blockss' <- process entry_ids block_live blocks linearRA_SCCs entry_ids block_live (reverse (concat blockss') ++ blocksAcc) sccs@@ -293,45 +294,41 @@ more sanity checking to guard against this eventuality. -} -process :: OutputableRegConstraint freeRegs instr+process :: forall freeRegs instr. (OutputableRegConstraint freeRegs instr) => [BlockId] -> BlockMap RegSet -> [GenBasicBlock (LiveInstr instr)]- -> [GenBasicBlock (LiveInstr instr)]- -> [[NatBasicBlock instr]]- -> Bool -> RegM freeRegs [[NatBasicBlock instr]]--process _ _ [] [] accum _- = return $ reverse accum--process entry_ids block_live [] next_round accum madeProgress- | not madeProgress+process entry_ids block_live =+ \blocks -> go blocks [] (return []) False+ where+ go :: [GenBasicBlock (LiveInstr instr)]+ -> [GenBasicBlock (LiveInstr instr)]+ -> [[NatBasicBlock instr]]+ -> Bool+ -> RegM freeRegs [[NatBasicBlock instr]]+ go [] [] accum _madeProgress+ = return $ reverse accum + go [] next_round accum madeProgress+ | not madeProgress {- BUGS: There are so many unreachable blocks in the code the warnings are overwhelming. pprTrace "RegAlloc.Linear.Main.process: no progress made, bailing out." ( text "Unreachable blocks:" $$ vcat (map ppr next_round)) -}- = return $ reverse accum-- | otherwise- = process entry_ids block_live- next_round [] accum False+ = return $ reverse accum -process entry_ids block_live (b@(BasicBlock id _) : blocks)- next_round accum madeProgress- = do- block_assig <- getBlockAssigR+ | otherwise+ = go next_round [] accum False - if isJust (mapLookup id block_assig)- || id `elem` entry_ids- then do- b' <- processBlock block_live b- process entry_ids block_live blocks- next_round (b' : accum) True+ go (b@(BasicBlock id _) : blocks) next_round accum madeProgress+ = do+ block_assig <- getBlockAssigR+ if isJust (mapLookup id block_assig) || id `elem` entry_ids+ then do b' <- processBlock block_live b+ go blocks next_round (b' : accum) True - else process entry_ids block_live blocks- (b : next_round) accum madeProgress+ else do go blocks (b : next_round) accum madeProgress -- | Do register allocation on this basic block@@ -347,7 +344,7 @@ initBlock id block_live (instrs', fixups)- <- linearRA block_live [] [] id instrs+ <- linearRA block_live id instrs -- pprTraceM "blockResult" $ ppr (instrs', fixups) return $ BasicBlock id instrs' : fixups @@ -384,30 +381,28 @@ -- | Do allocation for a sequence of instructions. linearRA- :: OutputableRegConstraint freeRegs instr+ :: forall freeRegs instr. (OutputableRegConstraint freeRegs instr) => BlockMap RegSet -- ^ map of what vregs are live on entry to each block.- -> [instr] -- ^ accumulator for instructions already processed.- -> [NatBasicBlock instr] -- ^ accumulator for blocks of fixup code. -> BlockId -- ^ id of the current block, for debugging. -> [LiveInstr instr] -- ^ liveness annotated instructions in this block.- -> RegM freeRegs ( [instr] -- instructions after register allocation , [NatBasicBlock instr]) -- fresh blocks of fixup code.---linearRA _ accInstr accFixup _ []- = return- ( reverse accInstr -- instrs need to be returned in the correct order.- , accFixup) -- it doesn't matter what order the fixup blocks are returned in.---linearRA block_live accInstr accFixups id (instr:instrs)- = do- (accInstr', new_fixups) <- raInsn block_live accInstr id instr-- linearRA block_live accInstr' (new_fixups ++ accFixups) id instrs+linearRA block_live block_id = go [] []+ where+ go :: [instr] -- ^ accumulator for instructions already processed.+ -> [NatBasicBlock instr] -- ^ accumulator for blocks of fixup code.+ -> [LiveInstr instr] -- ^ liveness annotated instructions in this block.+ -> RegM freeRegs+ ( [instr] -- instructions after register allocation+ , [NatBasicBlock instr] ) -- fresh blocks of fixup code.+ go !accInstr !accFixups [] = do+ return ( reverse accInstr -- instrs need to be returned in the correct order.+ , accFixups ) -- it doesn't matter what order the fixup blocks are returned in. + go accInstr accFixups (instr:instrs) = do+ (accInstr', new_fixups) <- raInsn block_live accInstr block_id instr+ go accInstr' (new_fixups ++ accFixups) instrs -- | Do allocation for a single instruction. raInsn@@ -600,8 +595,7 @@ | src == dst -> [] _ -> [patched_instr] - let code = squashed_instr ++ w_spills ++ reverse r_spills- ++ clobber_saves ++ new_instrs+ let code = concat [ squashed_instr, w_spills, reverse r_spills, clobber_saves, new_instrs ] -- pprTrace "patched-code" ((vcat $ map (docToSDoc . pprInstr) code)) $ do -- pprTrace "pached-fixup" ((ppr fixup_blocks)) $ do@@ -857,7 +851,7 @@ case freeRegs_thisClass of -- case (2): we have a free register (first_free : _) ->- do let final_reg+ do let !final_reg | Just reg <- pref_reg , reg `elem` freeRegs_thisClass = reg
compiler/GHC/CmmToAsm/Reg/Linear/FreeRegs.hs view
@@ -83,5 +83,6 @@ ArchAlpha -> panic "maxSpillSlots ArchAlpha" ArchMipseb -> panic "maxSpillSlots ArchMipseb" ArchMipsel -> panic "maxSpillSlots ArchMipsel"+ ArchRISCV64 -> panic "maxSpillSlots ArchRISCV64" ArchJavaScript-> panic "maxSpillSlots ArchJavaScript" ArchUnknown -> panic "maxSpillSlots ArchUnknown"
compiler/GHC/CmmToAsm/Reg/Linear/State.hs view
@@ -50,6 +50,7 @@ import GHC.Platform import GHC.Types.Unique import GHC.Types.Unique.Supply+import GHC.Exts (oneShot) import Control.Monad (ap) @@ -64,16 +65,21 @@ = RegM { unReg :: RA_State freeRegs -> RA_Result freeRegs a } deriving (Functor) +-- | Smart constructor for 'RegM', as described in Note [The one-shot state+-- monad trick] in GHC.Utils.Monad.+mkRegM :: (RA_State freeRegs -> RA_Result freeRegs a) -> RegM freeRegs a+mkRegM f = RegM (oneShot f)+ instance Applicative (RegM freeRegs) where- pure a = RegM $ \s -> RA_Result s a+ pure a = mkRegM $ \s -> RA_Result s a (<*>) = ap instance Monad (RegM freeRegs) where- m >>= k = RegM $ \s -> case unReg m s of { RA_Result s a -> unReg (k a) s }+ m >>= k = mkRegM $ \s -> case unReg m s of { RA_Result s a -> unReg (k a) s } -- | Get native code generator configuration getConfig :: RegM a NCGConfig-getConfig = RegM $ \s -> RA_Result s (ra_config s)+getConfig = mkRegM $ \s -> RA_Result s (ra_config s) -- | Get target platform from native code generator configuration getPlatform :: RegM a Platform@@ -117,7 +123,7 @@ spillR :: Instruction instr => Reg -> Unique -> RegM freeRegs (instr, Int) -spillR reg temp = RegM $ \s ->+spillR reg temp = mkRegM $ \s -> let (stack1,slot) = getStackSlotFor (ra_stack s) temp instr = mkSpillInstr (ra_config s) reg (ra_delta s) slot in@@ -127,42 +133,42 @@ loadR :: Instruction instr => Reg -> Int -> RegM freeRegs instr -loadR reg slot = RegM $ \s ->+loadR reg slot = mkRegM $ \s -> RA_Result s (mkLoadInstr (ra_config s) reg (ra_delta s) slot) getFreeRegsR :: RegM freeRegs freeRegs-getFreeRegsR = RegM $ \ s@RA_State{ra_freeregs = freeregs} ->+getFreeRegsR = mkRegM $ \ s@RA_State{ra_freeregs = freeregs} -> RA_Result s freeregs setFreeRegsR :: freeRegs -> RegM freeRegs ()-setFreeRegsR regs = RegM $ \ s ->+setFreeRegsR regs = mkRegM $ \ s -> RA_Result s{ra_freeregs = regs} () getAssigR :: RegM freeRegs (RegMap Loc)-getAssigR = RegM $ \ s@RA_State{ra_assig = assig} ->+getAssigR = mkRegM $ \ s@RA_State{ra_assig = assig} -> RA_Result s assig setAssigR :: RegMap Loc -> RegM freeRegs ()-setAssigR assig = RegM $ \ s ->+setAssigR assig = mkRegM $ \ s -> RA_Result s{ra_assig=assig} () getBlockAssigR :: RegM freeRegs (BlockAssignment freeRegs)-getBlockAssigR = RegM $ \ s@RA_State{ra_blockassig = assig} ->+getBlockAssigR = mkRegM $ \ s@RA_State{ra_blockassig = assig} -> RA_Result s assig setBlockAssigR :: BlockAssignment freeRegs -> RegM freeRegs ()-setBlockAssigR assig = RegM $ \ s ->+setBlockAssigR assig = mkRegM $ \ s -> RA_Result s{ra_blockassig = assig} () setDeltaR :: Int -> RegM freeRegs ()-setDeltaR n = RegM $ \ s ->+setDeltaR n = mkRegM $ \ s -> RA_Result s{ra_delta = n} () getDeltaR :: RegM freeRegs Int-getDeltaR = RegM $ \s -> RA_Result s (ra_delta s)+getDeltaR = mkRegM $ \s -> RA_Result s (ra_delta s) getUniqueR :: RegM freeRegs Unique-getUniqueR = RegM $ \s ->+getUniqueR = mkRegM $ \s -> case takeUniqFromSupply (ra_us s) of (uniq, us) -> RA_Result s{ra_us = us} uniq @@ -170,9 +176,9 @@ -- | Record that a spill instruction was inserted, for profiling. recordSpill :: SpillReason -> RegM freeRegs () recordSpill spill- = RegM $ \s -> RA_Result (s { ra_spills = spill : ra_spills s }) ()+ = mkRegM $ \s -> RA_Result (s { ra_spills = spill : ra_spills s }) () -- | Record a created fixup block recordFixupBlock :: BlockId -> BlockId -> BlockId -> RegM freeRegs () recordFixupBlock from between to- = RegM $ \s -> RA_Result (s { ra_fixups = (from,between,to) : ra_fixups s }) ()+ = mkRegM $ \s -> RA_Result (s { ra_fixups = (from,between,to) : ra_fixups s }) ()
compiler/GHC/CmmToAsm/Reg/Target.hs view
@@ -52,6 +52,7 @@ ArchAlpha -> panic "targetVirtualRegSqueeze ArchAlpha" ArchMipseb -> panic "targetVirtualRegSqueeze ArchMipseb" ArchMipsel -> panic "targetVirtualRegSqueeze ArchMipsel"+ ArchRISCV64 -> panic "targetVirtualRegSqueeze ArchRISCV64" ArchJavaScript-> panic "targetVirtualRegSqueeze ArchJavaScript" ArchUnknown -> panic "targetVirtualRegSqueeze ArchUnknown" @@ -71,6 +72,7 @@ ArchAlpha -> panic "targetRealRegSqueeze ArchAlpha" ArchMipseb -> panic "targetRealRegSqueeze ArchMipseb" ArchMipsel -> panic "targetRealRegSqueeze ArchMipsel"+ ArchRISCV64 -> panic "targetRealRegSqueeze ArchRISCV64" ArchJavaScript-> panic "targetRealRegSqueeze ArchJavaScript" ArchUnknown -> panic "targetRealRegSqueeze ArchUnknown" @@ -89,6 +91,7 @@ ArchAlpha -> panic "targetClassOfRealReg ArchAlpha" ArchMipseb -> panic "targetClassOfRealReg ArchMipseb" ArchMipsel -> panic "targetClassOfRealReg ArchMipsel"+ ArchRISCV64 -> panic "targetClassOfRealReg ArchRISCV64" ArchJavaScript-> panic "targetClassOfRealReg ArchJavaScript" ArchUnknown -> panic "targetClassOfRealReg ArchUnknown" @@ -107,6 +110,7 @@ ArchAlpha -> panic "targetMkVirtualReg ArchAlpha" ArchMipseb -> panic "targetMkVirtualReg ArchMipseb" ArchMipsel -> panic "targetMkVirtualReg ArchMipsel"+ ArchRISCV64 -> panic "targetMkVirtualReg ArchRISCV64" ArchJavaScript-> panic "targetMkVirtualReg ArchJavaScript" ArchUnknown -> panic "targetMkVirtualReg ArchUnknown" @@ -125,6 +129,7 @@ ArchAlpha -> panic "targetRegDotColor ArchAlpha" ArchMipseb -> panic "targetRegDotColor ArchMipseb" ArchMipsel -> panic "targetRegDotColor ArchMipsel"+ ArchRISCV64 -> panic "targetRegDotColor ArchRISCV64" ArchJavaScript-> panic "targetRegDotColor ArchJavaScript" ArchUnknown -> panic "targetRegDotColor ArchUnknown"
compiler/GHC/CmmToAsm/X86/CodeGen.hs view
@@ -4,13 +4,6 @@ {-# LANGUAGE NondecreasingIndentation #-} {-# LANGUAGE TupleSections #-} -#if __GLASGOW_HASKELL__ <= 808--- GHC 8.10 deprecates this flag, but GHC 8.8 needs it--- The default iteration limit is a bit too low for the definitions--- in this module.-{-# OPTIONS_GHC -fmax-pmcheck-iterations=10000000 #-}-#endif- {-# OPTIONS_GHC -Wno-incomplete-uni-patterns #-} -----------------------------------------------------------------------------@@ -79,7 +72,7 @@ import GHC.Cmm.Dataflow.Graph import GHC.Cmm.Dataflow.Label import GHC.Cmm.CLabel-import GHC.Core ( Tickish(..) )+import GHC.Types.Tickish ( GenTickish(..) ) import GHC.Types.SrcLoc ( srcSpanFile, srcSpanStartLine, srcSpanStartCol ) -- The rest:
compiler/GHC/CmmToC.hs view
@@ -1304,13 +1304,24 @@ commafy :: [SDoc] -> SDoc commafy xs = hsep $ punctuate comma xs --- Print in C hex format: 0x13fa+-- | Print in C hex format+--+-- Examples:+--+-- 5114 :: W32 ===> ((StgWord32)0x13faU)+-- (-5114) :: W32 ===> ((StgWord32)(-0x13faU))+--+-- We use casts to support types smaller than `unsigned int`; C literal+-- suffixes support longer but not shorter types. pprHexVal :: Platform -> Integer -> Width -> SDoc-pprHexVal platform w rep- | w < 0 = parens (char '-' <>- text "0x" <> intToDoc (-w) <> repsuffix rep)- | otherwise = text "0x" <> intToDoc w <> repsuffix rep+pprHexVal platform w rep = parens ctype <> rawlit where+ rawlit+ | w < 0 = parens (char '-' <>+ text "0x" <> intToDoc (-w) <> repsuffix rep)+ | otherwise = text "0x" <> intToDoc w <> repsuffix rep+ ctype = machRep_U_CType platform rep+ -- type suffix for literals: -- Integer literals are unsigned in Cmm/C. We explicitly cast to -- signed values for doing signed operations, but at all other
compiler/GHC/CmmToLlvm.hs view
@@ -66,7 +66,8 @@ let doWarn = wopt Opt_WarnUnsupportedLlvmVersion dflags when (not (llvmVersionSupported ver) && doWarn) $ putMsg logger dflags $ "You are using an unsupported version of LLVM!" $$- "Currently only " <> text (llvmVersionStr supportedLlvmVersion) <> " is supported." <+>+ "Currently only" <+> text (llvmVersionStr supportedLlvmVersionMin) <+>+ "to" <+> text (llvmVersionStr supportedLlvmVersionMax) <+> "is supported." <+> "System LLVM version: " <> text (llvmVersionStr ver) $$ "We will try though..." let isS390X = platformArch (targetPlatform dflags) == ArchS390X@@ -75,8 +76,14 @@ "Warning: For s390x the GHC calling convention is only supported since LLVM version 10." <+> "You are using LLVM version: " <> text (llvmVersionStr ver) + -- HACK: the Nothing case here is potentially wrong here but we+ -- currently don't use the LLVM version to guide code generation+ -- so this is okay.+ let llvm_ver :: LlvmVersion+ llvm_ver = fromMaybe supportedLlvmVersionMin mb_ver+ -- run code generation- a <- runLlvm logger dflags (fromMaybe supportedLlvmVersion mb_ver) bufh $+ a <- runLlvm logger dflags llvm_ver bufh $ llvmCodeGen' dflags cmm_stream bFlush bufh
compiler/GHC/CmmToLlvm/Base.hs view
@@ -15,7 +15,8 @@ LiveGlobalRegs, LlvmUnresData, LlvmData, UnresLabel, UnresStatic, - LlvmVersion, supportedLlvmVersion, llvmVersionSupported, parseLlvmVersion,+ LlvmVersion, supportedLlvmVersionMin, supportedLlvmVersionMax,+ llvmVersionSupported, parseLlvmVersion, llvmVersionStr, llvmVersionList, LlvmM,@@ -265,6 +266,7 @@ -- Newtype to avoid using the Eq instance! newtype LlvmVersion = LlvmVersion { llvmVersionNE :: NE.NonEmpty Int }+ deriving (Eq, Ord) parseLlvmVersion :: String -> Maybe LlvmVersion parseLlvmVersion =@@ -281,11 +283,13 @@ (ver_str, rest) = span isDigit s -- | The LLVM Version that is currently supported.-supportedLlvmVersion :: LlvmVersion-supportedLlvmVersion = LlvmVersion (sUPPORTED_LLVM_VERSION NE.:| [])+supportedLlvmVersionMin, supportedLlvmVersionMax :: LlvmVersion+supportedLlvmVersionMin = LlvmVersion (sUPPORTED_LLVM_VERSION_MIN NE.:| [])+supportedLlvmVersionMax = LlvmVersion (sUPPORTED_LLVM_VERSION_MAX NE.:| []) llvmVersionSupported :: LlvmVersion -> Bool-llvmVersionSupported (LlvmVersion v) = NE.head v == sUPPORTED_LLVM_VERSION+llvmVersionSupported v =+ v > supportedLlvmVersionMin && v <= supportedLlvmVersionMax llvmVersionStr :: LlvmVersion -> String llvmVersionStr = intercalate "." . map show . llvmVersionList
compiler/GHC/Core/Map/Expr.hs view
@@ -32,6 +32,7 @@ import GHC.Core.Map.Type import GHC.Core import GHC.Core.Type+import GHC.Types.Tickish import GHC.Types.Var import GHC.Utils.Misc@@ -324,11 +325,11 @@ in xtList (xtA env1) as f } -- TODO: this seems a bit dodgy, see 'eqTickish'-type TickishMap a = Map.Map (Tickish Id) a-lkTickish :: Tickish Id -> TickishMap a -> Maybe a+type TickishMap a = Map.Map CoreTickish a+lkTickish :: CoreTickish -> TickishMap a -> Maybe a lkTickish = lookupTM -xtTickish :: Tickish Id -> XT a -> TickishMap a -> TickishMap a+xtTickish :: CoreTickish -> XT a -> TickishMap a -> TickishMap a xtTickish = alterTM ------------------------
compiler/GHC/Core/Opt/CSE.hs view
@@ -18,7 +18,7 @@ import GHC.Core.Subst import GHC.Types.Var ( Var ) import GHC.Types.Var.Env ( mkInScopeSet )-import GHC.Types.Id ( Id, idType, idHasRules+import GHC.Types.Id ( Id, idType, idHasRules, zapStableUnfolding , idInlineActivation, setInlineActivation , zapIdOccInfo, zapIdUsageInfo, idInlinePragma , isJoinId, isJoinId_maybe )@@ -30,6 +30,7 @@ import GHC.Core import GHC.Utils.Outputable import GHC.Types.Basic+import GHC.Types.Tickish import GHC.Core.Map.Expr import GHC.Utils.Misc ( filterOut, equalLength, debugIsOn ) import GHC.Utils.Panic@@ -236,8 +237,8 @@ Nor do we want to change the reverse mapping. Suppose we have - {-# Unf = Stable (\pq. build blah) #-}- foo = <expr>+ foo {-# Unf = Stable (\pq. build blah) #-}+ = <expr> bar = <expr> There could conceivably be merit in rewriting the RHS of bar:@@ -250,6 +251,23 @@ In this case we still want to do CSE (#13340). Hence the use of isAnyInlinePragma rather than isStableUnfolding. +Now consider+ foo = <expr>+ bar {-# Unf = Stable ... #-}+ = <expr>++where the unfolding was added by strictness analysis, say. Then+CSE goes ahead, so we get+ bar = foo+and probably use SUBSTITUTE that will make 'bar' dead. But just+possibly not -- see Note [Dealing with ticks]. In that case we might+be left with+ bar = tick t1 (tick t2 foo)+in which case we would really like to get rid of the stable unfolding+(generated by the strictness analyser, say). Hence the zapStableUnfolding+in cse_bind. Not a big deal, and only makes a difference when ticks+get into the picture.+ Note [Corner case for case expressions] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Here is another reason that we do not use SUBSTITUTE for@@ -389,9 +407,10 @@ | otherwise = (env', (out_id'', out_rhs)) where- (env', out_id') = addBinding env in_id out_id out_rhs- (cse_done, out_rhs) = try_for_cse env in_rhs- out_id'' | cse_done = delayInlining toplevel out_id'+ (env', out_id') = addBinding env in_id out_id out_rhs cse_done+ (cse_done, out_rhs) = try_for_cse env in_rhs+ out_id'' | cse_done = zapStableUnfolding $+ delayInlining toplevel out_id' | otherwise = out_id' delayInlining :: TopLevelFlag -> Id -> Id@@ -409,19 +428,23 @@ | otherwise = bndr -addBinding :: CSEnv -- Includes InId->OutId cloning- -> InVar -- Could be a let-bound type- -> OutId -> OutExpr -- Processed binding- -> (CSEnv, OutId) -- Final env, final bndr+addBinding :: CSEnv -- Includes InId->OutId cloning+ -> InVar -- Could be a let-bound type+ -> OutId -> OutExpr -- Processed binding+ -> Bool -- True <=> RHS was CSE'd and is a variable+ -- or maybe (Tick t variable)+ -> (CSEnv, OutId) -- Final env, final bndr -- Extend the CSE env with a mapping [rhs -> out-id] -- unless we can instead just substitute [in-id -> rhs] -- -- It's possible for the binder to be a type variable (see -- Note [Type-let] in GHC.Core), in which case we can just substitute.-addBinding env in_id out_id rhs'+addBinding env in_id out_id rhs' cse_done | not (isId in_id) = (extendCSSubst env in_id rhs', out_id) | noCSE in_id = (env, out_id) | use_subst = (extendCSSubst env in_id rhs', out_id)+ | cse_done = (env, out_id)+ -- See Note [Dealing with ticks] | otherwise = (extendCSEnv env rhs' id_expr', zapped_id) where id_expr' = varToCoreExpr out_id@@ -438,9 +461,8 @@ -- Should we use SUBSTITUTE or EXTEND? -- See Note [CSE for bindings]- use_subst = case rhs' of- Var {} -> True- _ -> False+ use_subst | Var {} <- rhs' = True+ | otherwise = False -- | Given a binder `let x = e`, this function -- determines whether we should add `e -> x` to the cs_map@@ -487,6 +509,38 @@ This is done by cse_bind. I got it wrong the first time (#13367). +Note [Dealing with ticks]+~~~~~~~~~~~~~~~~~~~~~~~~~+Ticks complicate CSE a bit, as I discovered in the fallout from+fixing #19360.++* To get more CSE-ing, we strip all the tickishFloatable ticks from+ an expression+ - when inserting into the cs_map (see extendCSEnv)+ - when looking up in the cs_map (see call to lookupCSEnv in try_for_cse)+ Quite why only the tickishFloatble ticks, I'm not quite sure.++* If we get a hit in cs_map, we wrap the result in the ticks from the+ thing we are looking up (see try_for_cse)++Net result: if we get a hit, we might replace+ let x = tick t1 (tick t2 e)+with+ let x = tick t1 (tick t2 y)+where 'y' is the variable that 'e' maps to. Now consider addBinding for+the binding for 'x':++* We can't use SUBSTITUTE because those ticks might not be trivial (we+ use tickishIsCode in exprIsTrivial)++* We should not use EXTEND, because we definitely don't want to+ add (tick t1 (tick t2 y)) :-> x+ to the cs_map. Remember we strip off the ticks, so that would amount+ to adding y :-> x, very silly.++TL;DR: we do neither; hence the cse_done case in addBinding.++ Note [Delay inlining after CSE] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Suppose (#15445) we have@@ -603,14 +657,14 @@ combineAlts alt_env (map cse_alt alts) where ty' = substTy (csEnvSubst env) ty- scrut1 = tryForCSE env scrut+ (cse_done, scrut1) = try_for_cse env scrut bndr1 = zapIdOccInfo bndr -- Zapping the OccInfo is needed because the extendCSEnv -- in cse_alt may mean that a dead case binder -- becomes alive, and Lint rejects that (env1, bndr2) = addBinder env bndr1- (alt_env, bndr3) = addBinding env1 bndr bndr2 scrut1+ (alt_env, bndr3) = addBinding env1 bndr bndr2 scrut1 cse_done -- addBinding: see Note [CSE for case expressions] con_target :: OutExpr
compiler/GHC/Core/Opt/CallArity.hs view
@@ -706,7 +706,7 @@ | isDeadEndDiv result_info = length demands | otherwise = a - (demands, result_info) = splitStrictSig (idStrictness v)+ (demands, result_info) = splitDmdSig (idDmdSig v) --------------------------------------- -- Functions related to CallArityRes --
compiler/GHC/Core/Opt/CprAnal.hs view
@@ -21,20 +21,26 @@ import GHC.Utils.Outputable import GHC.Types.Var.Env import GHC.Types.Basic-import GHC.Core.DataCon import GHC.Types.Id import GHC.Types.Id.Info+import GHC.Core.DataCon+import GHC.Core.Multiplicity import GHC.Core.Utils ( exprIsHNF, dumpIdInfoOfProgram ) import GHC.Core.Type import GHC.Core.FamInstEnv import GHC.Core.Opt.WorkWrap.Utils import GHC.Utils.Misc+import GHC.Utils.Panic import GHC.Utils.Logger ( Logger, dumpIfSet_dyn, DumpFormat (..) )-import GHC.Data.Maybe ( isJust, isNothing )+import GHC.Data.Graph.UnVar -- for UnVarSet+import GHC.Data.Maybe ( isNothing ) import Control.Monad ( guard ) import Data.List ( mapAccumL ) +import GHC.Driver.Ppr+_ = pprTrace -- Tired of commenting out the import all the time+ {- Note [Constructed Product Result] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The goal of Constructed Product Result analysis is to identify functions that@@ -108,7 +114,7 @@ let env = emptyAnalEnv fam_envs let binds_plus_cpr = snd $ mapAccumL cprAnalTopBind env binds dumpIfSet_dyn logger dflags Opt_D_dump_cpr_signatures "Cpr signatures" FormatText $- dumpIdInfoOfProgram (ppr . cprInfo) binds_plus_cpr+ dumpIdInfoOfProgram (ppr . cprSigInfo) binds_plus_cpr -- See Note [Stamp out space leaks in demand analysis] in GHC.Core.Opt.DmdAnal seqBinds binds_plus_cpr `seq` return binds_plus_cpr @@ -177,7 +183,8 @@ | otherwise = (lam_ty, Lam var body') where- env' = extendSigEnvForDemand env var (idDemandInfo var)+ -- See Note [CPR for binders that will be unboxed]+ env' = extendSigEnvForArg env var (body_ty, body') = cprAnal env' body lam_ty = abstractCprTy body_ty @@ -185,11 +192,8 @@ = (res_ty, Case scrut' case_bndr ty alts') where (scrut_ty, scrut') = cprAnal env scrut- -- We used to give the case binder the CPR property unconditionally.- -- See Historic Note [Optimistic case binder CPR] env' = extendSigEnv env case_bndr (CprSig scrut_ty)- be_optimistic = assumeOptimisticFieldCpr scrut scrut_ty- (alt_tys, alts') = mapAndUnzip (cprAnalAlt env' be_optimistic) alts+ (alt_tys, alts') = mapAndUnzip (cprAnalAlt env' scrut_ty) alts res_ty = foldl' lubCprType botCprType alt_tys cprAnal' env (Let (NonRec id rhs) body)@@ -206,49 +210,28 @@ cprAnalAlt :: AnalEnv- -> Bool -- ^ Does Note [Optimistic field binder CPR] apply?- -> Alt Var -- ^ current alternative+ -> CprType -- ^ CPR type of the scrutinee+ -> Alt Var -- ^ current alternative -> (CprType, Alt Var)-cprAnalAlt env be_optimistic (Alt con bndrs rhs)+cprAnalAlt env scrut_ty (Alt con bndrs rhs) = (rhs_ty, Alt con bndrs rhs') where env_alt- | DataAlt dc <- con, be_optimistic- -- Optimistically give strictly used field binders the CPR property.- -- See Note [Optimistic field binder CPR].- -- What we actually want here is Nested CPR.- = giveStrictFieldsCpr env dc bndrs+ | DataAlt dc <- con+ , let ids = filter isId bndrs+ , CprType arity cpr <- scrut_ty+ , ASSERT( arity == 0 ) True+ = case unpackConFieldsCpr dc cpr of+ AllFieldsSame field_cpr+ | let sig = mkCprSig 0 field_cpr+ -> extendSigEnvAllSame env ids sig+ ForeachField field_cprs+ | let sigs = zipWith (mkCprSig . idArity) ids field_cprs+ -> extendSigEnvList env (zipEqual "cprAnalAlt" ids sigs) | otherwise = env (rhs_ty, rhs') = cprAnal env_alt rhs -giveStrictFieldsCpr :: AnalEnv -> DataCon -> [Id] -> AnalEnv--- See Note [Optimistic field binder CPR]-giveStrictFieldsCpr env dc bs = foldl' do_one_field env (fields_w_dmds dc bs)- where- -- 'extendSigEnvForDemand' gives 'id' the CPR property if 'dmd' is strict- do_one_field env (id, dmd) = extendSigEnvForDemand env id dmd- fields_w_dmds dc bndrs = -- returns the fields paired with their 'idDemandInfo'- -- See Note [Add demands for strict constructors] in GHC.Core.Opt.WorkWrap.Utils- [ (id, applyWhen (isMarkedStrict mark) strictifyDmd (idDemandInfo id))- | (id, mark) <- filter isId bndrs `zip` dataConRepStrictness dc- ]---- | Decide whether to optimistically give 'DataAlt' field binders the CPR--- property based on strictness.--- Tests (A) and (B) of Note [Optimistic field binder CPR].-assumeOptimisticFieldCpr :: CoreExpr -> CprType -> Bool-assumeOptimisticFieldCpr scrut scrut_ty = is_var scrut && case_will_cancel- where- -- Test (A): The case will only cancel when 'scrut' has the CPR property.- case_will_cancel | CprType 0 cpr <- scrut_ty = isJust (asConCpr cpr)- | otherwise = False- -- Test (B): Guess whether 'scrut' is a parameter. Surely not if it's not a- -- variable!- is_var (Cast e _) = is_var e- is_var (Var v) = isLocalId v- is_var _ = False- -- -- * CPR transformer --@@ -269,7 +252,7 @@ = fst $ cprAnal env rhs -- Imported function or data con worker | isGlobalId id- = getCprSig (idCprInfo id)+ = getCprSig (idCprSig id) | otherwise = topCprType @@ -291,11 +274,11 @@ | otherwise = mkCprSig 0 botCpr -- See Note [Initialising strictness] in GHC.Core.Opt.DmdAnal orig_virgin = ae_virgin orig_env- init_pairs | orig_virgin = [(setIdCprInfo id (init_sig id rhs), rhs) | (id, rhs) <- orig_pairs ]+ init_pairs | orig_virgin = [(setIdCprSig id (init_sig id rhs), rhs) | (id, rhs) <- orig_pairs ] | otherwise = orig_pairs- init_env = extendSigEnvList orig_env (map fst init_pairs)+ init_env = extendSigEnvFromIds orig_env (map fst init_pairs) - -- The fixed-point varies the idCprInfo field of the binders and and their+ -- The fixed-point varies the idCprSig field of the binders and and their -- entries in the AnalEnv, and terminates if that annotation does not change -- any more. loop :: Int -> AnalEnv -> [(Id,CoreExpr)] -> (AnalEnv, [(Id,CoreExpr)])@@ -308,7 +291,7 @@ (env', pairs') = step (applyWhen (n/=1) nonVirgin env) pairs -- Make sure we reset the virgin flag to what it was when we are stable reset_env' = env'{ ae_virgin = orig_virgin }- found_fixpoint = map (idCprInfo . fst) pairs' == map (idCprInfo . fst) pairs+ found_fixpoint = map (idCprSig . fst) pairs' == map (idCprSig . fst) pairs step :: AnalEnv -> [(Id, CoreExpr)] -> (AnalEnv, [(Id, CoreExpr)]) step env pairs = mapAccumL go env pairs@@ -342,7 +325,7 @@ | otherwise = rhs_ty -- See Note [Arity trimming for CPR signatures] sig = mkCprSigForArity (idArity id) rhs_ty'- id' = setIdCprInfo id sig+ id' = setIdCprSig id sig env' = extendSigEnv env id sig -- See Note [CPR for thunks]@@ -413,36 +396,69 @@ -- ^ Needed when expanding type families and synonyms of product types. } -type SigEnv = VarEnv CprSig- instance Outputable AnalEnv where ppr (AE { ae_sigs = env, ae_virgin = virgin }) = text "AE" <+> braces (vcat [ text "ae_virgin =" <+> ppr virgin , text "ae_sigs =" <+> ppr env ]) +-- | An environment storing 'CprSig's for local Ids.+-- Puts binders with 'topCprSig' in a space-saving 'IntSet'.+-- See Note [Efficient Top sigs in SigEnv].+data SigEnv+ = SE+ { se_tops :: !UnVarSet+ -- ^ All these Ids have 'topCprSig'. Like a 'VarSet', but more efficient.+ , se_sigs :: !(VarEnv CprSig)+ -- ^ Ids that have something other than 'topCprSig'.+ }++instance Outputable SigEnv where+ ppr (SE { se_tops = tops, se_sigs = sigs })+ = text "SE" <+> braces (vcat+ [ text "se_tops =" <+> ppr tops+ , text "se_sigs =" <+> ppr sigs ])+ emptyAnalEnv :: FamInstEnvs -> AnalEnv emptyAnalEnv fam_envs = AE- { ae_sigs = emptyVarEnv+ { ae_sigs = SE emptyUnVarSet emptyVarEnv , ae_virgin = True , ae_fam_envs = fam_envs } --- | Extend an environment with the CPR sigs attached to the id-extendSigEnvList :: AnalEnv -> [Id] -> AnalEnv-extendSigEnvList env ids- = env { ae_sigs = sigs' }- where- sigs' = extendVarEnvList (ae_sigs env) [ (id, idCprInfo id) | id <- ids ]+modifySigEnv :: (SigEnv -> SigEnv) -> AnalEnv -> AnalEnv+modifySigEnv f env = env { ae_sigs = f (ae_sigs env) } +lookupSigEnv :: AnalEnv -> Id -> Maybe CprSig+-- See Note [Efficient Top sigs in SigEnv]+lookupSigEnv AE{ae_sigs = SE tops sigs} id+ | id `elemUnVarSet` tops = Just topCprSig+ | otherwise = lookupVarEnv sigs id+ extendSigEnv :: AnalEnv -> Id -> CprSig -> AnalEnv+-- See Note [Efficient Top sigs in SigEnv] extendSigEnv env id sig- = env { ae_sigs = extendVarEnv (ae_sigs env) id sig }+ | isTopCprSig sig+ = modifySigEnv (\se -> se{se_tops = extendUnVarSet id (se_tops se)}) env+ | otherwise+ = modifySigEnv (\se -> se{se_sigs = extendVarEnv (se_sigs se) id sig}) env -lookupSigEnv :: AnalEnv -> Id -> Maybe CprSig-lookupSigEnv env id = lookupVarEnv (ae_sigs env) id+-- | Extend an environment with the (Id, CPR sig) pairs+extendSigEnvList :: AnalEnv -> [(Id, CprSig)] -> AnalEnv+extendSigEnvList env ids_cprs+ = foldl' (\env (id, sig) -> extendSigEnv env id sig) env ids_cprs +-- | Extend an environment with the CPR sigs attached to the ids+extendSigEnvFromIds :: AnalEnv -> [Id] -> AnalEnv+extendSigEnvFromIds env ids+ = foldl' (\env id -> extendSigEnv env id (idCprSig id)) env ids++-- | Extend an environment with the same CPR sig for all ids+extendSigEnvAllSame :: AnalEnv -> [Id] -> CprSig -> AnalEnv+extendSigEnvAllSame env ids sig+ = foldl' (\env id -> extendSigEnv env id sig) env ids+ nonVirgin :: AnalEnv -> AnalEnv nonVirgin env = env { ae_virgin = False } @@ -451,29 +467,63 @@ -- In this case, we can still look at their demand to attach CPR signatures -- anticipating the unboxing done by worker/wrapper. -- See Note [CPR for binders that will be unboxed].-extendSigEnvForDemand :: AnalEnv -> Id -> Demand -> AnalEnv-extendSigEnvForDemand env id dmd- | isId id- , Just (_, DataConPatContext { dcpc_dc = dc })- <- wantToUnbox (ae_fam_envs env) has_inlineable_prag (idType id) dmd- = extendSigEnv env id (CprSig (conCprType (dataConTag dc)))- | otherwise- = env+extendSigEnvForArg :: AnalEnv -> Id -> AnalEnv+extendSigEnvForArg env id+ = extendSigEnv env id (CprSig (argCprType env (idType id) (idDemandInfo id)))++-- | Produces a 'CprType' according to how a strict argument will be unboxed.+-- Examples:+--+-- * A head-strict demand @1L@ on @Int@ would translate to @1@+-- * A product demand @1P(1L,L)@ on @(Int, Bool)@ would translate to @1(1,)@+-- * A product demand @1P(1L,L)@ on @(a , Bool)@ would translate to @1(,)@,+-- because the unboxing strategy would not unbox the @a@.+argCprType :: AnalEnv -> Type -> Demand -> CprType+argCprType env arg_ty dmd = CprType 0 (go arg_ty dmd) where+ go ty dmd+ | Unbox (DataConPatContext { dcpc_dc = dc, dcpc_tc_args = tc_args }) ds+ <- wantToUnbox (ae_fam_envs env) no_inlineable_prag ty dmd+ -- No existentials; see Note [Which types are unboxed?])+ -- Otherwise we'd need to call dataConRepInstPat here and thread a+ -- UniqSupply. So argCprType is a bit less aggressive than it could+ -- be, for the sake of coding convenience.+ , null (dataConExTyCoVars dc)+ , let arg_tys = map scaledThing (dataConInstArgTys dc tc_args)+ = ConCpr (dataConTag dc) (zipWith go arg_tys ds)+ | otherwise+ = topCpr -- Rather than maintaining in AnalEnv whether we are in an INLINEABLE -- function, we just assume that we aren't. That flag is only relevant -- to Note [Do not unpack class dictionaries], the few unboxing -- opportunities on dicts it prohibits are probably irrelevant to CPR.- has_inlineable_prag = False+ no_inlineable_prag = False {- Note [Safe abortion in the fixed-point iteration] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~- Fixed-point iteration may fail to terminate. But we cannot simply give up and return the environment and code unchanged! We still need to do one additional round, to ensure that all expressions have been traversed at least once, and any unsound CPR annotations have been updated. +Note [Efficient Top sigs in SigEnv]+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+It's pretty common for binders in the SigEnv to have a 'topCprSig'.+Wide records with 100 fields like in T9675 even will generate code where the+majority of binders has Top signature. To save some allocations, we store+those binders with a Top signature in a separate UnVarSet (which is an IntSet+with a convenient Var-tailored API).++Why store top signatures at all in the SigEnv? After all, when 'cprTransform'+encounters a locally-bound Id without an entry in the SigEnv, it should behave+as if that binder has a Top signature!+Well, the problem is when case binders should have a Top signatures. They always+have an unfolding and thus look to 'cprTransform' as if they bind a data+structure, Note [CPR for data structures], and thus would always have the CPR+property. So we need some mechanism to separate data structures from case+binders with a Top signature, and the UnVarSet provides that in the least+convoluted way I can think of.+ Note [CPR for binders that will be unboxed] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ If a lambda-bound variable will be unboxed by worker/wrapper (so it must be@@ -496,21 +546,37 @@ f1, and so the boxed version *won't* be available; in that case it's very helpful to give 'x' the CPR property. -This is all done in 'extendSigEnvForDemand'.+This is all done in 'extendSigEnvForArg'. Note that - * We only want to do this for something that definitely unboxes as per- 'wantToUnbox', else we may get over-optimistic CPR results e.g.- (from \x -> x!).+ * Whether or not something unboxes is decided by 'wantToUnbox', else we may+ get over-optimistic CPR results (e.g., from \(x :: a) -> x!). - * This also (approximately) applies to DataAlt field binders;- See Note [Optimistic field binder CPR].+ * If the demand unboxes deeply, we can give the binder a /nested/ CPR+ property, e.g. + g :: (Int, Int) -> Int+ g p = case p of+ (x, y) | x < 0 -> 0+ | otherwise -> x++ `x` should have the CPR property because it will be unboxed. We do so+ by giving `p` the Nested CPR property `1(1,)`, indicating that we not only+ have `p` available unboxed, but also its field `x`. Analysis of the Case+ will then transfer the CPR property to `x`.++ Before we were able to express Nested CPR, we used to guess which field+ binders should get the CPR property.+ See Historic Note [Optimistic field binder CPR].+ * See Note [CPR examples] -Note [Optimistic field binder CPR]-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+Historic Note [Optimistic field binder CPR]+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+This Note describes how we used to guess whether fields have the CPR property+before we were able to express Nested CPR for arguments.+ Consider data T a = MkT a@@ -530,9 +596,6 @@ (A) Flat CPR on the scrutinee (B) A variable scrutinee. Otherwise surely it can't be a parameter. (C) Strict demand on the field binder `y` (or it binds a strict field)--(A) and (B) are tested in 'assumeOptimisticFieldCpr',-(C) in 'giveStrictFieldsCpr' via 'extendSigEnvForDemand'. While (A) is a necessary condition to give a field the CPR property, there are ways in which (B) and (C) are too lax, leading to unsound analysis results and
compiler/GHC/Core/Opt/DmdAnal.hs view
@@ -145,7 +145,7 @@ where e* are exported, but n* are not. Intuitively, we can see that @n1@ is only ever called with two arguments and in every call site, the first component of the result of the call-is evaluated. Thus, we'd like it to have idDemandInfo @UCU(C1(P(SU,A))@.+is evaluated. Thus, we'd like it to have idDemandInfo @LCL(CM(P(1L,A))@. NB: We may *not* give e2 a similar annotation, because it is exported and external callers might use it in arbitrary ways, expressed by 'topDmd'. This can then be exploited by Nested CPR and eta-expansion,@@ -220,7 +220,7 @@ -- -- It calls a function that knows how to analyse this \"body\" given -- an 'AnalEnv' with updated demand signatures for the binding group--- (reflecting their 'idStrictnessInfo') and expects to receive a+-- (reflecting their 'idDmdSigInfo') and expects to receive a -- 'DmdType' in return, which it uses to annotate the binding group with their -- 'idDemandInfo'. dmdAnalBind@@ -313,24 +313,6 @@ -- the vanilla call demand seem to be due to (b). So we don't -- bother to re-analyse the RHS. -{--Note [Ensure demand is strict]-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~-It's important not to analyse e with a lazy demand because-a) When we encounter case s of (a,b) ->- we demand s with U(d1d2)... but if the overall demand is lazy- that is wrong, and we'd need to reduce the demand on s,- which is inconvenient-b) More important, consider- f (let x = R in x+x), where f is lazy- We still want to mark x as demanded, because it will be when we- enter the let. If we analyse f's arg with a Lazy demand, we'll- just mark x as Lazy-c) The application rule wouldn't be right either- Evaluating (f x) in a L demand does *not* cause- evaluation of f in a C(L) demand!--}- -- If e is complicated enough to become a thunk, its contents will be evaluated -- at most once, so oneify it. dmdTransformThunkDmd :: CoreExpr -> Demand -> Demand@@ -357,9 +339,6 @@ -> SubDemand -- The main one takes a *SubDemand* -> CoreExpr -> (DmdType, CoreExpr) --- The SubDemand is always strict and not absent--- See Note [Ensure demand is strict]- dmdAnal env d e = -- pprTrace "dmdAnal" (ppr d <+> ppr e) $ dmdAnal' env d e @@ -649,7 +628,7 @@ see Note [Demand on case-alternative binders] in GHC.Types.Demand. This is crucial. Example: f x = case x of y { (a,b) -> k y a }-If we just take scrut_demand = U(L,A), then we won't pass x to the+If we just take scrut_demand = 1P(L,A), then we won't pass x to the worker, so the worker will rebuild x = (a, absent-error) and that'll crash.@@ -722,11 +701,11 @@ -- See #18429 for some perf measurements. | Just _ <- isClassOpId_maybe var = -- pprTrace "dmdTransform:DictSel" (ppr var $$ ppr dmd) $- dmdTransformDictSelSig (idStrictness var) dmd+ dmdTransformDictSelSig (idDmdSig var) dmd -- Imported functions | isGlobalId var- , let res = dmdTransformSig (idStrictness var) dmd- = -- pprTrace "dmdTransform:import" (vcat [ppr var, ppr (idStrictness var), ppr dmd, ppr res])+ , let res = dmdTransformSig (idDmdSig var) dmd+ = -- pprTrace "dmdTransform:import" (vcat [ppr var, ppr (idDmdSig var), ppr dmd, ppr res]) res -- Top-level or local let-bound thing for which we use LetDown ('useLetUp'). -- In that case, we have a strictness signature to unleash in our AnalEnv.@@ -761,12 +740,12 @@ -- | @dmdAnalRhsSig@ analyses the given RHS to compute a demand signature -- for the LetDown rule. It works as follows: ----- * assuming a demand of <U>+-- * assuming the weakest possible body sub-demand, L -- * looking at the definition -- * determining a strictness signature ----- Since it assumed a demand of <U>, the resulting signature is applicable at--- any call site.+-- Since it assumed a body sub-demand of L, the resulting signature is+-- applicable at any call site. dmdAnalRhsSig :: TopLevelFlag -> RecFlag@@ -793,9 +772,9 @@ (rhs_dmd_ty, rhs') = dmdAnal env rhs_dmd rhs DmdType rhs_fv rhs_dmds rhs_div = rhs_dmd_ty - sig = mkStrictSigForArity rhs_arity (DmdType sig_fv rhs_dmds rhs_div)+ sig = mkDmdSigForArity rhs_arity (DmdType sig_fv rhs_dmds rhs_div) - id' = id `setIdStrictness` sig+ id' = id `setIdDmdSig` sig env' = extendAnalEnv top_lvl env id' sig -- See Note [Aggregated demand for cardinality]@@ -906,10 +885,10 @@ ( B -> j 4 ) ( C -> \y. blah ) -The entire thing is in a C(S) context, so j's strictness signature+The entire thing is in a C1(L) context, so j's strictness signature will be [A]b meaning one absent argument, returns bottom. That seems odd because-there's a \y inside. But it's right because when consumed in a C(1)+there's a \y inside. But it's right because when consumed in a C1(L) context the RHS of the join point is indeed bottom. Note [Demand signatures are computed for a threshold demand based on idArity]@@ -922,7 +901,7 @@ Because idArity of a function varies independently of its cardinality properties (cf. Note [idArity varies independently of dmdTypeDepth]), we implicitly encode the arity for when a demand signature is sound to unleash-in its 'dmdTypeDepth' (cf. Note [Understanding DmdType and StrictSig] in+in its 'dmdTypeDepth' (cf. Note [Understanding DmdType and DmdSig] in GHC.Types.Demand). It is unsound to unleash a demand signature when the incoming number of arguments is less than that. See Note [What are demand signatures?] in GHC.Types.Demand for more details@@ -940,12 +919,12 @@ then \y -> ... y ... else \y -> ... y ... -We'd analyse `f` under a unary call demand C(S), corresponding to idArity+We'd analyse `f` under a unary call demand C1(L), corresponding to idArity being 1. That's enough to look under the manifest lambda and find out how a unary call would use `x`, but not enough to look into the lambdas in the if branches. -On the other hand, if we analysed for call demand C(C(S)), we'd get useful+On the other hand, if we analysed for call demand C1(C1(L)), we'd get useful strictness info for `y` (and more precise info on `x`) and possibly CPR information, but @@ -971,13 +950,13 @@ * idArity is analysis information itself, thus volatile * We already *have* dmdTypeDepth, wo why not just use it to encode the threshold for when to unleash the signature- (cf. Note [Understanding DmdType and StrictSig] in GHC.Types.Demand)+ (cf. Note [Understanding DmdType and DmdSig] in GHC.Types.Demand) Consider the following expression, for example: (let go x y = `x` seq ... in go) |> co -`go` might have a strictness signature of `<S><L>`. The simplifier will identify+`go` might have a strictness signature of `<1L><L>`. The simplifier will identify `go` as a nullary join point through `joinPointBinding_maybe` and float the coercion into the binding, leading to an arity decrease: @@ -1058,11 +1037,11 @@ the Nil case. Partly the Nil case is not a hot path. But more specifically, the whole function gets the CPR property if we do. -That motivated using a demand of C(C(C(S(L,L)))) for the RHS, where+That motivated using a demand of C1(C1(C1(P(L,L)))) for the RHS, where (solely because the result was a product) we used a product demand (albeit with lazy components) for the body. But that gives very silly behaviour -- see #17932. Happily it turns out now to be entirely-unnecessary: we get good results with C(C(C(S))). So I simply+unnecessary: we get good results with C1(C1(C1(L))). So I simply deleted the special case. -} @@ -1083,23 +1062,23 @@ = loop 1 initial_pairs where -- See Note [Initialising strictness]- initial_pairs | ae_virgin env = [(setIdStrictness id botSig, rhs) | (id, rhs) <- orig_pairs ]+ initial_pairs | ae_virgin env = [(setIdDmdSig id botSig, rhs) | (id, rhs) <- orig_pairs ] | otherwise = orig_pairs -- If fixed-point iteration does not yield a result we use this instead -- See Note [Safe abortion in the fixed-point iteration] abort :: (AnalEnv, DmdEnv, [(Id,CoreExpr)]) abort = (env, lazy_fv', zapped_pairs)- where (lazy_fv, pairs') = step True (zapIdStrictness orig_pairs)+ where (lazy_fv, pairs') = step True (zapIdDmdSig orig_pairs) -- Note [Lazy and unleashable free variables]- non_lazy_fvs = plusVarEnvList $ map (strictSigDmdEnv . idStrictness . fst) pairs'+ non_lazy_fvs = plusVarEnvList $ map (dmdSigDmdEnv . idDmdSig . fst) pairs' lazy_fv' = lazy_fv `plusVarEnv` mapVarEnv (const topDmd) non_lazy_fvs- zapped_pairs = zapIdStrictness pairs'+ zapped_pairs = zapIdDmdSig pairs' - -- The fixed-point varies the idStrictness field of the binders, and terminates if that+ -- The fixed-point varies the idDmdSig field of the binders, and terminates if that -- annotation does not change any more. loop :: Int -> [(Id,CoreExpr)] -> (AnalEnv, DmdEnv, [(Id,CoreExpr)])- loop n pairs = -- pprTrace "dmdFix" (ppr n <+> vcat [ ppr id <+> ppr (idStrictness id)+ loop n pairs = -- pprTrace "dmdFix" (ppr n <+> vcat [ ppr id <+> ppr (idDmdSig id) -- | (id,_)<- pairs]) $ loop' n pairs @@ -1108,7 +1087,7 @@ | n == 10 = abort | otherwise = loop (n+1) pairs' where- found_fixpoint = map (idStrictness . fst) pairs' == map (idStrictness . fst) pairs+ found_fixpoint = map (idDmdSig . fst) pairs' == map (idDmdSig . fst) pairs first_round = n == 1 (lazy_fv, pairs') = step first_round pairs final_anal_env = extendAnalEnvs top_lvl env (map fst pairs')@@ -1128,14 +1107,14 @@ -- so this can significantly reduce the number of iterations needed my_downRhs (env, lazy_fv) (id,rhs)- = -- pprTrace "my_downRhs" (ppr id $$ ppr (idStrictness id) $$ ppr sig) $+ = -- pprTrace "my_downRhs" (ppr id $$ ppr (idDmdSig id) $$ ppr sig) $ ((env', lazy_fv'), (id', rhs')) where (env', lazy_fv1, id', rhs') = dmdAnalRhsSig top_lvl Recursive env let_dmd id rhs lazy_fv' = plusVarEnv_C plusDmd lazy_fv lazy_fv1 - zapIdStrictness :: [(Id, CoreExpr)] -> [(Id, CoreExpr)]- zapIdStrictness pairs = [(setIdStrictness id nopSig, rhs) | (id, rhs) <- pairs ]+ zapIdDmdSig :: [(Id, CoreExpr)] -> [(Id, CoreExpr)]+ zapIdDmdSig pairs = [(setIdDmdSig id nopSig, rhs) | (id, rhs) <- pairs ] {- Note [Safe abortion in the fixed-point iteration] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~@@ -1169,7 +1148,7 @@ A g1 -> case (x |> g1) of (p,q) -> ... B -> error "urk" -where A,B are the constructors of a GADT. We'll get a U(U,U) demand+where A,B are the constructors of a GADT. We'll get a 1P(L,L) demand on x from the A branch, but that's a stupid demand for x itself, which has type 'a'. Indeed we get ASSERTs going off (notably in splitUseProdDmd, #8569).@@ -1180,7 +1159,7 @@ f 0 _ = 0 f _ (MkT n t) = f n t -Here f is lazy in T, but its *usage* is infinite: U(U,U(U,U(U, ...))).+Here f is lazy in T, but its *usage* is infinite: P(L,P(L,P(L, ...))). Notice that this happens because T is a product type, and is recrusive. If we are not careful, we'll fail to iterate to a fixpoint in dmdFix, and bale out entirely, which is inefficient and over-conservative.@@ -1221,11 +1200,11 @@ addLazyFVs :: DmdType -> DmdEnv -> DmdType addLazyFVs dmd_ty lazy_fvs = dmd_ty `plusDmdType` mkPlusDmdArg lazy_fvs- -- Using bothDmdType (rather than just both'ing the envs)+ -- Using plusDmdType (rather than just plus'ing the envs) -- is vital. Consider -- let f = \x -> (x,y) -- in error (f 3)- -- Here, y is treated as a lazy-fv of f, but we must `bothDmd` that L+ -- Here, y is treated as a lazy-fv of f, but we must `plusDmd` that L -- demand with the bottom coming up from 'error' -- -- I got a loop in the fixpointer without this, due to an interaction@@ -1400,7 +1379,7 @@ -- The DmdEnv gives the demand on the free vars of the function -- when it is given enough args to satisfy the strictness signature -type SigEnv = VarEnv (StrictSig, TopLevelFlag)+type SigEnv = VarEnv (DmdSig, TopLevelFlag) instance Outputable AnalEnv where ppr env = text "AE" <+> braces (vcat@@ -1427,16 +1406,16 @@ extendSigEnvs :: TopLevelFlag -> SigEnv -> [Id] -> SigEnv extendSigEnvs top_lvl sigs vars- = extendVarEnvList sigs [ (var, (idStrictness var, top_lvl)) | var <- vars]+ = extendVarEnvList sigs [ (var, (idDmdSig var, top_lvl)) | var <- vars] -extendAnalEnv :: TopLevelFlag -> AnalEnv -> Id -> StrictSig -> AnalEnv+extendAnalEnv :: TopLevelFlag -> AnalEnv -> Id -> DmdSig -> AnalEnv extendAnalEnv top_lvl env var sig = env { ae_sigs = extendSigEnv top_lvl (ae_sigs env) var sig } -extendSigEnv :: TopLevelFlag -> SigEnv -> Id -> StrictSig -> SigEnv+extendSigEnv :: TopLevelFlag -> SigEnv -> Id -> DmdSig -> SigEnv extendSigEnv top_lvl sigs var sig = extendVarEnv sigs var (sig, top_lvl) -lookupSigEnv :: AnalEnv -> Id -> Maybe (StrictSig, TopLevelFlag)+lookupSigEnv :: AnalEnv -> Id -> Maybe (DmdSig, TopLevelFlag) lookupSigEnv env id = lookupVarEnv (ae_sigs env) id nonVirgin :: AnalEnv -> AnalEnv@@ -1521,10 +1500,10 @@ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Some of the information that the demand analyser determines is not always preserved by the simplifier. For example, the simplifier will happily rewrite- \y [Demand=1*U] let x = y in x + x+ \y [Demand=MU] let x = y in x + x to- \y [Demand=1*U] y + y-which is quite a lie.+ \y [Demand=MU] y + y+which is quite a lie: Now y occurs more than just once. The once-used information is (currently) only used by the code generator, though. So:@@ -1541,7 +1520,7 @@ This way, correct information finds its way into the module interface (strictness signatures!) and the code generator (single-entry thunks!) -Note that, in contrast, the single-call information (C1(..)) /can/ be+Note that, in contrast, the single-call information (CM(..)) /can/ be relied upon, as the simplifier tends to be very careful about not duplicating actual function calls.
compiler/GHC/Core/Opt/FloatIn.hs view
@@ -34,6 +34,7 @@ import GHC.Types.Basic ( RecFlag(..), isRec ) import GHC.Types.Id ( isOneShotBndr, idType, isJoinId, isJoinId_maybe )+import GHC.Types.Tickish import GHC.Types.Var import GHC.Types.Var.Set
compiler/GHC/Core/Opt/FloatOut.hs view
@@ -22,6 +22,7 @@ import GHC.Utils.Logger ( dumpIfSet_dyn, DumpFormat (..), Logger ) import GHC.Types.Id ( Id, idArity, idType, isDeadEndId, isJoinId, isJoinId_maybe )+import GHC.Types.Tickish import GHC.Core.Opt.SetLevels import GHC.Types.Unique.Supply ( UniqSupply ) import GHC.Data.Bag@@ -738,7 +739,7 @@ where (floats', ceils) = partitionAtJoinCeiling floats -wrapTick :: Tickish Id -> FloatBinds -> FloatBinds+wrapTick :: CoreTickish -> FloatBinds -> FloatBinds wrapTick t (FB tops ceils defns) = FB (mapBag wrap_bind tops) (wrap_defns ceils) (M.map (M.map wrap_defns) defns)
compiler/GHC/Core/Opt/Pipeline.hs view
@@ -70,6 +70,7 @@ import GHC.Types.Demand ( zapDmdEnvSig ) import GHC.Types.Var.Set import GHC.Types.Var.Env+import GHC.Types.Tickish import GHC.Types.Unique.Supply ( UniqSupply ) import GHC.Types.Unique.FM import GHC.Types.Name.Ppr@@ -559,7 +560,7 @@ let rule_fn fn = getRules (RuleEnv rb vis_orphs) fn ++ (mg_rules guts) let ropts = initRuleOpts dflags- liftIO $ putLogMsg logger dflags NoReason Err.SevDump noSrcSpan+ liftIO $ putLogMsg logger dflags Err.MCDump noSrcSpan $ withPprStyle defaultDumpStyle (ruleCheckProgram ropts current_phase pat rule_fn (mg_binds guts))@@ -981,7 +982,7 @@ x_exported, and therefore carry the tick anyway. -} -type IndEnv = IdEnv (Id, [Tickish Var]) -- Maps local_id -> exported_id, ticks+type IndEnv = IdEnv (Id, [CoreTickish]) -- Maps local_id -> exported_id, ticks shortOutIndirections :: CoreProgram -> CoreProgram shortOutIndirections binds@@ -1095,8 +1096,8 @@ , local_id `setInlinePragma` defaultInlinePragma ) where local_info = idInfo local_id- transfer exp_info = exp_info `setStrictnessInfo` strictnessInfo local_info- `setCprInfo` cprInfo local_info+ transfer exp_info = exp_info `setDmdSigInfo` dmdSigInfo local_info+ `setCprSigInfo` cprSigInfo local_info `setUnfoldingInfo` unfoldingInfo local_info `setInlinePragInfo` inlinePragInfo local_info `setRuleInfo` addRuleInfo (ruleInfo exp_info) new_info@@ -1114,6 +1115,6 @@ } binds_plus_dmds = dmdAnalProgram opts fam_envs rules binds Logger.dumpIfSet_dyn logger dflags Opt_D_dump_str_signatures "Strictness signatures" FormatText $- dumpIdInfoOfProgram (ppr . zapDmdEnvSig . strictnessInfo) binds_plus_dmds+ dumpIdInfoOfProgram (ppr . zapDmdEnvSig . dmdSigInfo) binds_plus_dmds -- See Note [Stamp out space leaks in demand analysis] in GHC.Core.Opt.DmdAnal seqBinds binds_plus_dmds `seq` return binds_plus_dmds
compiler/GHC/Core/Opt/SetLevels.hs view
@@ -103,11 +103,12 @@ import GHC.Types.Unique.DSet ( getUniqDSet ) import GHC.Types.Var.Env import GHC.Types.Literal ( litIsTrivial )-import GHC.Types.Demand ( StrictSig, Demand, isStrUsedDmd, splitStrictSig, prependArgsStrictSig )+import GHC.Types.Demand ( DmdSig, Demand, isStrUsedDmd, splitDmdSig, prependArgsDmdSig ) import GHC.Types.Cpr ( mkCprSig, botCpr ) import GHC.Types.Name ( getOccName, mkSystemVarName ) import GHC.Types.Name.Occurrence ( occNameString ) import GHC.Types.Unique ( hasKey )+import GHC.Types.Tickish ( tickishIsCode ) import GHC.Core.Type ( Type, splitTyConApp_maybe, tyCoVarsOfType , mightBeUnliftedType, closeOverKindsDSet ) import GHC.Core.Multiplicity ( pattern Many )@@ -445,7 +446,7 @@ arity = idArity fn stricts :: [Demand] -- True for strict /value/ arguments- stricts = case splitStrictSig (idStrictness fn) of+ stricts = case splitDmdSig (idDmdSig fn) of (arg_ds, _) | arg_ds `lengthExceeds` n_val_args -> [] | otherwise@@ -821,7 +822,7 @@ t = f (g True) If f is lazy, we /do/ float (g True) because then we can allocate the thunk statically rather than dynamically. But if f is strict- we don't (see the use of idStrictness in lvlApp). It's not clear+ we don't (see the use of idDmdSig in lvlApp). It's not clear if this test is worth the bother: it's only about CAFs! It's controlled by a flag (floatConsts), because doing this too@@ -1023,7 +1024,7 @@ -} -annotateBotStr :: Id -> Arity -> Maybe (Arity, StrictSig) -> Id+annotateBotStr :: Id -> Arity -> Maybe (Arity, DmdSig) -> Id -- See Note [Bottoming floats] for why we want to add -- bottoming information right now --@@ -1032,8 +1033,8 @@ = case mb_str of Nothing -> id Just (arity, sig) -> id `setIdArity` (arity + n_extra)- `setIdStrictness` (prependArgsStrictSig n_extra sig)- `setIdCprInfo` mkCprSig (arity + n_extra) botCpr+ `setIdDmdSig` (prependArgsDmdSig n_extra sig)+ `setIdCprSig` mkCprSig (arity + n_extra) botCpr notWorthFloating :: CoreExpr -> [Var] -> Bool -- Returns True if the expression would be replaced by
compiler/GHC/Core/Opt/Simplify.hs view
@@ -5,6 +5,7 @@ -} {-# LANGUAGE CPP #-}+{-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -Wno-incomplete-record-updates -Wno-incomplete-uni-patterns #-} module GHC.Core.Opt.Simplify ( simplTopBinds, simplExpr, simplRules ) where@@ -41,8 +42,8 @@ import GHC.Core import GHC.Builtin.Types.Prim( realWorldStatePrimTy ) import GHC.Builtin.Names( runRWKey )-import GHC.Types.Demand ( StrictSig(..), Demand, dmdTypeDepth, isStrUsedDmd- , mkClosedStrictSig, topDmd, seqDmd, isDeadEndDiv )+import GHC.Types.Demand ( DmdSig(..), Demand, dmdTypeDepth, isStrUsedDmd+ , mkClosedDmdSig, topDmd, seqDmd, isDeadEndDiv ) import GHC.Types.Cpr ( mkCprSig, botCpr ) import GHC.Core.Ppr ( pprCoreExpr ) import GHC.Types.Unique ( hasKey )@@ -58,6 +59,7 @@ import GHC.Types.Basic import GHC.Utils.Monad ( mapAccumLM, liftIO ) import GHC.Utils.Logger+import GHC.Types.Tickish import GHC.Types.Var ( isTyCoVar ) import GHC.Data.Maybe ( orElse ) import Control.Monad@@ -165,6 +167,38 @@ the time: every update to a binder is automatically reflected to its bound occurrences. +Note [Bangs in the Simplifier]+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+Both SimplFloats and SimplEnv do *not* generally benefit from making+their fields strict. I don't know if this is because of good use of+laziness or unintended side effects like closures capturing more variables+after WW has run.++But the end result is that we keep these lazy, but force them in some places+where we know it's beneficial to the compiler.++Similarly environments returned from functions aren't *always* beneficial to+force. In some places they would never be demanded so forcing them early+increases allocation. In other places they almost always get demanded so+it's worthwhile to force them early.++Would it be better to through every allocation of e.g. SimplEnv and decide+wether or not to make this one strict? Absolutely! Would be a good use of+someones time? Absolutely not! I made these strict that showed up during+a profiled build or which I noticed while looking at core for one reason+or another.++The result sadly is that we end up with "random" bangs in the simplifier+where we sometimes force e.g. the returned environment from a function and+sometimes we don't for the same function. Depending on the context around+the call. The treatment is also not very consistent. I only added bangs+where I saw it making a difference either in the core or benchmarks. Some+patterns where it would be beneficial aren't convered as a consequence as+I neither have the time to go through all of the core and some cases are+too small to show up in benchmarks.+++ ************************************************************************ * * \subsection{Bindings}@@ -180,7 +214,8 @@ -- anything into scope, then we don't get a complaint about that. -- It's rather as if the top-level binders were imported. -- See note [Glomming] in "GHC.Core.Opt.OccurAnal".- ; env1 <- {-#SCC "simplTopBinds-simplRecBndrs" #-} simplRecBndrs env0 (bindersOfBinds binds0)+ -- See Note [Bangs in the Simplifier]+ ; !env1 <- {-#SCC "simplTopBinds-simplRecBndrs" #-} simplRecBndrs env0 (bindersOfBinds binds0) ; (floats, env2) <- {-#SCC "simplTopBinds-simpl_binds" #-} simpl_binds env1 binds0 ; freeTick SimplifierDone ; return (floats, env2) }@@ -193,7 +228,9 @@ simpl_binds env [] = return (emptyFloats env, env) simpl_binds env (bind:binds) = do { (float, env1) <- simpl_bind env bind ; (floats, env2) <- simpl_binds env1 binds- ; return (float `addFloats` floats, env2) }+ -- See Note [Bangs in the Simplifier]+ ; let !floats1 = float `addFloats` floats+ ; return (floats1, env2) } simpl_bind env (Rec pairs) = simplRecBind env TopLevel Nothing pairs@@ -294,7 +331,7 @@ = ASSERT( isId bndr ) ASSERT2( not (isJoinId bndr), ppr bndr ) -- pprTrace "simplLazyBind" ((ppr bndr <+> ppr bndr1) $$ ppr rhs $$ ppr (seIdSubst rhs_se)) $- do { let rhs_env = rhs_se `setInScopeFromE` env+ do { let !rhs_env = rhs_se `setInScopeFromE` env -- See Note [Bangs in the Simplifier] (tvs, body) = case collectTyAndValBinders rhs of (tvs, [], body) | surely_not_lam body -> (tvs, body)@@ -542,8 +579,8 @@ ; return (floats, bndr, rhs') } where info = idInfo bndr- worker_info = vanillaIdInfo `setStrictnessInfo` strictnessInfo info- `setCprInfo` cprInfo info+ worker_info = vanillaIdInfo `setDmdSigInfo` dmdSigInfo info+ `setCprSigInfo` cprSigInfo info `setDemandInfo` demandInfo info `setInlinePragInfo` inlinePragInfo info `setArityInfo` arityInfo info@@ -815,18 +852,18 @@ -- eta-expansion *reduces* the arity of the binding to less -- than that of the strictness sig. This can happen: see Note [Arity decrease]. info3 | isEvaldUnfolding new_unf- || (case strictnessInfo info2 of- StrictSig dmd_ty -> new_arity < dmdTypeDepth dmd_ty)+ || (case dmdSigInfo info2 of+ DmdSig dmd_ty -> new_arity < dmdTypeDepth dmd_ty) = zapDemandInfo info2 `orElse` info2 | otherwise = info2 -- Bottoming bindings: see Note [Bottoming bindings]- info4 | isDeadEndDiv div = info3 `setStrictnessInfo` bot_sig- `setCprInfo` bot_cpr+ info4 | isDeadEndDiv div = info3 `setDmdSigInfo` bot_sig+ `setCprSigInfo` bot_cpr | otherwise = info3 - bot_sig = mkClosedStrictSig (replicate new_arity topDmd) div+ bot_sig = mkClosedDmdSig (replicate new_arity topDmd) div bot_cpr = mkCprSig new_arity botCpr -- Zap call arity info. We have used it by now (via@@ -940,7 +977,7 @@ -} simplExpr :: SimplEnv -> CoreExpr -> SimplM CoreExpr-simplExpr env (Type ty)+simplExpr !env (Type ty) -- See Note [Bangs in the Simplifier] = do { ty' <- simplType env ty -- See Note [Avoiding space leaks in OutType] ; return (Type ty') } @@ -971,7 +1008,7 @@ -> SimplCont -> SimplM (SimplFloats, OutExpr) -simplExprF env e cont+simplExprF !env e !cont -- See Note [Bangs in the Simplifier] = {- pprTrace "simplExprF" (vcat [ ppr e , text "cont =" <+> ppr cont@@ -1160,7 +1197,7 @@ -- long as this is a non-scoping tick, to let case and application -- optimisations apply. -simplTick :: SimplEnv -> Tickish Id -> InExpr -> SimplCont+simplTick :: SimplEnv -> CoreTickish -> InExpr -> SimplCont -> SimplM (SimplFloats, OutExpr) simplTick env tickish expr cont -- A scoped tick turns into a continuation, so that we can spot@@ -1244,7 +1281,7 @@ -- do { let (inc,outc) = splitCont cont -- ; (env', expr') <- simplExprF (zapFloats env) expr inc -- ; let tickish' = simplTickish env tickish--- ; let wrap_float (b,rhs) = (zapIdStrictness (setIdArity b 0),+-- ; let wrap_float (b,rhs) = (zapIdDmdSig (setIdArity b 0), -- mkTick (mkNoCount tickish') rhs) -- -- when wrapping a float with mkTick, we better zap the Id's -- -- strictness info and arity, because it might be wrong now.@@ -1254,8 +1291,8 @@ simplTickish env tickish- | Breakpoint n ids <- tickish- = Breakpoint n (map (getDoneId . substId env) ids)+ | Breakpoint ext n ids <- tickish+ = Breakpoint ext n (map (getDoneId . substId env) ids) | otherwise = tickish -- Push type application and coercion inside a tick@@ -1868,24 +1905,33 @@ simplVar :: SimplEnv -> InVar -> SimplM OutExpr -- Look up an InVar in the environment simplVar env var- | isTyVar var = return (Type (substTyVar env var))- | isCoVar var = return (Coercion (substCoVar env var))+ -- Why $! ? See Note [Bangs in the Simplifier]+ | isTyVar var = return $! Type $! (substTyVar env var)+ | isCoVar var = return $! Coercion $! (substCoVar env var) | otherwise = case substId env var of- ContEx tvs cvs ids e -> simplExpr (setSubstEnv env tvs cvs ids) e+ ContEx tvs cvs ids e -> let env' = setSubstEnv env tvs cvs ids+ in simplExpr env' e DoneId var1 -> return (Var var1) DoneEx e _ -> return e simplIdF :: SimplEnv -> InId -> SimplCont -> SimplM (SimplFloats, OutExpr) simplIdF env var cont = case substId env var of- ContEx tvs cvs ids e -> simplExprF (setSubstEnv env tvs cvs ids) e cont- -- Don't trim; haven't already simplified e,- -- so the cont is not embodied in e+ ContEx tvs cvs ids e ->+ let env' = setSubstEnv env tvs cvs ids+ in simplExprF env' e cont+ -- Don't trim; haven't already simplified e,+ -- so the cont is not embodied in e - DoneId var1 -> completeCall env var1 (trimJoinCont var (isJoinId_maybe var1) cont)+ DoneId var1 ->+ let cont' = trimJoinCont var (isJoinId_maybe var1) cont+ in completeCall env var1 cont' - DoneEx e mb_join -> simplExprF (zapSubstEnv env) e (trimJoinCont var mb_join cont)+ DoneEx e mb_join ->+ let env' = zapSubstEnv env+ cont' = trimJoinCont var mb_join cont+ in simplExprF env' e cont' -- Note [zapSubstEnv] -- The template is already simplified, so don't re-substitute. -- This is VITAL. Consider@@ -1906,12 +1952,14 @@ -- Inline the variable's RHS = do { checkedTick (UnfoldingDone var) ; dump_inline expr cont- ; simplExprF (zapSubstEnv env) expr cont }+ ; let env1 = zapSubstEnv env+ ; simplExprF env1 expr cont } | otherwise -- Don't inline; instead rebuild the call = do { rule_base <- getSimplRules- ; let info = mkArgInfo env var (getRules rule_base var)+ ; let rules = getRules rule_base var+ info = mkArgInfo env var rules n_val_args call_cont ; rebuildCall env info cont } @@ -3996,14 +4044,17 @@ = return rule simpl_rule rule@(Rule { ru_bndrs = bndrs, ru_args = args- , ru_fn = fn_name, ru_rhs = rhs })+ , ru_fn = fn_name, ru_rhs = rhs+ , ru_act = act }) = do { (env', bndrs') <- simplBinders env bndrs ; let rhs_ty = substTy env' (exprType rhs) rhs_cont = case mb_cont of -- See Note [Rules and unfolding for join points] Nothing -> mkBoringStop rhs_ty Just cont -> ASSERT2( join_ok, bad_join_msg ) cont- rule_env = updMode updModeForRules env'+ lhs_env = updMode updModeForRules env'+ rhs_env = updMode (updModeForStableUnfoldings act) env'+ -- See Note [Simplifying the RHS of a RULE] fn_name' = case mb_new_id of Just id -> idName id Nothing -> fn_name@@ -4018,9 +4069,18 @@ bad_join_msg = vcat [ ppr mb_new_id, ppr rule , ppr (fmap isJoinId_maybe mb_new_id) ] - ; args' <- mapM (simplExpr rule_env) args- ; rhs' <- simplExprC rule_env rhs rhs_cont+ ; args' <- mapM (simplExpr lhs_env) args+ ; rhs' <- simplExprC rhs_env rhs rhs_cont ; return (rule { ru_bndrs = bndrs' , ru_fn = fn_name' , ru_args = args' , ru_rhs = rhs' }) }++{- Note [Simplifying the RHS of a RULE]+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+We can simplify the RHS of a RULE much as we do the RHS of a stable+unfolding. We used to use the much more conservative updModeForRules+for the RHS as well as the LHS, but that seems more conservative+than necesary. Allowing some inlining might, for example, eliminate+a binding.+-}
compiler/GHC/Core/Opt/Simplify/Env.hs view
@@ -90,7 +90,7 @@ -- Static in the sense of lexically scoped, -- wrt the original expression - seMode :: SimplMode+ seMode :: !SimplMode -- The current substitution , seTvSubst :: TvSubstEnv -- InTyVar |--> OutType@@ -103,7 +103,7 @@ -- The current set of in-scope variables -- They are all OutVars, and all bound in this module- , seInScope :: InScopeSet -- OutVars only+ , seInScope :: !InScopeSet -- OutVars only , seCaseDepth :: !Int -- Depth of multi-branch case alternatives }@@ -325,7 +325,10 @@ setMode mode env = env { seMode = mode } updMode :: (SimplMode -> SimplMode) -> SimplEnv -> SimplEnv-updMode upd env = env { seMode = upd (seMode env) }+updMode upd env+ = -- Avoid keeping env alive in case inlining fails.+ let mode = upd $! (seMode env)+ in env { seMode = mode } bumpCaseDepth :: SimplEnv -> SimplEnv bumpCaseDepth env = env { seCaseDepth = seCaseDepth env + 1 }@@ -363,8 +366,12 @@ addNewInScopeIds :: SimplEnv -> [CoreBndr] -> SimplEnv -- The new Ids are guaranteed to be freshly allocated addNewInScopeIds env@(SimplEnv { seInScope = in_scope, seIdSubst = id_subst }) vs- = env { seInScope = in_scope `extendInScopeSetList` vs,- seIdSubst = id_subst `delVarEnvList` vs }+-- See Note [Bangs in the Simplifier]+ = let !in_scope1 = in_scope `extendInScopeSetList` vs+ !id_subst1 = id_subst `delVarEnvList` vs+ in+ env { seInScope = in_scope1,+ seIdSubst = id_subst1 } -- Why delete? Consider -- let x = a*b in (x, \x -> x+3) -- We add [x |-> a*b] to the substitution, but we must@@ -544,8 +551,8 @@ = SimplFloats { sfLetFloats = unitLetFloat bind , sfJoinFloats = emptyJoinFloats , sfInScope = in_scope' }-- in_scope' = seInScope env `extendInScopeSetBind` bind+ -- See Note [Bangs in the Simplifier]+ !in_scope' = seInScope env `extendInScopeSetBind` bind extendFloats :: SimplFloats -> OutBind -> SimplFloats -- Add this binding to the floats, and extend the in-scope env too@@ -616,10 +623,11 @@ , sfJoinFloats = jfloats' , sfInScope = in_scope } where- floats' | isNilOL bs = emptyLetFloats- | otherwise = unitLetFloat (Rec (flattenBinds (fromOL bs)))- jfloats' | isNilOL jbs = emptyJoinFloats- | otherwise = unitJoinFloat (Rec (flattenBinds (fromOL jbs)))+ -- See Note [Bangs in the Simplifier]+ !floats' | isNilOL bs = emptyLetFloats+ | otherwise = unitLetFloat (Rec (flattenBinds (fromOL bs)))+ !jfloats' | isNilOL jbs = emptyJoinFloats+ | otherwise = unitJoinFloat (Rec (flattenBinds (fromOL jbs))) wrapFloats :: SimplFloats -> OutExpr -> OutExpr -- Wrap the floats around the expression; they should all@@ -649,12 +657,14 @@ = ASSERT( isNilOL jbs ) -- Can't be any top-level join bindings letFloatBinds lbs +{-# INLINE mapLetFloats #-} mapLetFloats :: LetFloats -> ((Id,CoreExpr) -> (Id,CoreExpr)) -> LetFloats mapLetFloats (LetFloats fs ff) fun- = LetFloats (mapOL app fs) ff+ = LetFloats fs1 ff where app (NonRec b e) = case fun (b,e) of (b',e') -> NonRec b' e'- app (Rec bs) = Rec (map fun bs)+ app (Rec bs) = Rec (strictMap fun bs)+ !fs1 = (mapOL' app fs) -- See Note [Bangs in the Simplifier] {- ************************************************************************@@ -748,7 +758,7 @@ -} simplBinders :: SimplEnv -> [InBndr] -> SimplM (SimplEnv, [OutBndr])-simplBinders env bndrs = mapAccumLM simplBinder env bndrs+simplBinders !env bndrs = mapAccumLM simplBinder env bndrs ------------- simplBinder :: SimplEnv -> InBndr -> SimplM (SimplEnv, OutBndr)@@ -757,7 +767,7 @@ -- Return with IdInfo already substituted, but (fragile) occurrence info zapped -- The substitution is extended only if the variable is cloned, because -- we *don't* need to use it to track occurrence info.-simplBinder env bndr+simplBinder !env bndr | isTyVar bndr = do { let (env', tv) = substTyVarBndr env bndr ; seqTyVar tv `seq` return (env', tv) } | otherwise = do { let (env', id) = substIdBndr env bndr@@ -766,16 +776,18 @@ --------------- simplNonRecBndr :: SimplEnv -> InBndr -> SimplM (SimplEnv, OutBndr) -- A non-recursive let binder-simplNonRecBndr env id- = do { let (env1, id1) = substIdBndr env id+simplNonRecBndr !env id+ -- See Note [Bangs in the Simplifier]+ = do { let (!env1, id1) = substIdBndr env id ; seqId id1 `seq` return (env1, id1) } --------------- simplRecBndrs :: SimplEnv -> [InBndr] -> SimplM SimplEnv -- Recursive let binders simplRecBndrs env@(SimplEnv {}) ids+ -- See Note [Bangs in the Simplifier] = ASSERT(all (not . isJoinId) ids)- do { let (env1, ids1) = mapAccumL substIdBndr env ids+ do { let (!env1, ids1) = mapAccumL substIdBndr env ids ; seqIds ids1 `seq` return env1 } @@ -810,6 +822,10 @@ -- all fragile info is zapped substNonCoVarIdBndr env id = subst_id_bndr env id (\x -> x) +-- Inline to make the (OutId -> OutId) function a known call.+-- This is especially important for `substNonCoVarIdBndr` which+-- passes an identity lambda.+{-# INLINE subst_id_bndr #-} subst_id_bndr :: SimplEnv -> InBndr -- Env and binder to transform -> (OutId -> OutId) -- Adjust the type@@ -817,7 +833,7 @@ subst_id_bndr env@(SimplEnv { seInScope = in_scope, seIdSubst = id_subst }) old_id adjust_type = ASSERT2( not (isCoVar old_id), ppr old_id )- (env { seInScope = in_scope `extendInScopeSet` new_id,+ (env { seInScope = new_in_scope, seIdSubst = new_subst }, new_id) -- It's important that both seInScope and seIdSubst are updated with -- the new_id, /after/ applying adjust_type. That's why adjust_type@@ -825,20 +841,23 @@ -- place that gives a non-identity adjust_type) we'd have to fiddle -- afresh with both seInScope and seIdSubst where- id1 = uniqAway in_scope old_id- id2 = substIdType env id1- id3 = zapFragileIdInfo id2 -- Zaps rules, worker-info, unfolding+ -- See Note [Bangs in the Simplifier]+ !id1 = uniqAway in_scope old_id+ !id2 = substIdType env id1+ !id3 = zapFragileIdInfo id2 -- Zaps rules, worker-info, unfolding -- and fragile OccInfo- new_id = adjust_type id3+ !new_id = adjust_type id3 -- Extend the substitution if the unique has changed, -- or there's some useful occurrence information -- See the notes with substTyVarBndr for the delSubstEnv- new_subst | new_id /= old_id+ !new_subst | new_id /= old_id = extendVarEnv id_subst old_id (DoneId new_id) | otherwise = delVarEnv id_subst old_id + !new_in_scope = in_scope `extendInScopeSet` new_id+ ------------------------------------ seqTyVar :: TyVar -> () seqTyVar b = b `seq` ()@@ -947,7 +966,7 @@ orig_ar = idJoinArity join_id orig_ty = idType join_id - new_join_ty = go orig_ar orig_ty+ new_join_ty = go orig_ar orig_ty :: Type go 0 _ = new_res_ty go n ty | Just (arg_bndr, res_ty) <- splitPiTy_maybe ty@@ -956,7 +975,8 @@ | otherwise = pprPanic "adjustJoinPointType" (ppr orig_ar <+> ppr orig_ty) - scale_bndr (Anon af t) = Anon af (scaleScaled mult t)+ -- See Note [Bangs in the Simplifier]+ scale_bndr (Anon af t) = Anon af $! (scaleScaled mult t) scale_bndr b@(Named _) = b {- Note [Scaling join point arguments]
compiler/GHC/Core/Opt/Simplify/Monad.hs view
@@ -5,7 +5,6 @@ \section[GHC.Core.Opt.Simplify.Monad]{The simplifier Monad} -} -{-# LANGUAGE DeriveFunctor #-} module GHC.Core.Opt.Simplify.Monad ( -- The monad SimplM,
compiler/GHC/Core/Opt/Simplify/Utils.hs view
@@ -57,6 +57,7 @@ import GHC.Types.Name import GHC.Types.Id import GHC.Types.Id.Info+import GHC.Types.Tickish import GHC.Types.Var import GHC.Types.Demand import GHC.Types.Var.Set@@ -166,7 +167,7 @@ , sc_cont :: SimplCont } | TickIt -- (TickIt t K)[e] = K[ tick t e ]- (Tickish Id) -- Tick tickish <hole>+ CoreTickish -- Tick tickish <hole> SimplCont type StaticEnv = SimplEnv -- Just the static part is relevant@@ -546,7 +547,7 @@ = vanilla_dmds -- See Note [Do not expose strictness if sm_inline=False] | otherwise = -- add_type_str fun_ty $- case splitStrictSig (idStrictness fun) of+ case splitDmdSig (idDmdSig fun) of (demands, result_info) | not (demands `lengthExceeds` n_val_args) -> -- Enough args, use the strictness given.@@ -883,12 +884,12 @@ updModeForStableUnfoldings :: Activation -> SimplMode -> SimplMode -- See Note [Simplifying inside stable unfoldings]-updModeForStableUnfoldings inline_rule_act current_mode- = current_mode { sm_phase = phaseFromActivation inline_rule_act+updModeForStableUnfoldings unf_act current_mode+ = current_mode { sm_phase = phaseFromActivation unf_act , sm_inline = True , sm_eta_expand = False }- -- sm_eta_expand: see Note [No eta expansion in stable unfoldings]- -- For sm_rules, just inherit; sm_rules might be "off"+ -- sm_eta_expand: see Note [No eta expansion in stable unfoldings]+ -- sm_rules: just inherit; sm_rules might be "off" -- because of -fno-enable-rewrite-rules where phaseFromActivation (ActiveAfter _ n) = Phase n@@ -1254,15 +1255,15 @@ | isExitJoinId bndr = Nothing -- Note [Do not inline exit join points] -- in module Exitify | not (one_occ (idOccInfo bndr)) = Nothing- | not (isStableUnfolding unf) = Just (extend_subst_with rhs)+ | not (isStableUnfolding unf) = Just $! (extend_subst_with rhs) -- Note [Stable unfoldings and preInlineUnconditionally] | not (isInlinePragma inline_prag)- , Just inl <- maybeUnfoldingTemplate unf = Just (extend_subst_with inl)+ , Just inl <- maybeUnfoldingTemplate unf = Just $! (extend_subst_with inl) | otherwise = Nothing where unf = idUnfolding bndr- extend_subst_with inl_rhs = extendIdSubst env bndr (mkContEx rhs_env inl_rhs)+ extend_subst_with inl_rhs = extendIdSubst env bndr $! (mkContEx rhs_env inl_rhs) one_occ IAmDead = True -- Happens in ((\x.1) v) one_occ OneOcc{ occ_n_br = 1@@ -1941,7 +1942,7 @@ abstract subst (NonRec id rhs) = do { (poly_id1, poly_app) <- mk_poly1 tvs_here id ; let (poly_id2, poly_rhs) = mk_poly2 poly_id1 tvs_here rhs'- subst' = GHC.Core.Subst.extendIdSubst subst id poly_app+ !subst' = GHC.Core.Subst.extendIdSubst subst id poly_app ; return (subst', NonRec poly_id2 poly_rhs) } where rhs' = GHC.Core.Subst.substExpr subst rhs
compiler/GHC/Core/Opt/SpecConstr.hs view
@@ -36,7 +36,7 @@ import GHC.Core.Coercion hiding( substCo ) import GHC.Core.Rules import GHC.Core.Type hiding ( substTy )-import GHC.Core.TyCon ( tyConUnique, tyConName )+import GHC.Core.TyCon (TyCon, tyConUnique, tyConName ) import GHC.Core.Multiplicity import GHC.Types.Id import GHC.Core.Ppr ( pprParendExpr )@@ -44,6 +44,7 @@ import GHC.Types.Var.Env import GHC.Types.Var.Set import GHC.Types.Name+import GHC.Types.Tickish import GHC.Types.Basic import GHC.Driver.Session ( DynFlags(..), GeneralFlag( Opt_SpecConstrKeen ) , gopt, hasPprDebug )@@ -64,7 +65,6 @@ import Data.List (nubBy, sortBy, partition) import GHC.Builtin.Names ( specTyConKey ) import GHC.Unit.Module-import GHC.Core.TyCon ( TyCon ) import GHC.Exts( SpecConstrAnnotation(..) ) import Data.Ord( comparing ) @@ -1716,7 +1716,7 @@ -- Usual w/w hack to avoid generating -- a spec_rhs of unlifted type and no args - spec_lam_args_str = handOutStrictnessInformation (fst (splitStrictSig spec_str)) spec_lam_args+ spec_lam_args_str = handOutStrictnessInformation (fst (splitDmdSig spec_str)) spec_lam_args -- Annotate the variables with the strictness information from -- the function (see Note [Strictness information in worker binders]) @@ -1725,8 +1725,8 @@ spec_id = mkLocalId spec_name Many (mkLamTypes spec_lam_args body_ty) -- See Note [Transfer strictness]- `setIdStrictness` spec_str- `setIdCprInfo` topCprSig+ `setIdDmdSig` spec_str+ `setIdCprSig` topCprSig `setIdArity` count isId spec_lam_args `asJoinId_maybe` spec_join_arity spec_str = calcSpecStrictness fn spec_lam_args pats@@ -1757,13 +1757,13 @@ calcSpecStrictness :: Id -- The original function -> [Var] -> [CoreExpr] -- Call pattern- -> StrictSig -- Strictness of specialised thing+ -> DmdSig -- Strictness of specialised thing -- See Note [Transfer strictness] calcSpecStrictness fn qvars pats- = mkClosedStrictSig spec_dmds div+ = mkClosedDmdSig spec_dmds div where spec_dmds = [ lookupVarEnv dmd_env qv `orElse` topDmd | qv <- qvars, isId qv ]- StrictSig (DmdType _ dmds div) = idStrictness fn+ DmdSig (DmdType _ dmds div) = idDmdSig fn dmd_env = go emptyVarEnv dmds pats
compiler/GHC/Core/Opt/Specialise.hs view
@@ -47,11 +47,13 @@ import GHC.Types.Unique.Supply import GHC.Types.Unique.DFM import GHC.Types.Name+import GHC.Types.Tickish import GHC.Types.Id.Make ( voidArgId, voidPrimId ) import GHC.Types.Var ( isLocalVar ) import GHC.Types.Var.Set import GHC.Types.Var.Env import GHC.Types.Id+import GHC.Types.Error import GHC.Utils.Monad ( foldlM ) import GHC.Utils.Misc@@ -801,13 +803,13 @@ tryWarnMissingSpecs dflags callers fn calls_for_fn | wopt Opt_WarnMissedSpecs dflags && not (null callers)- && allCallersInlined = doWarn $ Reason Opt_WarnMissedSpecs- | wopt Opt_WarnAllMissedSpecs dflags = doWarn $ Reason Opt_WarnAllMissedSpecs+ && allCallersInlined = doWarn $ WarningWithFlag Opt_WarnMissedSpecs+ | wopt Opt_WarnAllMissedSpecs dflags = doWarn $ WarningWithFlag Opt_WarnAllMissedSpecs | otherwise = return () where allCallersInlined = all (isAnyInlinePragma . idInlinePragma) callers doWarn reason =- warnMsg reason+ msg (mkMCDiagnostic reason) (vcat [ hang (text ("Could not specialise imported function") <+> quotes (ppr fn)) 2 (vcat [ text "when specialising" <+> quotes (ppr caller) | caller <- callers])@@ -1125,9 +1127,9 @@ ; return (mkLams bndrs (wrapDictBindsE dumped_dbs body'), free_uds) } ---------------specTickish :: SpecEnv -> Tickish Id -> Tickish Id-specTickish env (Breakpoint ix ids)- = Breakpoint ix [ id' | id <- ids, Var id' <- [specVar env id]]+specTickish :: SpecEnv -> CoreTickish -> CoreTickish+specTickish env (Breakpoint ext ix ids)+ = Breakpoint ext ix [ id' | id <- ids, Var id' <- [specVar env id]] -- drop vars from the list if they have a non-variable substitution. -- should never happen, but it's harmless to drop them anyway. specTickish _ other_tickish = other_tickish
compiler/GHC/Core/Opt/WorkWrap.hs view
@@ -511,9 +511,9 @@ where uf_opts = unfoldingOpts dflags fn_info = idInfo fn_id- (wrap_dmds, div) = splitStrictSig (strictnessInfo fn_info)+ (wrap_dmds, div) = splitDmdSig (dmdSigInfo fn_info) - cpr_ty = getCprSig (cprInfo fn_info)+ cpr_ty = getCprSig (cprSigInfo fn_info) -- Arity of the CPR sig should match idArity when it's not a join point. -- See Note [Arity trimming for CPR signatures] in GHC.Core.Opt.CprAnal cpr = ASSERT2( isJoinId fn_id || cpr_ty == topCprType || ct_arty cpr_ty == arityInfo fn_info@@ -584,7 +584,7 @@ where co :: (Int -> Int -> Char) ~ T -Then idArity is 2 (despite the type T), and it can have a StrictSig based on a+Then idArity is 2 (despite the type T), and it can have a DmdSig based on a threshold of 2. But we can't w/w it without a type error. The situation is less grave for PAPs, but the implicit eta expansion caused a@@ -602,7 +602,7 @@ ----------------------splitFun :: DynFlags -> FamInstEnvs -> Id -> IdInfo -> [Demand] -> Divergence -> CprResult -> CoreExpr+splitFun :: DynFlags -> FamInstEnvs -> Id -> IdInfo -> [Demand] -> Divergence -> Cpr -> CoreExpr -> UniqSM [(Id, CoreExpr)] splitFun dflags fam_envs fn_id fn_info wrap_dmds div cpr rhs | isRecordSelector fn_id -- See Note [No worker/wrapper for record selectors]@@ -638,7 +638,7 @@ mkWWBindPair :: DynFlags -> Id -> IdInfo -> Arity- -> CoreExpr -> Unique -> Divergence -> CprResult+ -> CoreExpr -> Unique -> Divergence -> Cpr -> ([Demand], JoinArity, Id -> CoreExpr, Expr CoreBndr -> CoreExpr) -> [(Id, CoreExpr)] mkWWBindPair dflags fn_id fn_info arity rhs work_uniq div cpr@@ -679,11 +679,11 @@ `setIdUnfolding` mkWorkerUnfolding simpl_opts work_fn fn_unfolding -- See Note [Worker-wrapper for INLINABLE functions] - `setIdStrictness` mkClosedStrictSig work_demands div+ `setIdDmdSig` mkClosedDmdSig work_demands div -- Even though we may not be at top level, -- it's ok to give it an empty DmdEnv - `setIdCprInfo` mkCprSig work_arity work_cpr_info+ `setIdCprSig` mkCprSig work_arity work_cpr_info `setIdDemandInfo` worker_demand
compiler/GHC/Core/Opt/WorkWrap/Utils.hs view
@@ -8,7 +8,7 @@ module GHC.Core.Opt.WorkWrap.Utils ( mkWwBodies, mkWWstr, mkWorkerArgs- , DataConPatContext(..), splitArgType_maybe, wantToUnbox+ , DataConPatContext(..), UnboxingDecision(..), splitArgType_maybe, wantToUnbox , findTypeShape , isWorkerSmallEnough )@@ -20,7 +20,7 @@ import GHC.Core import GHC.Core.Utils ( exprType, mkCast, mkDefaultCase, mkSingleAltCase- , dataConRepFSInstPat )+ , bindNonRec, dataConRepFSInstPat ) import GHC.Types.Id import GHC.Types.Id.Info ( JoinArity ) import GHC.Core.DataCon@@ -29,14 +29,14 @@ import GHC.Core.Make ( mkAbsentErrorApp, mkCoreUbxTup , mkCoreApp, mkCoreLet ) import GHC.Types.Id.Make ( voidArgId, voidPrimId )-import GHC.Builtin.Types ( tupleDataCon, unboxedUnitTy )-import GHC.Types.Literal ( absentLiteralOf, rubbishLit )+import GHC.Builtin.Types ( tupleDataCon )+import GHC.Types.Literal ( mkLitRubbish ) import GHC.Types.Var.Env ( mkInScopeSet ) import GHC.Types.Var.Set ( VarSet ) import GHC.Core.Type import GHC.Core.Multiplicity import GHC.Core.Predicate ( isClassPred )-import GHC.Types.RepType ( isVoidTy, typePrimRep )+import GHC.Types.RepType ( isVoidTy, typeMonoPrimRep_maybe ) import GHC.Core.Coercion import GHC.Core.FamInstEnv import GHC.Types.Basic ( Boxity(..) )@@ -135,7 +135,7 @@ -- See Note [Freshen WW arguments] -> Id -- The original function -> [Demand] -- Strictness of original function- -> CprResult -- Info about function result+ -> Cpr -- Info about function result -> UniqSM (Maybe WwResult) -- wrap_fn_args E = \x y -> E@@ -511,105 +511,100 @@ Another tricky case was when f :: forall a. a -> forall a. a->a (i.e. with shadowing), and then the worker used the same 'a' twice.+-} +{- ************************************************************************ * *-\subsection{Strictness stuff}+\subsection{Unboxing Decision for Strictness and CPR} * * ************************************************************************ -} -mkWWstr :: DynFlags- -> FamInstEnvs- -> Bool -- True <=> INLINEABLE pragma on this function defn- -- See Note [Do not unpack class dictionaries]- -> [Var] -- Wrapper args; have their demand info on them- -- *Includes type variables*- -> UniqSM (Bool, -- Is this useful- [Var], -- Worker args- CoreExpr -> CoreExpr, -- Wrapper body, lacking the worker call- -- and without its lambdas- -- This fn adds the unboxing-- CoreExpr -> CoreExpr) -- Worker body, lacking the original body of the function,- -- and lacking its lambdas.- -- This fn does the reboxing-mkWWstr dflags fam_envs has_inlineable_prag args- = go args- where- go_one arg = mkWWstr_one dflags fam_envs has_inlineable_prag arg-- go [] = return (False, [], nop_fn, nop_fn)- go (arg : args) = do { (useful1, args1, wrap_fn1, work_fn1) <- go_one arg- ; (useful2, args2, wrap_fn2, work_fn2) <- go args- ; return ( useful1 || useful2- , args1 ++ args2- , wrap_fn1 . wrap_fn2- , work_fn1 . work_fn2) }--{--Note [Unpacking arguments with product and polymorphic demands]-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~-The argument is unpacked in a case if it has a product type and has a-strict *and* used demand put on it. I.e., arguments, with demands such-as the following ones:-- <S,U(U, L)>- <S(L,S),U>--will be unpacked, but-- <S,U> or <B,U>--will not, because the pieces aren't used. This is quite important otherwise-we end up unpacking massive tuples passed to the bottoming function. Example:-- f :: ((Int,Int) -> String) -> (Int,Int) -> a- f g pr = error (g pr)-- main = print (f fst (1, error "no"))--Does 'main' print "error 1" or "error no"? We don't really want 'f'-to unbox its second argument. This actually happened in GHC's onwn-source code, in Packages.applyPackageFlag, which ended up un-boxing-the enormous DynFlags tuple, and being strict in the-as-yet-un-filled-in unitState files.--}--------------------------- mkWWstr_one wrap_arg = (useful, work_args, wrap_fn, work_fn)--- * wrap_fn assumes wrap_arg is in scope,--- brings into scope work_args (via cases)--- * work_fn assumes work_args are in scope, a--- brings into scope wrap_arg (via lets)--- See Note [How to do the worker/wrapper split]-mkWWstr_one :: DynFlags -> FamInstEnvs- -> Bool -- True <=> INLINEABLE pragma on this function defn- -- See Note [Do not unpack class dictionaries]- -> Var- -> UniqSM (Bool, [Var], CoreExpr -> CoreExpr, CoreExpr -> CoreExpr)-mkWWstr_one dflags fam_envs has_inlineable_prag arg- | isTyVar arg- = return (False, [arg], nop_fn, nop_fn)+-- | The information needed to build a pattern for a DataCon to be unboxed.+-- The pattern can be generated from 'dcpc_dc' and 'dcpc_tc_args' via+-- 'GHC.Core.Utils.dataConRepInstPat'. The coercion 'dcpc_co' is for newtype+-- wrappers.+--+-- If we get @DataConPatContext dc tys co@ for some type @ty@+-- and @dataConRepInstPat ... dc tys = (exs, flds)@, then+--+-- * @dc @exs flds :: T tys@+-- * @co :: T tys ~ ty@+data DataConPatContext+ = DataConPatContext+ { dcpc_dc :: !DataCon+ , dcpc_tc_args :: ![Type]+ , dcpc_co :: !Coercion+ } - | isAbsDmd dmd- , Just work_fn <- mk_absent_let dflags fam_envs arg dmd- -- Absent case. We can't always handle absence for arbitrary- -- unlifted types, so we need to choose just the cases we can- -- (that's what mk_absent_let does)- = return (True, [], nop_fn, work_fn)+-- | If @splitArgType_maybe ty = Just (dc, tys, co)@+-- then @dc \@tys \@_ex_tys (_args::_arg_tys) :: tc tys@+-- and @co :: ty ~ tc tys@+-- where underscore prefixes are holes, e.g. yet unspecified.+--+-- See Note [Which types are unboxed?].+splitArgType_maybe :: FamInstEnvs -> Type -> Maybe DataConPatContext+splitArgType_maybe fam_envs ty+ | let (co, ty1) = topNormaliseType_maybe fam_envs ty+ `orElse` (mkRepReflCo ty, ty)+ , Just (tc, tc_args) <- splitTyConApp_maybe ty1+ , Just con <- tyConSingleAlgDataCon_maybe tc+ = Just DataConPatContext { dcpc_dc = con+ , dcpc_tc_args = tc_args+ , dcpc_co = co }+splitArgType_maybe _ _ = Nothing - | Just (cs, acdc) <- wantToUnbox fam_envs has_inlineable_prag arg_ty dmd- = unbox_one dflags fam_envs arg cs acdc+-- | If @splitResultType_maybe n ty = Just (dc, tys, co)@+-- then @dc \@tys \@_ex_tys (_args::_arg_tys) :: tc tys@+-- and @co :: ty ~ tc tys@+-- where underscore prefixes are holes, e.g. yet unspecified.+-- @dc@ is the @n@th data constructor of @tc@.+--+-- See Note [Which types are unboxed?].+splitResultType_maybe :: FamInstEnvs -> ConTag -> Type -> Maybe DataConPatContext+splitResultType_maybe fam_envs con_tag ty+ | let (co, ty1) = topNormaliseType_maybe fam_envs ty+ `orElse` (mkRepReflCo ty, ty)+ , Just (tc, tc_args) <- splitTyConApp_maybe ty1+ , isDataTyCon tc -- NB: rules out unboxed sums and pairs!+ , let cons = tyConDataCons tc+ , cons `lengthAtLeast` con_tag -- This might not be true if we import the+ -- type constructor via a .hs-boot file (#8743)+ , let con = cons `getNth` (con_tag - fIRST_TAG)+ , null (dataConExTyCoVars con) -- no existentials;+ -- See Note [Which types are unboxed?]+ -- and GHC.Core.Opt.CprAnal.extendEnvForDataAlt+ -- where we also check this.+ , all isLinear (dataConInstArgTys con tc_args)+ -- Deactivates CPR worker/wrapper splits on constructors with non-linear+ -- arguments, for the moment, because they require unboxed tuple with variable+ -- multiplicity fields.+ = Just DataConPatContext { dcpc_dc = con+ , dcpc_tc_args = tc_args+ , dcpc_co = co }+splitResultType_maybe _ _ _ = Nothing - | otherwise -- Other cases- = return (False, [arg], nop_fn, nop_fn)+isLinear :: Scaled a -> Bool+isLinear (Scaled w _ ) =+ case w of+ One -> True+ _ -> False - where- arg_ty = idType arg- dmd = idDemandInfo arg+-- | Describes the outer shape of an argument to be unboxed or left as-is+-- Depending on how @s@ is instantiated (e.g., 'Demand').+data UnboxingDecision s+ = StopUnboxing+ -- ^ We ran out of strictness info. Leave untouched.+ | Unbox !DataConPatContext [s]+ -- ^ The argument is used strictly or the returned product was constructed, so+ -- unbox it.+ -- The 'DataConPatContext' carries the bits necessary for+ -- instantiation with 'dataConRepInstPat'.+ -- The @[s]@ carries the bits of information with which we can continue+ -- unboxing, e.g. @s@ will be 'Demand'. -wantToUnbox :: FamInstEnvs -> Bool -> Type -> Demand -> Maybe ([Demand], DataConPatContext)+wantToUnbox :: FamInstEnvs -> Bool -> Type -> Demand -> UnboxingDecision Demand -- See Note [Which types are unboxed?] wantToUnbox fam_envs has_inlineable_prag ty dmd = case splitArgType_maybe fam_envs ty of@@ -622,8 +617,10 @@ , not (has_inlineable_prag && isClassPred ty) -- See Note [mkWWstr and unsafeCoerce] , cs `lengthIs` arity- -> Just (cs, dcpc)- _ -> Nothing+ -- See Note [Add demands for strict constructors]+ , let cs' = addDataConStrictness dc cs+ -> Unbox dcpc cs'+ _ -> StopUnboxing where split_prod_dmd_arity dmd arity -- For seqDmd, it should behave like <S(AAAA)>, for some@@ -632,111 +629,97 @@ | _ :* Prod ds <- dmd = Just ds | otherwise = Nothing -unbox_one :: DynFlags -> FamInstEnvs -> Var- -> [Demand]- -> DataConPatContext- -> UniqSM (Bool, [Var], CoreExpr -> CoreExpr, CoreExpr -> CoreExpr)-unbox_one dflags fam_envs arg cs- DataConPatContext { dcpc_dc = dc, dcpc_tc_args = tc_args- , dcpc_co = co }- = do { (case_bndr_uniq:pat_bndrs_uniqs) <- getUniquesM- ; let ex_name_fss = map getOccFS $ dataConExTyCoVars dc- (ex_tvs', arg_ids) =- dataConRepFSInstPat (ex_name_fss ++ repeat ww_prefix) pat_bndrs_uniqs (idMult arg) dc tc_args- -- See Note [Add demands for strict constructors]- cs' = addDataConStrictness dc cs- arg_ids' = zipWithEqual "unbox_one" setIdDemandInfo arg_ids cs'- unbox_fn = mkUnpackCase (Var arg) co (idMult arg) case_bndr_uniq- dc (ex_tvs' ++ arg_ids')- arg_no_unf = zapStableUnfolding arg- -- See Note [Zap unfolding when beta-reducing]- -- in GHC.Core.Opt.Simplify; and see #13890- rebox_fn = Let (NonRec arg_no_unf con_app)- con_app = mkConApp2 dc tc_args (ex_tvs' ++ arg_ids') `mkCast` mkSymCo co- ; (_, worker_args, wrap_fn, work_fn) <- mkWWstr dflags fam_envs False (ex_tvs' ++ arg_ids')- ; return (True, worker_args, unbox_fn . wrap_fn, work_fn . rebox_fn) }- -- Don't pass the arg, rebox instead+{- Note [Which types are unboxed?]+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+Worker/wrapper will unbox ------------------------nop_fn :: CoreExpr -> CoreExpr-nop_fn body = body+ 1. A strict data type argument, that+ * is an algebraic data type (not a newtype)+ * has a single constructor (thus is a "product")+ * that may bind existentials+ We can transform+ > f (D @ex a b) = e+ to+ > $wf @ex a b = e+ via 'mkWWstr'. -addDataConStrictness :: DataCon -> [Demand] -> [Demand]--- See Note [Add demands for strict constructors]-addDataConStrictness con ds- = zipWithEqual "addDataConStrictness" add ds strs- where- strs = dataConRepStrictness con- add dmd str | isMarkedStrict str = strictifyDmd dmd- | otherwise = dmd+ 2. The constructed result of a function, if+ * its type is an algebraic data type (not a newtype)+ * (might have multiple constructors, in contrast to (1))+ * the applied data constructor *does not* bind existentials+ We can transform+ > f x y = let ... in D a b+ to+ > $wf x y = let ... in (# a, b #)+ via 'mkWWcpr'. -{- Note [How to do the worker/wrapper split]-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~-The worker-wrapper transformation, mkWWstr_one, takes into account-several possibilities to decide if the function is worthy for-splitting:+ NB: We don't allow existentials for CPR W/W, because we don't have unboxed+ dependent tuples (yet?). Otherwise, we could transform+ > f x y = let ... in D @ex (a :: ..ex..) (b :: ..ex..)+ to+ > $wf x y = let ... in (# @ex, (a :: ..ex..), (b :: ..ex..) #) -1. If an argument is absent, it would be silly to pass it to- the worker. Hence the isAbsDmd case. This case must come- first because a demand like <S,A> or <B,A> is possible.- E.g. <B,A> comes from a function like- f x = error "urk"- and <S,A> can come from Note [Add demands for strict constructors]+The respective tests are in 'splitArgType_maybe' and+'splitResultType_maybe', respectively. -2. If the argument is evaluated strictly, and we can split the- product demand (splitProdDmd_maybe), then unbox it and w/w its- pieces. For example+Note that the data constructor /can/ have evidence arguments: equality+constraints, type classes etc. So it can be GADT. These evidence+arguments are simply value arguments, and should not get in the way. - f :: (Int, Int) -> Int- f p = (case p of (a,b) -> a) + 1- is split to- f :: (Int, Int) -> Int- f p = case p of (a,b) -> $wf a+Note [Unpacking arguments with product and polymorphic demands]+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+The argument is unpacked in a case if it has a product type and has a+strict *and* used demand put on it. I.e., arguments, with demands such+as the following ones: - $wf :: Int -> Int- $wf a = a + 1+ <S,U(U, L)>+ <S(L,S),U> - and- g :: Bool -> (Int, Int) -> Int- g c p = case p of (a,b) ->- if c then a else b- is split to- g c p = case p of (a,b) -> $gw c a b- $gw c a b = if c then a else b+will be unpacked, but -2a But do /not/ split if the components are not used; that is, the- usage is just 'Used' rather than 'UProd'. In this case- splitProdDmd_maybe returns Nothing. Otherwise we risk decomposing- a massive tuple which is barely used. Example:+ <S,U> or <B,U> +will not, because the pieces aren't used. This is quite important otherwise+we end up unpacking massive tuples passed to the bottoming function. Example:+ f :: ((Int,Int) -> String) -> (Int,Int) -> a f g pr = error (g pr) main = print (f fst (1, error "no")) - Here, f does not take 'pr' apart, and it's stupid to do so.- Imagine that it had millions of fields. This actually happened- in GHC itself where the tuple was DynFlags+Does 'main' print "error 1" or "error no"? We don't really want 'f'+to unbox its second argument. This actually happened in GHC's onwn+source code, in Packages.applyPackageFlag, which ended up un-boxing+the enormous DynFlags tuple, and being strict in the+as-yet-un-filled-in unitState files. -3. A plain 'seqDmd', which is head-strict with usage UHead, can't- be split by splitProdDmd_maybe. But we want it to behave just- like U(AAAA) for suitable number of absent demands. So we have- a special case for it, with arity coming from the data constructor.+Note [Do not unpack class dictionaries]+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+If we have+ f :: Ord a => [a] -> Int -> a+ {-# INLINABLE f #-}+and we worker/wrapper f, we'll get a worker with an INLINABLE pragma+(see Note [Worker-wrapper for INLINABLE functions] in GHC.Core.Opt.WorkWrap),+which can still be specialised by the type-class specialiser, something like+ fw :: Ord a => [a] -> Int# -> a -Note [Worker-wrapper for bottoming functions]-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~-We used not to split if the result is bottom.-[Justification: there's no efficiency to be gained.]+BUT if f is strict in the Ord dictionary, we might unpack it, to get+ fw :: (a->a->Bool) -> [a] -> Int# -> a+and the type-class specialiser can't specialise that. An example is #6056. -But it's sometimes bad not to make a wrapper. Consider- fw = \x# -> let x = I# x# in case e of- p1 -> error_fn x- p2 -> error_fn x- p3 -> the real stuff-The re-boxing code won't go away unless error_fn gets a wrapper too.-[We don't do reboxing now, but in general it's better to pass an-unboxed thing to f, and have it reboxed in the error cases....]+But in any other situation a dictionary is just an ordinary value,+and can be unpacked. So we track the INLINABLE pragma, and switch+off the unpacking in mkWWstr_one (see the isClassPred test). +Historical note: #14955 describes how I got this fix wrong the first time.++Note [mkWWstr and unsafeCoerce]+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+By using unsafeCoerce, it is possible to make the number of demands fail to+match the number of constructor arguments; this happened in #8037.+If so, the worker/wrapper split doesn't work right and we get a Core Lint+bug. The fix here is simply to decline to do w/w if that happens.+ Note [Add demands for strict constructors] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider this program (due to Roman):@@ -857,15 +840,184 @@ applying the strictness demands to the final result of DmdAnal. The result is that we get the strict demand signature we wanted even if we can't float the case on `x` up through the case on `burble`.+-} +{-+************************************************************************+* *+\subsection{Strictness stuff}+* *+************************************************************************+-} -Note [mkWWstr and unsafeCoerce]-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~-By using unsafeCoerce, it is possible to make the number of demands fail to-match the number of constructor arguments; this happened in #8037.-If so, the worker/wrapper split doesn't work right and we get a Core Lint-bug. The fix here is simply to decline to do w/w if that happens.+mkWWstr :: DynFlags+ -> FamInstEnvs+ -> Bool -- True <=> INLINEABLE pragma on this function defn+ -- See Note [Do not unpack class dictionaries]+ -> [Var] -- Wrapper args; have their demand info on them+ -- *Includes type variables*+ -> UniqSM (Bool, -- Is this useful+ [Var], -- Worker args+ CoreExpr -> CoreExpr, -- Wrapper body, lacking the worker call+ -- and without its lambdas+ -- This fn adds the unboxing + CoreExpr -> CoreExpr) -- Worker body, lacking the original body of the function,+ -- and lacking its lambdas.+ -- This fn does the reboxing+mkWWstr dflags fam_envs has_inlineable_prag args+ = go args+ where+ go_one arg = mkWWstr_one dflags fam_envs has_inlineable_prag arg++ go [] = return (False, [], nop_fn, nop_fn)+ go (arg : args) = do { (useful1, args1, wrap_fn1, work_fn1) <- go_one arg+ ; (useful2, args2, wrap_fn2, work_fn2) <- go args+ ; return ( useful1 || useful2+ , args1 ++ args2+ , wrap_fn1 . wrap_fn2+ , work_fn1 . work_fn2) }++----------------------+-- mkWWstr_one wrap_arg = (useful, work_args, wrap_fn, work_fn)+-- * wrap_fn assumes wrap_arg is in scope,+-- brings into scope work_args (via cases)+-- * work_fn assumes work_args are in scope, a+-- brings into scope wrap_arg (via lets)+-- See Note [How to do the worker/wrapper split]+mkWWstr_one :: DynFlags -> FamInstEnvs+ -> Bool -- True <=> INLINEABLE pragma on this function defn+ -- See Note [Do not unpack class dictionaries]+ -> Var+ -> UniqSM (Bool, [Var], CoreExpr -> CoreExpr, CoreExpr -> CoreExpr)+mkWWstr_one dflags fam_envs has_inlineable_prag arg+ | isTyVar arg+ = return (False, [arg], nop_fn, nop_fn)++ | isAbsDmd dmd+ , Just work_fn <- mk_absent_let dflags arg dmd+ -- Absent case. We can't always handle absence for rep-polymorphic+ -- types, so we need to choose just the cases we can+ -- (that's what mk_absent_let does)+ = return (True, [], nop_fn, work_fn)++ | Unbox dcpc cs <- wantToUnbox fam_envs has_inlineable_prag arg_ty dmd+ = unbox_one dflags fam_envs arg cs dcpc++ | otherwise -- Other cases+ = return (False, [arg], nop_fn, nop_fn)++ where+ arg_ty = idType arg+ dmd = idDemandInfo arg++unbox_one :: DynFlags -> FamInstEnvs -> Var+ -> [Demand]+ -> DataConPatContext+ -> UniqSM (Bool, [Var], CoreExpr -> CoreExpr, CoreExpr -> CoreExpr)+unbox_one dflags fam_envs arg cs+ DataConPatContext { dcpc_dc = dc, dcpc_tc_args = tc_args+ , dcpc_co = co }+ = do { (case_bndr_uniq:pat_bndrs_uniqs) <- getUniquesM+ ; let ex_name_fss = map getOccFS $ dataConExTyCoVars dc+ (ex_tvs', arg_ids) =+ dataConRepFSInstPat (ex_name_fss ++ repeat ww_prefix) pat_bndrs_uniqs (idMult arg) dc tc_args+ arg_ids' = zipWithEqual "unbox_one" setIdDemandInfo arg_ids cs+ unbox_fn = mkUnpackCase (Var arg) co (idMult arg) case_bndr_uniq+ dc (ex_tvs' ++ arg_ids')+ arg_no_unf = zapStableUnfolding arg+ -- See Note [Zap unfolding when beta-reducing]+ -- in GHC.Core.Opt.Simplify; and see #13890+ rebox_fn = Let (NonRec arg_no_unf con_app)+ con_app = mkConApp2 dc tc_args (ex_tvs' ++ arg_ids') `mkCast` mkSymCo co+ ; (_, worker_args, wrap_fn, work_fn) <- mkWWstr dflags fam_envs False (ex_tvs' ++ arg_ids')+ ; return (True, worker_args, unbox_fn . wrap_fn, work_fn . rebox_fn) }+ -- Don't pass the arg, rebox instead++----------------------+nop_fn :: CoreExpr -> CoreExpr+nop_fn body = body++addDataConStrictness :: DataCon -> [Demand] -> [Demand]+-- See Note [Add demands for strict constructors]+addDataConStrictness con ds+ | Nothing <- dataConWrapId_maybe con+ -- DataCon worker=wrapper. Implies no strict fields, so nothing to do+ = ds+addDataConStrictness con ds+ = zipWithEqual "addDataConStrictness" add ds strs+ where+ strs = dataConRepStrictness con+ add dmd str | isMarkedStrict str = strictifyDmd dmd+ | otherwise = dmd++{- Note [How to do the worker/wrapper split]+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+The worker-wrapper transformation, mkWWstr_one, takes into account+several possibilities to decide if the function is worthy for+splitting:++1. If an argument is absent, it would be silly to pass it to+ the worker. Hence the isAbsDmd case. This case must come+ first because a demand like <S,A> or <B,A> is possible.+ E.g. <B,A> comes from a function like+ f x = error "urk"+ and <S,A> can come from Note [Add demands for strict constructors]++2. If the argument is evaluated strictly, and we can split the+ product demand (splitProdDmd_maybe), then unbox it and w/w its+ pieces. For example++ f :: (Int, Int) -> Int+ f p = (case p of (a,b) -> a) + 1+ is split to+ f :: (Int, Int) -> Int+ f p = case p of (a,b) -> $wf a++ $wf :: Int -> Int+ $wf a = a + 1++ and+ g :: Bool -> (Int, Int) -> Int+ g c p = case p of (a,b) ->+ if c then a else b+ is split to+ g c p = case p of (a,b) -> $gw c a b+ $gw c a b = if c then a else b++2a But do /not/ split if the components are not used; that is, the+ usage is just 'Used' rather than 'UProd'. In this case+ splitProdDmd_maybe returns Nothing. Otherwise we risk decomposing+ a massive tuple which is barely used. Example:++ f :: ((Int,Int) -> String) -> (Int,Int) -> a+ f g pr = error (g pr)++ main = print (f fst (1, error "no"))++ Here, f does not take 'pr' apart, and it's stupid to do so.+ Imagine that it had millions of fields. This actually happened+ in GHC itself where the tuple was DynFlags++3. A plain 'seqDmd', which is head-strict with usage UHead, can't+ be split by splitProdDmd_maybe. But we want it to behave just+ like U(AAAA) for suitable number of absent demands. So we have+ a special case for it, with arity coming from the data constructor.++Note [Worker-wrapper for bottoming functions]+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+We used not to split if the result is bottom.+[Justification: there's no efficiency to be gained.]++But it's sometimes bad not to make a wrapper. Consider+ fw = \x# -> let x = I# x# in case e of+ p1 -> error_fn x+ p2 -> error_fn x+ p3 -> the real stuff+The re-boxing code won't go away unless error_fn gets a wrapper too.+[We don't do reboxing now, but in general it's better to pass an+unboxed thing to f, and have it reboxed in the error cases....]+ Note [Record evaluated-ness in worker/wrapper] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Suppose we have@@ -913,97 +1065,8 @@ Type scrutiny that is specific to demand analysis * * ************************************************************************--Note [Do not unpack class dictionaries]-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~-If we have- f :: Ord a => [a] -> Int -> a- {-# INLINABLE f #-}-and we worker/wrapper f, we'll get a worker with an INLINABLE pragma-(see Note [Worker-wrapper for INLINABLE functions] in GHC.Core.Opt.WorkWrap),-which can still be specialised by the type-class specialiser, something like- fw :: Ord a => [a] -> Int# -> a--BUT if f is strict in the Ord dictionary, we might unpack it, to get- fw :: (a->a->Bool) -> [a] -> Int# -> a-and the type-class specialiser can't specialise that. An example is #6056.--But in any other situation a dictionary is just an ordinary value,-and can be unpacked. So we track the INLINABLE pragma, and switch-off the unpacking in mkWWstr_one (see the isClassPred test).--Historical note: #14955 describes how I got this fix wrong the first time. -} --- | The result of 'splitArgType_maybe' and 'splitResultType_maybe'.------ Both splits--- * Take a type `ty`--- * Succeed with (DataConPatContext dc tys co)--- iff co :: T tys ~ ty--- and `dc` is the appropriate DataCon of `T`--- and `T` is suitable for the kind of split--- (differs for strictness and CPR, see Note [Which types are unboxed?])-data DataConPatContext- = DataConPatContext- { dcpc_dc :: !DataCon- , dcpc_tc_args :: ![Type]- , dcpc_co :: !Coercion- }---- | If @splitArgType_maybe ty = Just (dc, tys, co)@--- then @dc \@tys \@_ex_tys (_args::_arg_tys) :: tc tys@--- and @co :: ty ~ tc tys@--- where underscore prefixes are holes, e.g. yet unspecified.------ See Note [Which types are unboxed?].-splitArgType_maybe :: FamInstEnvs -> Type -> Maybe DataConPatContext-splitArgType_maybe fam_envs ty- | let (co, ty1) = topNormaliseType_maybe fam_envs ty- `orElse` (mkRepReflCo ty, ty)- , Just (tc, tc_args) <- splitTyConApp_maybe ty1- , Just con <- tyConSingleAlgDataCon_maybe tc- = Just DataConPatContext { dcpc_dc = con- , dcpc_tc_args = tc_args- , dcpc_co = co }-splitArgType_maybe _ _ = Nothing---- | If @splitResultType_maybe n ty = Just (dc, tys, co)@--- then @dc \@tys \@_ex_tys (_args::_arg_tys) :: tc tys@--- and @co :: ty ~ tc tys@--- where underscore prefixes are holes, e.g. yet unspecified.--- @dc@ is the @n@th data constructor of @tc@.------ See Note [Which types are unboxed?].-splitResultType_maybe :: FamInstEnvs -> ConTag -> Type -> Maybe DataConPatContext-splitResultType_maybe fam_envs con_tag ty- | let (co, ty1) = topNormaliseType_maybe fam_envs ty- `orElse` (mkRepReflCo ty, ty)- , Just (tc, tc_args) <- splitTyConApp_maybe ty1- , isDataTyCon tc -- NB: rules out unboxed sums and pairs!- , let cons = tyConDataCons tc- , cons `lengthAtLeast` con_tag -- This might not be true if we import the- -- type constructor via a .hs-boot file (#8743)- , let con = cons `getNth` (con_tag - fIRST_TAG)- , null (dataConExTyCoVars con) -- no existentials;- -- See Note [Which types are unboxed?]- -- and GHC.Core.Opt.CprAnal.extendEnvForDataAlt- -- where we also check this.- , all isLinear (dataConInstArgTys con tc_args)- -- Deactivates CPR worker/wrapper splits on constructors with non-linear- -- arguments, for the moment, because they require unboxed tuple with variable- -- multiplicity fields.- = Just DataConPatContext { dcpc_dc = con- , dcpc_tc_args = tc_args- , dcpc_co = co }-splitResultType_maybe _ _ _ = Nothing--isLinear :: Scaled a -> Bool-isLinear (Scaled w _ ) =- case w of- One -> True- _ -> False- findTypeShape :: FamInstEnvs -> Type -> TypeShape -- Uncover the arrow and product shape of a type -- The data type TypeShape is defined in GHC.Types.Demand@@ -1062,43 +1125,7 @@ subst = extendTCvInScopeList (zipTvSubst univ_tvs tc_args) ex_tvs arg_tys = map (substTy subst . scaledThing) (dataConRepArgTys dc) -{- Note [Which types are unboxed?]-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~-Worker/wrapper will unbox-- 1. A strict data type argument, that- * is an algebraic data type (not a newtype)- * has a single constructor (thus is a "product")- * that may bind existentials- We can transform- > f (D @ex a b) = e- to- > $wf @ex a b = e- via 'mkWWstr'.-- 2. The constructed result of a function, if- * its type is an algebraic data type (not a newtype)- * (might have multiple constructors, in contrast to (1))- * the applied data constructor *does not* bind existentials- We can transform- > f x y = let ... in D a b- to- > $wf x y = let ... in (# a, b #)- via 'mkWWcpr'.-- NB: We don't allow existentials for CPR W/W, because we don't have unboxed- dependent tuples (yet?). Otherwise, we could transform- > f x y = let ... in D @ex (a :: ..ex..) (b :: ..ex..)- to- > $wf x y = let ... in (# @ex, (a :: ..ex..), (b :: ..ex..) #)--The respective tests are in 'splitArgType_maybe' and-'splitResultType_maybe', respectively.--Note that the data constructor /can/ have evidence arguments: equality-constraints, type classes etc. So it can be GADT. These evidence-arguments are simply value arguments, and should not get in the way.-+{- ************************************************************************ * * \subsection{CPR stuff}@@ -1118,7 +1145,7 @@ mkWWcpr :: Bool -> FamInstEnvs -> Type -- function body type- -> CprResult -- CPR analysis results+ -> Cpr -- CPR analysis results -> UniqSM (Bool, -- Is w/w'ing useful? CoreExpr -> CoreExpr, -- New wrapper CoreExpr -> CoreExpr, -- New worker@@ -1131,12 +1158,13 @@ | otherwise = case asConCpr cpr of Nothing -> return (False, id, id, body_ty) -- No CPR info- Just con_tag | Just dcpc <- splitResultType_maybe fam_envs con_tag body_ty- -> mkWWcpr_help dcpc- | otherwise- -- See Note [non-algebraic or open body type warning]- -> WARN( True, text "mkWWcpr: non-algebraic or open body type" <+> ppr body_ty )- return (False, id, id, body_ty)+ Just (con_tag, _cprs)+ | Just dcpc <- splitResultType_maybe fam_envs con_tag body_ty+ -> mkWWcpr_help dcpc+ | otherwise+ -- See Note [non-algebraic or open body type warning]+ -> WARN( True, text "mkWWcpr: non-algebraic or open body type" <+> ppr body_ty )+ return (False, id, id, body_ty) mkWWcpr_help :: DataConPatContext -> UniqSM (Bool, CoreExpr -> CoreExpr, CoreExpr -> CoreExpr, Type)@@ -1253,70 +1281,74 @@ * * ************************************************************************ -Note [Absent errors]-~~~~~~~~~~~~~~~~~~~~+Note [Absent fillers]+~~~~~~~~~~~~~~~~~~~~~ Consider- data T = MkT [Int] [Int] ![Int]- f :: T -> Int# -> blah- f ps w = case ps of MkT xs _ _ -> <body mentioning xs>-Then f gets a strictness sig of <S(L,A,A)><A>. We make worker $wf thus: -$wf :: [Int] -> blah-$wf xs = case ps of MkT xs _ _ -> <body mentioning xs>- where- ys = absentError "ys :: [Int]"- zs = LitRubbish True- ps = MkT xs ys zs- w = 0#+ data T = MkT [Int] [Int] ![Int] -- NB: last field is strict+ f :: T -> Int# -> blah+ f ps w = case ps of MkT xs ys zs -> <body mentioning xs> -We make a let-binding for Absent arguments, such as ys and w, that are not even-passed to the worker. They should, of course, never be used. We distinguish four-cases:+Then f gets a strictness sig of <S(L,A,A)><A>. We make a worker $wf thus: -1. Ordinary boxed, lifted arguments, like 'ys' We make a new binding for Ids- that are marked absent, thus- let ys = absentError "ys :: [Int]"- The idea is that this binding will never be used; but if it- buggily is used we'll get a runtime error message.+ $wf :: [Int] -> blah+ $wf xs = case ps of MkT xs _ _ -> <body mentioning xs>+ where+ ys = absentError "ys :: [Int]"+ zs = RUBBISH[LiftedRep] @[Int]+ ps = MkT xs ys zs+ w = RUBBISH[IntRep] @Int# -2. Boxed, lifted types, with a strict demand, like 'zs'. You may ask: how the- demand be both absent and strict? That's exactly what happens for 'zs': it- is not used, so its demand is Absent, but then during w/w, in- addDataConStrictness, we strictify the demand. So it gets cardinality C_10,- the empty interval.+The absent arguments 'ys', 'zs' and 'w' aren't even passed to the worker.+And neither should they! They are never used, their value is irrelevant (hence+they are *dead code*) and they are probably discarded after the next run of the+Simplifier (when they are in fact *unreachable code*). Yet, we have to come up+with "filler" values that we bind the absent arg Ids to. - We don't want to use an error-thunk for 'zs' because MkT's third argument has- a bang, and hence should be always evaluated. This turned out to be- important when fixing #16970, which establishes the invariant that strict- constructor arguments are always evaluated. So we use LitRubbish instead- of an error thunk -- see #19133.+That is exactly what Note [Rubbish values] are for: A convenient way to+conjure filler values at any type (and any representation or levity!). - These first two cases are distinguished by isStrictDmd in lifted_rhs.+Needless to say, there are some wrinkles: -3. Unboxed types, like 'w', with a type like Float#, Int#. Coping with absence- for unboxed types is important; see, for example, #4306 and #15627. We- simply find a suitable literal, using Literal.absentLiteralOf. We don't have- literals for every primitive type, so the function is partial.+ 1. In case we have a absent, /lazy/, and /lifted/ arg, we use an error-thunk+ instead. If absence analysis was wrong (e.g., #11126) and the binding+ in fact is used, then we get a nice panic message instead of undefined+ runtime behavior (See Modes of failure from Note [Rubbish values]). -4. Boxed, unlifted types, like (Array# t). We can't use absentError because- unlifted bindings ares strict. So we use LitRubbish, which we need to apply- to the required type.+ Obviously, we can't use an error-thunk if the value is of unlifted rep+ (like 'Int#' or 'MutVar#'), because we'd immediately evaluate the panic. -Case (2) and (4) crucially use LitRubbish as the placeholder: see Note [Rubbish-literals] in GHC.Types.Literal. We could do that in case (1) as well, but we-get slightly better self-checking with an error thunk.+ 2. We also mustn't put an error-thunk (that fills in for an absent value of+ lifted rep) in a strict field, because #16970 establishes the invariant+ that strict fields are always evaluated, by (re-)evaluating what is put in+ a strict field. That's the reason why 'zs' binds a rubbish literal instead+ of an error-thunk, see #19133. -Suppose we use LitRubbish and absence analysis is Wrong, so that the "absent"-value is used after all. Then in case (2) we could get a seg-fault, because we-may have replaced, say, a [Either Int Bool] by (), and that will fail if we do-case analysis on it. Similarly with boxed unlifted types, case (4).+ How do we detect when we are about to put an error-thunk in a strict field?+ Ideally, we'd just look at the 'StrictnessMark' of the DataCon's field, but+ it's quite nasty to thread the marks though 'mkWWstr' and 'mkWWstr_one'.+ So we rather look out for a necessary condition for strict fields:+ Note [Add demands for strict constructors] makes it so that the demand on+ 'zs' is absent and /strict/: It will get cardinality 'C_10', the empty+ interval, rather than 'C_00'. Hence the 'isStrictDmd' check: It guarantees+ we never fill in an error-thunk for an absent strict field.+ But that also means we emit a rubbish lit for other args that have+ cardinality 'C_10' (say, the arg to a bottoming function) where we could've+ used an error-thunk, but that's a small price to pay for simplicity. -In case (3), if absence analysis is wrong we could conceivably get an exception,-from a divide-by-zero with the absent value. But it's very unlikely.+ 3. We can only emit a RubbishLit if the arg's type @arg_ty@ is mono-rep, e.g.+ of the form @TYPE rep@ where @rep@ is not (and doesn't contain) a variable.+ Why? Because if we don't know its representation (e.g. size in memory,+ register class), we don't know what or how much rubbish to emit in codegen.+ 'typeMonoPrimRep_maybe' returns 'Nothing' in this case and we simply fall+ back to passing the original parameter to the worker. -Only in case (1) can we guarantee a civilised runtime error. Not much we can do-about this; we really rely on absence analysis to be correct.+ Note that currently this case should not occur, because binders always+ have to be representation monomorphic. But in the future, we might allow+ levity polymorphism, e.g. a polymorphic levity variable in 'BoxedRep'. +While (1) and (2) are simply an optimisation in terms of compiler debugging+experience, (3) should be irrelevant in most programs, if not all. Historical note: I did try the experiment of using an error thunk for unlifted things too, relying on the simplifier to drop it as dead code. But this is@@ -1340,66 +1372,46 @@ -- -- If @mk_absent_let _ id == Just wrap@, then @wrap e@ will wrap a let binding -- for @id@ with that RHS around @e@. Otherwise, there could no suitable RHS be--- found (currently only happens for bindings of 'VecRep' representation).-mk_absent_let :: DynFlags -> FamInstEnvs -> Id -> Demand -> Maybe (CoreExpr -> CoreExpr)-mk_absent_let dflags fam_envs arg dmd-- -- The lifted case: Bind 'absentError'- -- See Note [Absent errors]- | not (isUnliftedType arg_ty)- = Just (Let (NonRec lifted_arg lifted_rhs))- -- The 'UnliftedRep' (because polymorphic) case: Bind @__RUBBISH \@arg_ty@- -- See Note [Absent errors]-- | [UnliftedRep] <- typePrimRep arg_ty- = Just (Let (NonRec arg unlifted_rhs))-- -- The monomorphic unlifted cases: Bind to some literal, if possible- -- See Note [Absent errors]- | Just tc <- tyConAppTyCon_maybe nty- , Just lit <- absentLiteralOf tc- = Just (Let (NonRec arg (Lit lit `mkCast` mkSymCo co)))+-- found.+mk_absent_let :: DynFlags -> Id -> Demand -> Maybe (CoreExpr -> CoreExpr)+mk_absent_let dflags arg dmd+ -- The lifted case: Bind 'absentError' for a nice panic message if we are+ -- wrong (like we were in #11126). See (1) in Note [Absent fillers]+ | Just [LiftedRep] <- mb_mono_prim_reps+ , not (isStrictDmd dmd) -- See (2) in Note [Absent fillers]+ = Just (Let (NonRec arg panic_rhs)) - | nty `eqType` unboxedUnitTy- = Just (Let (NonRec arg (Var voidPrimId `mkCast` mkSymCo co)))+ -- The default case for mono rep: Bind @RUBBISH[prim_reps] \@arg_ty@+ -- See Note [Absent fillers], the main part+ | Just prim_reps <- mb_mono_prim_reps+ = Just (bindNonRec arg (mkTyApps (Lit (mkLitRubbish prim_reps)) [arg_ty])) - | otherwise+ -- Catch all: Either @arg_ty@ wasn't of form @TYPE rep@ or @rep@ wasn't mono rep.+ -- See (3) in Note [Absent fillers]+ | Nothing <- mb_mono_prim_reps = WARN( True, text "No absent value for" <+> ppr arg_ty )- Nothing -- Can happen for 'State#' and things of 'VecRep'+ Nothing where- lifted_arg = arg `setIdStrictness` botSig `setIdCprInfo` mkCprSig 0 botCpr- -- Note in strictness signature that this is bottoming- -- (for the sake of the "empty case scrutinee not known to- -- diverge for sure lint" warning)-- lifted_rhs | isStrictDmd dmd = mkTyApps (Lit (rubbishLit True)) [arg_ty]- | otherwise = mkAbsentErrorApp arg_ty msg- unlifted_rhs = mkTyApps (Lit (rubbishLit False)) [arg_ty]-- arg_ty = idType arg+ arg_ty = idType arg+ mb_mono_prim_reps = typeMonoPrimRep_maybe arg_ty - -- Normalise the type to have best chance of finding an absent literal- -- e.g. (#17852) data unlifted N = MkN Int#- -- f :: N -> a -> a- -- f _ x = x- (co, nty) = topNormaliseType_maybe fam_envs arg_ty- `orElse` (mkRepReflCo arg_ty, arg_ty)+ panic_rhs = mkAbsentErrorApp arg_ty msg - msg = showSDoc (gopt_set dflags Opt_SuppressUniques)- (vcat- [ text "Arg:" <+> ppr arg- , text "Type:" <+> ppr arg_ty- , file_msg- ])- file_msg = case outputFile dflags of- Nothing -> empty- Just f -> text "In output file " <+> quotes (text f)+ msg = showSDoc (gopt_set dflags Opt_SuppressUniques)+ (vcat+ [ text "Arg:" <+> ppr arg+ , text "Type:" <+> ppr arg_ty+ , file_msg+ ]) -- We need to suppress uniques here because otherwise they'd -- end up in the generated code as strings. This is bad for -- determinism, because with different uniques the strings -- will have different lengths and hence different costs for -- the inliner leading to different inlining. -- See also Note [Unique Determinism] in GHC.Types.Unique+ file_msg = case outputFile dflags of+ Nothing -> empty+ Just f -> text "In output file " <+> quotes (text f) ww_prefix :: FastString ww_prefix = fsLit "ww"
compiler/GHC/Core/Rules.hs view
@@ -58,6 +58,7 @@ import GHC.Types.Name.Set import GHC.Types.Name.Env import GHC.Types.Unique.FM+import GHC.Types.Tickish import GHC.Core.Unify as Unify ( ruleMatchTyKiX ) import GHC.Types.Basic import GHC.Driver.Session ( DynFlags, gopt, targetPlatform, homeUnitId_ )
compiler/GHC/Core/Tidy.hs view
@@ -30,6 +30,7 @@ import GHC.Types.Unique.FM import GHC.Types.Name hiding (tidyNameOcc) import GHC.Types.SrcLoc+import GHC.Types.Tickish import GHC.Data.Maybe import Data.List (mapAccumL) @@ -88,8 +89,9 @@ (Alt con vs (tidyExpr env' rhs)) ------------ Tickish ---------------tidyTickish :: TidyEnv -> Tickish Id -> Tickish Id-tidyTickish env (Breakpoint ix ids) = Breakpoint ix (map (tidyVarOcc env) ids)+tidyTickish :: TidyEnv -> CoreTickish -> CoreTickish+tidyTickish env (Breakpoint ext ix ids)+ = Breakpoint ext ix (map (tidyVarOcc env) ids) tidyTickish _ other_tickish = other_tickish ------------ Rules --------------@@ -206,7 +208,7 @@ new_info = vanillaIdInfo `setOccInfo` occInfo old_info `setArityInfo` arityInfo old_info- `setStrictnessInfo` zapDmdEnvSig (strictnessInfo old_info)+ `setDmdSigInfo` zapDmdEnvSig (dmdSigInfo old_info) `setDemandInfo` demandInfo old_info `setInlinePragInfo` inlinePragInfo old_info `setUnfoldingInfo` new_unf
− compiler/GHC/CoreToByteCode.hs
@@ -1,2116 +0,0 @@-{-# LANGUAGE CPP #-}-{-# LANGUAGE DeriveFunctor #-}-{-# LANGUAGE GeneralizedNewtypeDeriving #-}-{-# LANGUAGE RecordWildCards #-}--{-# OPTIONS_GHC -fprof-auto-top #-}-{-# OPTIONS_GHC -Wno-incomplete-uni-patterns #-}------- (c) The University of Glasgow 2002-2006------- | GHC.CoreToByteCode: Generate bytecode from Core-module GHC.CoreToByteCode ( UnlinkedBCO, byteCodeGen, coreExprToBCOs ) where--#include "GhclibHsVersions.h"--import GHC.Prelude--import GHC.Driver.Session-import GHC.Driver.Env--import GHC.ByteCode.Instr-import GHC.ByteCode.Asm-import GHC.ByteCode.Types--import GHC.Platform-import GHC.Platform.Profile--import GHC.Runtime.Interpreter-import GHCi.FFI-import GHCi.RemoteTypes-import GHC.Types.Basic-import GHC.Utils.Outputable-import GHC.Types.Name-import GHC.Types.Id.Make-import GHC.Types.Id-import GHC.Types.ForeignCall-import GHC.Core.Utils-import GHC.Core-import GHC.Core.Ppr-import GHC.Types.Literal-import GHC.Builtin.PrimOps-import GHC.Core.FVs-import GHC.Core.Type-import GHC.Types.RepType-import GHC.Core.DataCon-import GHC.Core.TyCon-import GHC.Utils.Misc-import GHC.Utils.Logger-import GHC.Types.Var.Set-import GHC.Builtin.Types ( unboxedUnitTy )-import GHC.Builtin.Types.Prim-import GHC.Core.TyCo.Ppr ( pprType )-import GHC.Utils.Error-import GHC.Types.Unique-import GHC.Builtin.Uniques-import GHC.Data.FastString-import GHC.Utils.Panic-import GHC.StgToCmm.Closure ( NonVoid(..), fromNonVoid, nonVoidIds )-import GHC.StgToCmm.Layout-import GHC.Runtime.Heap.Layout hiding (WordOff, ByteOff, wordsToBytes)-import GHC.Data.Bitmap-import GHC.Data.OrdList-import GHC.Data.Maybe-import GHC.Types.Var.Env-import GHC.Builtin.Names ( unsafeEqualityProofName )--import Data.List ( genericReplicate, genericLength, intersperse- , partition, scanl', sort, sortBy, zip4, zip6, nub )-import Foreign-import Control.Monad-import Data.Char--import GHC.Types.Unique.Supply-import GHC.Unit.Module--import Control.Exception-import Data.Array-import Data.Coerce (coerce)-import Data.ByteString (ByteString)-import Data.Map (Map)-import Data.IntMap (IntMap)-import qualified Data.Map as Map-import qualified Data.IntMap as IntMap-import qualified GHC.Data.FiniteMap as Map-import Data.Ord-import GHC.Stack.CCS-import Data.Either ( partitionEithers )---- -------------------------------------------------------------------------------- Generating byte code for a complete module--byteCodeGen :: HscEnv- -> Module- -> CoreProgram- -> [TyCon]- -> Maybe ModBreaks- -> IO CompiledByteCode-byteCodeGen hsc_env this_mod binds tycs mb_modBreaks- = withTiming logger dflags- (text "GHC.CoreToByteCode"<+>brackets (ppr this_mod))- (const ()) $ do- -- Split top-level binds into strings and others.- -- See Note [generating code for top-level string literal bindings].- let (strings, flatBinds) = partitionEithers $ do -- list monad- (bndr, rhs) <- flattenBinds binds- return $ case exprIsTickedString_maybe rhs of- Just str -> Left (bndr, str)- _ -> Right (bndr, simpleFreeVars rhs)- stringPtrs <- allocateTopStrings hsc_env strings-- us <- mkSplitUniqSupply 'y'- (BcM_State{..}, proto_bcos) <-- runBc hsc_env us this_mod mb_modBreaks (mkVarEnv stringPtrs) $- mapM schemeTopBind flatBinds-- when (notNull ffis)- (panic "GHC.CoreToByteCode.byteCodeGen: missing final emitBc?")-- dumpIfSet_dyn logger dflags Opt_D_dump_BCOs- "Proto-BCOs" FormatByteCode- (vcat (intersperse (char ' ') (map ppr proto_bcos)))-- cbc <- assembleBCOs hsc_env proto_bcos tycs (map snd stringPtrs)- (case modBreaks of- Nothing -> Nothing- Just mb -> Just mb{ modBreaks_breakInfo = breakInfo })-- -- Squash space leaks in the CompiledByteCode. This is really- -- important, because when loading a set of modules into GHCi- -- we don't touch the CompiledByteCode until the end when we- -- do linking. Forcing out the thunks here reduces space- -- usage by more than 50% when loading a large number of- -- modules.- evaluate (seqCompiledByteCode cbc)-- return cbc-- where dflags = hsc_dflags hsc_env- logger = hsc_logger hsc_env--allocateTopStrings- :: HscEnv- -> [(Id, ByteString)]- -> IO [(Var, RemotePtr ())]-allocateTopStrings hsc_env topStrings = do- let !(bndrs, strings) = unzip topStrings- ptrs <- iservCmd hsc_env $ MallocStrings strings- return $ zip bndrs ptrs--{--Note [generating code for top-level string literal bindings]--Here is a summary on how the byte code generator deals with top-level string-literals:--1. Top-level string literal bindings are separated from the rest of the module.--2. The strings are allocated via iservCmd, in allocateTopStrings--3. The mapping from binders to allocated strings (topStrings) are maintained in- BcM and used when generating code for variable references.--}---- -------------------------------------------------------------------------------- Generating byte code for an expression---- Returns: the root BCO for this expression-coreExprToBCOs :: HscEnv- -> Module- -> CoreExpr- -> IO UnlinkedBCO-coreExprToBCOs hsc_env this_mod expr- = withTiming logger dflags- (text "GHC.CoreToByteCode"<+>brackets (ppr this_mod))- (const ()) $ do- -- create a totally bogus name for the top-level BCO; this- -- should be harmless, since it's never used for anything- let invented_name = mkSystemVarName (mkPseudoUniqueE 0) (fsLit "ExprTopLevel")-- -- the uniques are needed to generate fresh variables when we introduce new- -- let bindings for ticked expressions- us <- mkSplitUniqSupply 'y'- (BcM_State _dflags _us _this_mod _final_ctr mallocd _ _ _, proto_bco)- <- runBc hsc_env us this_mod Nothing emptyVarEnv $- schemeR [] (invented_name, simpleFreeVars expr)-- when (notNull mallocd)- (panic "GHC.CoreToByteCode.coreExprToBCOs: missing final emitBc?")-- dumpIfSet_dyn logger dflags Opt_D_dump_BCOs "Proto-BCOs" FormatByteCode- (ppr proto_bco)-- assembleOneBCO hsc_env proto_bco- where dflags = hsc_dflags hsc_env- logger = hsc_logger hsc_env---- The regular freeVars function gives more information than is useful to--- us here. We need only the free variables, not everything in an FVAnn.--- Historical note: At one point FVAnn was more sophisticated than just--- a set. Now it isn't. So this function is much simpler. Keeping it around--- so that if someone changes FVAnn, they will get a nice type error right--- here.-simpleFreeVars :: CoreExpr -> AnnExpr Id DVarSet-simpleFreeVars = freeVars---- -------------------------------------------------------------------------------- Compilation schema for the bytecode generator--type BCInstrList = OrdList BCInstr--newtype ByteOff = ByteOff Int- deriving (Enum, Eq, Integral, Num, Ord, Real)--newtype WordOff = WordOff Int- deriving (Enum, Eq, Integral, Num, Ord, Real)--wordsToBytes :: Platform -> WordOff -> ByteOff-wordsToBytes platform = fromIntegral . (* platformWordSizeInBytes platform) . fromIntegral---- Used when we know we have a whole number of words-bytesToWords :: Platform -> ByteOff -> WordOff-bytesToWords platform (ByteOff bytes) =- let (q, r) = bytes `quotRem` (platformWordSizeInBytes platform)- in if r == 0- then fromIntegral q- else panic $ "GHC.CoreToByteCode.bytesToWords: bytes=" ++ show bytes--wordSize :: Platform -> ByteOff-wordSize platform = ByteOff (platformWordSizeInBytes platform)--type Sequel = ByteOff -- back off to this depth before ENTER--type StackDepth = ByteOff---- | Maps Ids to their stack depth. This allows us to avoid having to mess with--- it after each push/pop.-type BCEnv = Map Id StackDepth -- To find vars on the stack--{--ppBCEnv :: BCEnv -> SDoc-ppBCEnv p- = text "begin-env"- $$ nest 4 (vcat (map pp_one (sortBy cmp_snd (Map.toList p))))- $$ text "end-env"- where- pp_one (var, offset) = int offset <> colon <+> ppr var <+> ppr (bcIdArgRep var)- cmp_snd x y = compare (snd x) (snd y)--}---- Create a BCO and do a spot of peephole optimisation on the insns--- at the same time.-mkProtoBCO- :: Platform- -> name- -> BCInstrList- -> Either [AnnAlt Id DVarSet] (AnnExpr Id DVarSet)- -- ^ original expression; for debugging only- -> Int- -> Word16- -> [StgWord]- -> Bool -- True <=> is a return point, rather than a function- -> [FFIInfo]- -> ProtoBCO name-mkProtoBCO platform nm instrs_ordlist origin arity bitmap_size bitmap is_ret ffis- = ProtoBCO {- protoBCOName = nm,- protoBCOInstrs = maybe_with_stack_check,- protoBCOBitmap = bitmap,- protoBCOBitmapSize = bitmap_size,- protoBCOArity = arity,- protoBCOExpr = origin,- protoBCOFFIs = ffis- }- where- -- Overestimate the stack usage (in words) of this BCO,- -- and if >= iNTERP_STACK_CHECK_THRESH, add an explicit- -- stack check. (The interpreter always does a stack check- -- for iNTERP_STACK_CHECK_THRESH words at the start of each- -- BCO anyway, so we only need to add an explicit one in the- -- (hopefully rare) cases when the (overestimated) stack use- -- exceeds iNTERP_STACK_CHECK_THRESH.- maybe_with_stack_check- | is_ret && stack_usage < fromIntegral (pc_AP_STACK_SPLIM (platformConstants platform)) = peep_d- -- don't do stack checks at return points,- -- everything is aggregated up to the top BCO- -- (which must be a function).- -- That is, unless the stack usage is >= AP_STACK_SPLIM,- -- see bug #1466.- | stack_usage >= fromIntegral iNTERP_STACK_CHECK_THRESH- = STKCHECK stack_usage : peep_d- | otherwise- = peep_d -- the supposedly common case-- -- We assume that this sum doesn't wrap- stack_usage = sum (map bciStackUse peep_d)-- -- Merge local pushes- peep_d = peep (fromOL instrs_ordlist)-- peep (PUSH_L off1 : PUSH_L off2 : PUSH_L off3 : rest)- = PUSH_LLL off1 (off2-1) (off3-2) : peep rest- peep (PUSH_L off1 : PUSH_L off2 : rest)- = PUSH_LL off1 (off2-1) : peep rest- peep (i:rest)- = i : peep rest- peep []- = []--argBits :: Platform -> [ArgRep] -> [Bool]-argBits _ [] = []-argBits platform (rep : args)- | isFollowableArg rep = False : argBits platform args- | otherwise = take (argRepSizeW platform rep) (repeat True) ++ argBits platform args---- -------------------------------------------------------------------------------- schemeTopBind---- Compile code for the right-hand side of a top-level binding--schemeTopBind :: (Id, AnnExpr Id DVarSet) -> BcM (ProtoBCO Name)-schemeTopBind (id, rhs)- | Just data_con <- isDataConWorkId_maybe id,- isNullaryRepDataCon data_con = do- platform <- profilePlatform <$> getProfile- -- Special case for the worker of a nullary data con.- -- It'll look like this: Nil = /\a -> Nil a- -- If we feed it into schemeR, we'll get- -- Nil = Nil- -- because mkConAppCode treats nullary constructor applications- -- by just re-using the single top-level definition. So- -- for the worker itself, we must allocate it directly.- -- ioToBc (putStrLn $ "top level BCO")- emitBc (mkProtoBCO platform (getName id) (toOL [PACK data_con 0, ENTER])- (Right rhs) 0 0 [{-no bitmap-}] False{-not alts-})-- | otherwise- = schemeR [{- No free variables -}] (getName id, rhs)----- -------------------------------------------------------------------------------- schemeR---- Compile code for a right-hand side, to give a BCO that,--- when executed with the free variables and arguments on top of the stack,--- will return with a pointer to the result on top of the stack, after--- removing the free variables and arguments.------ Park the resulting BCO in the monad. Also requires the--- name of the variable to which this value was bound,--- so as to give the resulting BCO a name.--schemeR :: [Id] -- Free vars of the RHS, ordered as they- -- will appear in the thunk. Empty for- -- top-level things, which have no free vars.- -> (Name, AnnExpr Id DVarSet)- -> BcM (ProtoBCO Name)-schemeR fvs (nm, rhs)-{-- | trace (showSDoc (- (char ' '- $$ (ppr.filter (not.isTyVar).dVarSetElems.fst) rhs- $$ pprCoreExpr (deAnnotate rhs)- $$ char ' '- ))) False- = undefined- | otherwise--}- = schemeR_wrk fvs nm rhs (collect rhs)---- If an expression is a lambda (after apply bcView), return the--- list of arguments to the lambda (in R-to-L order) and the--- underlying expression-collect :: AnnExpr Id DVarSet -> ([Var], AnnExpr' Id DVarSet)-collect (_, e) = go [] e- where- go xs e | Just e' <- bcView e = go xs e'- go xs (AnnLam x (_,e))- | typePrimRep (idType x) `lengthExceeds` 1- = multiValException- | otherwise- = go (x:xs) e- go xs not_lambda = (reverse xs, not_lambda)--schemeR_wrk- :: [Id]- -> Name- -> AnnExpr Id DVarSet -- expression e, for debugging only- -> ([Var], AnnExpr' Var DVarSet) -- result of collect on e- -> BcM (ProtoBCO Name)-schemeR_wrk fvs nm original_body (args, body)- = do- profile <- getProfile- let- platform = profilePlatform profile- all_args = reverse args ++ fvs- arity = length all_args- -- all_args are the args in reverse order. We're compiling a function- -- \fv1..fvn x1..xn -> e- -- i.e. the fvs come first-- -- Stack arguments always take a whole number of words, we never pack- -- them unlike constructor fields.- szsb_args = map (wordsToBytes platform . idSizeW platform) all_args- sum_szsb_args = sum szsb_args- p_init = Map.fromList (zip all_args (mkStackOffsets 0 szsb_args))-- -- make the arg bitmap- bits = argBits platform (reverse (map (bcIdArgRep platform) all_args))- bitmap_size = genericLength bits- bitmap = mkBitmap platform bits- body_code <- schemeER_wrk sum_szsb_args p_init body-- emitBc (mkProtoBCO platform nm body_code (Right original_body)- arity bitmap_size bitmap False{-not alts-})---- introduce break instructions for ticked expressions-schemeER_wrk :: StackDepth -> BCEnv -> AnnExpr' Id DVarSet -> BcM BCInstrList-schemeER_wrk d p rhs- | AnnTick (Breakpoint tick_no fvs) (_annot, newRhs) <- rhs- = do code <- schemeE d 0 p newRhs- cc_arr <- getCCArray- this_mod <- moduleName <$> getCurrentModule- platform <- profilePlatform <$> getProfile- let idOffSets = getVarOffSets platform d p fvs- let breakInfo = CgBreakInfo- { cgb_vars = idOffSets- , cgb_resty = exprType (deAnnotate' newRhs)- }- newBreakInfo tick_no breakInfo- hsc_env <- getHscEnv- let cc | Just interp <- hsc_interp hsc_env- , interpreterProfiled interp- = cc_arr ! tick_no- | otherwise = toRemotePtr nullPtr- let breakInstr = BRK_FUN (fromIntegral tick_no) (getUnique this_mod) cc- return $ breakInstr `consOL` code- | otherwise = schemeE d 0 p rhs--getVarOffSets :: Platform -> StackDepth -> BCEnv -> [Id] -> [Maybe (Id, Word16)]-getVarOffSets platform depth env = map getOffSet- where- getOffSet id = case lookupBCEnv_maybe id env of- Nothing -> Nothing- Just offset ->- -- michalt: I'm not entirely sure why we need the stack- -- adjustment by 2 here. I initially thought that there's- -- something off with getIdValFromApStack (the only user of this- -- value), but it looks ok to me. My current hypothesis is that- -- this "adjustment" is needed due to stack manipulation for- -- BRK_FUN in Interpreter.c In any case, this is used only when- -- we trigger a breakpoint.- let !var_depth_ws =- trunc16W $ bytesToWords platform (depth - offset) + 2- in Just (id, var_depth_ws)--truncIntegral16 :: Integral a => a -> Word16-truncIntegral16 w- | w > fromIntegral (maxBound :: Word16)- = panic "stack depth overflow"- | otherwise- = fromIntegral w--trunc16B :: ByteOff -> Word16-trunc16B = truncIntegral16--trunc16W :: WordOff -> Word16-trunc16W = truncIntegral16--fvsToEnv :: BCEnv -> DVarSet -> [Id]--- Takes the free variables of a right-hand side, and--- delivers an ordered list of the local variables that will--- be captured in the thunk for the RHS--- The BCEnv argument tells which variables are in the local--- environment: these are the ones that should be captured------ The code that constructs the thunk, and the code that executes--- it, have to agree about this layout-fvsToEnv p fvs = [v | v <- dVarSetElems fvs,- isId v, -- Could be a type variable- v `Map.member` p]---- -------------------------------------------------------------------------------- schemeE--returnUnboxedAtom- :: StackDepth- -> Sequel- -> BCEnv- -> AnnExpr' Id DVarSet- -> ArgRep- -> BcM BCInstrList--- Returning an unlifted value.--- Heave it on the stack, SLIDE, and RETURN.-returnUnboxedAtom d s p e e_rep = do- dflags <- getDynFlags- let platform = targetPlatform dflags- (push, szb) <- pushAtom d p e- return (push -- value onto stack- `appOL` mkSlideB platform szb (d - s) -- clear to sequel- `snocOL` RETURN_UBX e_rep) -- go---- Compile code to apply the given expression to the remaining args--- on the stack, returning a HNF.-schemeE- :: StackDepth -> Sequel -> BCEnv -> AnnExpr' Id DVarSet -> BcM BCInstrList-schemeE d s p e- | Just e' <- bcView e- = schemeE d s p e'---- Delegate tail-calls to schemeT.-schemeE d s p e@(AnnApp _ _) = schemeT d s p e--schemeE d s p e@(AnnLit lit) = do- platform <- profilePlatform <$> getProfile- returnUnboxedAtom d s p e (typeArgRep platform (literalType lit))-schemeE d s p e@(AnnCoercion {}) = returnUnboxedAtom d s p e V--schemeE d s p e@(AnnVar v)- -- See Note [Not-necessarily-lifted join points], step 3.- | isNNLJoinPoint v = doTailCall d s p (protectNNLJoinPointId v) [AnnVar voidPrimId]- | isUnliftedType (idType v) = do- platform <- profilePlatform <$> getProfile- returnUnboxedAtom d s p e (bcIdArgRep platform v)- | otherwise = schemeT d s p e--schemeE d s p (AnnLet (AnnNonRec x (_,rhs)) (_,body))- | (AnnVar v, args_r_to_l) <- splitApp rhs,- Just data_con <- isDataConWorkId_maybe v,- dataConRepArity data_con == length args_r_to_l- = do -- Special case for a non-recursive let whose RHS is a- -- saturated constructor application.- -- Just allocate the constructor and carry on- alloc_code <- mkConAppCode d s p data_con args_r_to_l- platform <- targetPlatform <$> getDynFlags- let !d2 = d + wordSize platform- body_code <- schemeE d2 s (Map.insert x d2 p) body- return (alloc_code `appOL` body_code)---- General case for let. Generates correct, if inefficient, code in--- all situations.-schemeE d s p (AnnLet binds (_,body)) = do- platform <- targetPlatform <$> getDynFlags- let (xs,rhss) = case binds of AnnNonRec x rhs -> ([x],[rhs])- AnnRec xs_n_rhss -> unzip xs_n_rhss- n_binds = genericLength xs-- fvss = map (fvsToEnv p' . fst) rhss-- -- See Note [Not-necessarily-lifted join points], step 2.- (xs',rhss') = zipWithAndUnzip protectNNLJoinPointBind xs rhss-- -- Sizes of free vars- size_w = trunc16W . idSizeW platform- sizes = map (\rhs_fvs -> sum (map size_w rhs_fvs)) fvss-- -- the arity of each rhs- arities = map (genericLength . fst . collect) rhss'-- -- This p', d' defn is safe because all the items being pushed- -- are ptrs, so all have size 1 word. d' and p' reflect the stack- -- after the closures have been allocated in the heap (but not- -- filled in), and pointers to them parked on the stack.- offsets = mkStackOffsets d (genericReplicate n_binds (wordSize platform))- p' = Map.insertList (zipE xs' offsets) p- d' = d + wordsToBytes platform n_binds- zipE = zipEqual "schemeE"-- -- ToDo: don't build thunks for things with no free variables- build_thunk- :: StackDepth- -> [Id]- -> Word16- -> ProtoBCO Name- -> Word16- -> Word16- -> BcM BCInstrList- build_thunk _ [] size bco off arity- = return (PUSH_BCO bco `consOL` unitOL (mkap (off+size) size))- where- mkap | arity == 0 = MKAP- | otherwise = MKPAP- build_thunk dd (fv:fvs) size bco off arity = do- (push_code, pushed_szb) <- pushAtom dd p' (AnnVar fv)- more_push_code <-- build_thunk (dd + pushed_szb) fvs size bco off arity- return (push_code `appOL` more_push_code)-- alloc_code = toOL (zipWith mkAlloc sizes arities)- where mkAlloc sz 0- | is_tick = ALLOC_AP_NOUPD sz- | otherwise = ALLOC_AP sz- mkAlloc sz arity = ALLOC_PAP arity sz-- is_tick = case binds of- AnnNonRec id _ -> occNameFS (getOccName id) == tickFS- _other -> False-- compile_bind d' fvs x rhs size arity off = do- bco <- schemeR fvs (getName x,rhs)- build_thunk d' fvs size bco off arity-- compile_binds =- [ compile_bind d' fvs x rhs size arity (trunc16W n)- | (fvs, x, rhs, size, arity, n) <-- zip6 fvss xs' rhss' sizes arities [n_binds, n_binds-1 .. 1]- ]- body_code <- schemeE d' s p' body- thunk_codes <- sequence compile_binds- return (alloc_code `appOL` concatOL thunk_codes `appOL` body_code)---- Introduce a let binding for a ticked case expression. This rule--- *should* only fire when the expression was not already let-bound--- (the code gen for let bindings should take care of that). Todo: we--- call exprFreeVars on a deAnnotated expression, this may not be the--- best way to calculate the free vars but it seemed like the least--- intrusive thing to do-schemeE d s p exp@(AnnTick (Breakpoint _id _fvs) _rhs)- | isLiftedTypeKind (typeKind ty)- = do id <- newId ty- -- Todo: is emptyVarSet correct on the next line?- let letExp = AnnLet (AnnNonRec id (fvs, exp)) (emptyDVarSet, AnnVar id)- schemeE d s p letExp-- | otherwise- = do -- If the result type is not definitely lifted, then we must generate- -- let f = \s . tick<n> e- -- in f realWorld#- -- When we stop at the breakpoint, _result will have an unlifted- -- type and hence won't be bound in the environment, but the- -- breakpoint will otherwise work fine.- --- -- NB (#12007) this /also/ applies for if (ty :: TYPE r), where- -- r :: RuntimeRep is a variable. This can happen in the- -- continuations for a pattern-synonym matcher- -- match = /\(r::RuntimeRep) /\(a::TYPE r).- -- \(k :: Int -> a) \(v::T).- -- case v of MkV n -> k n- -- Here (k n) :: a :: TYPE r, so we don't know if it's lifted- -- or not; but that should be fine provided we add that void arg.-- id <- newId (mkVisFunTyMany realWorldStatePrimTy ty)- st <- newId realWorldStatePrimTy- let letExp = AnnLet (AnnNonRec id (fvs, AnnLam st (emptyDVarSet, exp)))- (emptyDVarSet, (AnnApp (emptyDVarSet, AnnVar id)- (emptyDVarSet, AnnVar realWorldPrimId)))- schemeE d s p letExp-- where- exp' = deAnnotate' exp- fvs = exprFreeVarsDSet exp'- ty = exprType exp'---- ignore other kinds of tick-schemeE d s p (AnnTick _ (_, rhs)) = schemeE d s p rhs---- no alts: scrut is guaranteed to diverge-schemeE d s p (AnnCase (_,scrut) _ _ []) = schemeE d s p scrut---- handle pairs with one void argument (e.g. state token)-schemeE d s p (AnnCase scrut bndr _ [AnnAlt (DataAlt dc) [bind1, bind2] rhs])- | isUnboxedTupleDataCon dc- -- Convert- -- case .... of x { (# V'd-thing, a #) -> ... }- -- to- -- case .... of a { DEFAULT -> ... }- -- because the return convention for both are identical.- --- -- Note that it does not matter losing the void-rep thing from the- -- envt (it won't be bound now) because we never look such things up.- , Just res <- case (typePrimRep (idType bind1), typePrimRep (idType bind2)) of- ([], [_])- -> Just $ doCase d s p scrut bind2 [AnnAlt DEFAULT [] rhs] (Just bndr)- ([_], [])- -> Just $ doCase d s p scrut bind1 [AnnAlt DEFAULT [] rhs] (Just bndr)- _ -> Nothing- = res---- handle unit tuples-schemeE d s p (AnnCase scrut bndr _ [AnnAlt (DataAlt dc) [bind1] rhs])- | isUnboxedTupleDataCon dc- , typePrimRep (idType bndr) `lengthAtMost` 1- = doCase d s p scrut bind1 [AnnAlt DEFAULT [] rhs] (Just bndr)---- handle nullary tuples-schemeE d s p (AnnCase scrut bndr _ alt@[AnnAlt DEFAULT [] _])- | isUnboxedTupleType (idType bndr)- , Just ty <- case typePrimRep (idType bndr) of- [_] -> Just (unwrapType (idType bndr))- [] -> Just unboxedUnitTy- _ -> Nothing- -- handles any pattern with a single non-void binder; in particular I/O- -- monad returns (# RealWorld#, a #)- = doCase d s p scrut (bndr `setIdType` ty) alt (Just bndr)--schemeE d s p (AnnCase scrut bndr _ alts)- = doCase d s p scrut bndr alts Nothing{-not an unboxed tuple-}--schemeE _ _ _ expr- = pprPanic "GHC.CoreToByteCode.schemeE: unhandled case"- (pprCoreExpr (deAnnotate' expr))---- Is this Id a not-necessarily-lifted join point?--- See Note [Not-necessarily-lifted join points], step 1-isNNLJoinPoint :: Id -> Bool-isNNLJoinPoint x = isJoinId x &&- Just True /= isLiftedType_maybe (idType x)---- If necessary, modify this Id and body to protect not-necessarily-lifted join points.--- See Note [Not-necessarily-lifted join points], step 2.-protectNNLJoinPointBind :: Id -> AnnExpr Id DVarSet -> (Id, AnnExpr Id DVarSet)-protectNNLJoinPointBind x rhs@(fvs, _)- | isNNLJoinPoint x- = (protectNNLJoinPointId x, (fvs, AnnLam voidArgId rhs))-- | otherwise- = (x, rhs)---- Update an Id's type to take a Void# argument.--- Precondition: the Id is a not-necessarily-lifted join point.--- See Note [Not-necessarily-lifted join points]-protectNNLJoinPointId :: Id -> Id-protectNNLJoinPointId x- = ASSERT( isNNLJoinPoint x )- updateIdTypeButNotMult (unboxedUnitTy `mkVisFunTyMany`) x--{-- Ticked Expressions- -------------------- The idea is that the "breakpoint<n,fvs> E" is really just an annotation on- the code. When we find such a thing, we pull out the useful information,- and then compile the code as if it was just the expression E.--Note [Not-necessarily-lifted join points]-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~-A join point variable is essentially a goto-label: it is, for example,-never used as an argument to another function, and it is called only-in tail position. See Note [Join points] and Note [Invariants on join points],-both in GHC.Core. Because join points do not compile to true, red-blooded-variables (with, e.g., registers allocated to them), they are allowed-to be levity-polymorphic. (See invariant #6 in Note [Invariants on join points]-in GHC.Core.)--However, in this byte-code generator, join points *are* treated just as-ordinary variables. There is no check whether a binding is for a join point-or not; they are all treated uniformly. (Perhaps there is a missed optimization-opportunity here, but that is beyond the scope of my (Richard E's) Thursday.)--We thus must have *some* strategy for dealing with levity-polymorphic and-unlifted join points. Levity-polymorphic variables are generally not allowed-(though levity-polymorphic join points *are*; see Note [Invariants on join points]-in GHC.Core, point 6), and we don't wish to evaluate unlifted join points eagerly.-The questionable join points are *not-necessarily-lifted join points*-(NNLJPs). (Not having such a strategy led to #16509, which panicked in the-isUnliftedType check in the AnnVar case of schemeE.) Here is the strategy:--1. Detect NNLJPs. This is done in isNNLJoinPoint.--2. When binding an NNLJP, add a `\ (_ :: (# #)) ->` to its RHS, and modify the- type to tack on a `(# #) ->`.- Note that functions are never levity-polymorphic, so this transformation- changes an NNLJP to a non-levity-polymorphic join point. This is done- in protectNNLJoinPointBind, called from the AnnLet case of schemeE.--3. At an occurrence of an NNLJP, add an application to void# (called voidPrimId),- being careful to note the new type of the NNLJP. This is done in the AnnVar- case of schemeE, with help from protectNNLJoinPointId.--Here is an example. Suppose we have-- f = \(r :: RuntimeRep) (a :: TYPE r) (x :: T).- join j :: a- j = error @r @a "bloop"- in case x of- A -> j- B -> j- C -> error @r @a "blurp"--Our plan is to behave is if the code was-- f = \(r :: RuntimeRep) (a :: TYPE r) (x :: T).- let j :: (Void# -> a)- j = \ _ -> error @r @a "bloop"- in case x of- A -> j void#- B -> j void#- C -> error @r @a "blurp"--It's a bit hacky, but it works well in practice and is local. I suspect the-Right Fix is to take advantage of join points as goto-labels.---}---- Compile code to do a tail call. Specifically, push the fn,--- slide the on-stack app back down to the sequel depth,--- and enter. Four cases:------ 0. (Nasty hack).--- An application "GHC.Prim.tagToEnum# <type> unboxed-int".--- The int will be on the stack. Generate a code sequence--- to convert it to the relevant constructor, SLIDE and ENTER.------ 1. The fn denotes a ccall. Defer to generateCCall.------ 2. (Another nasty hack). Spot (# a::V, b #) and treat--- it simply as b -- since the representations are identical--- (the V takes up zero stack space). Also, spot--- (# b #) and treat it as b.------ 3. Application of a constructor, by defn saturated.--- Split the args into ptrs and non-ptrs, and push the nonptrs,--- then the ptrs, and then do PACK and RETURN.------ 4. Otherwise, it must be a function call. Push the args--- right to left, SLIDE and ENTER.--schemeT :: StackDepth -- Stack depth- -> Sequel -- Sequel depth- -> BCEnv -- stack env- -> AnnExpr' Id DVarSet- -> BcM BCInstrList--schemeT d s p app-- -- Case 0- | Just (arg, constr_names) <- maybe_is_tagToEnum_call app- = implement_tagToId d s p arg constr_names-- -- Case 1- | Just (CCall ccall_spec) <- isFCallId_maybe fn- = if isSupportedCConv ccall_spec- then generateCCall d s p ccall_spec fn args_r_to_l- else unsupportedCConvException--- -- Case 2: Constructor application- | Just con <- maybe_saturated_dcon- , isUnboxedTupleDataCon con- = do- platform <- profilePlatform <$> getProfile- case args_r_to_l of- [arg1,arg2] | isVAtom platform arg1 ->- unboxedTupleReturn d s p arg2- [arg1,arg2] | isVAtom platform arg2 ->- unboxedTupleReturn d s p arg1- _other -> multiValException-- -- Case 3: Ordinary data constructor- | Just con <- maybe_saturated_dcon- = do alloc_con <- mkConAppCode d s p con args_r_to_l- platform <- profilePlatform <$> getProfile- return (alloc_con `appOL`- mkSlideW 1 (bytesToWords platform $ d - s) `snocOL`- ENTER)-- -- Case 4: Tail call of function- | otherwise- = doTailCall d s p fn args_r_to_l-- where- -- Extract the args (R->L) and fn- -- The function will necessarily be a variable,- -- because we are compiling a tail call- (AnnVar fn, args_r_to_l) = splitApp app-- -- Only consider this to be a constructor application iff it is- -- saturated. Otherwise, we'll call the constructor wrapper.- n_args = length args_r_to_l- maybe_saturated_dcon- = case isDataConWorkId_maybe fn of- Just con | dataConRepArity con == n_args -> Just con- _ -> Nothing---- -------------------------------------------------------------------------------- Generate code to build a constructor application,--- leaving it on top of the stack--mkConAppCode- :: StackDepth- -> Sequel- -> BCEnv- -> DataCon -- The data constructor- -> [AnnExpr' Id DVarSet] -- Args, in *reverse* order- -> BcM BCInstrList-mkConAppCode _ _ _ con [] -- Nullary constructor- = ASSERT( isNullaryRepDataCon con )- return (unitOL (PUSH_G (getName (dataConWorkId con))))- -- Instead of doing a PACK, which would allocate a fresh- -- copy of this constructor, use the single shared version.--mkConAppCode orig_d _ p con args_r_to_l =- ASSERT( args_r_to_l `lengthIs` dataConRepArity con ) app_code- where- app_code = do- profile <- getProfile- let platform = profilePlatform profile-- -- The args are initially in reverse order, but mkVirtHeapOffsets- -- expects them to be left-to-right.- let non_voids =- [ NonVoid (prim_rep, arg)- | arg <- reverse args_r_to_l- , let prim_rep = atomPrimRep arg- , not (isVoidRep prim_rep)- ]- (_, _, args_offsets) =- mkVirtHeapOffsetsWithPadding profile StdHeader non_voids-- do_pushery !d (arg : args) = do- (push, arg_bytes) <- case arg of- (Padding l _) -> return $! pushPadding l- (FieldOff a _) -> pushConstrAtom d p (fromNonVoid a)- more_push_code <- do_pushery (d + arg_bytes) args- return (push `appOL` more_push_code)- do_pushery !d [] = do- let !n_arg_words = trunc16W $ bytesToWords platform (d - orig_d)- return (unitOL (PACK con n_arg_words))-- -- Push on the stack in the reverse order.- do_pushery orig_d (reverse args_offsets)----- -------------------------------------------------------------------------------- Returning an unboxed tuple with one non-void component (the only--- case we can handle).------ Remember, we don't want to *evaluate* the component that is being--- returned, even if it is a pointed type. We always just return.--unboxedTupleReturn- :: StackDepth -> Sequel -> BCEnv -> AnnExpr' Id DVarSet -> BcM BCInstrList-unboxedTupleReturn d s p arg = do- platform <- profilePlatform <$> getProfile- returnUnboxedAtom d s p arg (atomRep platform arg)---- -------------------------------------------------------------------------------- Generate code for a tail-call--doTailCall- :: StackDepth- -> Sequel- -> BCEnv- -> Id- -> [AnnExpr' Id DVarSet]- -> BcM BCInstrList-doTailCall init_d s p fn args = do- platform <- profilePlatform <$> getProfile- do_pushes init_d args (map (atomRep platform) args)- where- do_pushes !d [] reps = do- ASSERT( null reps ) return ()- (push_fn, sz) <- pushAtom d p (AnnVar fn)- platform <- profilePlatform <$> getProfile- ASSERT( sz == wordSize platform ) return ()- let slide = mkSlideB platform (d - init_d + wordSize platform) (init_d - s)- return (push_fn `appOL` (slide `appOL` unitOL ENTER))- do_pushes !d args reps = do- let (push_apply, n, rest_of_reps) = findPushSeq reps- (these_args, rest_of_args) = splitAt n args- (next_d, push_code) <- push_seq d these_args- platform <- profilePlatform <$> getProfile- instrs <- do_pushes (next_d + wordSize platform) rest_of_args rest_of_reps- -- ^^^ for the PUSH_APPLY_ instruction- return (push_code `appOL` (push_apply `consOL` instrs))-- push_seq d [] = return (d, nilOL)- push_seq d (arg:args) = do- (push_code, sz) <- pushAtom d p arg- (final_d, more_push_code) <- push_seq (d + sz) args- return (final_d, push_code `appOL` more_push_code)---- v. similar to CgStackery.findMatch, ToDo: merge-findPushSeq :: [ArgRep] -> (BCInstr, Int, [ArgRep])-findPushSeq (P: P: P: P: P: P: rest)- = (PUSH_APPLY_PPPPPP, 6, rest)-findPushSeq (P: P: P: P: P: rest)- = (PUSH_APPLY_PPPPP, 5, rest)-findPushSeq (P: P: P: P: rest)- = (PUSH_APPLY_PPPP, 4, rest)-findPushSeq (P: P: P: rest)- = (PUSH_APPLY_PPP, 3, rest)-findPushSeq (P: P: rest)- = (PUSH_APPLY_PP, 2, rest)-findPushSeq (P: rest)- = (PUSH_APPLY_P, 1, rest)-findPushSeq (V: rest)- = (PUSH_APPLY_V, 1, rest)-findPushSeq (N: rest)- = (PUSH_APPLY_N, 1, rest)-findPushSeq (F: rest)- = (PUSH_APPLY_F, 1, rest)-findPushSeq (D: rest)- = (PUSH_APPLY_D, 1, rest)-findPushSeq (L: rest)- = (PUSH_APPLY_L, 1, rest)-findPushSeq _- = panic "GHC.CoreToByteCode.findPushSeq"---- -------------------------------------------------------------------------------- Case expressions--doCase- :: StackDepth- -> Sequel- -> BCEnv- -> AnnExpr Id DVarSet- -> Id- -> [AnnAlt Id DVarSet]- -> Maybe Id -- Just x <=> is an unboxed tuple case with scrut binder,- -- don't enter the result- -> BcM BCInstrList-doCase d s p (_,scrut) bndr alts is_unboxed_tuple- | typePrimRep (idType bndr) `lengthExceeds` 1- = multiValException-- | otherwise- = do- profile <- getProfile- hsc_env <- getHscEnv- let- platform = profilePlatform profile-- profiling- | Just interp <- hsc_interp hsc_env- = interpreterProfiled interp- | otherwise = False-- -- Top of stack is the return itbl, as usual.- -- underneath it is the pointer to the alt_code BCO.- -- When an alt is entered, it assumes the returned value is- -- on top of the itbl.- ret_frame_size_b :: StackDepth- ret_frame_size_b = 2 * wordSize platform-- -- The extra frame we push to save/restore the CCCS when profiling- save_ccs_size_b | profiling = 2 * wordSize platform- | otherwise = 0-- -- An unlifted value gets an extra info table pushed on top- -- when it is returned.- unlifted_itbl_size_b :: StackDepth- unlifted_itbl_size_b | isAlgCase = 0- | otherwise = wordSize platform-- -- depth of stack after the return value has been pushed- d_bndr =- d + ret_frame_size_b + wordsToBytes platform (idSizeW platform bndr)-- -- depth of stack after the extra info table for an unboxed return- -- has been pushed, if any. This is the stack depth at the- -- continuation.- d_alts = d_bndr + unlifted_itbl_size_b-- -- Env in which to compile the alts, not including- -- any vars bound by the alts themselves- p_alts0 = Map.insert bndr d_bndr p-- p_alts = case is_unboxed_tuple of- Just ubx_bndr -> Map.insert ubx_bndr d_bndr p_alts0- Nothing -> p_alts0-- bndr_ty = idType bndr- isAlgCase = not (isUnliftedType bndr_ty) && isNothing is_unboxed_tuple-- -- given an alt, return a discr and code for it.- codeAlt (AnnAlt DEFAULT _ (_,rhs))- = do rhs_code <- schemeE d_alts s p_alts rhs- return (NoDiscr, rhs_code)-- codeAlt alt@(AnnAlt _ bndrs (_,rhs))- -- primitive or nullary constructor alt: no need to UNPACK- | null real_bndrs = do- rhs_code <- schemeE d_alts s p_alts rhs- return (my_discr alt, rhs_code)- -- If an alt attempts to match on an unboxed tuple or sum, we must- -- bail out, as the bytecode compiler can't handle them.- -- (See #14608.)- | any (\bndr -> typePrimRep (idType bndr) `lengthExceeds` 1) bndrs- = multiValException- -- algebraic alt with some binders- | otherwise =- let (tot_wds, _ptrs_wds, args_offsets) =- mkVirtHeapOffsets profile NoHeader- [ NonVoid (bcIdPrimRep id, id)- | NonVoid id <- nonVoidIds real_bndrs- ]- size = WordOff tot_wds-- stack_bot = d_alts + wordsToBytes platform size-- -- convert offsets from Sp into offsets into the virtual stack- p' = Map.insertList- [ (arg, stack_bot - ByteOff offset)- | (NonVoid arg, offset) <- args_offsets ]- p_alts- in do- MASSERT(isAlgCase)- rhs_code <- schemeE stack_bot s p' rhs- return (my_discr alt,- unitOL (UNPACK (trunc16W size)) `appOL` rhs_code)- where- real_bndrs = filterOut isTyVar bndrs-- my_discr (AnnAlt DEFAULT _ _) = NoDiscr {-shouldn't really happen-}- my_discr (AnnAlt (DataAlt dc) _ _)- | isUnboxedTupleDataCon dc || isUnboxedSumDataCon dc- = multiValException- | otherwise- = DiscrP (fromIntegral (dataConTag dc - fIRST_TAG))- my_discr (AnnAlt (LitAlt l) _ _)- = case l of LitNumber LitNumInt i -> DiscrI (fromInteger i)- LitNumber LitNumWord w -> DiscrW (fromInteger w)- LitFloat r -> DiscrF (fromRational r)- LitDouble r -> DiscrD (fromRational r)- LitChar i -> DiscrI (ord i)- _ -> pprPanic "schemeE(AnnCase).my_discr" (ppr l)-- maybe_ncons- | not isAlgCase = Nothing- | otherwise- = case [dc | AnnAlt (DataAlt dc) _ _ <- alts] of- [] -> Nothing- (dc:_) -> Just (tyConFamilySize (dataConTyCon dc))-- -- the bitmap is relative to stack depth d, i.e. before the- -- BCO, info table and return value are pushed on.- -- This bit of code is v. similar to buildLivenessMask in CgBindery,- -- except that here we build the bitmap from the known bindings of- -- things that are pointers, whereas in CgBindery the code builds the- -- bitmap from the free slots and unboxed bindings.- -- (ToDo: merge?)- --- -- NOTE [7/12/2006] bug #1013, testcase ghci/should_run/ghci002.- -- The bitmap must cover the portion of the stack up to the sequel only.- -- Previously we were building a bitmap for the whole depth (d), but we- -- really want a bitmap up to depth (d-s). This affects compilation of- -- case-of-case expressions, which is the only time we can be compiling a- -- case expression with s /= 0.- bitmap_size = trunc16W $ bytesToWords platform (d - s)- bitmap_size' :: Int- bitmap_size' = fromIntegral bitmap_size- bitmap = intsToReverseBitmap platform bitmap_size'{-size-}- (sort (filter (< bitmap_size') rel_slots))- where- binds = Map.toList p- -- NB: unboxed tuple cases bind the scrut binder to the same offset- -- as one of the alt binders, so we have to remove any duplicates here:- rel_slots = nub $ map fromIntegral $ concatMap spread binds- spread (id, offset) | isFollowableArg (bcIdArgRep platform id) = [ rel_offset ]- | otherwise = []- where rel_offset = trunc16W $ bytesToWords platform (d - offset)-- alt_stuff <- mapM codeAlt alts- alt_final <- mkMultiBranch maybe_ncons alt_stuff-- let- alt_bco_name = getName bndr- alt_bco = mkProtoBCO platform alt_bco_name alt_final (Left alts)- 0{-no arity-} bitmap_size bitmap True{-is alts-}--- trace ("case: bndr = " ++ showSDocDebug (ppr bndr) ++ "\ndepth = " ++ show d ++ "\nenv = \n" ++ showSDocDebug (ppBCEnv p) ++--- "\n bitmap = " ++ show bitmap) $ do-- scrut_code <- schemeE (d + ret_frame_size_b + save_ccs_size_b)- (d + ret_frame_size_b + save_ccs_size_b)- p scrut- alt_bco' <- emitBc alt_bco- let push_alts- | isAlgCase = PUSH_ALTS alt_bco'- | otherwise = PUSH_ALTS_UNLIFTED alt_bco' (typeArgRep platform bndr_ty)- return (push_alts `consOL` scrut_code)----- -------------------------------------------------------------------------------- Deal with a CCall.---- Taggedly push the args onto the stack R->L,--- deferencing ForeignObj#s and adjusting addrs to point to--- payloads in Ptr/Byte arrays. Then, generate the marshalling--- (machine) code for the ccall, and create bytecodes to call that and--- then return in the right way.--generateCCall- :: StackDepth- -> Sequel- -> BCEnv- -> CCallSpec -- where to call- -> Id -- of target, for type info- -> [AnnExpr' Id DVarSet] -- args (atoms)- -> BcM BCInstrList-generateCCall d0 s p (CCallSpec target cconv safety) fn args_r_to_l- = do- profile <- getProfile-- let- platform = profilePlatform profile- -- useful constants- addr_size_b :: ByteOff- addr_size_b = wordSize platform-- -- Get the args on the stack, with tags and suitably- -- dereferenced for the CCall. For each arg, return the- -- depth to the first word of the bits for that arg, and the- -- ArgRep of what was actually pushed.-- pargs- :: ByteOff -> [AnnExpr' Id DVarSet] -> BcM [(BCInstrList, PrimRep)]- pargs _ [] = return []- pargs d (a:az)- = let arg_ty = unwrapType (exprType (deAnnotate' a))-- in case tyConAppTyCon_maybe arg_ty of- -- Don't push the FO; instead push the Addr# it- -- contains.- Just t- | t == arrayPrimTyCon || t == mutableArrayPrimTyCon- -> do rest <- pargs (d + addr_size_b) az- code <- parg_ArrayishRep (fromIntegral (arrPtrsHdrSize profile)) d p a- return ((code,AddrRep):rest)-- | t == smallArrayPrimTyCon || t == smallMutableArrayPrimTyCon- -> do rest <- pargs (d + addr_size_b) az- code <- parg_ArrayishRep (fromIntegral (smallArrPtrsHdrSize profile)) d p a- return ((code,AddrRep):rest)-- | t == byteArrayPrimTyCon || t == mutableByteArrayPrimTyCon- -> do rest <- pargs (d + addr_size_b) az- code <- parg_ArrayishRep (fromIntegral (arrWordsHdrSize profile)) d p a- return ((code,AddrRep):rest)-- -- Default case: push taggedly, but otherwise intact.- _- -> do (code_a, sz_a) <- pushAtom d p a- rest <- pargs (d + sz_a) az- return ((code_a, atomPrimRep a) : rest)-- -- Do magic for Ptr/Byte arrays. Push a ptr to the array on- -- the stack but then advance it over the headers, so as to- -- point to the payload.- parg_ArrayishRep- :: Word16- -> StackDepth- -> BCEnv- -> AnnExpr' Id DVarSet- -> BcM BCInstrList- parg_ArrayishRep hdrSize d p a- = do (push_fo, _) <- pushAtom d p a- -- The ptr points at the header. Advance it over the- -- header and then pretend this is an Addr#.- return (push_fo `snocOL` SWIZZLE 0 hdrSize)-- code_n_reps <- pargs d0 args_r_to_l- let- (pushs_arg, a_reps_pushed_r_to_l) = unzip code_n_reps- a_reps_sizeW = sum (map (repSizeWords platform) a_reps_pushed_r_to_l)-- push_args = concatOL pushs_arg- !d_after_args = d0 + wordsToBytes platform a_reps_sizeW- a_reps_pushed_RAW- | null a_reps_pushed_r_to_l || not (isVoidRep (head a_reps_pushed_r_to_l))- = panic "GHC.CoreToByteCode.generateCCall: missing or invalid World token?"- | otherwise- = reverse (tail a_reps_pushed_r_to_l)-- -- Now: a_reps_pushed_RAW are the reps which are actually on the stack.- -- push_args is the code to do that.- -- d_after_args is the stack depth once the args are on.-- -- Get the result rep.- (returns_void, r_rep)- = case maybe_getCCallReturnRep (idType fn) of- Nothing -> (True, VoidRep)- Just rr -> (False, rr)- {-- Because the Haskell stack grows down, the a_reps refer to- lowest to highest addresses in that order. The args for the call- are on the stack. Now push an unboxed Addr# indicating- the C function to call. Then push a dummy placeholder for the- result. Finally, emit a CCALL insn with an offset pointing to the- Addr# just pushed, and a literal field holding the mallocville- address of the piece of marshalling code we generate.- So, just prior to the CCALL insn, the stack looks like this- (growing down, as usual):-- <arg_n>- ...- <arg_1>- Addr# address_of_C_fn- <placeholder-for-result#> (must be an unboxed type)-- The interpreter then calls the marshall code mentioned- in the CCALL insn, passing it (& <placeholder-for-result#>),- that is, the addr of the topmost word in the stack.- When this returns, the placeholder will have been- filled in. The placeholder is slid down to the sequel- depth, and we RETURN.-- This arrangement makes it simple to do f-i-dynamic since the Addr#- value is the first arg anyway.-- The marshalling code is generated specifically for this- call site, and so knows exactly the (Haskell) stack- offsets of the args, fn address and placeholder. It- copies the args to the C stack, calls the stacked addr,- and parks the result back in the placeholder. The interpreter- calls it as a normal C call, assuming it has a signature- void marshall_code ( StgWord* ptr_to_top_of_stack )- -}- -- resolve static address- maybe_static_target :: Maybe Literal- maybe_static_target =- case target of- DynamicTarget -> Nothing- StaticTarget _ _ _ False ->- panic "generateCCall: unexpected FFI value import"- StaticTarget _ target _ True ->- Just (LitLabel target mb_size IsFunction)- where- mb_size- | OSMinGW32 <- platformOS platform- , StdCallConv <- cconv- = Just (fromIntegral a_reps_sizeW * platformWordSizeInBytes platform)- | otherwise- = Nothing-- let- is_static = isJust maybe_static_target-- -- Get the arg reps, zapping the leading Addr# in the dynamic case- a_reps -- | trace (showSDoc (ppr a_reps_pushed_RAW)) False = error "???"- | is_static = a_reps_pushed_RAW- | otherwise = if null a_reps_pushed_RAW- then panic "GHC.CoreToByteCode.generateCCall: dyn with no args"- else tail a_reps_pushed_RAW-- -- push the Addr#- (push_Addr, d_after_Addr)- | Just machlabel <- maybe_static_target- = (toOL [PUSH_UBX machlabel 1], d_after_args + addr_size_b)- | otherwise -- is already on the stack- = (nilOL, d_after_args)-- -- Push the return placeholder. For a call returning nothing,- -- this is a V (tag).- r_sizeW = repSizeWords platform r_rep- d_after_r = d_after_Addr + wordsToBytes platform r_sizeW- push_r =- if returns_void- then nilOL- else unitOL (PUSH_UBX (mkDummyLiteral platform r_rep) (trunc16W r_sizeW))-- -- generate the marshalling code we're going to call-- -- Offset of the next stack frame down the stack. The CCALL- -- instruction needs to describe the chunk of stack containing- -- the ccall args to the GC, so it needs to know how large it- -- is. See comment in Interpreter.c with the CCALL instruction.- stk_offset = trunc16W $ bytesToWords platform (d_after_r - s)-- conv = case cconv of- CCallConv -> FFICCall- StdCallConv -> FFIStdCall- _ -> panic "GHC.CoreToByteCode: unexpected calling convention"-- -- the only difference in libffi mode is that we prepare a cif- -- describing the call type by calling libffi, and we attach the- -- address of this to the CCALL instruction.--- let ffires = primRepToFFIType platform r_rep- ffiargs = map (primRepToFFIType platform) a_reps- hsc_env <- getHscEnv- token <- ioToBc $ iservCmd hsc_env (PrepFFI conv ffiargs ffires)- recordFFIBc token-- let- -- do the call- do_call = unitOL (CCALL stk_offset token flags)- where flags = case safety of- PlaySafe -> 0x0- PlayInterruptible -> 0x1- PlayRisky -> 0x2-- -- slide and return- d_after_r_min_s = bytesToWords platform (d_after_r - s)- wrapup = mkSlideW (trunc16W r_sizeW) (d_after_r_min_s - r_sizeW)- `snocOL` RETURN_UBX (toArgRep platform r_rep)- --trace (show (arg1_offW, args_offW , (map argRepSizeW a_reps) )) $- return (- push_args `appOL`- push_Addr `appOL` push_r `appOL` do_call `appOL` wrapup- )--primRepToFFIType :: Platform -> PrimRep -> FFIType-primRepToFFIType platform r- = case r of- VoidRep -> FFIVoid- IntRep -> signed_word- WordRep -> unsigned_word- Int8Rep -> FFISInt8- Word8Rep -> FFIUInt8- Int16Rep -> FFISInt16- Word16Rep -> FFIUInt16- Int32Rep -> FFISInt32- Word32Rep -> FFIUInt32- Int64Rep -> FFISInt64- Word64Rep -> FFIUInt64- AddrRep -> FFIPointer- FloatRep -> FFIFloat- DoubleRep -> FFIDouble- _ -> panic "primRepToFFIType"- where- (signed_word, unsigned_word) = case platformWordSize platform of- PW4 -> (FFISInt32, FFIUInt32)- PW8 -> (FFISInt64, FFIUInt64)---- Make a dummy literal, to be used as a placeholder for FFI return--- values on the stack.-mkDummyLiteral :: Platform -> PrimRep -> Literal-mkDummyLiteral platform pr- = case pr of- IntRep -> mkLitInt platform 0- WordRep -> mkLitWord platform 0- Int8Rep -> mkLitInt8 0- Word8Rep -> mkLitWord8 0- Int16Rep -> mkLitInt16 0- Word16Rep -> mkLitWord16 0- Int32Rep -> mkLitInt32 0- Word32Rep -> mkLitWord32 0- Int64Rep -> mkLitInt64 0- Word64Rep -> mkLitWord64 0- AddrRep -> LitNullAddr- DoubleRep -> LitDouble 0- FloatRep -> LitFloat 0- _ -> pprPanic "mkDummyLiteral" (ppr pr)----- Convert (eg)--- GHC.Prim.Char# -> GHC.Prim.State# GHC.Prim.RealWorld--- -> (# GHC.Prim.State# GHC.Prim.RealWorld, GHC.Prim.Int# #)------ to Just IntRep--- and check that an unboxed pair is returned wherein the first arg is V'd.------ Alternatively, for call-targets returning nothing, convert------ GHC.Prim.Char# -> GHC.Prim.State# GHC.Prim.RealWorld--- -> (# GHC.Prim.State# GHC.Prim.RealWorld #)------ to Nothing--maybe_getCCallReturnRep :: Type -> Maybe PrimRep-maybe_getCCallReturnRep fn_ty- = let- (_a_tys, r_ty) = splitFunTys (dropForAlls fn_ty)- r_reps = typePrimRepArgs r_ty-- blargh :: a -- Used at more than one type- blargh = pprPanic "maybe_getCCallReturn: can't handle:"- (pprType fn_ty)- in- case r_reps of- [] -> panic "empty typePrimRepArgs"- [VoidRep] -> Nothing- [rep]- | isGcPtrRep rep -> blargh- | otherwise -> Just rep-- -- if it was, it would be impossible to create a- -- valid return value placeholder on the stack- _ -> blargh--maybe_is_tagToEnum_call :: AnnExpr' Id DVarSet -> Maybe (AnnExpr' Id DVarSet, [Name])--- Detect and extract relevant info for the tagToEnum kludge.-maybe_is_tagToEnum_call app- | AnnApp (_, AnnApp (_, AnnVar v) (_, AnnType t)) arg <- app- , Just TagToEnumOp <- isPrimOpId_maybe v- = Just (snd arg, extract_constr_Names t)- | otherwise- = Nothing- where- extract_constr_Names ty- | rep_ty <- unwrapType ty- , Just tyc <- tyConAppTyCon_maybe rep_ty- , isDataTyCon tyc- = map (getName . dataConWorkId) (tyConDataCons tyc)- -- NOTE: use the worker name, not the source name of- -- the DataCon. See "GHC.Core.DataCon" for details.- | otherwise- = pprPanic "maybe_is_tagToEnum_call.extract_constr_Ids" (ppr ty)--{- ------------------------------------------------------------------------------Note [Implementing tagToEnum#]-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~-(implement_tagToId arg names) compiles code which takes an argument-'arg', (call it i), and enters the i'th closure in the supplied list-as a consequence. The [Name] is a list of the constructors of this-(enumeration) type.--The code we generate is this:- push arg- push bogus-word-- TESTEQ_I 0 L1- PUSH_G <lbl for first data con>- JMP L_Exit-- L1: TESTEQ_I 1 L2- PUSH_G <lbl for second data con>- JMP L_Exit- ...etc...- Ln: TESTEQ_I n L_fail- PUSH_G <lbl for last data con>- JMP L_Exit-- L_fail: CASEFAIL-- L_exit: SLIDE 1 n- ENTER--The 'bogus-word' push is because TESTEQ_I expects the top of the stack-to have an info-table, and the next word to have the value to be-tested. This is very weird, but it's the way it is right now. See-Interpreter.c. We don't actually need an info-table here; we just-need to have the argument to be one-from-top on the stack, hence pushing-a 1-word null. See #8383.--}---implement_tagToId- :: StackDepth- -> Sequel- -> BCEnv- -> AnnExpr' Id DVarSet- -> [Name]- -> BcM BCInstrList--- See Note [Implementing tagToEnum#]-implement_tagToId d s p arg names- = ASSERT( notNull names )- do (push_arg, arg_bytes) <- pushAtom d p arg- labels <- getLabelsBc (genericLength names)- label_fail <- getLabelBc- label_exit <- getLabelBc- dflags <- getDynFlags- let infos = zip4 labels (tail labels ++ [label_fail])- [0 ..] names- platform = targetPlatform dflags- steps = map (mkStep label_exit) infos- slide_ws = bytesToWords platform (d - s + arg_bytes)-- return (push_arg- `appOL` unitOL (PUSH_UBX LitNullAddr 1)- -- Push bogus word (see Note [Implementing tagToEnum#])- `appOL` concatOL steps- `appOL` toOL [ LABEL label_fail, CASEFAIL,- LABEL label_exit ]- `appOL` mkSlideW 1 (slide_ws + 1)- -- "+1" to account for bogus word- -- (see Note [Implementing tagToEnum#])- `appOL` unitOL ENTER)- where- mkStep l_exit (my_label, next_label, n, name_for_n)- = toOL [LABEL my_label,- TESTEQ_I n next_label,- PUSH_G name_for_n,- JMP l_exit]----- -------------------------------------------------------------------------------- pushAtom---- Push an atom onto the stack, returning suitable code & number of--- stack words used.------ The env p must map each variable to the highest- numbered stack--- slot for it. For example, if the stack has depth 4 and we--- tagged-ly push (v :: Int#) on it, the value will be in stack[4],--- the tag in stack[5], the stack will have depth 6, and p must map v--- to 5 and not to 4. Stack locations are numbered from zero, so a--- depth 6 stack has valid words 0 .. 5.--pushAtom- :: StackDepth -> BCEnv -> AnnExpr' Id DVarSet -> BcM (BCInstrList, ByteOff)-pushAtom d p e- | Just e' <- bcView e- = pushAtom d p e'--pushAtom _ _ (AnnCoercion {}) -- Coercions are zero-width things,- = return (nilOL, 0) -- treated just like a variable V---- See Note [Empty case alternatives] in GHC.Core--- and Note [Bottoming expressions] in GHC.Core.Utils:--- The scrutinee of an empty case evaluates to bottom-pushAtom d p (AnnCase (_, a) _ _ []) -- trac #12128- = pushAtom d p a--pushAtom d p (AnnVar var)- | [] <- typePrimRep (idType var)- = return (nilOL, 0)-- | isFCallId var- = pprPanic "pushAtom: shouldn't get an FCallId here" (ppr var)-- | Just primop <- isPrimOpId_maybe var- = do- platform <- targetPlatform <$> getDynFlags- return (unitOL (PUSH_PRIMOP primop), wordSize platform)-- | Just d_v <- lookupBCEnv_maybe var p -- var is a local variable- = do platform <- targetPlatform <$> getDynFlags-- let !szb = idSizeCon platform var- with_instr instr = do- let !off_b = trunc16B $ d - d_v- return (unitOL (instr off_b), wordSize platform)-- case szb of- 1 -> with_instr PUSH8_W- 2 -> with_instr PUSH16_W- 4 -> with_instr PUSH32_W- _ -> do- let !szw = bytesToWords platform szb- !off_w = trunc16W $ bytesToWords platform (d - d_v) + szw - 1- return (toOL (genericReplicate szw (PUSH_L off_w)), szb)- -- d - d_v offset from TOS to the first slot of the object- --- -- d - d_v + sz - 1 offset from the TOS of the last slot of the object- --- -- Having found the last slot, we proceed to copy the right number of- -- slots on to the top of the stack.-- | otherwise -- var must be a global variable- = do topStrings <- getTopStrings- platform <- targetPlatform <$> getDynFlags- case lookupVarEnv topStrings var of- Just ptr -> pushAtom d p $ AnnLit $ mkLitWord platform $- fromIntegral $ ptrToWordPtr $ fromRemotePtr ptr- Nothing -> do- let sz = idSizeCon platform var- MASSERT( sz == wordSize platform )- return (unitOL (PUSH_G (getName var)), sz)---pushAtom _ _ (AnnLit lit) = do- platform <- targetPlatform <$> getDynFlags- let code :: PrimRep -> BcM (BCInstrList, ByteOff)- code rep =- return (unitOL instr, size_bytes)- where- size_bytes = ByteOff $ primRepSizeB platform rep- -- Here we handle the non-word-width cases specifically since we- -- must emit different bytecode for them.- instr =- case size_bytes of- 1 -> PUSH_UBX8 lit- 2 -> PUSH_UBX16 lit- 4 -> PUSH_UBX32 lit- _ -> PUSH_UBX lit (trunc16W $ bytesToWords platform size_bytes)-- case lit of- LitLabel {} -> code AddrRep- LitFloat {} -> code FloatRep- LitDouble {} -> code DoubleRep- LitChar {} -> code WordRep- LitNullAddr -> code AddrRep- LitString {} -> code AddrRep- LitRubbish {} -> code WordRep- LitNumber nt _ -> case nt of- LitNumInt -> code IntRep- LitNumWord -> code WordRep- LitNumInt8 -> code Int8Rep- LitNumWord8 -> code Word8Rep- LitNumInt16 -> code Int16Rep- LitNumWord16 -> code Word16Rep- LitNumInt32 -> code Int32Rep- LitNumWord32 -> code Word32Rep- LitNumInt64 -> code Int64Rep- LitNumWord64 -> code Word64Rep- -- No LitInteger's or LitNatural's should be left by the time this is- -- called. CorePrep should have converted them all to a real core- -- representation.- LitNumInteger -> panic "pushAtom: LitInteger"- LitNumNatural -> panic "pushAtom: LitNatural"--pushAtom _ _ expr- = pprPanic "GHC.CoreToByteCode.pushAtom"- (pprCoreExpr (deAnnotate' expr))----- | Push an atom for constructor (i.e., PACK instruction) onto the stack.--- This is slightly different to @pushAtom@ due to the fact that we allow--- packing constructor fields. See also @mkConAppCode@ and @pushPadding@.-pushConstrAtom- :: StackDepth -> BCEnv -> AnnExpr' Id DVarSet -> BcM (BCInstrList, ByteOff)--pushConstrAtom _ _ (AnnLit lit@(LitFloat _)) =- return (unitOL (PUSH_UBX32 lit), 4)--pushConstrAtom d p (AnnVar v)- | Just d_v <- lookupBCEnv_maybe v p = do -- v is a local variable- platform <- targetPlatform <$> getDynFlags- let !szb = idSizeCon platform v- done instr = do- let !off = trunc16B $ d - d_v- return (unitOL (instr off), szb)- case szb of- 1 -> done PUSH8- 2 -> done PUSH16- 4 -> done PUSH32- _ -> pushAtom d p (AnnVar v)--pushConstrAtom d p expr = pushAtom d p expr--pushPadding :: Int -> (BCInstrList, ByteOff)-pushPadding !n = go n (nilOL, 0)- where- go n acc@(!instrs, !off) = case n of- 0 -> acc- 1 -> (instrs `mappend` unitOL PUSH_PAD8, off + 1)- 2 -> (instrs `mappend` unitOL PUSH_PAD16, off + 2)- 3 -> go 1 (go 2 acc)- 4 -> (instrs `mappend` unitOL PUSH_PAD32, off + 4)- _ -> go (n - 4) (go 4 acc)---- -------------------------------------------------------------------------------- Given a bunch of alts code and their discrs, do the donkey work--- of making a multiway branch using a switch tree.--- What a load of hassle!--mkMultiBranch :: Maybe Int -- # datacons in tycon, if alg alt- -- a hint; generates better code- -- Nothing is always safe- -> [(Discr, BCInstrList)]- -> BcM BCInstrList-mkMultiBranch maybe_ncons raw_ways = do- lbl_default <- getLabelBc-- let- mkTree :: [(Discr, BCInstrList)] -> Discr -> Discr -> BcM BCInstrList- mkTree [] _range_lo _range_hi = return (unitOL (JMP lbl_default))- -- shouldn't happen?-- mkTree [val] range_lo range_hi- | range_lo == range_hi- = return (snd val)- | null defaults -- Note [CASEFAIL]- = do lbl <- getLabelBc- return (testEQ (fst val) lbl- `consOL` (snd val- `appOL` (LABEL lbl `consOL` unitOL CASEFAIL)))- | otherwise- = return (testEQ (fst val) lbl_default `consOL` snd val)-- -- Note [CASEFAIL] It may be that this case has no default- -- branch, but the alternatives are not exhaustive - this- -- happens for GADT cases for example, where the types- -- prove that certain branches are impossible. We could- -- just assume that the other cases won't occur, but if- -- this assumption was wrong (because of a bug in GHC)- -- then the result would be a segfault. So instead we- -- emit an explicit test and a CASEFAIL instruction that- -- causes the interpreter to barf() if it is ever- -- executed.-- mkTree vals range_lo range_hi- = let n = length vals `div` 2- vals_lo = take n vals- vals_hi = drop n vals- v_mid = fst (head vals_hi)- in do- label_geq <- getLabelBc- code_lo <- mkTree vals_lo range_lo (dec v_mid)- code_hi <- mkTree vals_hi v_mid range_hi- return (testLT v_mid label_geq- `consOL` (code_lo- `appOL` unitOL (LABEL label_geq)- `appOL` code_hi))-- the_default- = case defaults of- [] -> nilOL- [(_, def)] -> LABEL lbl_default `consOL` def- _ -> panic "mkMultiBranch/the_default"- instrs <- mkTree notd_ways init_lo init_hi- return (instrs `appOL` the_default)- where- (defaults, not_defaults) = partition (isNoDiscr.fst) raw_ways- notd_ways = sortBy (comparing fst) not_defaults-- testLT (DiscrI i) fail_label = TESTLT_I i fail_label- testLT (DiscrW i) fail_label = TESTLT_W i fail_label- testLT (DiscrF i) fail_label = TESTLT_F i fail_label- testLT (DiscrD i) fail_label = TESTLT_D i fail_label- testLT (DiscrP i) fail_label = TESTLT_P i fail_label- testLT NoDiscr _ = panic "mkMultiBranch NoDiscr"-- testEQ (DiscrI i) fail_label = TESTEQ_I i fail_label- testEQ (DiscrW i) fail_label = TESTEQ_W i fail_label- testEQ (DiscrF i) fail_label = TESTEQ_F i fail_label- testEQ (DiscrD i) fail_label = TESTEQ_D i fail_label- testEQ (DiscrP i) fail_label = TESTEQ_P i fail_label- testEQ NoDiscr _ = panic "mkMultiBranch NoDiscr"-- -- None of these will be needed if there are no non-default alts- (init_lo, init_hi)- | null notd_ways- = panic "mkMultiBranch: awesome foursome"- | otherwise- = case fst (head notd_ways) of- DiscrI _ -> ( DiscrI minBound, DiscrI maxBound )- DiscrW _ -> ( DiscrW minBound, DiscrW maxBound )- DiscrF _ -> ( DiscrF minF, DiscrF maxF )- DiscrD _ -> ( DiscrD minD, DiscrD maxD )- DiscrP _ -> ( DiscrP algMinBound, DiscrP algMaxBound )- NoDiscr -> panic "mkMultiBranch NoDiscr"-- (algMinBound, algMaxBound)- = case maybe_ncons of- -- XXX What happens when n == 0?- Just n -> (0, fromIntegral n - 1)- Nothing -> (minBound, maxBound)-- isNoDiscr NoDiscr = True- isNoDiscr _ = False-- dec (DiscrI i) = DiscrI (i-1)- dec (DiscrW w) = DiscrW (w-1)- dec (DiscrP i) = DiscrP (i-1)- dec other = other -- not really right, but if you- -- do cases on floating values, you'll get what you deserve-- -- same snotty comment applies to the following- minF, maxF :: Float- minD, maxD :: Double- minF = -1.0e37- maxF = 1.0e37- minD = -1.0e308- maxD = 1.0e308----- -------------------------------------------------------------------------------- Supporting junk for the compilation schemes---- Describes case alts-data Discr- = DiscrI Int- | DiscrW Word- | DiscrF Float- | DiscrD Double- | DiscrP Word16- | NoDiscr- deriving (Eq, Ord)--instance Outputable Discr where- ppr (DiscrI i) = int i- ppr (DiscrW w) = text (show w)- ppr (DiscrF f) = text (show f)- ppr (DiscrD d) = text (show d)- ppr (DiscrP i) = ppr i- ppr NoDiscr = text "DEF"---lookupBCEnv_maybe :: Id -> BCEnv -> Maybe ByteOff-lookupBCEnv_maybe = Map.lookup--idSizeW :: Platform -> Id -> WordOff-idSizeW platform = WordOff . argRepSizeW platform . bcIdArgRep platform--idSizeCon :: Platform -> Id -> ByteOff-idSizeCon platform = ByteOff . primRepSizeB platform . bcIdPrimRep--bcIdArgRep :: Platform -> Id -> ArgRep-bcIdArgRep platform = toArgRep platform . bcIdPrimRep--bcIdPrimRep :: Id -> PrimRep-bcIdPrimRep id- | [rep] <- typePrimRepArgs (idType id)- = rep- | otherwise- = pprPanic "bcIdPrimRep" (ppr id <+> dcolon <+> ppr (idType id))--repSizeWords :: Platform -> PrimRep -> WordOff-repSizeWords platform rep = WordOff $ argRepSizeW platform (toArgRep platform rep)--isFollowableArg :: ArgRep -> Bool-isFollowableArg P = True-isFollowableArg _ = False--isVoidArg :: ArgRep -> Bool-isVoidArg V = True-isVoidArg _ = False---- See bug #1257-multiValException :: a-multiValException = throwGhcException (ProgramError- ("Error: bytecode compiler can't handle unboxed tuples and sums.\n"++- " Possibly due to foreign import/export decls in source.\n"++- " Workaround: use -fobject-code, or compile this module to .o separately."))---- | Indicate if the calling convention is supported-isSupportedCConv :: CCallSpec -> Bool-isSupportedCConv (CCallSpec _ cconv _) = case cconv of- CCallConv -> True -- we explicitly pattern match on every- StdCallConv -> True -- convention to ensure that a warning- PrimCallConv -> False -- is triggered when a new one is added- JavaScriptCallConv -> False- CApiConv -> False---- See bug #10462-unsupportedCConvException :: a-unsupportedCConvException = throwGhcException (ProgramError- ("Error: bytecode compiler can't handle some foreign calling conventions\n"++- " Workaround: use -fobject-code, or compile this module to .o separately."))--mkSlideB :: Platform -> ByteOff -> ByteOff -> OrdList BCInstr-mkSlideB platform !nb !db = mkSlideW n d- where- !n = trunc16W $ bytesToWords platform nb- !d = bytesToWords platform db--mkSlideW :: Word16 -> WordOff -> OrdList BCInstr-mkSlideW !n !ws- | ws > fromIntegral limit- -- If the amount to slide doesn't fit in a Word16, generate multiple slide- -- instructions- = SLIDE n limit `consOL` mkSlideW n (ws - fromIntegral limit)- | ws == 0- = nilOL- | otherwise- = unitOL (SLIDE n $ fromIntegral ws)- where- limit :: Word16- limit = maxBound--splitApp :: AnnExpr' Var ann -> (AnnExpr' Var ann, [AnnExpr' Var ann])- -- The arguments are returned in *right-to-left* order-splitApp e | Just e' <- bcView e = splitApp e'-splitApp (AnnApp (_,f) (_,a)) = case splitApp f of- (f', as) -> (f', a:as)-splitApp e = (e, [])---bcView :: AnnExpr' Var ann -> Maybe (AnnExpr' Var ann)--- The "bytecode view" of a term discards--- a) type abstractions--- b) type applications--- c) casts--- d) ticks (but not breakpoints)--- e) case unsafeEqualityProof of UnsafeRefl -> e ==> e--- Type lambdas *can* occur in random expressions,--- whereas value lambdas cannot; that is why they are nuked here-bcView (AnnCast (_,e) _) = Just e-bcView (AnnLam v (_,e)) | isTyVar v = Just e-bcView (AnnApp (_,e) (_, AnnType _)) = Just e-bcView (AnnTick Breakpoint{} _) = Nothing-bcView (AnnTick _other_tick (_,e)) = Just e-bcView (AnnCase (_,e) _ _ alts) -- Handle unsafe equality proof- | AnnVar id <- bcViewLoop e- , idName id == unsafeEqualityProofName- , [AnnAlt _ _ (_, rhs)] <- alts- = Just rhs-bcView _ = Nothing--bcViewLoop :: AnnExpr' Var ann -> AnnExpr' Var ann-bcViewLoop e =- case bcView e of- Nothing -> e- Just e' -> bcViewLoop e'--isVAtom :: Platform -> AnnExpr' Var ann -> Bool-isVAtom platform expr = case expr of- e | Just e' <- bcView e -> isVAtom platform e'- (AnnVar v) -> isVoidArg (bcIdArgRep platform v)- (AnnCoercion {}) -> True- _ -> False--atomPrimRep :: AnnExpr' Id ann -> PrimRep-atomPrimRep e | Just e' <- bcView e = atomPrimRep e'-atomPrimRep (AnnVar v) = bcIdPrimRep v-atomPrimRep (AnnLit l) = typePrimRep1 (literalType l)---- #12128:--- A case expression can be an atom because empty cases evaluate to bottom.--- See Note [Empty case alternatives] in GHC.Core-atomPrimRep (AnnCase _ _ ty _) =- ASSERT(case typePrimRep ty of [LiftedRep] -> True; _ -> False) LiftedRep-atomPrimRep (AnnCoercion {}) = VoidRep-atomPrimRep other = pprPanic "atomPrimRep" (ppr (deAnnotate' other))--atomRep :: Platform -> AnnExpr' Id ann -> ArgRep-atomRep platform e = toArgRep platform (atomPrimRep e)---- | Let szsw be the sizes in bytes of some items pushed onto the stack, which--- has initial depth @original_depth@. Return the values which the stack--- environment should map these items to.-mkStackOffsets :: ByteOff -> [ByteOff] -> [ByteOff]-mkStackOffsets original_depth szsb = tail (scanl' (+) original_depth szsb)--typeArgRep :: Platform -> Type -> ArgRep-typeArgRep platform = toArgRep platform . typePrimRep1---- -------------------------------------------------------------------------------- The bytecode generator's monad--data BcM_State- = BcM_State- { bcm_hsc_env :: HscEnv- , uniqSupply :: UniqSupply -- for generating fresh variable names- , thisModule :: Module -- current module (for breakpoints)- , nextlabel :: Word32 -- for generating local labels- , ffis :: [FFIInfo] -- ffi info blocks, to free later- -- Should be free()d when it is GCd- , modBreaks :: Maybe ModBreaks -- info about breakpoints- , breakInfo :: IntMap CgBreakInfo- , topStrings :: IdEnv (RemotePtr ()) -- top-level string literals- -- See Note [generating code for top-level string literal bindings].- }--newtype BcM r = BcM (BcM_State -> IO (BcM_State, r)) deriving (Functor)--ioToBc :: IO a -> BcM a-ioToBc io = BcM $ \st -> do- x <- io- return (st, x)--runBc :: HscEnv -> UniqSupply -> Module -> Maybe ModBreaks- -> IdEnv (RemotePtr ())- -> BcM r- -> IO (BcM_State, r)-runBc hsc_env us this_mod modBreaks topStrings (BcM m)- = m (BcM_State hsc_env us this_mod 0 [] modBreaks IntMap.empty topStrings)--thenBc :: BcM a -> (a -> BcM b) -> BcM b-thenBc (BcM expr) cont = BcM $ \st0 -> do- (st1, q) <- expr st0- let BcM k = cont q- (st2, r) <- k st1- return (st2, r)--thenBc_ :: BcM a -> BcM b -> BcM b-thenBc_ (BcM expr) (BcM cont) = BcM $ \st0 -> do- (st1, _) <- expr st0- (st2, r) <- cont st1- return (st2, r)--returnBc :: a -> BcM a-returnBc result = BcM $ \st -> (return (st, result))--instance Applicative BcM where- pure = returnBc- (<*>) = ap- (*>) = thenBc_--instance Monad BcM where- (>>=) = thenBc- (>>) = (*>)--instance HasDynFlags BcM where- getDynFlags = BcM $ \st -> return (st, hsc_dflags (bcm_hsc_env st))--getHscEnv :: BcM HscEnv-getHscEnv = BcM $ \st -> return (st, bcm_hsc_env st)--getProfile :: BcM Profile-getProfile = targetProfile <$> getDynFlags--emitBc :: ([FFIInfo] -> ProtoBCO Name) -> BcM (ProtoBCO Name)-emitBc bco- = BcM $ \st -> return (st{ffis=[]}, bco (ffis st))--recordFFIBc :: RemotePtr C_ffi_cif -> BcM ()-recordFFIBc a- = BcM $ \st -> return (st{ffis = FFIInfo a : ffis st}, ())--getLabelBc :: BcM LocalLabel-getLabelBc- = BcM $ \st -> do let nl = nextlabel st- when (nl == maxBound) $- panic "getLabelBc: Ran out of labels"- return (st{nextlabel = nl + 1}, LocalLabel nl)--getLabelsBc :: Word32 -> BcM [LocalLabel]-getLabelsBc n- = BcM $ \st -> let ctr = nextlabel st- in return (st{nextlabel = ctr+n}, coerce [ctr .. ctr+n-1])--getCCArray :: BcM (Array BreakIndex (RemotePtr CostCentre))-getCCArray = BcM $ \st ->- let breaks = expectJust "GHC.CoreToByteCode.getCCArray" $ modBreaks st in- return (st, modBreaks_ccs breaks)---newBreakInfo :: BreakIndex -> CgBreakInfo -> BcM ()-newBreakInfo ix info = BcM $ \st ->- return (st{breakInfo = IntMap.insert ix info (breakInfo st)}, ())--newUnique :: BcM Unique-newUnique = BcM $- \st -> case takeUniqFromSupply (uniqSupply st) of- (uniq, us) -> let newState = st { uniqSupply = us }- in return (newState, uniq)--getCurrentModule :: BcM Module-getCurrentModule = BcM $ \st -> return (st, thisModule st)--getTopStrings :: BcM (IdEnv (RemotePtr ()))-getTopStrings = BcM $ \st -> return (st, topStrings st)--newId :: Type -> BcM Id-newId ty = do- uniq <- newUnique- return $ mkSysLocal tickFS uniq Many ty--tickFS :: FastString-tickFS = fsLit "ticked"
compiler/GHC/CoreToStg.hs view
@@ -1,4 +1,6 @@-{-# LANGUAGE CPP, DeriveFunctor #-}+{-# LANGUAGE CPP #-}+{-# LANGUAGE DeriveFunctor #-}+{-# LANGUAGE TypeFamilies #-} -- -- (c) The GRASP/AQUA Project, Glasgow University, 1993-1998@@ -22,6 +24,7 @@ , exprIsTickedString_maybe ) import GHC.Core.Opt.Arity ( manifestArity ) import GHC.Stg.Syntax+import GHC.Stg.Debug import GHC.Core.Type import GHC.Types.RepType@@ -31,11 +34,12 @@ import GHC.Types.Id.Info import GHC.Core.DataCon import GHC.Types.CostCentre+import GHC.Types.Tickish import GHC.Types.Var.Env import GHC.Unit.Module import GHC.Types.Name ( isExternalName, nameModule_maybe ) import GHC.Types.Basic ( Arity )-import GHC.Builtin.Types ( unboxedUnitDataCon, unitDataConId )+import GHC.Builtin.Types ( unboxedUnitDataCon ) import GHC.Types.Literal import GHC.Utils.Outputable import GHC.Utils.Monad@@ -46,6 +50,7 @@ import GHC.Platform.Ways import GHC.Driver.Ppr import GHC.Types.ForeignCall+import GHC.Types.IPE import GHC.Types.Demand ( isUsedOnceDmd ) import GHC.Builtin.PrimOps ( PrimCall(..) ) import GHC.Types.SrcLoc ( mkGeneralSrcSpan )@@ -226,14 +231,21 @@ -- Setting variable info: top-level, binds, RHSs -- -------------------------------------------------------------- -coreToStg :: DynFlags -> Module -> CoreProgram- -> ([StgTopBinding], CollectedCCs)-coreToStg dflags this_mod pgm- = (pgm', final_ccs)++coreToStg :: DynFlags -> Module -> ModLocation -> CoreProgram+ -> ([StgTopBinding], InfoTableProvMap, CollectedCCs)+coreToStg dflags this_mod ml pgm+ = (pgm'', denv, final_ccs) where (_, (local_ccs, local_cc_stacks), pgm') = coreTopBindsToStg dflags this_mod emptyVarEnv emptyCollectedCCs pgm + -- See Note [Mapping Info Tables to Source Positions]+ (!pgm'', !denv) =+ if gopt Opt_InfoTableMap dflags+ then collectDebugInformation dflags ml pgm'+ else (pgm', emptyInfoTableProvMap)+ prof = WayProf `Set.member` ways dflags final_ccs@@ -376,12 +388,8 @@ -- CorePrep should have converted them all to a real core representation. coreToStgExpr (Lit (LitNumber LitNumInteger _)) = panic "coreToStgExpr: LitInteger" coreToStgExpr (Lit (LitNumber LitNumNatural _)) = panic "coreToStgExpr: LitNatural"-coreToStgExpr (Lit l) = return (StgLit l)-coreToStgExpr (App (Lit lit) _some_boxed_type)- | isRubbishLit lit- -- We lower 'LitRubbish' to @()@ here, which is much easier than doing it in- -- a STG to Cmm pass. Doesn't matter whether it is lifted or unlifted- = coreToStgExpr (Var unitDataConId)+coreToStgExpr (Lit l) = return (StgLit l)+coreToStgExpr (App l@(Lit LitRubbish{}) Type{}) = coreToStgExpr l coreToStgExpr (Var v) = coreToStgApp v [] [] coreToStgExpr (Coercion _) -- See Note [Coercion tokens]@@ -404,13 +412,10 @@ text "Unexpected value lambda:" $$ ppr expr coreToStgExpr (Tick tick expr)- = do case tick of- HpcTick{} -> return ()- ProfNote{} -> return ()- SourceNote{} -> return ()- Breakpoint{} -> panic "coreToStgExpr: breakpoint should not happen"- expr2 <- coreToStgExpr expr- return (StgTick tick expr2)+ = do+ let !stg_tick = coreToStgTick (exprType expr) tick+ !expr2 <- coreToStgExpr expr+ return (StgTick stg_tick expr2) coreToStgExpr (Cast expr _) = coreToStgExpr expr@@ -475,15 +480,16 @@ | otherwise = case prim_reps of- [LiftedRep] -> case tyConAppTyCon_maybe (unwrapType bndr_ty) of- Just tc- | isAbstractTyCon tc -> look_for_better_tycon- | isAlgTyCon tc -> AlgAlt tc- | otherwise -> ASSERT2( _is_poly_alt_tycon tc, ppr tc )- PolyAlt- Nothing -> PolyAlt- [unlifted] -> PrimAlt unlifted- not_unary -> MultiValAlt (length not_unary)+ [rep] | isGcPtrRep rep ->+ case tyConAppTyCon_maybe (unwrapType bndr_ty) of+ Just tc+ | isAbstractTyCon tc -> look_for_better_tycon+ | isAlgTyCon tc -> AlgAlt tc+ | otherwise -> ASSERT2( _is_poly_alt_tycon tc, ppr tc )+ PolyAlt+ Nothing -> PolyAlt+ [non_gcd] -> PrimAlt non_gcd+ not_unary -> MultiValAlt (length not_unary) where bndr_ty = idType bndr prim_reps = typePrimRep bndr_ty@@ -514,7 +520,7 @@ coreToStgApp :: Id -- Function -> [CoreArg] -- Arguments- -> [Tickish Id] -- Debug ticks+ -> [CoreTickish] -- Debug ticks -> CtsM StgExpr coreToStgApp f args ticks = do (args', ticks') <- coreToStgArgs args@@ -536,7 +542,7 @@ res_ty = exprType (mkApps (Var f) args) app = case idDetails f of DataConWorkId dc- | saturated -> StgConApp dc args'+ | saturated -> StgConApp dc NoNumber args' (dropRuntimeRepArgs (fromMaybe [] (tyConAppArgs_maybe res_ty))) -- Some primitive operator that might be implemented as a library call.@@ -558,7 +564,8 @@ TickBoxOpId {} -> pprPanic "coreToStg TickBox" $ ppr (f,args') _other -> StgApp f args' - tapp = foldr StgTick app (ticks ++ ticks')+ add_tick !t !e = StgTick t e+ tapp = foldr add_tick app (map (coreToStgTick res_ty) ticks ++ ticks') -- Forcing these fixes a leak in the code generator, noticed while -- profiling for trac #4367@@ -569,7 +576,7 @@ -- This is the guy that turns applications into A-normal form -- --------------------------------------------------------------------------- -coreToStgArgs :: [CoreArg] -> CtsM ([StgArg], [Tickish Id])+coreToStgArgs :: [CoreArg] -> CtsM ([StgArg], [StgTickish]) coreToStgArgs [] = return ([], []) @@ -584,7 +591,8 @@ coreToStgArgs (Tick t e : args) = ASSERT( not (tickishIsCode t) ) do { (args', ts) <- coreToStgArgs (e : args)- ; return (args', t:ts) }+ ; let !t' = coreToStgTick (exprType e) t+ ; return (args', t':ts) } coreToStgArgs (arg : args) = do -- Non-type argument (stg_args, ticks) <- coreToStgArgs args@@ -593,7 +601,7 @@ (aticks, arg'') = stripStgTicksTop tickishFloatable arg' stg_arg = case arg'' of StgApp v [] -> StgVarArg v- StgConApp con [] _ -> StgVarArg (dataConWorkId con)+ StgConApp con _ [] _ -> StgVarArg (dataConWorkId con) StgLit lit -> StgLitArg lit _ -> pprPanic "coreToStgArgs" (ppr arg) @@ -616,6 +624,13 @@ WARN( bad_args, text "Dangerous-looking argument. Probable cause: bad unsafeCoerce#" $$ ppr arg ) return (stg_arg : stg_args, ticks ++ aticks) +coreToStgTick :: Type -- type of the ticked expression+ -> CoreTickish+ -> StgTickish+coreToStgTick _ty (HpcTick m i) = HpcTick m i+coreToStgTick _ty (SourceNote span nm) = SourceNote span nm+coreToStgTick _ty (ProfNote cc cnt scope) = ProfNote cc cnt scope+coreToStgTick !ty (Breakpoint _ bid fvs) = Breakpoint ty bid fvs -- --------------------------------------------------------------------------- -- The magic for lets:@@ -710,13 +725,13 @@ -- After this point we know that `bndrs` is empty, -- so this is not a function binding- | StgConApp con args _ <- unticked_rhs+ | StgConApp con mn args _ <- unticked_rhs , -- Dynamic StgConApps are updatable not (isDllConApp dflags this_mod con args) = -- CorePrep does this right, but just to make sure ASSERT2( not (isUnboxedTupleDataCon con || isUnboxedSumDataCon con) , ppr bndr $$ ppr con $$ ppr args)- ( StgRhsCon dontCareCCS con args, ccs )+ ( StgRhsCon dontCareCCS con mn ticks args, ccs ) -- Otherwise it's a CAF, see Note [Cost-centre initialization plan]. | gopt Opt_AutoSccsOnIndividualCafs dflags@@ -732,7 +747,7 @@ , ccs ) where- unticked_rhs = stripStgTicksTopE (not . tickishIsCode) rhs+ (ticks, unticked_rhs) = stripStgTicksTop (not . tickishIsCode) rhs upd_flag | isUsedOnceDmd (idDemandInfo bndr) = SingleEntry | otherwise = Updatable@@ -768,15 +783,15 @@ ReEntrant -- ignored for LNE [] rhs - | StgConApp con args _ <- unticked_rhs- = StgRhsCon currentCCS con args+ | StgConApp con mn args _ <- unticked_rhs+ = StgRhsCon currentCCS con mn ticks args | otherwise = StgRhsClosure noExtFieldSilent currentCCS upd_flag [] rhs where- unticked_rhs = stripStgTicksTopE (not . tickishIsCode) rhs+ (ticks, unticked_rhs) = stripStgTicksTop (not . tickishIsCode) rhs upd_flag | isUsedOnceDmd (idDemandInfo bndr) = SingleEntry | otherwise = Updatable@@ -943,24 +958,39 @@ -- | Precondition: argument expression is an 'App', and there is a 'Var' at the -- head of the 'App' chain.-myCollectArgs :: CoreExpr -> (Id, [CoreArg], [Tickish Id])+myCollectArgs :: CoreExpr -> (Id, [CoreArg], [CoreTickish]) myCollectArgs expr = go expr [] [] where go (Var v) as ts = (v, as, ts) go (App f a) as ts = go f (a:as) ts- go (Tick t e) as ts = ASSERT( all isTypeArg as )+ go (Tick t e) as ts = ASSERT2( not (tickishIsCode t) || all isTypeArg as+ , ppr e $$ ppr as $$ ppr ts )+ -- See Note [Ticks in applications] go e as (t:ts) -- ticks can appear in type apps go (Cast e _) as ts = go e as ts go (Lam b e) as ts | isTyVar b = go e as ts -- Note [Collect args] go _ _ _ = pprPanic "CoreToStg.myCollectArgs" (ppr expr) --- Note [Collect args]--- ~~~~~~~~~~~~~~~~~~~------ This big-lambda case occurred following a rather obscure eta expansion.--- It all seems a bit yukky to me.+{- Note [Collect args]+~~~~~~~~~~~~~~~~~~~~~~+This big-lambda case occurred following a rather obscure eta expansion.+It all seems a bit yukky to me.++Note [Ticks in applications]+~~~~~~~~~~~~~~~~~~~~~~~~~~~~+We can get an application like+ (tick t f) True False+via inlining in the CorePrep pass; see Note [Inlining in CorePrep]+in GHC.CoreToStg.Prep. The tick does not satisfy tickishIsCode;+the inlining-in-CorePrep happens for cpExprIsTrivial which tests+tickishIsCode.++So we test the same thing here, pushing any non-code ticks to+the top (they don't generate any code, after all). This showed+up in the fallout from fixing #19360.+-} stgArity :: Id -> HowBound -> Arity stgArity _ (LetBound _ arity) = arity
compiler/GHC/CoreToStg/Prep.hs view
@@ -72,6 +72,7 @@ import GHC.Types.Name ( NamedThing(..), nameSrcSpan, isInternalName ) import GHC.Types.SrcLoc ( SrcSpan(..), realSrcLocSpan, mkRealSrcLoc ) import GHC.Types.Literal+import GHC.Types.Tickish import GHC.Types.TyThing import GHC.Types.CostCentre ( CostCentre, ccFromThisModule ) import GHC.Types.Unique.Supply@@ -192,7 +193,7 @@ corePrepPgm hsc_env this_mod mod_loc binds data_tycons = withTiming logger dflags (text "CorePrep"<+>brackets (ppr this_mod))- (const ()) $ do+ (\(a,b) -> a `seqList` b `seq` ()) $ do us <- mkSplitUniqSupply 's' initialCorePrepEnv <- mkInitialCorePrepEnv hsc_env @@ -221,7 +222,7 @@ corePrepExpr hsc_env expr = do let dflags = hsc_dflags hsc_env let logger = hsc_logger hsc_env- withTiming logger dflags (text "CorePrep [expr]") (const ()) $ do+ withTiming logger dflags (text "CorePrep [expr]") (\e -> e `seq` ()) $ do us <- mkSplitUniqSupply 's' initialCorePrepEnv <- mkInitialCorePrepEnv hsc_env let new_expr = initUs_ us (cpeBodyNF initialCorePrepEnv expr)@@ -610,9 +611,9 @@ = do { body <- cpeBodyNF env expr ; return (emptyFloats, mkTick tickish' body) } where- tickish' | Breakpoint n fvs <- tickish+ tickish' | Breakpoint ext n fvs <- tickish -- See also 'substTickish'- = Breakpoint n (map (getIdFromTrivialExpr . lookupCorePrepEnv env) fvs)+ = Breakpoint ext n (map (getIdFromTrivialExpr . lookupCorePrepEnv env) fvs) | otherwise = tickish @@ -731,7 +732,7 @@ data ArgInfo = CpeApp CoreArg | CpeCast Coercion- | CpeTick (Tickish Id)+ | CpeTick CoreTickish instance Outputable ArgInfo where ppr (CpeApp arg) = text "app" <+> ppr arg@@ -848,8 +849,8 @@ ; (app, floats) <- rebuild_app args e2 (exprType e2) emptyFloats stricts ; mb_saturate hd app floats depth } where- stricts = case idStrictness v of- StrictSig (DmdType _ demands _)+ stricts = case idDmdSig v of+ DmdSig (DmdType _ demands _) | listLengthCmp demands depth /= GT -> demands -- length demands <= depth | otherwise -> []@@ -963,7 +964,7 @@ GHC.Magic. This definition is used in cases where runRW is curried. * In addition to its normal Haskell definition in GHC.Magic, we give it- a special late inlining here in CorePrep and GHC.CoreToByteCode, avoiding+ a special late inlining here in CorePrep and GHC.StgToByteCode, avoiding the incorrect sharing due to float-out noted above. * It is levity-polymorphic:@@ -1344,7 +1345,7 @@ Since call-by-value is much cheaper than call-by-need, we case-bind arguments that are either - 1. Strictly evaluated anyway, according to the StrictSig of the callee, or+ 1. Strictly evaluated anyway, according to the DmdSig of the callee, or 2. ok-for-spec, according to 'exprOkForSpeculation' While (1) is a no-brainer and always beneficial, (2) is a bit@@ -1369,7 +1370,7 @@ -- but lifted binding -- | See Note [Floating Ticks in CorePrep]- | FloatTick (Tickish Id)+ | FloatTick CoreTickish data Floats = Floats OkToSpec (OrdList FloatingBind) @@ -1407,8 +1408,21 @@ -- Don't make a case for a HNF binding, even if it's strict -- Otherwise we get case (\x -> e) of ...! - | is_unlifted = ASSERT2( ok_for_spec, ppr rhs )- FloatCase rhs bndr DEFAULT [] True+ | is_unlifted = FloatCase rhs bndr DEFAULT [] True+ -- we used to ASSERT2(ok_for_spec, ppr rhs) here, but it is now disabled+ -- because exprOkForSpeculation isn't stable under ANF-ing. See for+ -- example #19489 where the following unlifted expression:+ --+ -- GHC.Prim.(#|_#) @LiftedRep @LiftedRep @[a_ax0] @[a_ax0]+ -- (GHC.Types.: @a_ax0 a2_agq a3_agl)+ --+ -- is ok-for-spec but is ANF-ised into:+ --+ -- let sat = GHC.Types.: @a_ax0 a2_agq a3_agl+ -- in GHC.Prim.(#|_#) @LiftedRep @LiftedRep @[a_ax0] @[a_ax0] sat+ --+ -- which isn't ok-for-spec because of the let-expression.+ | is_hnf = FloatLet (NonRec bndr rhs) | otherwise = FloatLet (NonRec (setIdDemandInfo bndr dmd) rhs) -- See Note [Pin demand info on floats]
compiler/GHC/Data/Graph/UnVar.hs view
@@ -17,7 +17,7 @@ module GHC.Data.Graph.UnVar ( UnVarSet , emptyUnVarSet, mkUnVarSet, varEnvDom, unionUnVarSet, unionUnVarSets- , delUnVarSet+ , extendUnVarSet, delUnVarSet , elemUnVarSet, isEmptyUnVarSet , UnVarGraph , emptyUnVarGraph
compiler/GHC/Driver/Backpack.hs view
@@ -737,6 +737,7 @@ summariseRequirement pn mod_name = do hsc_env <- getSession let dflags = hsc_dflags hsc_env+ let home_unit = hsc_home_unit hsc_env let PackageName pn_fs = pn location <- liftIO $ mkHomeModLocation2 dflags mod_name@@ -748,7 +749,8 @@ hie_timestamp <- liftIO $ modificationTimeIfExists (ml_hie_file location) let loc = srcLocSpan (mkSrcLoc (mkFastString (bkp_filename env)) 1 1) - mod <- liftIO $ addHomeModuleToFinder hsc_env mod_name location+ let fc = hsc_FC hsc_env+ mod <- liftIO $ addHomeModuleToFinder fc home_unit mod_name location extra_sig_imports <- liftIO $ findExtraSigImports hsc_env HsigFile mod_name @@ -764,6 +766,7 @@ ms_textual_imps = extra_sig_imports, ms_parsed_mod = Just (HsParsedModule { hpm_module = L loc (HsModule {+ hsmodAnn = noAnn, hsmodLayout = NoLayoutInfo, hsmodName = Just (L loc mod_name), hsmodExports = Nothing,@@ -772,8 +775,7 @@ hsmodDeprecMessage = Nothing, hsmodHaddockModHeader = Nothing }),- hpm_src_files = [],- hpm_annotations = ApiAnns Map.empty Nothing Map.empty []+ hpm_src_files = [] }), ms_hspp_file = "", -- none, it came inline ms_hspp_opts = dflags,@@ -797,7 +799,8 @@ Nothing -- GHC API buffer support not supported [] -- No exclusions case r of- Nothing -> throwOneError (mkPlainMsgEnvelope loc (text "module" <+> ppr modname <+> text "was not found"))+ Nothing -> throwOneError (mkPlainMsgEnvelope ErrorWithoutFlag+ loc (text "module" <+> ppr modname <+> text "was not found")) Just (Left err) -> throwErrors err Just (Right summary) -> return summary @@ -861,7 +864,10 @@ (implicit_sigs, inst_deps) <- liftIO $ implicitRequirementsShallow hsc_env normal_imports -- So that Finder can find it, even though it doesn't exist...- this_mod <- liftIO $ addHomeModuleToFinder hsc_env modname location+ this_mod <- liftIO $ do+ let home_unit = hsc_home_unit hsc_env+ let fc = hsc_FC hsc_env+ addHomeModuleToFinder fc home_unit modname location return $ ExtendedModSummary { emsModSummary = ModSummary {@@ -883,8 +889,7 @@ -- This is our hack to get the parse tree to the right spot ms_parsed_mod = Just (HsParsedModule { hpm_module = hsmod,- hpm_src_files = [], -- TODO if we preprocessed it- hpm_annotations = ApiAnns Map.empty Nothing Map.empty [] -- BOGUS+ hpm_src_files = [] -- TODO if we preprocessed it }), ms_hs_date = time, ms_obj_date = Nothing, -- TODO do this, but problem: hi_timestamp is BOGUS
compiler/GHC/Driver/CodeOutput.hs view
@@ -10,6 +10,7 @@ ( codeOutput , outputForeignStubs , profilingInitCode+ , ipInitCode ) where @@ -35,8 +36,9 @@ import GHC.Data.Stream ( Stream ) import qualified GHC.Data.Stream as Stream -import GHC.SysTools.FileCleanup+import GHC.Utils.TmpFs + import GHC.Utils.Error import GHC.Utils.Outputable import GHC.Utils.Panic@@ -64,23 +66,24 @@ ************************************************************************ -} -codeOutput :: Logger- -> DynFlags- -> UnitState- -> Module- -> FilePath- -> ModLocation- -> ForeignStubs- -> [(ForeignSrcLang, FilePath)]- -- ^ additional files to be compiled with the C compiler- -> [UnitId]- -> Stream IO RawCmmGroup a -- Compiled C--- -> IO (FilePath,- (Bool{-stub_h_exists-}, Maybe FilePath{-stub_c_exists-}),- [(ForeignSrcLang, FilePath)]{-foreign_fps-},- a)--codeOutput logger dflags unit_state this_mod filenm location foreign_stubs foreign_fps pkg_deps+codeOutput+ :: Logger+ -> TmpFs+ -> DynFlags+ -> UnitState+ -> Module+ -> FilePath+ -> ModLocation+ -> (a -> ForeignStubs)+ -> [(ForeignSrcLang, FilePath)]+ -- ^ additional files to be compiled with the C compiler+ -> [UnitId]+ -> Stream IO RawCmmGroup a -- Compiled C--+ -> IO (FilePath,+ (Bool{-stub_h_exists-}, Maybe FilePath{-stub_c_exists-}),+ [(ForeignSrcLang, FilePath)]{-foreign_fps-},+ a)+codeOutput logger tmpfs dflags unit_state this_mod filenm location genForeignStubs foreign_fps pkg_deps cmm_stream = do {@@ -97,8 +100,7 @@ { case cmmLint (targetPlatform dflags) cmm of Just err -> do { putLogMsg logger dflags- NoReason- SevDump+ MCDump noSrcSpan $ withPprStyle defaultDumpStyle err ; ghcExit logger dflags 1@@ -107,7 +109,6 @@ ; return cmm } - ; stubs_exist <- outputForeignStubs logger dflags unit_state this_mod location foreign_stubs ; a <- case backend dflags of NCG -> outputAsm logger dflags this_mod location filenm linted_cmm_stream@@ -115,6 +116,8 @@ LLVM -> outputLlvm logger dflags filenm linted_cmm_stream Interpreter -> panic "codeOutput: Interpreter" NoBackend -> panic "codeOutput: NoBackend"+ ; let stubs = genForeignStubs a+ ; stubs_exist <- outputForeignStubs logger tmpfs dflags unit_state this_mod location stubs ; return (filenm, stubs_exist, foreign_fps, a) } @@ -195,19 +198,26 @@ ************************************************************************ -} -outputForeignStubs :: Logger -> DynFlags -> UnitState -> Module -> ModLocation -> ForeignStubs- -> IO (Bool, -- Header file created- Maybe FilePath) -- C file created-outputForeignStubs logger dflags unit_state mod location stubs+outputForeignStubs+ :: Logger+ -> TmpFs+ -> DynFlags+ -> UnitState+ -> Module+ -> ModLocation+ -> ForeignStubs+ -> IO (Bool, -- Header file created+ Maybe FilePath) -- C file created+outputForeignStubs logger tmpfs dflags unit_state mod location stubs = do let stub_h = mkStubPaths dflags (moduleName mod) location- stub_c <- newTempName logger dflags TFL_CurrentModule "c"+ stub_c <- newTempName logger tmpfs dflags TFL_CurrentModule "c" case stubs of NoStubs -> return (False, Nothing) - ForeignStubs h_code c_code -> do+ ForeignStubs (CHeader h_code) (CStub c_code) -> do let stub_c_output_d = pprCode CStyle c_code stub_c_output_w = showSDoc dflags stub_c_output_d@@ -225,9 +235,14 @@ -- we need the #includes from the rts package for the stub files let rts_includes =- let rts_pkg = unsafeLookupUnitId unit_state rtsUnitId in- concatMap mk_include (unitIncludes rts_pkg)- mk_include i = "#include \"" ++ ST.unpack i ++ "\"\n"+ let mrts_pkg = lookupUnitId unit_state rtsUnitId+ mk_include i = "#include \"" ++ ST.unpack i ++ "\"\n"+ in case mrts_pkg of+ Just rts_pkg -> concatMap mk_include (unitIncludes rts_pkg)+ -- This case only happens when compiling foreign stub for the rts+ -- library itself. The only time we do this at the moment is for+ -- IPE information for the RTS info tables+ Nothing -> "" -- wrapper code mentions the ffi_arg type, which comes from ffi.h ffi_includes@@ -277,9 +292,9 @@ -- module; -- | Generate code to initialise cost centres-profilingInitCode :: Platform -> Module -> CollectedCCs -> SDoc+profilingInitCode :: Platform -> Module -> CollectedCCs -> CStub profilingInitCode platform this_mod (local_CCs, singleton_CCSs)- = vcat+ = CStub $ vcat $ map emit_cc_decl local_CCs ++ map emit_ccs_decl singleton_CCSs ++ [emit_cc_list local_CCs]@@ -314,3 +329,34 @@ | cc <- ccs ] ++ [text "NULL"]) <> semi++-- | Generate code to initialise info pointer origin+-- See note [Mapping Info Tables to Source Positions]+ipInitCode :: DynFlags -> Module -> [InfoProvEnt] -> CStub+ipInitCode dflags this_mod ents+ = if not (gopt Opt_InfoTableMap dflags)+ then mempty+ else CStub $ vcat+ $ map emit_ipe_decl ents+ ++ [emit_ipe_list ents]+ ++ [ text "static void ip_init_" <> ppr this_mod+ <> text "(void) __attribute__((constructor));"+ , text "static void ip_init_" <> ppr this_mod <> text "(void)"+ , braces (vcat+ [ text "registerInfoProvList" <> parens local_ipe_list_label <> semi+ ])+ ]+ where+ platform = targetPlatform dflags+ emit_ipe_decl ipe =+ text "extern InfoProvEnt" <+> ipe_lbl <> text "[];"+ where ipe_lbl = pprCLabel platform CStyle (mkIPELabel ipe)+ local_ipe_list_label = text "local_ipe_" <> ppr this_mod+ emit_ipe_list ipes =+ text "static InfoProvEnt *" <> local_ipe_list_label <> text "[] ="+ <+> braces (vcat $ [ pprCLabel platform CStyle (mkIPELabel ipe) <> comma+ | ipe <- ipes+ ] ++ [text "NULL"])+ <> semi++
compiler/GHC/Driver/Main.hs view
@@ -1,6 +1,7 @@-{-# LANGUAGE CPP #-}-{-# LANGUAGE BangPatterns #-}+{-# LANGUAGE BangPatterns #-}+{-# LANGUAGE CPP #-} {-# LANGUAGE NondecreasingIndentation #-}+ {-# OPTIONS_GHC -fprof-auto-top #-} -------------------------------------------------------------------------------@@ -98,7 +99,7 @@ import GHC.Driver.Hooks import GHC.Runtime.Context-import GHC.Runtime.Interpreter ( addSptEntry )+import GHC.Runtime.Interpreter ( addSptEntry, hscInterp ) import GHC.Runtime.Loader ( initializePlugins ) import GHCi.RemoteTypes ( ForeignHValue ) import GHC.ByteCode.Types@@ -112,7 +113,7 @@ import GHC.HsToCore -import GHC.CoreToByteCode ( byteCodeGen, coreExprToBCOs )+import GHC.StgToByteCode ( byteCodeGen, stgExprToBCOs ) import GHC.IfaceToCore ( typecheckIface ) @@ -122,14 +123,15 @@ import GHC.Iface.Tidy import GHC.Iface.Ext.Ast ( mkHieFile ) import GHC.Iface.Ext.Types ( getAsts, hie_asts, hie_module )-import GHC.Iface.Ext.Binary ( readHieFile, writeHieFile , hie_file_result, NameCacheUpdater(..))+import GHC.Iface.Ext.Binary ( readHieFile, writeHieFile , hie_file_result) import GHC.Iface.Ext.Debug ( diffFile, validateScopes )-import GHC.Iface.Env ( updNameCache ) import GHC.Core import GHC.Core.Tidy ( tidyExpr ) import GHC.Core.Type ( Type, Kind ) import GHC.Core.Lint ( lintInteractiveExpr )+import GHC.Core.Multiplicity+import GHC.Core.Utils ( exprType ) import GHC.Core.ConLike import GHC.Core.Opt.Pipeline import GHC.Core.TyCon@@ -139,7 +141,6 @@ import GHC.CoreToStg.Prep import GHC.CoreToStg ( coreToStg ) -import GHC.Parser.Annotation import GHC.Parser.Errors import GHC.Parser.Errors.Ppr import GHC.Parser@@ -155,6 +156,7 @@ import GHC.Builtin.Utils import GHC.Builtin.Names+import GHC.Builtin.Uniques ( mkPseudoUniqueE ) import qualified GHC.StgToCmm as StgToCmm ( codeGen ) import GHC.StgToCmm.Types (CgInfos (..), ModuleLFInfos)@@ -166,6 +168,7 @@ import GHC.Cmm.Info import GHC.Unit+import GHC.Unit.Finder import GHC.Unit.External import GHC.Unit.State import GHC.Unit.Module.ModDetails@@ -186,7 +189,7 @@ import GHC.Types.Error import GHC.Types.Fixity.Env import GHC.Types.CostCentre-import GHC.Types.Unique.Supply+import GHC.Types.IPE import GHC.Types.SourceFile import GHC.Types.SrcLoc import GHC.Types.Name@@ -204,6 +207,7 @@ import GHC.Utils.Exception import GHC.Utils.Misc import GHC.Utils.Logger+import GHC.Utils.TmpFs import GHC.Data.FastString import GHC.Data.Bag@@ -219,7 +223,6 @@ import System.FilePath as FilePath import System.Directory import System.IO (fixIO)-import qualified Data.Map as M import qualified Data.Set as S import Data.Set (Set) import Data.Functor@@ -240,11 +243,10 @@ -- we don't store the unit databases and the unit state to still -- allow `setSessionDynFlags` to be used to set unit db flags. eps_var <- newIORef initExternalPackageState- us <- mkSplitUniqSupply 'r'- nc_var <- newIORef (initNameCache us knownKeyNames)- fc_var <- newIORef emptyInstalledModuleEnv- emptyLoader <- uninitializedLoader+ nc_var <- initNameCache 'r' knownKeyNames+ fc_var <- initFinderCache logger <- initLogger+ tmpfs <- initTmpFs -- FIXME: it's sad that we have so many "unitialized" fields filled with -- empty stuff or lazy panics. We should have two kinds of HscEnv -- (initialized or not) instead and less fields that are mutable over time.@@ -259,12 +261,12 @@ , hsc_FC = fc_var , hsc_type_env_var = Nothing , hsc_interp = Nothing- , hsc_loader = emptyLoader , hsc_unit_env = panic "hsc_unit_env not initialized" , hsc_plugins = [] , hsc_static_plugins = [] , hsc_unit_dbs = Nothing , hsc_hooks = emptyHooks+ , hsc_tmpfs = tmpfs } -- -----------------------------------------------------------------------------@@ -275,8 +277,8 @@ clearWarnings :: Hsc () clearWarnings = Hsc $ \_ _ -> return ((), emptyBag) -logWarnings :: WarningMessages -> Hsc ()-logWarnings w = Hsc $ \_ w0 -> return ((), w0 `unionBags` w)+logDiagnostics :: Bag (MsgEnvelope DiagnosticMessage) -> Hsc ()+logDiagnostics w = Hsc $ \_ w0 -> return ((), w0 `unionBags` w) getHscEnv :: Hsc HscEnv getHscEnv = Hsc $ \e w -> return (e, w)@@ -295,7 +297,7 @@ logWarningsReportErrors (warnings,errors) = do let warns = fmap pprWarning warnings errs = fmap pprError errors- logWarnings warns+ logDiagnostics warns when (not $ isEmptyBag errs) $ throwErrors errs -- | Log warnings and throw errors, assuming the messages@@ -304,10 +306,10 @@ handleWarningsThrowErrors (warnings, errors) = do let warns = fmap pprWarning warnings errs = fmap pprError errors- logWarnings warns+ logDiagnostics warns dflags <- getDynFlags logger <- getLogger- (wWarns, wErrs) <- warningsToMessages dflags <$> getWarnings+ let (wWarns, wErrs) = partitionMessageBag warns liftIO $ printBagOfErrors logger dflags wWarns throwErrors (unionBags errs wErrs) @@ -327,27 +329,27 @@ -- 2. If there are no error messages, but the second result indicates failure -- there should be warnings in the first result. That is, if the action -- failed, it must have been due to the warnings (i.e., @-Werror@).-ioMsgMaybe :: IO (Messages DecoratedSDoc, Maybe a) -> Hsc a+ioMsgMaybe :: IO (Messages DiagnosticMessage, Maybe a) -> Hsc a ioMsgMaybe ioA = do (msgs, mb_r) <- liftIO ioA let (warns, errs) = partitionMessages msgs- logWarnings warns+ logDiagnostics warns case mb_r of Nothing -> throwErrors errs Just r -> ASSERT( isEmptyBag errs ) return r -- | like ioMsgMaybe, except that we ignore error messages and return -- 'Nothing' instead.-ioMsgMaybe' :: IO (Messages DecoratedSDoc, Maybe a) -> Hsc (Maybe a)+ioMsgMaybe' :: IO (Messages DiagnosticMessage, Maybe a) -> Hsc (Maybe a) ioMsgMaybe' ioA = do (msgs, mb_r) <- liftIO $ ioA- logWarnings (getWarningMessages msgs)+ logDiagnostics (getWarningMessages msgs) return mb_r -- ----------------------------------------------------------------------------- -- | Lookup things in the compiler's environment -hscTcRnLookupRdrName :: HscEnv -> Located RdrName -> IO [Name]+hscTcRnLookupRdrName :: HscEnv -> LocatedN RdrName -> IO [Name] hscTcRnLookupRdrName hsc_env0 rdr_name = runInteractiveHsc hsc_env0 $ do { hsc_env <- getHscEnv@@ -421,11 +423,13 @@ handleWarningsThrowErrors (getMessages pst) POk pst rdr_module -> do let (warns, errs) = bimap (fmap pprWarning) (fmap pprError) (getMessages pst)- logWarnings warns+ logDiagnostics warns liftIO $ dumpIfSet_dyn logger dflags Opt_D_dump_parsed "Parser" FormatHaskell (ppr rdr_module) liftIO $ dumpIfSet_dyn logger dflags Opt_D_dump_parsed_ast "Parser AST"- FormatHaskell (showAstData NoBlankSrcSpan rdr_module)+ FormatHaskell (showAstData NoBlankSrcSpan+ NoBlankEpAnnotations+ rdr_module) liftIO $ dumpIfSet_dyn logger dflags Opt_D_source_stats "Source Statistics" FormatText (ppSourceStats False rdr_module) when (not $ isEmptyBag errs) $ throwErrors errs@@ -456,16 +460,9 @@ -- filter them out: srcs2 <- liftIO $ filterM doesFileExist srcs1 - let api_anns = ApiAnns {- apiAnnItems = M.fromListWith (++) $ annotations pst,- apiAnnEofPos = eof_pos pst,- apiAnnComments = M.fromList (annotations_comments pst),- apiAnnRogueComments = comment_q pst- }- res = HsParsedModule {+ let res = HsParsedModule { hpm_module = rdr_module,- hpm_src_files = srcs2,- hpm_annotations = api_anns+ hpm_src_files = srcs2 } -- apply parse transformation of plugins@@ -484,7 +481,7 @@ dflags <- getDynFlags logger <- getLogger liftIO $ dumpIfSet_dyn logger dflags Opt_D_dump_rn_ast "Renamer"- FormatHaskell (showAstData NoBlankSrcSpan rn_info)+ FormatHaskell (showAstData NoBlankSrcSpan NoBlankEpAnnotations rn_info) -- Create HIE files when (gopt Opt_WriteHie dflags) $ do@@ -506,7 +503,7 @@ putMsg logger dflags $ text "Got invalid scopes" mapM_ (putMsg logger dflags) xs -- Roundtrip testing- file' <- readHieFile (NCU $ updNameCache $ hsc_NC hs_env) out_file+ file' <- readHieFile (hsc_NC hs_env) out_file case diffFile hieFile (hie_file_result file') of [] -> putMsg logger dflags $ text "Got no roundtrip errors"@@ -568,12 +565,12 @@ hsc_env <- getHscEnv dflags <- getDynFlags + let reason = WarningWithFlag Opt_WarnMissingSafeHaskellMode -- -Wmissing-safe-haskell-mode when (not (safeHaskellModeEnabled dflags) && wopt Opt_WarnMissingSafeHaskellMode dflags) $- logWarnings $ unitBag $- makeIntoWarning (Reason Opt_WarnMissingSafeHaskellMode) $- mkPlainWarnMsg (getLoc (hpm_module mod)) $+ logDiagnostics $ unitBag $+ mkPlainMsgEnvelope reason (getLoc (hpm_module mod)) $ warnMissingSafeHaskellMode tcg_res <- {-# SCC "Typecheck-Rename" #-}@@ -600,15 +597,15 @@ case wopt Opt_WarnSafe dflags of True | safeHaskell dflags == Sf_Safe -> return ()- | otherwise -> (logWarnings $ unitBag $- makeIntoWarning (Reason Opt_WarnSafe) $- mkPlainWarnMsg (warnSafeOnLoc dflags) $+ | otherwise -> (logDiagnostics $ unitBag $+ mkPlainMsgEnvelope (WarningWithFlag Opt_WarnSafe)+ (warnSafeOnLoc dflags) $ errSafe tcg_res') False | safeHaskell dflags == Sf_Trustworthy && wopt Opt_WarnTrustworthySafe dflags ->- (logWarnings $ unitBag $- makeIntoWarning (Reason Opt_WarnTrustworthySafe) $- mkPlainWarnMsg (trustworthyOnLoc dflags) $+ (logDiagnostics $ unitBag $+ mkPlainMsgEnvelope (WarningWithFlag Opt_WarnTrustworthySafe)+ (trustworthyOnLoc dflags) $ errTwthySafe tcg_res') False -> return () return tcg_res'@@ -971,8 +968,13 @@ in addBootSuffix_maybe (mi_boot iface) with_hi write_iface dflags' iface =+ let !iface_name = buildIfName (hiSuf dflags')+ in {-# SCC "writeIface" #-}- writeIface logger dflags' (buildIfName (hiSuf dflags')) iface+ withTiming logger dflags'+ (text "WriteIface"<+>brackets (text iface_name))+ (const ())+ (writeIface logger dflags' iface_name iface) when (write_interface || force_write_interface) $ do @@ -1134,7 +1136,7 @@ case safeLanguageOn dflags of True -> do -- XSafe: we nuke user written RULES- logWarnings $ warns (tcg_rules tcg_env')+ logDiagnostics $ warns (tcg_rules tcg_env') return tcg_env' { tcg_rules = [] } False -- SafeInferred: user defined RULES, so not safe@@ -1147,9 +1149,9 @@ warns rules = listToBag $ map warnRules rules - warnRules :: GenLocated SrcSpan (RuleDecl GhcTc) -> MsgEnvelope DecoratedSDoc+ warnRules :: LRuleDecl GhcTc -> MsgEnvelope DiagnosticMessage warnRules (L loc (HsRule { rd_name = n })) =- mkPlainWarnMsg loc $+ mkPlainMsgEnvelope WarningWithoutFlag (locA loc) $ text "Rule \"" <> ftext (snd $ unLoc n) <> text "\" ignored" $+$ text "User defined rules are disabled under Safe Haskell" @@ -1193,7 +1195,7 @@ return (infErrs, infPkgs) -- restore old errors- logWarnings oldErrs+ logDiagnostics oldErrs case (isEmptyBag safeErrs) of -- Failed safe check@@ -1225,7 +1227,7 @@ cond' :: ImportedModsVal -> ImportedModsVal -> Hsc ImportedModsVal cond' v1 v2 | imv_is_safe v1 /= imv_is_safe v2- = throwOneError $ mkPlainMsgEnvelope (imv_span v1)+ = throwOneError $ mkPlainMsgEnvelope ErrorWithoutFlag (imv_span v1) (text "Module" <+> ppr (imv_name v1) <+> (text $ "is imported both as a safe and unsafe import!")) | otherwise@@ -1293,7 +1295,7 @@ iface <- lookup' m case iface of -- can't load iface to check trust!- Nothing -> throwOneError $ mkPlainMsgEnvelope l+ Nothing -> throwOneError $ mkPlainMsgEnvelope ErrorWithoutFlag l $ text "Can't load the interface file for" <+> ppr m <> text ", to check that it can be safely imported" @@ -1319,28 +1321,28 @@ (True, False) -> pkgTrustErr (False, _ ) -> modTrustErr in do- logWarnings warns- logWarnings errs+ logDiagnostics warns+ logDiagnostics errs return (trust == Sf_Trustworthy, pkgRs) where state = hsc_units hsc_env inferredImportWarn = unitBag- $ makeIntoWarning (Reason Opt_WarnInferredSafeImports)- $ mkWarnMsg l (pkgQual state)+ $ mkShortMsgEnvelope (WarningWithFlag Opt_WarnInferredSafeImports)+ l (pkgQual state) $ sep [ text "Importing Safe-Inferred module " <> ppr (moduleName m) <> text " from explicitly Safe module" ]- pkgTrustErr = unitBag $ mkMsgEnvelope l (pkgQual state) $+ pkgTrustErr = unitBag $ mkShortMsgEnvelope ErrorWithoutFlag l (pkgQual state) $ sep [ ppr (moduleName m) <> text ": Can't be safely imported!" , text "The package (" <> (pprWithUnitState state $ ppr (moduleUnit m)) <> text ") the module resides in isn't trusted." ]- modTrustErr = unitBag $ mkMsgEnvelope l (pkgQual state) $+ modTrustErr = unitBag $ mkShortMsgEnvelope ErrorWithoutFlag l (pkgQual state) $ sep [ ppr (moduleName m) <> text ": Can't be safely imported!" , text "The module itself isn't safe." ]@@ -1386,7 +1388,7 @@ | unitIsTrusted $ unsafeLookupUnitId state pkg = acc | otherwise- = (:acc) $ mkMsgEnvelope noSrcSpan (pkgQual state)+ = (:acc) $ mkShortMsgEnvelope ErrorWithoutFlag noSrcSpan (pkgQual state) $ pprWithUnitState state $ text "The package (" <> ppr pkg@@ -1409,9 +1411,10 @@ markUnsafeInfer tcg_env whyUnsafe = do dflags <- getDynFlags + let reason = WarningWithFlag Opt_WarnUnsafe when (wopt Opt_WarnUnsafe dflags)- (logWarnings $ unitBag $ makeIntoWarning (Reason Opt_WarnUnsafe) $- mkPlainWarnMsg (warnUnsafeOnLoc dflags) (whyUnsafe' dflags))+ (logDiagnostics $ unitBag $+ mkPlainMsgEnvelope reason (warnUnsafeOnLoc dflags) (whyUnsafe' dflags)) liftIO $ writeIORef (tcg_safeInfer tcg_env) (False, whyUnsafe) -- NOTE: Only wipe trust when not in an explicitly safe haskell mode. Other@@ -1432,7 +1435,7 @@ ] badFlags df = concatMap (badFlag df) unsafeFlagsForInfer badFlag df (str,loc,on,_)- | on df = [mkLocMessage SevOutput (loc df) $+ | on df = [mkLocMessage MCOutput (loc df) $ text str <+> text "is not allowed in Safe Haskell"] | otherwise = [] badInsts insts = concatMap badInst insts@@ -1441,7 +1444,7 @@ checkOverlap _ = True badInst ins | checkOverlap (overlapMode (is_flag ins))- = [mkLocMessage SevOutput (nameSrcSpan $ getName $ is_dfun ins) $+ = [mkLocMessage MCOutput (nameSrcSpan $ getName $ is_dfun ins) $ ppr (overlapMode $ is_flag ins) <+> text "overlap mode isn't allowed in Safe Haskell"] | otherwise = []@@ -1525,6 +1528,7 @@ dflags = hsc_dflags hsc_env logger = hsc_logger hsc_env hooks = hsc_hooks hsc_env+ tmpfs = hsc_tmpfs hsc_env data_tycons = filter isDataTyCon tycons -- cg_tycons includes newtypes, for the benefit of External Core, -- but we don't generate any code for newtypes@@ -1535,20 +1539,23 @@ (prepd_binds, local_ccs) <- {-# SCC "CorePrep" #-} corePrepPgm hsc_env this_mod location core_binds data_tycons+ ----------------- Convert to STG ------------------- (stg_binds, (caf_ccs, caf_cc_stacks))+ (stg_binds, denv, (caf_ccs, caf_cc_stacks)) <- {-# SCC "CoreToStg" #-}- myCoreToStg logger dflags this_mod prepd_binds+ withTiming logger dflags+ (text "CoreToStg"<+>brackets (ppr this_mod))+ (\(a, b, (c,d)) -> a `seqList` b `seq` c `seqList` d `seqList` ())+ (myCoreToStg logger dflags (hsc_IC hsc_env) this_mod location prepd_binds) - let cost_centre_info = (S.toList local_ccs ++ caf_ccs, caf_cc_stacks)+ let cost_centre_info =+ (S.toList local_ccs ++ caf_ccs, caf_cc_stacks) platform = targetPlatform dflags prof_init- | sccProfilingEnabled dflags = profilingInitCode platform this_mod cost_centre_info- | otherwise = empty- foreign_stubs = foreign_stubs0 `appendStubC` prof_init+ | sccProfilingEnabled dflags = profilingInitCode platform this_mod cost_centre_info+ | otherwise = mempty ------------------ Code generation ------------------- -- The back-end is streamed: each top-level function goes -- from Stg all the way to asm before dealing with the next -- top-level function, so showPass isn't very useful here.@@ -1558,7 +1565,7 @@ (text "CodeGen"<+>brackets (ppr this_mod)) (const ()) $ do cmms <- {-# SCC "StgToCmm" #-}- doCodeGen hsc_env this_mod data_tycons+ doCodeGen hsc_env this_mod denv data_tycons cost_centre_info stg_binds hpc_info @@ -1574,9 +1581,12 @@ return a rawcmms1 = Stream.mapM dump rawcmms0 + let foreign_stubs st = foreign_stubs0 `appendStubC` prof_init+ `appendStubC` cgIPEStub st+ (output_filename, (_stub_h_exists, stub_c_exists), foreign_fps, cg_infos) <- {-# SCC "codeOutput" #-}- codeOutput logger dflags (hsc_units hsc_env) this_mod output_filename location+ codeOutput logger tmpfs dflags (hsc_units hsc_env) this_mod output_filename location foreign_stubs foreign_files dependencies rawcmms1 return (output_filename, stub_c_exists, foreign_fps, cg_infos) @@ -1588,6 +1598,7 @@ hscInteractive hsc_env cgguts location = do let dflags = hsc_dflags hsc_env let logger = hsc_logger hsc_env+ let tmpfs = hsc_tmpfs hsc_env let CgGuts{ -- This is the last use of the ModGuts in a compilation. -- From now on, we just use the bits we need. cg_module = this_mod,@@ -1606,33 +1617,38 @@ -- Do saturation and convert to A-normal form (prepd_binds, _) <- {-# SCC "CorePrep" #-} corePrepPgm hsc_env this_mod location core_binds data_tycons++ (stg_binds, _infotable_prov, _caf_ccs__caf_cc_stacks)+ <- {-# SCC "CoreToStg" #-}+ myCoreToStg logger dflags (hsc_IC hsc_env) this_mod location prepd_binds ----------------- Generate byte code ------------------- comp_bc <- byteCodeGen hsc_env this_mod prepd_binds data_tycons mod_breaks+ comp_bc <- byteCodeGen hsc_env this_mod stg_binds data_tycons mod_breaks ------------------ Create f-x-dynamic C-side stuff ----- (_istub_h_exists, istub_c_exists)- <- outputForeignStubs logger dflags (hsc_units hsc_env) this_mod location foreign_stubs+ <- outputForeignStubs logger tmpfs dflags (hsc_units hsc_env) this_mod location foreign_stubs return (istub_c_exists, comp_bc, spt_entries) ------------------------------ -hscCompileCmmFile :: HscEnv -> FilePath -> FilePath -> IO ()+hscCompileCmmFile :: HscEnv -> FilePath -> FilePath -> IO (Maybe FilePath) hscCompileCmmFile hsc_env filename output_filename = runHsc hsc_env $ do let dflags = hsc_dflags hsc_env let logger = hsc_logger hsc_env let hooks = hsc_hooks hsc_env+ let tmpfs = hsc_tmpfs hsc_env home_unit = hsc_home_unit hsc_env platform = targetPlatform dflags- cmm <- ioMsgMaybe+ -- Make up a module name to give the NCG. We can't pass bottom here+ -- lest we reproduce #11784.+ mod_name = mkModuleName $ "Cmm$" ++ FilePath.takeFileName filename+ cmm_mod = mkHomeModule home_unit mod_name+ (cmm, ents) <- ioMsgMaybe $ do (warns,errs,cmm) <- withTiming logger dflags (text "ParseCmm"<+>brackets (text filename)) (\_ -> ())- $ parseCmmFile dflags home_unit filename+ $ parseCmmFile dflags cmm_mod home_unit filename return (mkMessages (fmap pprWarning warns `unionBags` fmap pprError errs), cmm) liftIO $ do dumpIfSet_dyn logger dflags Opt_D_dump_cmm_verbose_by_proc "Parsed Cmm" FormatCMM (pdoc platform cmm)- let -- Make up a module name to give the NCG. We can't pass bottom here- -- lest we reproduce #11784.- mod_name = mkModuleName $ "Cmm$" ++ FilePath.takeFileName filename- cmm_mod = mkHomeModule home_unit mod_name -- Compile decls in Cmm files one decl at a time, to avoid re-ordering -- them in SRT analysis.@@ -1651,9 +1667,14 @@ Nothing -> cmmToRawCmm logger dflags (Stream.yield cmmgroup) Just h -> h dflags Nothing (Stream.yield cmmgroup) - _ <- codeOutput logger dflags (hsc_units hsc_env) cmm_mod output_filename no_loc NoStubs [] []+ let foreign_stubs _ =+ let ip_init = ipInitCode dflags cmm_mod ents+ in NoStubs `appendStubC` ip_init++ (_output_filename, (_stub_h_exists, stub_c_exists), _foreign_fps, _caf_infos)+ <- codeOutput logger tmpfs dflags (hsc_units hsc_env) cmm_mod output_filename no_loc foreign_stubs [] [] rawCmms- return ()+ return stub_c_exists where no_loc = ModLocation{ ml_hs_file = Just filename, ml_hi_file = panic "hscCompileCmmFile: no hi file",@@ -1680,7 +1701,7 @@ (5-10%). -} -doCodeGen :: HscEnv -> Module -> [TyCon]+doCodeGen :: HscEnv -> Module -> InfoTableProvMap -> [TyCon] -> CollectedCCs -> [StgTopBinding] -> HpcInfo@@ -1688,25 +1709,26 @@ -- Note we produce a 'Stream' of CmmGroups, so that the -- backend can be run incrementally. Otherwise it generates all -- the C-- up front, which has a significant space cost.-doCodeGen hsc_env this_mod data_tycons+doCodeGen hsc_env this_mod denv data_tycons cost_centre_info stg_binds hpc_info = do let dflags = hsc_dflags hsc_env let logger = hsc_logger hsc_env let hooks = hsc_hooks hsc_env- platform = targetPlatform dflags+ let tmpfs = hsc_tmpfs hsc_env+ let platform = targetPlatform dflags let stg_binds_w_fvs = annTopBindingsFreeVars stg_binds dumpIfSet_dyn logger dflags Opt_D_dump_stg_final "Final STG:" FormatSTG (pprGenStgTopBindings (initStgPprOpts dflags) stg_binds_w_fvs) let stg_to_cmm = case stgToCmmHook hooks of- Nothing -> StgToCmm.codeGen logger+ Nothing -> StgToCmm.codeGen logger tmpfs Just h -> h - let cmm_stream :: Stream IO CmmGroup ModuleLFInfos+ let cmm_stream :: Stream IO CmmGroup (CStub, ModuleLFInfos) -- See Note [Forcing of stg_binds] cmm_stream = stg_binds_w_fvs `seqList` {-# SCC "StgToCmm" #-}- stg_to_cmm dflags this_mod data_tycons cost_centre_info stg_binds_w_fvs hpc_info+ stg_to_cmm dflags this_mod denv data_tycons cost_centre_info stg_binds_w_fvs hpc_info -- codegen consumes a stream of CmmGroup, and produces a new -- stream of CmmGroup (not necessarily synchronised: one@@ -1723,12 +1745,12 @@ pipeline_stream :: Stream IO CmmGroupSRTs CgInfos pipeline_stream = do- (non_cafs, lf_infos) <-+ (non_cafs, (used_info, lf_infos)) <- {-# SCC "cmmPipeline" #-} Stream.mapAccumL_ (cmmPipeline hsc_env) (emptySRT this_mod) ppr_stream1 <&> first (srtMapNonCAFs . moduleSRTMap) - return CgInfos{ cgNonCafs = non_cafs, cgLFInfos = lf_infos }+ return CgInfos{ cgNonCafs = non_cafs, cgLFInfos = lf_infos, cgIPEStub = used_info } dump2 a = do unless (null a) $@@ -1737,20 +1759,42 @@ return (Stream.mapM dump2 pipeline_stream) -myCoreToStg :: Logger -> DynFlags -> Module -> CoreProgram+myCoreToStgExpr :: Logger -> DynFlags -> InteractiveContext+ -> Module -> ModLocation -> CoreExpr+ -> IO ( StgRhs+ , InfoTableProvMap+ , CollectedCCs )+myCoreToStgExpr logger dflags ictxt this_mod ml prepd_expr = do+ {- Create a temporary binding (just because myCoreToStg needs a+ binding for the stg2stg step) -}+ let bco_tmp_id = mkSysLocal (fsLit "BCO_toplevel")+ (mkPseudoUniqueE 0)+ Many+ (exprType prepd_expr)+ ([StgTopLifted (StgNonRec _ stg_expr)], prov_map, collected_ccs) <-+ myCoreToStg logger+ dflags+ ictxt+ this_mod+ ml+ [NonRec bco_tmp_id prepd_expr]+ return (stg_expr, prov_map, collected_ccs)++myCoreToStg :: Logger -> DynFlags -> InteractiveContext+ -> Module -> ModLocation -> CoreProgram -> IO ( [StgTopBinding] -- output program+ , InfoTableProvMap , CollectedCCs ) -- CAF cost centre info (declared and used)-myCoreToStg logger dflags this_mod prepd_binds = do- let (stg_binds, cost_centre_info)+myCoreToStg logger dflags ictxt this_mod ml prepd_binds = do+ let (stg_binds, denv, cost_centre_info) = {-# SCC "Core2Stg" #-}- coreToStg dflags this_mod prepd_binds+ coreToStg dflags this_mod ml prepd_binds stg_binds2 <- {-# SCC "Stg2Stg" #-}- stg2stg logger dflags this_mod stg_binds-- return (stg_binds2, cost_centre_info)+ stg2stg logger dflags ictxt this_mod stg_binds + return (stg_binds2, denv, cost_centre_info) {- ********************************************************************** %* *@@ -1845,8 +1889,10 @@ hscParsedDecls :: HscEnv -> [LHsDecl GhcPs] -> IO ([TyThing], InteractiveContext) hscParsedDecls hsc_env decls = runInteractiveHsc hsc_env $ do- {- Rename and typecheck it -} hsc_env <- getHscEnv+ let interp = hscInterp hsc_env++ {- Rename and typecheck it -} tc_gblenv <- ioMsgMaybe $ tcRnDeclsi hsc_env decls {- Grab the new instances -}@@ -1887,12 +1933,21 @@ (prepd_binds, _) <- {-# SCC "CorePrep" #-} liftIO $ corePrepPgm hsc_env this_mod iNTERACTIVELoc core_binds data_tycons + (stg_binds, _infotable_prov, _caf_ccs__caf_cc_stacks)+ <- {-# SCC "CoreToStg" #-}+ liftIO $ myCoreToStg (hsc_logger hsc_env)+ (hsc_dflags hsc_env)+ (hsc_IC hsc_env)+ this_mod+ iNTERACTIVELoc+ prepd_binds+ {- Generate byte code -} cbc <- liftIO $ byteCodeGen hsc_env this_mod- prepd_binds data_tycons mod_breaks+ stg_binds data_tycons mod_breaks let src_span = srcLocSpan interactiveSrcLoc- liftIO $ loadDecls hsc_env src_span cbc+ liftIO $ loadDecls interp hsc_env src_span cbc {- Load static pointer table entries -} liftIO $ hscAddSptEntries hsc_env (cg_spt_entries tidy_cg)@@ -1922,10 +1977,11 @@ -- See Note [Grand plan for static forms] in "GHC.Iface.Tidy.StaticPtrTable". hscAddSptEntries :: HscEnv -> [SptEntry] -> IO () hscAddSptEntries hsc_env entries = do+ let interp = hscInterp hsc_env let add_spt_entry :: SptEntry -> IO () add_spt_entry (SptEntry i fpr) = do- val <- loadName hsc_env (idName i)- addSptEntry hsc_env fpr val+ val <- loadName interp hsc_env (idName i)+ addSptEntry interp fpr val mapM_ add_spt_entry entries {-@@ -1951,7 +2007,7 @@ case is of [L _ i] -> return i _ -> liftIO $ throwOneError $- mkPlainMsgEnvelope noSrcSpan $+ mkPlainMsgEnvelope ErrorWithoutFlag noSrcSpan $ text "parse error in import declaration" -- | Typecheck an expression (but don't run it)@@ -1980,7 +2036,7 @@ maybe_stmt <- hscParseStmt expr case maybe_stmt of Just (L _ (BodyStmt _ expr _ _)) -> return expr- _ -> throwOneError $ mkPlainMsgEnvelope noSrcSpan+ _ -> throwOneError $ mkPlainMsgEnvelope ErrorWithoutFlag noSrcSpan (text "not an expression:" <+> quotes (text expr)) hscParseStmt :: String -> Hsc (Maybe (GhciLStmt GhcPs))@@ -1994,7 +2050,7 @@ hscParseType :: String -> Hsc (LHsType GhcPs) hscParseType = hscParseThing parseType -hscParseIdentifier :: HscEnv -> String -> IO (Located RdrName)+hscParseIdentifier :: HscEnv -> String -> IO (LocatedN RdrName) hscParseIdentifier hsc_env str = runInteractiveHsc hsc_env $ hscParseThing parseIdentifier str @@ -2022,7 +2078,7 @@ liftIO $ dumpIfSet_dyn logger dflags Opt_D_dump_parsed "Parser" FormatHaskell (ppr thing) liftIO $ dumpIfSet_dyn logger dflags Opt_D_dump_parsed_ast "Parser AST"- FormatHaskell (showAstData NoBlankSrcSpan thing)+ FormatHaskell (showAstData NoBlankSrcSpan NoBlankEpAnnotations thing) return thing @@ -2053,13 +2109,28 @@ {- Lint if necessary -} ; lintInteractiveExpr (text "hscCompileExpr") hsc_env prepd_expr+ ; let iNTERACTIVELoc = ModLocation{ ml_hs_file = Nothing,+ ml_hi_file = panic "hscCompileCoreExpr':ml_hi_file",+ ml_obj_file = panic "hscCompileCoreExpr':ml_obj_file",+ ml_hie_file = panic "hscCompileCoreExpr':ml_hie_file" } + ; let ictxt = hsc_IC hsc_env+ ; (stg_expr, _, _) <-+ myCoreToStgExpr (hsc_logger hsc_env)+ (hsc_dflags hsc_env)+ ictxt+ (icInteractiveModule ictxt)+ iNTERACTIVELoc+ prepd_expr+ {- Convert to BCOs -}- ; bcos <- coreExprToBCOs hsc_env- (icInteractiveModule (hsc_IC hsc_env)) prepd_expr+ ; bcos <- stgExprToBCOs hsc_env+ (icInteractiveModule ictxt)+ (exprType prepd_expr)+ stg_expr {- load it -}- ; loadExpr hsc_env srcspan bcos }+ ; loadExpr (hscInterp hsc_env) hsc_env srcspan bcos } {- **********************************************************************
compiler/GHC/Driver/Make.hs view
@@ -47,6 +47,7 @@ import GHC.Tc.Utils.Backpack import GHC.Tc.Utils.Monad ( initIfaceCheck ) +import GHC.Runtime.Interpreter import qualified GHC.Linker.Loader as Linker import GHC.Linker.Types @@ -83,9 +84,10 @@ import GHC.Utils.Misc import GHC.Utils.Error import GHC.Utils.Logger-import GHC.SysTools.FileCleanup+import GHC.Utils.TmpFs import GHC.Types.Basic+import GHC.Types.Error import GHC.Types.Target import GHC.Types.SourceFile import GHC.Types.SourceError@@ -219,7 +221,7 @@ -- source files may have appeared in the home package that shadow -- external package modules, so we have to discard the existing -- cached finder data.- liftIO $ flushFinderCaches hsc_env+ liftIO $ flushFinderCaches (hsc_FC hsc_env) (hsc_home_unit hsc_env) mod_summariesE <- liftIO $ downsweep hsc_env (mgExtendedModSummaries old_graph)@@ -316,9 +318,8 @@ (text "Modules are not listed in command line but needed for compilation: ") 4 (sep (map ppr missing))- warn = makeIntoWarning- (Reason Opt_WarnMissingHomeModules)- (mkPlainMsgEnvelope noSrcSpan msg)+ warn =+ mkPlainMsgEnvelope (WarningWithFlag Opt_WarnMissingHomeModules) noSrcSpan msg -- | Describes which modules of the module graph need to be loaded. data LoadHowMuch@@ -383,9 +384,8 @@ = filter (\arg -> not $ any (matching state arg) loadedPackages) requestedArgs - let warn = makeIntoWarning- (Reason Opt_WarnUnusedPackages)- (mkPlainMsgEnvelope noSrcSpan msg)+ let warn =+ mkPlainMsgEnvelope (WarningWithFlag Opt_WarnUnusedPackages) noSrcSpan msg msg = vcat [ text "The following packages were specified" <+> text "via -package or -package-id flags," , text "but were not needed for compilation:"@@ -433,6 +433,7 @@ let hpt1 = hsc_HPT hsc_env let dflags = hsc_dflags hsc_env let logger = hsc_logger hsc_env+ let interp = hscInterp hsc_env -- The "bad" boot modules are the ones for which we have -- B.hs-boot in the module graph, but no B.hs@@ -506,7 +507,7 @@ -- this list only serves as a poor man's set. Just hmi <- [lookupHpt pruned_hpt m], Just linkable <- [hm_linkable hmi] ]- liftIO $ unload hsc_env stable_linkables+ liftIO $ unload interp hsc_env stable_linkables -- We could at this point detect cycles which aren't broken by -- a source-import, and complain immediately, but it seems better@@ -568,8 +569,6 @@ -- an unstable module (#7231). mg = fmap (fmap ModuleNode) stable_mg ++ unstable_mg - -- clean up between compilations- let cleanup hsc_env = cleanCurrentModuleTempFiles (hsc_logger hsc_env) (hsc_dflags hsc_env) liftIO $ debugTraceMsg logger dflags 2 (hang (text "Ready for upsweep") 2 (ppr mg)) @@ -581,7 +580,7 @@ setSession hsc_env{ hsc_HPT = emptyHomePackageTable } (upsweep_ok, modsUpswept) <- withDeferredDiagnostics $- upsweep_fn mHscMessage pruned_hpt stable_mods cleanup mg+ upsweep_fn mHscMessage pruned_hpt stable_mods mg -- Make modsDone be the summaries for each home module now -- available; this should equal the domain of hpt3.@@ -601,7 +600,7 @@ -- Clean up after ourselves hsc_env1 <- getSession- liftIO $ cleanCurrentModuleTempFiles logger dflags+ liftIO $ cleanCurrentModuleTempFiles logger (hsc_tmpfs hsc_env1) dflags -- Issue a warning for the confusing case where the user -- said '-o foo' but we're not going to do any linking.@@ -620,6 +619,7 @@ hsc_env <- getSession linkresult <- liftIO $ link (ghcLink dflags) logger+ (hsc_tmpfs hsc_env) (hsc_hooks hsc_env) dflags (hsc_unit_env hsc_env)@@ -665,9 +665,9 @@ lookupHpt hpt4 (moduleName ms_mod) >>= hm_linkable ]- liftIO $- changeTempFilesLifetime dflags TFL_CurrentModule unneeded_temps- liftIO $ cleanCurrentModuleTempFiles logger dflags+ tmpfs <- hsc_tmpfs <$> getSession+ liftIO $ changeTempFilesLifetime tmpfs TFL_CurrentModule unneeded_temps+ liftIO $ cleanCurrentModuleTempFiles logger tmpfs dflags let hpt5 = retainInTopLevelEnvs (map ms_mod_name mods_to_keep) hpt4@@ -686,6 +686,7 @@ hsc_env <- getSession linkresult <- liftIO $ link (ghcLink dflags) logger+ (hsc_tmpfs hsc_env) (hsc_hooks hsc_env) dflags (hsc_unit_env hsc_env)@@ -710,7 +711,8 @@ -- If the link failed, unload everything and return. loadFinish _all_ok Failed = do hsc_env <- getSession- liftIO $ unload hsc_env []+ let interp = hscInterp hsc_env+ liftIO $ unload interp hsc_env [] modifySession discardProg return Failed @@ -841,10 +843,10 @@ -- --------------------------------------------------------------------------- -- -- | Unloading-unload :: HscEnv -> [Linkable] -> IO ()-unload hsc_env stable_linkables -- Unload everything *except* 'stable_linkables'+unload :: Interp -> HscEnv -> [Linkable] -> IO ()+unload interp hsc_env stable_linkables -- Unload everything *except* 'stable_linkables' = case ghcLink (hsc_dflags hsc_env) of- LinkInMemory -> Linker.unload hsc_env stable_linkables+ LinkInMemory -> Linker.unload interp hsc_env stable_linkables _other -> return () -- -----------------------------------------------------------------------------@@ -997,7 +999,7 @@ -- | Each module is given a unique 'LogQueue' to redirect compilation messages -- to. A 'Nothing' value contains the result of compilation, and denotes the -- end of the message queue.-data LogQueue = LogQueue !(IORef [Maybe (WarnReason, Severity, SrcSpan, SDoc)])+data LogQueue = LogQueue !(IORef [Maybe (MessageClass, SrcSpan, SDoc)]) !(MVar ()) -- | The graph of modules to compile and their corresponding result 'MVar' and@@ -1067,14 +1069,14 @@ -> Maybe Messager -> HomePackageTable -> StableModules- -> (HscEnv -> IO ()) -> [SCC ModuleGraphNode] -> m (SuccessFlag, [ModuleGraphNode])-parUpsweep n_jobs mHscMessage old_hpt stable_mods cleanup sccs = do+parUpsweep n_jobs mHscMessage old_hpt stable_mods sccs = do hsc_env <- getSession let dflags = hsc_dflags hsc_env let logger = hsc_logger hsc_env+ let tmpfs = hsc_tmpfs hsc_env -- The bits of shared state we'll be using: @@ -1176,18 +1178,15 @@ -- deal with synchronously printing these messages. let lcl_logger = pushLogHook (const (parLogAction log_queue)) thread_safe_logger - --- -- Use a local filesToClean var so that we can clean up- -- intermediate files in a timely fashion (as soon as- -- compilation for that module is finished) without having to- -- worry about accidentally deleting a simultaneous compile's- -- important files.- lcl_files_to_clean <- newIORef emptyFilesToClean- let lcl_dflags = dflags { filesToClean = lcl_files_to_clean }+ -- Use a local TmpFs so that we can clean up intermediate files+ -- in a timely fashion (as soon as compilation for that module+ -- is finished) without having to worry about accidentally+ -- deleting a simultaneous compile's important files.+ lcl_tmpfs <- forkTmpFsFrom tmpfs -- Unmask asynchronous exceptions and perform the thread-local -- work to compile the module (see parUpsweep_one).- m_res <- MC.try $ unmask $ prettyPrintGhcErrors lcl_dflags $+ m_res <- MC.try $ unmask $ prettyPrintGhcErrors dflags $ case mod of InstantiationNode iuid -> do hsc_env <- readMVar hsc_env_var@@ -1195,8 +1194,8 @@ pure Succeeded ModuleNode ems -> parUpsweep_one (emsModSummary ems) home_mod_map comp_graph_loops- lcl_logger lcl_dflags (hsc_home_unit hsc_env)- mHscMessage cleanup+ lcl_logger lcl_tmpfs dflags (hsc_home_unit hsc_env)+ mHscMessage par_sem hsc_env_var old_hpt_var stable_mods mod_idx (length sccs) @@ -1208,7 +1207,7 @@ -- interrupt, and the user doesn't have to be informed -- about that. when (fromException exc /= Just ThreadKilled)- (errorMsg lcl_logger lcl_dflags (text (show exc)))+ (errorMsg lcl_logger dflags (text (show exc))) return Failed -- Populate the result MVar.@@ -1220,13 +1219,8 @@ writeLogQueue log_queue Nothing -- Add the remaining files that weren't cleaned up to the- -- global filesToClean ref, for cleanup later.- FilesToClean- { ftcCurrentModule = cm_files- , ftcGhcSession = gs_files- } <- readIORef (filesToClean lcl_dflags)- addFilesToClean dflags TFL_CurrentModule $ Set.toList cm_files- addFilesToClean dflags TFL_GhcSession $ Set.toList gs_files+ -- global TmpFs, for cleanup later.+ mergeTmpFsInto lcl_tmpfs tmpfs -- Kill all the workers, masking interrupts (since killThread is -- interruptible). XXX: This is not ideal.@@ -1259,7 +1253,7 @@ return (success_flag,ok_results) where- writeLogQueue :: LogQueue -> Maybe (WarnReason,Severity,SrcSpan,SDoc) -> IO ()+ writeLogQueue :: LogQueue -> Maybe (MessageClass,SrcSpan,SDoc) -> IO () writeLogQueue (LogQueue ref sem) msg = do atomicModifyIORef' ref $ \msgs -> (msg:msgs,()) _ <- tryPutMVar sem ()@@ -1268,8 +1262,8 @@ -- The log_action callback that is used to synchronize messages from a -- worker thread. parLogAction :: LogQueue -> LogAction- parLogAction log_queue _dflags !reason !severity !srcSpan !msg =- writeLogQueue log_queue (Just (reason,severity,srcSpan,msg))+ parLogAction log_queue _dflags !msgClass !srcSpan !msg =+ writeLogQueue log_queue (Just (msgClass,srcSpan,msg)) -- Print each message from the log_queue using the log_action from the -- session's DynFlags.@@ -1282,8 +1276,8 @@ print_loop [] = read_msgs print_loop (x:xs) = case x of- Just (reason,severity,srcSpan,msg) -> do- putLogMsg logger dflags reason severity srcSpan msg+ Just (msgClass,srcSpan,msg) -> do+ putLogMsg logger dflags msgClass srcSpan msg print_loop xs -- Exit the loop once we encounter the end marker. Nothing -> return ()@@ -1298,14 +1292,14 @@ -- ^ The list of all module loops within the compilation graph. -> Logger -- ^ The thread-local Logger+ -> TmpFs+ -- ^ The thread-local TmpFs -> DynFlags -- ^ The thread-local DynFlags -> HomeUnit -- ^ The home-unit -> Maybe Messager -- ^ The messager- -> (HscEnv -> IO ())- -- ^ The callback for cleaning up intermediate files -> QSem -- ^ The semaphore for limiting the number of simultaneous compiles -> MVar HscEnv@@ -1320,7 +1314,7 @@ -- ^ The total number of modules -> IO SuccessFlag -- ^ The result of this compile-parUpsweep_one mod home_mod_map comp_graph_loops lcl_logger lcl_dflags home_unit mHscMessage cleanup par_sem+parUpsweep_one mod home_mod_map comp_graph_loops lcl_logger lcl_tmpfs lcl_dflags home_unit mHscMessage par_sem hsc_env_var old_hpt_var stable_mods mod_index num_mods = do let this_build_mod = mkBuildModule0 mod@@ -1430,9 +1424,7 @@ let withSem sem = MC.bracket_ (waitQSem sem) (signalQSem sem) mb_mod_info <- withSem par_sem $ handleSourceError (\err -> do logg err; return Nothing) $ do- -- Have the ModSummary and HscEnv point to our local log_action- -- and filesToClean var.- let lcl_mod = localize_mod mod+ -- Have the HscEnv point to our local logger and tmpfs. let lcl_hsc_env = localize_hsc_env hsc_env -- Re-typecheck the loop@@ -1440,7 +1432,7 @@ -- we close a recursive module loop, see bug #12035. type_env_var <- liftIO $ newIORef emptyNameEnv let lcl_hsc_env' = lcl_hsc_env { hsc_type_env_var =- Just (ms_mod lcl_mod, type_env_var) }+ Just (ms_mod mod, type_env_var) } lcl_hsc_env'' <- case finish_loop of Nothing -> return lcl_hsc_env' -- In the non-parallel case, the retypecheck prior to@@ -1454,7 +1446,7 @@ -- Compile the module. mod_info <- upsweep_mod lcl_hsc_env'' mHscMessage old_hpt stable_mods- lcl_mod mod_index num_mods+ mod mod_index num_mods return (Just mod_info) case mb_mod_info of@@ -1483,18 +1475,16 @@ return (hsc_env'', localize_hsc_env hsc_env'') -- Clean up any intermediate files.- cleanup lcl_hsc_env'+ cleanCurrentModuleTempFiles (hsc_logger lcl_hsc_env')+ (hsc_tmpfs lcl_hsc_env')+ (hsc_dflags lcl_hsc_env') return Succeeded where- localize_mod mod- = mod { ms_hspp_opts = (ms_hspp_opts mod)- { filesToClean = filesToClean lcl_dflags } }- localize_hsc_env hsc_env = hsc_env { hsc_logger = lcl_logger- , hsc_dflags = (hsc_dflags hsc_env)- { filesToClean = filesToClean lcl_dflags } }+ , hsc_tmpfs = lcl_tmpfs+ } -- ----------------------------------------------------------------------------- --@@ -1510,7 +1500,6 @@ => Maybe Messager -> HomePackageTable -- ^ HPT from last time round (pruned) -> StableModules -- ^ stable modules (see checkStability)- -> (HscEnv -> IO ()) -- ^ How to clean up unwanted tmp files -> [SCC ModuleGraphNode] -- ^ Mods to do (the worklist) -> m (SuccessFlag, [ModuleGraphNode])@@ -1520,7 +1509,7 @@ -- 2. The 'HscEnv' in the monad has an updated HPT -- 3. A list of modules which succeeded loading. -upsweep mHscMessage old_hpt stable_mods cleanup sccs = do+upsweep mHscMessage old_hpt stable_mods sccs = do (res, done) <- upsweep' old_hpt emptyMG sccs 1 (length sccs) return (res, reverse $ mgModSummaries' done) where@@ -1588,7 +1577,9 @@ hsc_env <- getSession -- Remove unwanted tmp files between compilations- liftIO (cleanup hsc_env)+ liftIO $ cleanCurrentModuleTempFiles (hsc_logger hsc_env)+ (hsc_tmpfs hsc_env)+ (hsc_dflags hsc_env) -- Get ready to tie the knot type_env_var <- liftIO $ newIORef emptyNameEnv@@ -2230,8 +2221,8 @@ warn :: Located ModuleName -> WarnMsg warn (L loc mod) =- mkPlainMsgEnvelope loc- (text "Warning: {-# SOURCE #-} unnecessary in import of "+ mkPlainMsgEnvelope WarningWithoutFlag loc+ (text "{-# SOURCE #-} unnecessary in import of " <+> quotes (ppr mod)) @@ -2274,10 +2265,10 @@ -- otherwise those modules will fail to compile. -- See Note [-fno-code mode] #8025 let default_backend = platformDefaultBackend (targetPlatform dflags)- home_unit = hsc_home_unit hsc_env+ let home_unit = hsc_home_unit hsc_env+ let tmpfs = hsc_tmpfs hsc_env map1 <- case backend dflags of- NoBackend -> enableCodeGenForTH logger home_unit default_backend map0- Interpreter -> enableCodeGenForUnboxedTuplesOrSums logger default_backend map0+ NoBackend -> enableCodeGenForTH logger tmpfs home_unit default_backend map0 _ -> return map0 if null errs then pure $ concat $ modNodeMapElems map1@@ -2295,14 +2286,20 @@ old_summary_map = mkNodeMap old_summaries getRootSummary :: Target -> IO (Either ErrorMessages ExtendedModSummary)- getRootSummary (Target (TargetFile file mb_phase) obj_allowed maybe_buf)+ getRootSummary Target { targetId = TargetFile file mb_phase+ , targetAllowObjCode = obj_allowed+ , targetContents = maybe_buf+ } = do exists <- liftIO $ doesFileExist file if exists || isJust maybe_buf then summariseFile hsc_env old_summaries file mb_phase obj_allowed maybe_buf- else return $ Left $ unitBag $ mkPlainMsgEnvelope noSrcSpan $+ else return $ Left $ unitBag $ mkPlainMsgEnvelope ErrorWithoutFlag noSrcSpan $ text "can't find file:" <+> text file- getRootSummary (Target (TargetModule modl) obj_allowed maybe_buf)+ getRootSummary Target { targetId = TargetModule modl+ , targetAllowObjCode = obj_allowed+ , targetContents = maybe_buf+ } = do maybe_summary <- summariseModule hsc_env old_summary_map NotBoot (L rootLoc modl) obj_allowed maybe_buf excl_mods@@ -2372,12 +2369,13 @@ -- See Note [-fno-code mode] enableCodeGenForTH :: Logger+ -> TmpFs -> HomeUnit -> Backend -> ModNodeMap [Either ErrorMessages ExtendedModSummary] -> IO (ModNodeMap [Either ErrorMessages ExtendedModSummary])-enableCodeGenForTH logger home_unit =- enableCodeGenWhen logger condition should_modify TFL_CurrentModule TFL_GhcSession+enableCodeGenForTH logger tmpfs home_unit =+ enableCodeGenWhen logger tmpfs condition should_modify TFL_CurrentModule TFL_GhcSession where condition = isTemplateHaskellOrQQNonBoot should_modify (ModSummary { ms_hspp_opts = dflags }) =@@ -2386,38 +2384,15 @@ -- can't compile anything anyway! See #16219. isHomeUnitDefinite home_unit --- | Update the every ModSummary that is depended on--- by a module that needs unboxed tuples. We enable codegen to--- the specified target, disable optimization and change the .hi--- and .o file locations to be temporary files.------ This is used in order to load code that uses unboxed tuples--- or sums into GHCi while still allowing some code to be interpreted.-enableCodeGenForUnboxedTuplesOrSums- :: Logger- -> Backend- -> ModNodeMap [Either ErrorMessages ExtendedModSummary]- -> IO (ModNodeMap [Either ErrorMessages ExtendedModSummary])-enableCodeGenForUnboxedTuplesOrSums logger =- enableCodeGenWhen logger condition should_modify TFL_GhcSession TFL_CurrentModule- where- condition ms =- unboxed_tuples_or_sums (ms_hspp_opts ms) &&- not (gopt Opt_ByteCode (ms_hspp_opts ms)) &&- (isBootSummary ms == NotBoot)- unboxed_tuples_or_sums d =- xopt LangExt.UnboxedTuples d || xopt LangExt.UnboxedSums d- should_modify (ModSummary { ms_hspp_opts = dflags }) =- backend dflags == Interpreter---- | Helper used to implement 'enableCodeGenForTH' and--- 'enableCodeGenForUnboxedTuples'. In particular, this enables+-- | Helper used to implement 'enableCodeGenForTH'.+-- In particular, this enables -- unoptimized code generation for all modules that meet some -- condition (first parameter), or are dependencies of those -- modules. The second parameter is a condition to check before -- marking modules for code generation. enableCodeGenWhen :: Logger+ -> TmpFs -> (ModSummary -> Bool) -> (ModSummary -> Bool) -> TempFileLifetime@@ -2425,7 +2400,7 @@ -> Backend -> ModNodeMap [Either ErrorMessages ExtendedModSummary] -> IO (ModNodeMap [Either ErrorMessages ExtendedModSummary])-enableCodeGenWhen logger condition should_modify staticLife dynLife bcknd nodemap =+enableCodeGenWhen logger tmpfs condition should_modify staticLife dynLife bcknd nodemap = traverse (traverse (traverse enable_code_gen)) nodemap where enable_code_gen :: ExtendedModSummary -> IO ExtendedModSummary@@ -2440,9 +2415,9 @@ , ms_mod `Set.member` needs_codegen_set = do let new_temp_file suf dynsuf = do- tn <- newTempName logger dflags staticLife suf+ tn <- newTempName logger tmpfs dflags staticLife suf let dyn_tn = tn -<.> dynsuf- addFilesToClean dflags dynLife [dyn_tn]+ addFilesToClean tmpfs dynLife [dyn_tn] return tn -- We don't want to create .o or .hi files unless we have been asked -- to by the user. But we need them, so we patch their locations in@@ -2579,7 +2554,10 @@ -- Tell the Finder cache where it is, so that subsequent calls -- to findModule will find it, even if it's not on any search path- mod <- liftIO $ addHomeModuleToFinder hsc_env pi_mod_name location+ mod <- liftIO $ do+ let home_unit = hsc_home_unit hsc_env+ let fc = hsc_FC hsc_env+ addHomeModuleToFinder fc home_unit pi_mod_name location liftIO $ makeNewModSummary hsc_env $ MakeNewModSummary { nms_src_fn = src_fn@@ -2630,7 +2608,10 @@ -- and it was likely flushed in depanal. This is not technically -- needed when we're called from sumariseModule but it shouldn't -- hurt.- _ <- addHomeModuleToFinder hsc_env+ _ <- do+ let home_unit = hsc_home_unit hsc_env+ let fc = hsc_FC hsc_env+ addHomeModuleToFinder fc home_unit (moduleName (ms_mod old_summary)) location hi_timestamp <- maybeGetIfaceDate dflags location@@ -2691,8 +2672,10 @@ | otherwise = find_it where- dflags = hsc_dflags hsc_env+ dflags = hsc_dflags hsc_env home_unit = hsc_home_unit hsc_env+ fc = hsc_FC hsc_env+ units = hsc_units hsc_env check_timestamp old_summary location src_fn = checkSummaryTimestamp@@ -2701,7 +2684,7 @@ old_summary location find_it = do- found <- findImportedModule hsc_env wanted_mod Nothing+ found <- findImportedModule fc units home_unit dflags wanted_mod Nothing case found of Found location mod | isJust (ml_hs_file location) ->@@ -2746,7 +2729,7 @@ | otherwise = HsSrcFile when (pi_mod_name /= wanted_mod) $- throwE $ unitBag $ mkPlainMsgEnvelope pi_mod_name_loc $+ throwE $ unitBag $ mkPlainMsgEnvelope ErrorWithoutFlag pi_mod_name_loc $ text "File name does not match module name:" $$ text "Saw:" <+> quotes (ppr pi_mod_name) $$ text "Expected:" <+> quotes (ppr wanted_mod)@@ -2758,7 +2741,7 @@ | (k,v) <- ((pi_mod_name, mkHoleModule pi_mod_name) : homeUnitInstantiations home_unit) ])- in throwE $ unitBag $ mkPlainMsgEnvelope pi_mod_name_loc $+ in throwE $ unitBag $ mkPlainMsgEnvelope ErrorWithoutFlag pi_mod_name_loc $ text "Unexpected signature:" <+> quotes (ppr pi_mod_name) $$ if gopt Opt_BuildingCabalPackage dflags then parens (text "Try adding" <+> quotes (ppr pi_mod_name)@@ -2892,12 +2875,15 @@ fatals <- liftIO $ newIORef [] logger <- getLogger - let deferDiagnostics _dflags !reason !severity !srcSpan !msg = do- let action = putLogMsg logger dflags reason severity srcSpan msg- case severity of- SevWarning -> atomicModifyIORef' warnings $ \i -> (action: i, ())- SevError -> atomicModifyIORef' errors $ \i -> (action: i, ())- SevFatal -> atomicModifyIORef' fatals $ \i -> (action: i, ())+ let deferDiagnostics _dflags !msgClass !srcSpan !msg = do+ let action = putLogMsg logger dflags msgClass srcSpan msg+ case msgClass of+ MCDiagnostic SevWarning _reason+ -> atomicModifyIORef' warnings $ \i -> (action: i, ())+ MCDiagnostic SevError _reason+ -> atomicModifyIORef' errors $ \i -> (action: i, ())+ MCFatal+ -> atomicModifyIORef' fatals $ \i -> (action: i, ()) _ -> action printDeferredDiagnostics = liftIO $@@ -2912,24 +2898,24 @@ (\_ -> popLogHookM >> printDeferredDiagnostics) (\_ -> f) -noModError :: HscEnv -> SrcSpan -> ModuleName -> FindResult -> MsgEnvelope DecoratedSDoc+noModError :: HscEnv -> SrcSpan -> ModuleName -> FindResult -> MsgEnvelope DiagnosticMessage -- ToDo: we don't have a proper line number for this error noModError hsc_env loc wanted_mod err- = mkPlainMsgEnvelope loc $ cannotFindModule hsc_env wanted_mod err+ = mkPlainMsgEnvelope ErrorWithoutFlag loc $ cannotFindModule hsc_env wanted_mod err noHsFileErr :: SrcSpan -> String -> ErrorMessages noHsFileErr loc path- = unitBag $ mkPlainMsgEnvelope loc $ text "Can't find" <+> text path+ = unitBag $ mkPlainMsgEnvelope ErrorWithoutFlag loc $ text "Can't find" <+> text path moduleNotFoundErr :: ModuleName -> ErrorMessages moduleNotFoundErr mod- = unitBag $ mkPlainMsgEnvelope noSrcSpan $+ = unitBag $ mkPlainMsgEnvelope ErrorWithoutFlag noSrcSpan $ text "module" <+> quotes (ppr mod) <+> text "cannot be found locally" multiRootsErr :: [ModSummary] -> IO () multiRootsErr [] = panic "multiRootsErr" multiRootsErr summs@(summ1:_)- = throwOneError $ mkPlainMsgEnvelope noSrcSpan $+ = throwOneError $ mkPlainMsgEnvelope ErrorWithoutFlag noSrcSpan $ text "module" <+> quotes (ppr mod) <+> text "is defined in multiple files:" <+> sep (map text files)
compiler/GHC/Driver/MakeFile.hs view
@@ -31,7 +31,7 @@ import GHC.Types.SrcLoc import Data.List (partition) import GHC.Data.FastString-import GHC.SysTools.FileCleanup+import GHC.Utils.TmpFs import GHC.Iface.Load (cannotFindModule) @@ -82,10 +82,11 @@ when (null (depSuffixes dflags)) $ liftIO $ throwGhcExceptionIO (ProgramError "You must specify at least one -dep-suffix") - files <- liftIO $ beginMkDependHS logger dflags+ tmpfs <- hsc_tmpfs <$> getSession+ files <- liftIO $ beginMkDependHS logger tmpfs dflags -- Do the downsweep to find all the modules- targets <- mapM (\s -> GHC.guessTarget s Nothing) srcs+ targets <- mapM (\s -> GHC.guessTarget s Nothing Nothing) srcs GHC.setTargets targets let excl_mods = depExcludeMods dflags module_graph <- GHC.depanal excl_mods True {- Allow dup roots -}@@ -131,11 +132,11 @@ mkd_tmp_file :: FilePath, -- Name of the temporary file mkd_tmp_hdl :: Handle } -- Handle of the open temporary file -beginMkDependHS :: Logger -> DynFlags -> IO MkDepFiles-beginMkDependHS logger dflags = do+beginMkDependHS :: Logger -> TmpFs -> DynFlags -> IO MkDepFiles+beginMkDependHS logger tmpfs dflags = do -- open a new temp file in which to stuff the dependency info -- as we go along.- tmp_file <- newTempName logger dflags TFL_CurrentModule "dep"+ tmp_file <- newTempName logger tmpfs dflags TFL_CurrentModule "dep" tmp_hdl <- openFile tmp_file WriteMode -- open the makefile@@ -285,24 +286,27 @@ -> IsBootInterface -- Source import -> Bool -- Record dependency on package modules -> IO (Maybe FilePath) -- Interface file-findDependency hsc_env srcloc pkg imp is_boot include_pkg_deps- = do { -- Find the module; this will be fast because- -- we've done it once during downsweep- r <- findImportedModule hsc_env imp pkg- ; case r of- Found loc _- -- Home package: just depend on the .hi or hi-boot file- | isJust (ml_hs_file loc) || include_pkg_deps- -> return (Just (addBootSuffix_maybe is_boot (ml_hi_file loc)))+findDependency hsc_env srcloc pkg imp is_boot include_pkg_deps = do+ let fc = hsc_FC hsc_env+ let home_unit = hsc_home_unit hsc_env+ let units = hsc_units hsc_env+ let dflags = hsc_dflags hsc_env+ -- Find the module; this will be fast because+ -- we've done it once during downsweep+ r <- findImportedModule fc units home_unit dflags imp pkg+ case r of+ Found loc _+ -- Home package: just depend on the .hi or hi-boot file+ | isJust (ml_hs_file loc) || include_pkg_deps+ -> return (Just (addBootSuffix_maybe is_boot (ml_hi_file loc))) - -- Not in this package: we don't need a dependency- | otherwise- -> return Nothing+ -- Not in this package: we don't need a dependency+ | otherwise+ -> return Nothing - fail ->- throwOneError $ mkPlainMsgEnvelope srcloc $- cannotFindModule hsc_env imp fail- }+ fail ->+ throwOneError $ mkPlainMsgEnvelope ErrorWithoutFlag srcloc $+ cannotFindModule hsc_env imp fail ----------------------------- writeDependency :: FilePath -> Handle -> [FilePath] -> FilePath -> IO ()
compiler/GHC/Driver/Pipeline.hs view
@@ -62,7 +62,7 @@ import GHC.Parser.Errors.Ppr import GHC.SysTools-import GHC.SysTools.FileCleanup+import GHC.Utils.TmpFs import GHC.Linker.ExtraObj import GHC.Linker.Dynamic@@ -151,7 +151,7 @@ where srcspan = srcLocSpan $ mkSrcLoc (mkFastString input_fn) 1 1 handler (ProgramError msg) = return $ Left $ unitBag $- mkPlainMsgEnvelope srcspan $ text msg+ mkPlainMsgEnvelope ErrorWithoutFlag srcspan $ text msg handler ex = throwGhcExceptionIO ex -- ---------------------------------------------------------------------------@@ -196,6 +196,7 @@ = do let logger = hsc_logger hsc_env0+ let tmpfs = hsc_tmpfs hsc_env0 debugTraceMsg logger dflags1 2 (text "compile: input file" <+> text input_fnpp) -- Run the pipeline up to codeGen (so everything up to, but not including, STG)@@ -208,10 +209,10 @@ let flags = hsc_dflags hsc_env0 in do unless (gopt Opt_KeepHiFiles flags) $- addFilesToClean flags TFL_CurrentModule $+ addFilesToClean tmpfs TFL_CurrentModule $ [ml_hi_file $ ms_location summary] unless (gopt Opt_KeepOFiles flags) $- addFilesToClean flags TFL_GhcSession $+ addFilesToClean tmpfs TFL_GhcSession $ [ml_obj_file $ ms_location summary] case (status, bcknd) of@@ -236,7 +237,7 @@ let !linkable = LM (ms_hs_date summary) this_mod [] return $! HomeModInfo iface hmi_details (Just linkable) (HscUpdateSig iface hmi_details, _) -> do- output_fn <- getOutputFilename logger next_phase+ output_fn <- getOutputFilename logger tmpfs next_phase (Temporary TFL_CurrentModule) basename dflags next_phase (Just location) @@ -286,7 +287,7 @@ (hs_unlinked ++ stub_o) return $! HomeModInfo final_iface hmi_details (Just linkable) (HscRecomp{}, _) -> do- output_fn <- getOutputFilename logger next_phase+ output_fn <- getOutputFilename logger tmpfs next_phase (Temporary TFL_CurrentModule) basename dflags next_phase (Just location) -- We're in --make mode: finish the compilation pipeline.@@ -342,7 +343,7 @@ current_dir = takeDirectory basename old_paths = includePaths dflags2 loadAsByteCode- | Just (Target _ obj _) <- findTarget summary (hsc_targets hsc_env0)+ | Just Target { targetAllowObjCode = obj } <- findTarget summary (hsc_targets hsc_env0) , not obj = True | otherwise = False@@ -418,7 +419,8 @@ -- https://gitlab.haskell.org/ghc/ghc/issues/12673 -- and https://github.com/haskell/cabal/issues/2257 let logger = hsc_logger hsc_env- empty_stub <- newTempName logger dflags TFL_CurrentModule "c"+ let tmpfs = hsc_tmpfs hsc_env+ empty_stub <- newTempName logger tmpfs dflags TFL_CurrentModule "c" let home_unit = hsc_home_unit hsc_env src = text "int" <+> ppr (mkHomeModule home_unit mod_name) <+> text "= 0;" writeFile empty_stub (showSDoc dflags (pprCode CStyle src))@@ -484,6 +486,7 @@ -- libraries. link :: GhcLink -- ^ interactive or batch -> Logger -- ^ Logger+ -> TmpFs -> Hooks -> DynFlags -- ^ dynamic flags -> UnitEnv -- ^ unit environment@@ -498,13 +501,13 @@ -- exports main, i.e., we have good reason to believe that linking -- will succeed. -link ghcLink logger hooks dflags unit_env batch_attempt_linking hpt =+link ghcLink logger tmpfs hooks dflags unit_env batch_attempt_linking hpt = case linkHook hooks of Nothing -> case ghcLink of NoLink -> return Succeeded- LinkBinary -> link' logger dflags unit_env batch_attempt_linking hpt- LinkStaticLib -> link' logger dflags unit_env batch_attempt_linking hpt- LinkDynLib -> link' logger dflags unit_env batch_attempt_linking hpt+ LinkBinary -> link' logger tmpfs dflags unit_env batch_attempt_linking hpt+ LinkStaticLib -> link' logger tmpfs dflags unit_env batch_attempt_linking hpt+ LinkDynLib -> link' logger tmpfs dflags unit_env batch_attempt_linking hpt LinkInMemory | platformMisc_ghcWithInterpreter $ platformMisc dflags -> -- Not Linking...(demand linker will do the job)@@ -519,13 +522,14 @@ show other) link' :: Logger+ -> TmpFs -> DynFlags -- ^ dynamic flags -> UnitEnv -- ^ unit environment -> Bool -- ^ attempt linking in batch mode? -> HomePackageTable -- ^ what to link -> IO SuccessFlag -link' logger dflags unit_env batch_attempt_linking hpt+link' logger tmpfs dflags unit_env batch_attempt_linking hpt | batch_attempt_linking = do let@@ -565,11 +569,11 @@ -- Don't showPass in Batch mode; doLink will do that for us. let link = case ghcLink dflags of- LinkBinary -> linkBinary- LinkStaticLib -> linkStaticLib- LinkDynLib -> linkDynLibCheck+ LinkBinary -> linkBinary logger tmpfs+ LinkStaticLib -> linkStaticLib logger+ LinkDynLib -> linkDynLibCheck logger tmpfs other -> panicBadLink other- link logger dflags unit_env obj_files pkg_deps+ link dflags unit_env obj_files pkg_deps debugTraceMsg logger dflags 3 (text "link: done") @@ -678,11 +682,12 @@ dflags = hsc_dflags hsc_env logger = hsc_logger hsc_env unit_env = hsc_unit_env hsc_env+ tmpfs = hsc_tmpfs hsc_env in case ghcLink dflags of NoLink -> return ()- LinkBinary -> linkBinary logger dflags unit_env o_files []- LinkStaticLib -> linkStaticLib logger dflags unit_env o_files []- LinkDynLib -> linkDynLibCheck logger dflags unit_env o_files []+ LinkBinary -> linkBinary logger tmpfs dflags unit_env o_files []+ LinkStaticLib -> linkStaticLib logger dflags unit_env o_files []+ LinkDynLib -> linkDynLibCheck logger tmpfs dflags unit_env o_files [] other -> panicBadLink other @@ -719,6 +724,7 @@ dflags = dflags0 { dumpPrefix = Just (basename ++ ".") } hsc_env = hsc_env0 {hsc_dflags = dflags} logger = hsc_logger hsc_env+ tmpfs = hsc_tmpfs hsc_env (input_basename, suffix) = splitExtension input_fn suffix' = drop 1 suffix -- strip off the .@@ -766,7 +772,7 @@ input_fn' <- case (start_phase, mb_input_buf) of (RealPhase real_start_phase, Just input_buf) -> do let suffix = phaseInputExt real_start_phase- fn <- newTempName logger dflags TFL_CurrentModule suffix+ fn <- newTempName logger tmpfs dflags TFL_CurrentModule suffix hdl <- openBinaryFile fn WriteMode -- Add a LINE pragma so reported source locations will -- mention the real input file, not this temp file.@@ -869,7 +875,8 @@ return input_fn output -> do pst <- getPipeState- final_fn <- liftIO $ getOutputFilename logger+ tmpfs <- hsc_tmpfs <$> getPipeSession+ final_fn <- liftIO $ getOutputFilename logger tmpfs stopPhase output (src_basename env) dflags stopPhase (maybe_loc pst) when (final_fn /= input_fn) $ do@@ -954,10 +961,11 @@ phaseOutputFilename :: Phase{-next phase-} -> CompPipeline FilePath phaseOutputFilename next_phase = do PipeEnv{stop_phase, src_basename, output_spec} <- getPipeEnv- PipeState{maybe_loc} <- getPipeState+ PipeState{maybe_loc,hsc_env} <- getPipeState dflags <- getDynFlags logger <- getLogger- liftIO $ getOutputFilename logger stop_phase output_spec+ let tmpfs = hsc_tmpfs hsc_env+ liftIO $ getOutputFilename logger tmpfs stop_phase output_spec src_basename dflags next_phase maybe_loc -- | Computes the next output filename for something in the compilation@@ -976,17 +984,24 @@ -- compiling; this can be used to override the default output -- of an object file. (TODO: do we actually need this?) getOutputFilename- :: Logger -> Phase -> PipelineOutput -> String- -> DynFlags -> Phase{-next phase-} -> Maybe ModLocation -> IO FilePath-getOutputFilename logger stop_phase output basename dflags next_phase maybe_location+ :: Logger+ -> TmpFs+ -> Phase+ -> PipelineOutput+ -> String+ -> DynFlags+ -> Phase -- next phase+ -> Maybe ModLocation+ -> IO FilePath+getOutputFilename logger tmpfs stop_phase output basename dflags next_phase maybe_location | is_last_phase, Persistent <- output = persistent_fn | is_last_phase, SpecificFile <- output = case outputFile dflags of Just f -> return f Nothing -> panic "SpecificFile: No filename" | keep_this_output = persistent_fn- | Temporary lifetime <- output = newTempName logger dflags lifetime suffix- | otherwise = newTempName logger dflags TFL_CurrentModule+ | Temporary lifetime <- output = newTempName logger tmpfs dflags lifetime suffix+ | otherwise = newTempName logger tmpfs dflags TFL_CurrentModule suffix where hcsuf = hcSuf dflags@@ -1043,6 +1058,7 @@ ++ [("", "-mcpu=" ++ mcpu) | not (null mcpu) , not (any (isInfixOf "-mcpu") (getOpts dflags opt_lc)) ] ++ [("", "-mattr=" ++ attrs) | not (null attrs) ]+ ++ [("", "-target-abi=" ++ abi) | not (null abi) ] where target = platformMisc_llvmTarget $ platformMisc dflags Just (LlvmTarget _ mcpu mattr) = lookup target (llvmTargets $ llvmConfig dflags)@@ -1074,6 +1090,11 @@ ++ ["+bmi" | isBmiEnabled dflags ] ++ ["+bmi2" | isBmi2Enabled dflags ] + abi :: String+ abi = case platformArch (targetPlatform dflags) of+ ArchRISCV64 -> "lp64d"+ _ -> ""+ -- ----------------------------------------------------------------------------- -- | Each phase in the pipeline returns the next phase to execute, and the -- name of the file in which the output was placed.@@ -1154,7 +1175,10 @@ else do output_fn <- phaseOutputFilename (HsPp sf) hsc_env <- getPipeSession- liftIO $ doCpp logger (hsc_dflags hsc_env) (hsc_unit_env hsc_env)+ liftIO $ doCpp logger+ (hsc_tmpfs hsc_env)+ (hsc_dflags hsc_env)+ (hsc_unit_env hsc_env) True{-raw-} input_fn output_fn -- re-read the pragmas now that we've preprocessed the file@@ -1279,7 +1303,10 @@ PipeState{hsc_env=hsc_env'} <- getPipeState -- Tell the finder cache about this module- mod <- liftIO $ addHomeModuleToFinder hsc_env' mod_name location+ mod <- liftIO $ do+ let home_unit = hsc_home_unit hsc_env'+ let fc = hsc_FC hsc_env'+ addHomeModuleToFinder fc home_unit mod_name location -- Make the ModSummary to hand to hscMain let@@ -1383,7 +1410,10 @@ hsc_env <- getPipeSession logger <- getLogger output_fn <- phaseOutputFilename Cmm- liftIO $ doCpp logger (hsc_dflags hsc_env) (hsc_unit_env hsc_env)+ liftIO $ doCpp logger+ (hsc_tmpfs hsc_env)+ (hsc_dflags hsc_env)+ (hsc_unit_env hsc_env) False{-not raw-} input_fn output_fn return (RealPhase Cmm, output_fn)@@ -1394,7 +1424,9 @@ let next_phase = hscPostBackendPhase HsSrcFile (backend dflags) output_fn <- phaseOutputFilename next_phase PipeState{hsc_env} <- getPipeState- liftIO $ hscCompileCmmFile hsc_env input_fn output_fn+ mstub <- liftIO $ hscCompileCmmFile hsc_env input_fn output_fn+ stub_o <- liftIO (mapM (compileStub hsc_env) mstub)+ setForeignOs (maybeToList stub_o) return (RealPhase next_phase, output_fn) -----------------------------------------------------------------------------@@ -1407,6 +1439,7 @@ let dflags = hsc_dflags hsc_env let unit_env = hsc_unit_env hsc_env let home_unit = hsc_home_unit hsc_env+ let tmpfs = hsc_tmpfs hsc_env let platform = ue_platform unit_env let hcc = cc_phase `eqPhase` HCc @@ -1484,7 +1517,7 @@ ghcVersionH <- liftIO $ getGhcVersionPathName dflags unit_env logger <- getLogger- liftIO $ GHC.SysTools.runCc (phaseForeignLanguage cc_phase) logger dflags (+ liftIO $ GHC.SysTools.runCc (phaseForeignLanguage cc_phase) logger tmpfs dflags ( [ GHC.SysTools.FileOption "" input_fn , GHC.SysTools.Option "-o" , GHC.SysTools.FileOption "" output_fn@@ -1739,7 +1772,7 @@ -- merge in stub objects runPhase (RealPhase MergeForeign) input_fn = do- PipeState{foreign_os} <- getPipeState+ PipeState{foreign_os,hsc_env} <- getPipeState output_fn <- phaseOutputFilename StopLn liftIO $ createDirectoryIfMissing True (takeDirectory output_fn) if null foreign_os@@ -1747,7 +1780,8 @@ else do dflags <- getDynFlags logger <- getLogger- liftIO $ joinObjectFiles logger dflags (input_fn : foreign_os) output_fn+ let tmpfs = hsc_tmpfs hsc_env+ liftIO $ joinObjectFiles logger tmpfs dflags (input_fn : foreign_os) output_fn return (RealPhase StopLn, output_fn) -- warning suppression@@ -1822,14 +1856,14 @@ return [] -linkDynLibCheck :: Logger -> DynFlags -> UnitEnv -> [String] -> [UnitId] -> IO ()-linkDynLibCheck logger dflags unit_env o_files dep_units = do+linkDynLibCheck :: Logger -> TmpFs -> DynFlags -> UnitEnv -> [String] -> [UnitId] -> IO ()+linkDynLibCheck logger tmpfs dflags unit_env o_files dep_units = do when (haveRtsOptsFlags dflags) $- putLogMsg logger dflags NoReason SevInfo noSrcSpan+ putLogMsg logger dflags MCInfo noSrcSpan $ withPprStyle defaultUserStyle (text "Warning: -rtsopts and -with-rtsopts have no effect with -shared." $$ text " Call hs_init_ghc() from your main() function to set these options.")- linkDynLib logger dflags unit_env o_files dep_units+ linkDynLib logger tmpfs dflags unit_env o_files dep_units -- -----------------------------------------------------------------------------@@ -1838,8 +1872,8 @@ -- | Run CPP -- -- UnitState is needed to compute MIN_VERSION macros-doCpp :: Logger -> DynFlags -> UnitEnv -> Bool -> FilePath -> FilePath -> IO ()-doCpp logger dflags unit_env raw input_fn output_fn = do+doCpp :: Logger -> TmpFs -> DynFlags -> UnitEnv -> Bool -> FilePath -> FilePath -> IO ()+doCpp logger tmpfs dflags unit_env raw input_fn output_fn = do let hscpp_opts = picPOpts dflags let cmdline_include_paths = includePaths dflags let unit_state = ue_units unit_env@@ -1854,7 +1888,8 @@ let verbFlags = getVerbFlags dflags let cpp_prog args | raw = GHC.SysTools.runCpp logger dflags args- | otherwise = GHC.SysTools.runCc Nothing logger dflags (GHC.SysTools.Option "-E" : args)+ | otherwise = GHC.SysTools.runCc Nothing logger tmpfs dflags+ (GHC.SysTools.Option "-E" : args) let platform = targetPlatform dflags targetArch = stringEncodeArch $ platformArch platform@@ -1897,7 +1932,7 @@ pkgs = catMaybes (map (lookupUnit unit_state) uids) mb_macro_include <- if not (null pkgs) && gopt Opt_VersionMacros dflags- then do macro_stub <- newTempName logger dflags TFL_CurrentModule "h"+ then do macro_stub <- newTempName logger tmpfs dflags TFL_CurrentModule "h" writeFile macro_stub (generatePackageVersionMacros pkgs) -- Include version macros for every *exposed* package. -- Without -hide-all-packages and with a package database@@ -2027,12 +2062,12 @@ -} -joinObjectFiles :: Logger -> DynFlags -> [FilePath] -> FilePath -> IO ()-joinObjectFiles logger dflags o_files output_fn = do+joinObjectFiles :: Logger -> TmpFs -> DynFlags -> [FilePath] -> FilePath -> IO ()+joinObjectFiles logger tmpfs dflags o_files output_fn = do let toolSettings' = toolSettings dflags ldIsGnuLd = toolSettings_ldIsGnuLd toolSettings' osInfo = platformOS (targetPlatform dflags)- ld_r args = GHC.SysTools.runMergeObjects logger dflags (+ ld_r args = GHC.SysTools.runMergeObjects logger tmpfs dflags ( -- See Note [Produce big objects on Windows] concat [ [GHC.SysTools.Option "--oformat", GHC.SysTools.Option "pe-bigobj-x86-64"]@@ -2052,14 +2087,14 @@ if ldIsGnuLd then do- script <- newTempName logger dflags TFL_CurrentModule "ldscript"+ script <- newTempName logger tmpfs dflags TFL_CurrentModule "ldscript" cwd <- getCurrentDirectory let o_files_abs = map (\x -> "\"" ++ (cwd </> x) ++ "\"") o_files writeFile script $ "INPUT(" ++ unwords o_files_abs ++ ")" ld_r [GHC.SysTools.FileOption "" script] else if toolSettings_ldSupportsFilelist toolSettings' then do- filelist <- newTempName logger dflags TFL_CurrentModule "filelist"+ filelist <- newTempName logger tmpfs dflags TFL_CurrentModule "filelist" writeFile filelist $ unlines o_files ld_r [GHC.SysTools.Option "-filelist", GHC.SysTools.FileOption "" filelist]
compiler/GHC/Hs/Stats.hs view
@@ -137,7 +137,7 @@ data_info (DataDecl { tcdDataDefn = HsDataDefn { dd_cons = cs- , dd_derivs = L _ derivs}})+ , dd_derivs = derivs}}) = ( length cs , foldl' (\s dc -> length (deriv_clause_tys $ unLoc dc) + s) 0 derivs )
compiler/GHC/HsToCore.hs view
@@ -82,6 +82,7 @@ import GHC.Types.Name.Env import GHC.Types.Name.Ppr import GHC.Types.HpcInfo+import GHC.Types.Error import GHC.Unit import GHC.Unit.Module.ModGuts@@ -101,7 +102,7 @@ -} -- | Main entry point to the desugarer.-deSugar :: HscEnv -> ModLocation -> TcGblEnv -> IO (Messages DecoratedSDoc, Maybe ModGuts)+deSugar :: HscEnv -> ModLocation -> TcGblEnv -> IO (Messages DiagnosticMessage, Maybe ModGuts) -- Can modify PCS by faulting in more declarations deSugar hsc_env@@ -161,7 +162,7 @@ ; ds_rules <- mapMaybeM dsRule rules ; let hpc_init | gopt Opt_Hpc dflags = hpcInitCode (hsc_dflags hsc_env) mod ds_hpc_info- | otherwise = empty+ | otherwise = mempty ; return ( ds_ev_binds , foreign_prs `appOL` core_prs `appOL` spec_prs , spec_rules ++ ds_rules@@ -214,7 +215,7 @@ ; foreign_files <- readIORef th_foreign_files_var - ; let (doc_hdr, decl_docs, arg_docs) = extractDocs tcg_env+ ; (doc_hdr, decl_docs, arg_docs) <- extractDocs tcg_env ; let mod_guts = ModGuts { mg_module = mod,@@ -285,7 +286,7 @@ and Rec the rest. -} -deSugarExpr :: HscEnv -> LHsExpr GhcTc -> IO (Messages DecoratedSDoc, Maybe CoreExpr)+deSugarExpr :: HscEnv -> LHsExpr GhcTc -> IO (Messages DiagnosticMessage, Maybe CoreExpr) deSugarExpr hsc_env tc_expr = do let dflags = hsc_dflags hsc_env let logger = hsc_logger hsc_env@@ -403,7 +404,7 @@ , rd_tmvs = vars , rd_lhs = lhs , rd_rhs = rhs }))- = putSrcSpanDs loc $+ = putSrcSpanDs (locA loc) $ do { let bndrs' = [var | L _ (RuleBndr _ (L _ var)) <- vars] ; lhs' <- unsetGOptM Opt_EnableRewriteRules $@@ -419,7 +420,7 @@ -- and take the body apart into a (f args) form ; dflags <- getDynFlags ; case decomposeRuleLhs dflags bndrs'' lhs'' of {- Left msg -> do { warnDs NoReason msg; return Nothing } ;+ Left msg -> do { diagnosticDs WarningWithoutFlag msg; return Nothing } ; Right (final_bndrs, fn_id, args) -> do { let is_local = isLocalId fn_id@@ -455,25 +456,25 @@ | isLocalId lhs_id || canUnfold (idUnfolding lhs_id) -- If imported with no unfolding, no worries , idInlineActivation lhs_id `competesWith` rule_act- = warnDs (Reason Opt_WarnInlineRuleShadowing)- (vcat [ hang (text "Rule" <+> pprRuleName rule_name- <+> text "may never fire")- 2 (text "because" <+> quotes (ppr lhs_id)- <+> text "might inline first")- , text "Probable fix: add an INLINE[n] or NOINLINE[n] pragma for"- <+> quotes (ppr lhs_id)- , whenPprDebug (ppr (idInlineActivation lhs_id) $$ ppr rule_act) ])+ = diagnosticDs (WarningWithFlag Opt_WarnInlineRuleShadowing)+ (vcat [ hang (text "Rule" <+> pprRuleName rule_name+ <+> text "may never fire")+ 2 (text "because" <+> quotes (ppr lhs_id)+ <+> text "might inline first")+ , text "Probable fix: add an INLINE[n] or NOINLINE[n] pragma for"+ <+> quotes (ppr lhs_id)+ , whenPprDebug (ppr (idInlineActivation lhs_id) $$ ppr rule_act) ]) | check_rules_too , bad_rule : _ <- get_bad_rules lhs_id- = warnDs (Reason Opt_WarnInlineRuleShadowing)- (vcat [ hang (text "Rule" <+> pprRuleName rule_name- <+> text "may never fire")- 2 (text "because rule" <+> pprRuleName (ruleName bad_rule)- <+> text "for"<+> quotes (ppr lhs_id)- <+> text "might fire first")- , text "Probable fix: add phase [n] or [~n] to the competing rule"- , whenPprDebug (ppr bad_rule) ])+ = diagnosticDs (WarningWithFlag Opt_WarnInlineRuleShadowing)+ (vcat [ hang (text "Rule" <+> pprRuleName rule_name+ <+> text "may never fire")+ 2 (text "because rule" <+> pprRuleName (ruleName bad_rule)+ <+> text "for"<+> quotes (ppr lhs_id)+ <+> text "might fire first")+ , text "Probable fix: add phase [n] or [~n] to the competing rule"+ , whenPprDebug (ppr bad_rule) ]) | otherwise = return ()
compiler/GHC/HsToCore/Arrows.hs view
@@ -166,10 +166,6 @@ do_premap ids b_ty c_ty d_ty f g = do_compose ids b_ty c_ty d_ty (do_arr ids b_ty c_ty f) g -mkFailExpr :: HsMatchContext GhcRn -> Type -> DsM CoreExpr-mkFailExpr ctxt ty- = mkErrorAppDs pAT_ERROR_ID ty (matchContextErrString ctxt)- -- construct CoreExpr for \ (a :: a_ty, b :: b_ty) -> a mkFstExpr :: Type -> Type -> DsM CoreExpr mkFstExpr a_ty b_ty = do@@ -301,7 +297,8 @@ mkHsEnvStackExpr :: [Id] -> Id -> LHsExpr GhcTc mkHsEnvStackExpr env_ids stack_id- = mkLHsTupleExpr [mkLHsVarTuple env_ids, nlHsVar stack_id]+ = mkLHsTupleExpr [mkLHsVarTuple env_ids noExtField, nlHsVar stack_id]+ noExtField -- Translation of arrow abstraction @@ -558,14 +555,17 @@ let left_id = HsConLikeOut noExtField (RealDataCon left_con) right_id = HsConLikeOut noExtField (RealDataCon right_con)- left_expr ty1 ty2 e = noLoc $ HsApp noExtField- (noLoc $ mkHsWrap (mkWpTyApps [ty1, ty2]) left_id ) e- right_expr ty1 ty2 e = noLoc $ HsApp noExtField- (noLoc $ mkHsWrap (mkWpTyApps [ty1, ty2]) right_id) e+ left_expr ty1 ty2 e = noLocA $ HsApp noComments+ (noLocA $ mkHsWrap (mkWpTyApps [ty1, ty2]) left_id ) e+ right_expr ty1 ty2 e = noLocA $ HsApp noComments+ (noLocA $ mkHsWrap (mkWpTyApps [ty1, ty2]) right_id) e -- Prefix each tuple with a distinct series of Left's and Right's, -- in a balanced way, keeping track of the types. + merge_branches :: ([LHsExpr GhcTc], Type, CoreExpr)+ -> ([LHsExpr GhcTc], Type, CoreExpr)+ -> ([LHsExpr GhcTc], Type, CoreExpr) -- AZ merge_branches (builds1, in_ty1, core_exp1) (builds2, in_ty2, core_exp2) = (map (left_expr in_ty1 in_ty2) builds1 ++@@ -594,7 +594,7 @@ dsCmd ids local_vars stack_ty res_ty (HsCmdLamCase _ mg@MG { mg_ext = MatchGroupTc [Scaled arg_mult arg_ty] _ }) env_ids = do arg_id <- newSysLocalDs arg_mult arg_ty- let case_cmd = noLoc $ HsCmdCase noExtField (nlHsVar arg_id) mg+ let case_cmd = noLocA $ HsCmdCase noExtField (nlHsVar arg_id) mg dsCmdLam ids local_vars stack_ty res_ty [nlVarPat arg_id] case_cmd env_ids -- D; ys |-a cmd : stk --> t@@ -603,8 +603,7 @@ -- -- ---> premap (\ ((xs),stk) -> let binds in ((ys),stk)) c -dsCmd ids local_vars stack_ty res_ty (HsCmdLet _ lbinds@(L _ binds) body)- env_ids = do+dsCmd ids local_vars stack_ty res_ty (HsCmdLet _ lbinds@binds body) env_ids = do let defined_vars = mkVarSet (collectLocalBinders CollWithDictBinders binds) local_vars' = defined_vars `unionVarSet` local_vars@@ -633,7 +632,7 @@ dsCmd ids local_vars stack_ty res_ty do_block@(HsCmdDo stmts_ty (L loc stmts)) env_ids = do- putSrcSpanDs loc $+ putSrcSpanDsA loc $ dsNoLevPoly stmts_ty (text "In the do-command:" <+> ppr do_block) (core_stmts, env_ids') <- dsCmdDo ids local_vars res_ty stmts env_ids@@ -705,7 +704,7 @@ DIdSet, -- subset of local vars that occur free [Id]) -- the same local vars as a list, fed back dsfixCmd ids local_vars stk_ty cmd_ty cmd- = do { putSrcSpanDs (getLoc cmd) $ dsNoLevPoly cmd_ty+ = do { putSrcSpanDs (getLocA cmd) $ dsNoLevPoly cmd_ty (text "When desugaring the command:" <+> ppr cmd) ; trimInput (dsLCmd ids local_vars stk_ty cmd_ty cmd) } @@ -795,7 +794,7 @@ -- ---> premap (\ (xs) -> ((xs), ())) c dsCmdDo ids local_vars res_ty [L loc (LastStmt _ body _ _)] env_ids = do- putSrcSpanDs loc $ dsNoLevPoly res_ty+ putSrcSpanDsA loc $ dsNoLevPoly res_ty (text "In the command:" <+> ppr body) (core_body, env_ids') <- dsLCmd ids local_vars unitTy res_ty body env_ids let env_ty = mkBigCoreVarTupTy env_ids@@ -962,7 +961,7 @@ -- arr (\((xs1),(xs2)) -> (xs')) >>> ss' dsCmdStmt ids local_vars out_ids- (RecStmt { recS_stmts = stmts+ (RecStmt { recS_stmts = L _ stmts , recS_later_ids = later_ids, recS_rec_ids = rec_ids , recS_ext = RecStmtTc { recS_later_rets = later_rets , recS_rec_rets = rec_rets } })@@ -1153,10 +1152,10 @@ -- List of leaf expressions, with set of variables bound in each -leavesMatch :: LMatch GhcTc (Located (body GhcTc))- -> [(Located (body GhcTc), IdSet)]+leavesMatch :: LMatch GhcTc (LocatedA (body GhcTc))+ -> [(LocatedA (body GhcTc), IdSet)] leavesMatch (L _ (Match { m_pats = pats- , m_grhss = GRHSs _ grhss (L _ binds) }))+ , m_grhss = GRHSs _ grhss binds })) = let defined_vars = mkVarSet (collectPatsBinders CollWithDictBinders pats) `unionVarSet`@@ -1170,24 +1169,28 @@ -- Replace the leaf commands in a match replaceLeavesMatch- :: Type -- new result type- -> [Located (body' GhcTc)] -- replacement leaf expressions of that type- -> LMatch GhcTc (Located (body GhcTc)) -- the matches of a case command- -> ([Located (body' GhcTc)], -- remaining leaf expressions- LMatch GhcTc (Located (body' GhcTc))) -- updated match+ :: ( Anno (Match GhcTc (LocatedA (body' GhcTc))) ~ Anno (Match GhcTc (LocatedA (body GhcTc)))+ , Anno (GRHS GhcTc (LocatedA (body' GhcTc))) ~ Anno (GRHS GhcTc (LocatedA (body GhcTc))))+ => Type -- new result type+ -> [LocatedA (body' GhcTc)] -- replacement leaf expressions of that type+ -> LMatch GhcTc (LocatedA (body GhcTc)) -- the matches of a case command+ -> ([LocatedA (body' GhcTc)], -- remaining leaf expressions+ LMatch GhcTc (LocatedA (body' GhcTc))) -- updated match replaceLeavesMatch _res_ty leaves (L loc match@(Match { m_grhss = GRHSs x grhss binds })) = let (leaves', grhss') = mapAccumL replaceLeavesGRHS leaves grhss in- (leaves', L loc (match { m_ext = noExtField, m_grhss = GRHSs x grhss' binds }))+ (leaves', L loc (match { m_ext = noAnn, m_grhss = GRHSs x grhss' binds })) replaceLeavesGRHS- :: [Located (body' GhcTc)] -- replacement leaf expressions of that type- -> LGRHS GhcTc (Located (body GhcTc)) -- rhss of a case command- -> ([Located (body' GhcTc)], -- remaining leaf expressions- LGRHS GhcTc (Located (body' GhcTc))) -- updated GRHS+ :: ( Anno (Match GhcTc (LocatedA (body' GhcTc))) ~ Anno (Match GhcTc (LocatedA (body GhcTc)))+ , Anno (GRHS GhcTc (LocatedA (body' GhcTc))) ~ Anno (GRHS GhcTc (LocatedA (body GhcTc))))+ => [LocatedA (body' GhcTc)] -- replacement leaf expressions of that type+ -> LGRHS GhcTc (LocatedA (body GhcTc)) -- rhss of a case command+ -> ([LocatedA (body' GhcTc)], -- remaining leaf expressions+ LGRHS GhcTc (LocatedA (body' GhcTc))) -- updated GRHS replaceLeavesGRHS (leaf:leaves) (L loc (GRHS x stmts _)) = (leaves, L loc (GRHS x stmts leaf)) replaceLeavesGRHS [] _ = panic "replaceLeavesGRHS []"
compiler/GHC/HsToCore/Binds.hs view
@@ -108,7 +108,7 @@ bang_binds = filterBag (isBangedHsBind . unLoc) binds top_level_err desc (L loc bind)- = putSrcSpanDs loc $+ = putSrcSpanDs (locA loc) $ errDs (hang (text "Top-level" <+> text desc <+> text "aren't allowed:") 2 (ppr bind)) @@ -125,7 +125,7 @@ dsLHsBind :: LHsBind GhcTc -> DsM ([Id], [(Id,CoreExpr)]) dsLHsBind (L loc bind) = do dflags <- getDynFlags- putSrcSpanDs loc $ dsHsBind dflags bind+ putSrcSpanDs (locA loc) $ dsHsBind dflags bind -- | Desugar a single binding (or group of recursive binds). dsHsBind :: DynFlags@@ -665,16 +665,16 @@ dsSpec mb_poly_rhs (L loc (SpecPrag poly_id spec_co spec_inl)) | isJust (isClassOpId_maybe poly_id) = putSrcSpanDs loc $- do { warnDs NoReason (text "Ignoring useless SPECIALISE pragma for class method selector"- <+> quotes (ppr poly_id))+ do { diagnosticDs WarningWithoutFlag (text "Ignoring useless SPECIALISE pragma for class method selector"+ <+> quotes (ppr poly_id)) ; return Nothing } -- There is no point in trying to specialise a class op -- Moreover, classops don't (currently) have an inl_sat arity set -- (it would be Just 0) and that in turn makes makeCorePair bleat | no_act_spec && isNeverActive rule_act = putSrcSpanDs loc $- do { warnDs NoReason (text "Ignoring useless SPECIALISE pragma for NOINLINE function:"- <+> quotes (ppr poly_id))+ do { diagnosticDs WarningWithoutFlag (text "Ignoring useless SPECIALISE pragma for NOINLINE function:"+ <+> quotes (ppr poly_id)) ; return Nothing } -- Function is NOINLINE, and the specialisation inherits that -- See Note [Activation pragmas for SPECIALISE] @@ -699,7 +699,7 @@ -- , text "ds_rhs:" <+> ppr ds_lhs ]) $ dflags <- getDynFlags ; case decomposeRuleLhs dflags spec_bndrs ds_lhs of {- Left msg -> do { warnDs NoReason msg; return Nothing } ;+ Left msg -> do { diagnosticDs WarningWithoutFlag msg; return Nothing } ; Right (rule_bndrs, _fn, rule_lhs_args) -> do { this_mod <- getModule@@ -720,7 +720,7 @@ -- Commented out: see Note [SPECIALISE on INLINE functions] -- ; when (isInlinePragma id_inl)--- (warnDs $ text "SPECIALISE pragma on INLINE function probably won't fire:"+-- (diagnosticDs $ text "SPECIALISE pragma on INLINE function probably won't fire:" -- <+> quotes (ppr poly_name)) ; return (Just (unitOL (spec_id, spec_rhs), rule))@@ -769,7 +769,7 @@ let rule = mkRule this_mod False is_local name act fn bndrs args rhs dflags <- getDynFlags when (isOrphan (ru_orphan rule) && wopt Opt_WarnOrphans dflags) $- warnDs (Reason Opt_WarnOrphans) (ruleOrphWarn rule)+ diagnosticDs (WarningWithFlag Opt_WarnOrphans) (ruleOrphWarn rule) return rule ruleOrphWarn :: CoreRule -> SDoc
compiler/GHC/HsToCore/Coverage.hs view
@@ -27,7 +27,6 @@ import GHC.Cmm.CLabel import GHC.Core.Type-import GHC.Core import GHC.Core.TyCon import GHC.Data.Maybe@@ -49,6 +48,8 @@ import GHC.Types.HpcInfo import GHC.Types.CostCentre import GHC.Types.CostCentre.State+import GHC.Types.ForeignStubs+import GHC.Types.Tickish import Control.Monad import Data.List (isSuffixOf, intersperse)@@ -135,7 +136,7 @@ -- Try look for a file generated from a .hsc file to a -- .hs file, by peeking ahead. let top_pos = catMaybes $ foldr (\ (L pos _) rest ->- srcSpanFileName_maybe pos : rest) [] binds+ srcSpanFileName_maybe (locA pos) : rest) [] binds in case top_pos of (file_name:_) | ".hsc" `isSuffixOf` unpackFS file_name@@ -145,8 +146,9 @@ mkModBreaks :: HscEnv -> Module -> Int -> [MixEntry_] -> IO (Maybe ModBreaks) mkModBreaks hsc_env mod count entries- | breakpointsEnabled (hsc_dflags hsc_env) = do- breakArray <- GHCi.newBreakArray hsc_env (length entries)+ | Just interp <- hsc_interp hsc_env+ , breakpointsEnabled (hsc_dflags hsc_env) = do+ breakArray <- GHCi.newBreakArray interp (length entries) ccs <- mkCCSArray hsc_env mod count entries let locsTicks = listArray (0,count-1) [ span | (span,_,_,_) <- entries ]@@ -168,7 +170,7 @@ case hsc_interp hsc_env of Just interp | GHCi.interpreterProfiled interp -> do let module_str = moduleNameString (moduleName modul)- costcentres <- GHCi.mkCostCentres hsc_env module_str (map mk_one entries)+ costcentres <- GHCi.mkCostCentres interp module_str (map mk_one entries) return (listArray (0,count-1) costcentres) _ -> return (listArray (0,-1) [])@@ -312,7 +314,7 @@ addPathEntry name $ addTickMatchGroup False (fun_matches funBind) - blackListed <- isBlackListed pos+ blackListed <- isBlackListed (locA pos) exported_names <- liftM exports getEnv -- We don't want to generate code for blacklisted positions@@ -325,7 +327,7 @@ tick <- if not blackListed && shouldTickBind density toplev exported simple inline then- bindTick density name pos fvs+ bindTick density name (locA pos) fvs else return Nothing @@ -365,14 +367,14 @@ -- Allocate the ticks - rhs_tick <- bindTick density name pos fvs+ rhs_tick <- bindTick density name (locA pos) fvs let rhs_ticks = rhs_tick `mbCons` initial_rhs_ticks patvar_tickss <- case simplePatId of Just{} -> return initial_patvar_tickss Nothing -> do let patvars = map getOccString (collectPatBinders CollNoDictBinders lhs)- patvar_ticks <- mapM (\v -> bindTick density v pos fvs) patvars+ patvar_ticks <- mapM (\v -> bindTick density v (locA pos) fvs) patvars return (zipWith mbCons patvar_ticks (initial_patvar_tickss ++ repeat []))@@ -384,7 +386,7 @@ addTickLHsBind patsyn_bind@(L _ (PatSynBind {})) = return patsyn_bind bindTick- :: TickDensity -> String -> SrcSpan -> FreeVars -> TM (Maybe (Tickish Id))+ :: TickDensity -> String -> SrcSpan -> FreeVars -> TM (Maybe CoreTickish) bindTick density name pos fvs = do decl_path <- getPathEntry let@@ -423,7 +425,8 @@ TickCallSites | isCallSite e0 -> tick_it _other -> dont_tick_it where- tick_it = allocTickBox (ExpBox False) False False pos $ addTickHsExpr e0+ tick_it = allocTickBox (ExpBox False) False False (locA pos)+ $ addTickHsExpr e0 dont_tick_it = addTickLHsExprNever e -- Add a tick to an expression which is the RHS of an equation or a binding.@@ -440,7 +443,8 @@ TickCallSites | isCallSite e0 -> tick_it _other -> dont_tick_it where- tick_it = allocTickBox (ExpBox False) False False pos $ addTickHsExpr e0+ tick_it = allocTickBox (ExpBox False) False False (locA pos)+ $ addTickHsExpr e0 dont_tick_it = addTickLHsExprNever e -- The inner expression of an evaluation context:@@ -467,7 +471,8 @@ | otherwise -> tick_it _other -> addTickLHsExprEvalInner e where- tick_it = allocTickBox (ExpBox False) False False pos $ addTickHsExpr e0+ tick_it = allocTickBox (ExpBox False) False False (locA pos)+ $ addTickHsExpr e0 dont_tick_it = addTickLHsExprNever e -- version of addTick that does not actually add a tick,@@ -494,13 +499,14 @@ addTickLHsExprOptAlt :: Bool -> LHsExpr GhcTc -> TM (LHsExpr GhcTc) addTickLHsExprOptAlt oneOfMany (L pos e0) = ifDensity TickForCoverage- (allocTickBox (ExpBox oneOfMany) False False pos $ addTickHsExpr e0)+ (allocTickBox (ExpBox oneOfMany) False False (locA pos)+ $ addTickHsExpr e0) (addTickLHsExpr (L pos e0)) addBinTickLHsExpr :: (Bool -> BoxLabel) -> LHsExpr GhcTc -> TM (LHsExpr GhcTc) addBinTickLHsExpr boxLabel (L pos e0) = ifDensity TickForCoverage- (allocBinTickBox boxLabel pos $ addTickHsExpr e0)+ (allocBinTickBox boxLabel (locA pos) $ addTickHsExpr e0) (addTickLHsExpr (L pos e0)) @@ -573,9 +579,9 @@ = do { let isOneOfMany = case alts of [_] -> False; _ -> True ; alts' <- mapM (liftL $ addTickGRHS isOneOfMany False) alts ; return $ HsMultiIf ty alts' }-addTickHsExpr (HsLet x (L l binds) e) =+addTickHsExpr (HsLet x binds e) = bindLocals (collectLocalBinders CollNoDictBinders binds) $- liftM2 (HsLet x . L l)+ liftM2 (HsLet x) (addTickHsLocalBinds binds) -- to think about: !patterns. (addTickLHsExprLetBody e) addTickHsExpr (HsDo srcloc cxt (L l stmts))@@ -594,10 +600,14 @@ = do { rec_binds' <- addTickHsRecordBinds rec_binds ; return (expr { rcon_flds = rec_binds' }) } -addTickHsExpr expr@(RecordUpd { rupd_expr = e, rupd_flds = flds })+addTickHsExpr expr@(RecordUpd { rupd_expr = e, rupd_flds = Left flds }) = do { e' <- addTickLHsExpr e ; flds' <- mapM addTickHsRecField flds- ; return (expr { rupd_expr = e', rupd_flds = flds' }) }+ ; return (expr { rupd_expr = e', rupd_flds = Left flds' }) }+addTickHsExpr expr@(RecordUpd { rupd_expr = e, rupd_flds = Right flds })+ = do { e' <- addTickLHsExpr e+ ; flds' <- mapM addTickHsRecField flds+ ; return (expr { rupd_expr = e', rupd_flds = Right flds' }) } addTickHsExpr (ExprWithTySig x e ty) = liftM3 ExprWithTySig@@ -626,6 +636,8 @@ addTickHsExpr e@(HsTcBracketOut {}) = return e addTickHsExpr e@(HsRnBracketOut {}) = return e addTickHsExpr e@(HsSpliceE {}) = return e+addTickHsExpr e@(HsGetField {}) = return e+addTickHsExpr e@(HsProjection {}) = return e addTickHsExpr (HsProc x pat cmdtop) = liftM2 (HsProc x) (addTickLPat pat)@@ -637,10 +649,10 @@ liftM (XExpr . ExpansionExpr . HsExpanded a) $ (addTickHsExpr b) -addTickTupArg :: LHsTupArg GhcTc -> TM (LHsTupArg GhcTc)-addTickTupArg (L l (Present x e)) = do { e' <- addTickLHsExpr e- ; return (L l (Present x e')) }-addTickTupArg (L l (Missing ty)) = return (L l (Missing ty))+addTickTupArg :: HsTupArg GhcTc -> TM (HsTupArg GhcTc)+addTickTupArg (Present x e) = do { e' <- addTickLHsExpr e+ ; return (Present x e') }+addTickTupArg (Missing ty) = return (Missing ty) addTickMatchGroup :: Bool{-is lambda-} -> MatchGroup GhcTc (LHsExpr GhcTc)@@ -660,11 +672,11 @@ addTickGRHSs :: Bool -> Bool -> GRHSs GhcTc (LHsExpr GhcTc) -> TM (GRHSs GhcTc (LHsExpr GhcTc))-addTickGRHSs isOneOfMany isLambda (GRHSs x guarded (L l local_binds)) =+addTickGRHSs isOneOfMany isLambda (GRHSs x guarded local_binds) = bindLocals binders $ do local_binds' <- addTickHsLocalBinds local_binds guarded' <- mapM (liftL (addTickGRHS isOneOfMany isLambda)) guarded- return $ GRHSs x guarded' (L l local_binds')+ return $ GRHSs x guarded' local_binds' where binders = collectLocalBinders CollNoDictBinders local_binds @@ -682,7 +694,7 @@ TickForCoverage -> addTickLHsExprOptAlt isOneOfMany expr TickAllFunctions | isLambda -> addPathEntry "\\" $- allocTickBox (ExpBox False) True{-count-} False{-not top-} pos $+ allocTickBox (ExpBox False) True{-count-} False{-not top-} (locA pos) $ addTickHsExpr e0 _otherwise -> addTickLHsExprRHS expr@@ -724,13 +736,13 @@ (addTick isGuard e) (addTickSyntaxExpr hpcSrcSpan bind') (addTickSyntaxExpr hpcSrcSpan guard')-addTickStmt _isGuard (LetStmt x (L l binds)) =- liftM (LetStmt x . L l)+addTickStmt _isGuard (LetStmt x binds) =+ liftM (LetStmt x) (addTickHsLocalBinds binds) addTickStmt isGuard (ParStmt x pairs mzipExpr bindExpr) = liftM3 (ParStmt x) (mapM (addTickStmtAndBinders isGuard) pairs)- (unLoc <$> addTickLHsExpr (L hpcSrcSpan mzipExpr))+ (unLoc <$> addTickLHsExpr (L (noAnnSrcSpan hpcSrcSpan) mzipExpr)) (addTickSyntaxExpr hpcSrcSpan bindExpr) addTickStmt isGuard (ApplicativeStmt body_ty args mb_join) = do args' <- mapM (addTickApplicativeArg isGuard) args@@ -745,16 +757,16 @@ t_u <- addTickLHsExprRHS using t_f <- addTickSyntaxExpr hpcSrcSpan returnExpr t_b <- addTickSyntaxExpr hpcSrcSpan bindExpr- t_m <- fmap unLoc (addTickLHsExpr (L hpcSrcSpan liftMExpr))+ t_m <- fmap unLoc (addTickLHsExpr (L (noAnnSrcSpan hpcSrcSpan) liftMExpr)) return $ stmt { trS_stmts = t_s, trS_by = t_y, trS_using = t_u , trS_ret = t_f, trS_bind = t_b, trS_fmap = t_m } addTickStmt isGuard stmt@(RecStmt {})- = do { stmts' <- addTickLStmts isGuard (recS_stmts stmt)+ = do { stmts' <- addTickLStmts isGuard (unLoc $ recS_stmts stmt) ; ret' <- addTickSyntaxExpr hpcSrcSpan (recS_ret_fn stmt) ; mfix' <- addTickSyntaxExpr hpcSrcSpan (recS_mfix_fn stmt) ; bind' <- addTickSyntaxExpr hpcSrcSpan (recS_bind_fn stmt)- ; return (stmt { recS_stmts = stmts', recS_ret_fn = ret'+ ; return (stmt { recS_stmts = noLocA stmts', recS_ret_fn = ret' , recS_mfix_fn = mfix', recS_bind_fn = bind' }) } addTick :: Maybe (Bool -> BoxLabel) -> LHsExpr GhcTc -> TM (LHsExpr GhcTc)@@ -776,7 +788,7 @@ addTickArg (ApplicativeArgMany x stmts ret pat ctxt) = (ApplicativeArgMany x) <$> addTickLStmts isGuard stmts- <*> (unLoc <$> addTickLHsExpr (L hpcSrcSpan ret))+ <*> (unLoc <$> addTickLHsExpr (L (noAnnSrcSpan hpcSrcSpan) ret)) <*> addTickLPat pat <*> pure ctxt @@ -825,7 +837,7 @@ -- There is no location here, so we might need to use a context location?? addTickSyntaxExpr :: SrcSpan -> SyntaxExpr GhcTc -> TM (SyntaxExpr GhcTc) addTickSyntaxExpr pos syn@(SyntaxExprTc { syn_expr = x }) = do- x' <- fmap unLoc (addTickLHsExpr (L pos x))+ x' <- fmap unLoc (addTickLHsExpr (L (noAnnSrcSpan pos) x)) return $ syn { syn_expr = x' } addTickSyntaxExpr _ NoSyntaxExprTc = return NoSyntaxExprTc @@ -869,9 +881,9 @@ (addBinTickLHsExpr (BinBox CondBinBox) e1) (addTickLHsCmd c2) (addTickLHsCmd c3)-addTickHsCmd (HsCmdLet x (L l binds) c) =+addTickHsCmd (HsCmdLet x binds c) = bindLocals (collectLocalBinders CollNoDictBinders binds) $- liftM2 (HsCmdLet x . L l)+ liftM2 (HsCmdLet x) (addTickHsLocalBinds binds) -- to think about: !patterns. (addTickLHsCmd c) addTickHsCmd (HsCmdDo srcloc (L l stmts))@@ -912,11 +924,11 @@ return $ match { m_grhss = gRHSs' } addTickCmdGRHSs :: GRHSs GhcTc (LHsCmd GhcTc) -> TM (GRHSs GhcTc (LHsCmd GhcTc))-addTickCmdGRHSs (GRHSs x guarded (L l local_binds)) =+addTickCmdGRHSs (GRHSs x guarded local_binds) = bindLocals binders $ do local_binds' <- addTickHsLocalBinds local_binds guarded' <- mapM (liftL addTickCmdGRHS) guarded- return $ GRHSs x guarded' (L l local_binds')+ return $ GRHSs x guarded' local_binds' where binders = collectLocalBinders CollNoDictBinders local_binds @@ -959,15 +971,15 @@ (addTickLHsCmd c) (addTickSyntaxExpr hpcSrcSpan bind') (addTickSyntaxExpr hpcSrcSpan guard')-addTickCmdStmt (LetStmt x (L l binds)) =- liftM (LetStmt x . L l)+addTickCmdStmt (LetStmt x binds) =+ liftM (LetStmt x) (addTickHsLocalBinds binds) addTickCmdStmt stmt@(RecStmt {})- = do { stmts' <- addTickLCmdStmts (recS_stmts stmt)+ = do { stmts' <- addTickLCmdStmts (unLoc $ recS_stmts stmt) ; ret' <- addTickSyntaxExpr hpcSrcSpan (recS_ret_fn stmt) ; mfix' <- addTickSyntaxExpr hpcSrcSpan (recS_mfix_fn stmt) ; bind' <- addTickSyntaxExpr hpcSrcSpan (recS_bind_fn stmt)- ; return (stmt { recS_stmts = stmts', recS_ret_fn = ret'+ ; return (stmt { recS_stmts = noLocA stmts', recS_ret_fn = ret' , recS_mfix_fn = mfix', recS_bind_fn = bind' }) } addTickCmdStmt ApplicativeStmt{} = panic "ToDo: addTickCmdStmt ApplicativeLastStmt"@@ -980,12 +992,11 @@ = do { fields' <- mapM addTickHsRecField fields ; return (HsRecFields fields' dd) } -addTickHsRecField :: LHsRecField' id (LHsExpr GhcTc)- -> TM (LHsRecField' id (LHsExpr GhcTc))-addTickHsRecField (L l (HsRecField id expr pun))+addTickHsRecField :: LHsRecField' GhcTc id (LHsExpr GhcTc)+ -> TM (LHsRecField' GhcTc id (LHsExpr GhcTc))+addTickHsRecField (L l (HsRecField x id expr pun)) = do { expr' <- addTickLHsExpr expr- ; return (L l (HsRecField id expr' pun)) }-+ ; return (L l (HsRecField x id expr' pun)) } addTickArithSeqInfo :: ArithSeqInfo GhcTc -> TM (ArithSeqInfo GhcTc) addTickArithSeqInfo (From e1) =@@ -1036,13 +1047,17 @@ data TickishType = ProfNotes | HpcTicks | Breakpoints | SourceNotes deriving (Eq) +sourceNotesEnabled :: DynFlags -> Bool+sourceNotesEnabled dflags =+ (debugLevel dflags > 0) || (gopt Opt_InfoTableMap dflags)+ coveragePasses :: DynFlags -> [TickishType] coveragePasses dflags = ifa (breakpointsEnabled dflags) Breakpoints $ ifa (gopt Opt_Hpc dflags) HpcTicks $ ifa (sccProfilingEnabled dflags && profAuto dflags /= NoProfAuto) ProfNotes $- ifa (debugLevel dflags > 0) SourceNotes []+ ifa (sourceNotesEnabled dflags) SourceNotes [] where ifa f x xs | f = x:xs | otherwise = xs @@ -1175,16 +1190,16 @@ (fvs, e) <- getFreeVars m env <- getEnv tickish <- mkTickish boxLabel countEntries topOnly pos fvs (declPath env)- return (L pos (HsTick noExtField tickish (L pos e)))+ return (L (noAnnSrcSpan pos) (HsTick noExtField tickish (L (noAnnSrcSpan pos) e))) ) (do e <- m- return (L pos e)+ return (L (noAnnSrcSpan pos) e) ) -- the tick application inherits the source position of its -- expression argument to support nested box allocations allocATickBox :: BoxLabel -> Bool -> Bool -> SrcSpan -> FreeVars- -> TM (Maybe (Tickish Id))+ -> TM (Maybe CoreTickish) allocATickBox boxLabel countEntries topOnly pos fvs = ifGoodTickSrcSpan pos (do let@@ -1198,7 +1213,7 @@ mkTickish :: BoxLabel -> Bool -> Bool -> SrcSpan -> OccEnv Id -> [String]- -> TM (Tickish Id)+ -> TM CoreTickish mkTickish boxLabel countEntries topOnly pos fvs decl_path = do let ids = filter (not . isUnliftedType . idType) $ occEnvElts fvs@@ -1225,7 +1240,7 @@ count = countEntries && gopt Opt_ProfCountEntries dflags return $ ProfNote cc count True{-scopes-} - Breakpoints -> Breakpoint <$> addMixEntry me <*> pure ids+ Breakpoints -> Breakpoint noExtField <$> addMixEntry me <*> pure ids SourceNotes | RealSrcSpan pos' _ <- pos -> return $ SourceNote pos' cc_name@@ -1238,7 +1253,7 @@ allocBinTickBox boxLabel pos m = do env <- getEnv case tickishType env of- HpcTicks -> do e <- liftM (L pos) m+ HpcTicks -> do e <- liftM (L (noAnnSrcSpan pos)) m ifGoodTickSrcSpan pos (mkBinTickBoxHpc boxLabel pos e) (return e)@@ -1254,7 +1269,8 @@ <*> pure e tick <- HpcTick (this_mod env) <$> addMixEntry (pos,declPath env, [],ExpBox False)- return $ L pos $ HsTick noExtField tick (L pos binTick)+ let pos' = noAnnSrcSpan pos+ return $ L pos' $ HsTick noExtField tick (L pos' binTick) mkHpcPos :: SrcSpan -> HpcPos mkHpcPos pos@(RealSrcSpan s _)@@ -1312,10 +1328,10 @@ hs_hpc_module("Main",8,1150288664,_hpc_tickboxes_Main_hpc);} -} -hpcInitCode :: DynFlags -> Module -> HpcInfo -> SDoc-hpcInitCode _ _ (NoHpcInfo {}) = Outputable.empty+hpcInitCode :: DynFlags -> Module -> HpcInfo -> CStub+hpcInitCode _ _ (NoHpcInfo {}) = mempty hpcInitCode dflags this_mod (HpcInfo tickCount hashNo)- = vcat+ = CStub $ vcat [ text "static void hpc_init_" <> ppr this_mod <> text "(void) __attribute__((constructor));" , text "static void hpc_init_" <> ppr this_mod <> text "(void)"
compiler/GHC/HsToCore/Docs.hs view
@@ -25,17 +25,25 @@ import GHC.Types.Name.Set import GHC.Types.SrcLoc import GHC.Tc.Types+import GHC.Parser.Annotation import Control.Applicative+import Control.Monad.IO.Class import Data.Bifunctor (first)+import Data.IntMap (IntMap)+import qualified Data.IntMap as IM import Data.Map (Map) import qualified Data.Map as M import Data.Maybe import Data.Semigroup+import GHC.IORef (readIORef) -- | Extract docs from renamer output.-extractDocs :: TcGblEnv- -> (Maybe HsDocString, DeclDocMap, ArgDocMap)+-- This is monadic since we need to be able to read documentation added from+-- Template Haskell's @putDoc@, which is stored in 'tcg_th_docs'.+extractDocs :: MonadIO m+ => TcGblEnv+ -> m (Maybe HsDocString, DeclDocMap, ArgDocMap) -- ^ -- 1. Module header -- 2. Docs on top level declarations@@ -45,8 +53,20 @@ , tcg_insts = insts , tcg_fam_insts = fam_insts , tcg_doc_hdr = mb_doc_hdr- } =- (unLoc <$> mb_doc_hdr, DeclDocMap doc_map, ArgDocMap arg_map)+ , tcg_th_docs = th_docs_var+ } = do+ th_docs <- liftIO $ readIORef th_docs_var+ let doc_hdr = th_doc_hdr <|> (unLoc <$> mb_doc_hdr)+ ExtractedTHDocs+ th_doc_hdr+ (DeclDocMap th_doc_map)+ (ArgDocMap th_arg_map)+ (DeclDocMap th_inst_map) = extractTHDocs th_docs+ return+ ( doc_hdr+ , DeclDocMap (th_doc_map <> th_inst_map <> doc_map)+ , ArgDocMap (th_arg_map `unionArgMaps` arg_map)+ ) where (doc_map, arg_map) = maybe (M.empty, M.empty) (mkMaps local_insts)@@ -59,10 +79,10 @@ -- For each declaration, find its names, its subordinates, and its doc strings. mkMaps :: [Name] -> [(LHsDecl GhcRn, [HsDocString])]- -> (Map Name (HsDocString), Map Name (Map Int (HsDocString)))+ -> (Map Name (HsDocString), Map Name (IntMap HsDocString)) mkMaps instances decls = ( f' (map (nubByName fst) decls')- , f (filterMapping (not . M.null) args)+ , f (filterMapping (not . IM.null) args) ) where (decls', args) = unzip (map mappings decls)@@ -78,15 +98,15 @@ mappings :: (LHsDecl GhcRn, [HsDocString]) -> ( [(Name, HsDocString)]- , [(Name, Map Int (HsDocString))]+ , [(Name, IntMap HsDocString)] )- mappings (L (RealSrcSpan l _) decl, docStrs) =+ mappings (L (SrcSpanAnn _ (RealSrcSpan l _)) decl, docStrs) = (dm, am) where doc = concatDocs docStrs args = declTypeDocs decl - subs :: [(Name, [(HsDocString)], Map Int (HsDocString))]+ subs :: [(Name, [HsDocString], IntMap HsDocString)] subs = subordinates instanceMap decl (subDocs, subArgs) =@@ -96,7 +116,7 @@ subNs = [ n | (n, _, _) <- subs ] dm = [(n, d) | (n, Just d) <- zip ns (repeat doc) ++ zip subNs subDocs] am = [(n, args) | n <- ns] ++ zip subNs subArgs- mappings (L (UnhelpfulSpan _) _, _) = ([], [])+ mappings (L (SrcSpanAnn _ (UnhelpfulSpan _)) _, _) = ([], []) instanceMap :: Map RealSrcSpan Name instanceMap = M.fromList [(l, n) | n <- instances, RealSrcSpan l _ <- [getSrcSpan n] ]@@ -115,8 +135,8 @@ user-written. This lets us relate Names (from ClsInsts) to comments (associated with InstDecls and DerivDecls). -}--getMainDeclBinder :: CollectPass (GhcPass p) => HsDecl (GhcPass p) -> [IdP (GhcPass p)]+getMainDeclBinder :: (Anno (IdGhcP p) ~ SrcSpanAnnN, CollectPass (GhcPass p))+ => HsDecl (GhcPass p) -> [IdP (GhcPass p)] getMainDeclBinder (TyClD _ d) = [tcdName d] getMainDeclBinder (ValD _ d) = case collectHsBindBinders CollNoDictBinders d of@@ -140,9 +160,9 @@ -- Extract the source location where an instance is defined. This is used -- to correlate InstDecls with their Instance/CoAxiom Names, via the -- instanceMap.-getInstLoc :: InstDecl (GhcPass p) -> SrcSpan+getInstLoc :: Anno (IdGhcP p) ~ SrcSpanAnnN => InstDecl (GhcPass p) -> SrcSpan getInstLoc = \case- ClsInstD _ (ClsInstDecl { cid_poly_ty = ty }) -> getLoc ty+ ClsInstD _ (ClsInstDecl { cid_poly_ty = ty }) -> getLocA ty -- The Names of data and type family instances have their SrcSpan's attached -- to the *type constructor*. For example, the Name "D:R:Foo:Int" would have -- its SrcSpan attached here:@@ -150,25 +170,25 @@ -- type instance Foo Int = Bool -- ^^^ DataFamInstD _ (DataFamInstDecl- { dfid_eqn = FamEqn { feqn_tycon = L l _ }}) -> l+ { dfid_eqn = FamEqn { feqn_tycon = L l _ }}) -> locA l -- Since CoAxioms' Names refer to the whole line for type family instances -- in particular, we need to dig a bit deeper to pull out the entire -- equation. This does not happen for data family instances, for some reason. TyFamInstD _ (TyFamInstDecl- { tfid_eqn = FamEqn { feqn_tycon = L l _ }}) -> l+ { tfid_eqn = FamEqn { feqn_tycon = L l _ }}) -> locA l -- | Get all subordinate declarations inside a declaration, and their docs. -- A subordinate declaration is something like the associate type or data -- family of a type class. subordinates :: Map RealSrcSpan Name -> HsDecl GhcRn- -> [(Name, [(HsDocString)], Map Int (HsDocString))]+ -> [(Name, [HsDocString], IntMap HsDocString)] subordinates instMap decl = case decl of InstD _ (ClsInstD _ d) -> do DataFamInstDecl { dfid_eqn = FamEqn { feqn_tycon = L l _ , feqn_rhs = defn }} <- unLoc <$> cid_datafam_insts d- [ (n, [], M.empty) | Just n <- [lookupSrcSpan l instMap] ] ++ dataSubs defn+ [ (n, [], IM.empty) | Just n <- [lookupSrcSpan (locA l) instMap] ] ++ dataSubs defn InstD _ (DataFamInstD _ (DataFamInstDecl d)) -> dataSubs (feqn_rhs d)@@ -181,7 +201,7 @@ , name <- getMainDeclBinder d, not (isValD d) ] dataSubs :: HsDataDefn GhcRn- -> [(Name, [HsDocString], Map Int (HsDocString))]+ -> [(Name, [HsDocString], IntMap HsDocString)] dataSubs dd = constrs ++ fields ++ derivs where cons = map unLoc $ (dd_cons dd)@@ -189,14 +209,15 @@ , maybeToList $ fmap unLoc $ con_doc c , conArgDocs c) | c <- cons, cname <- getConNames c ]- fields = [ (extFieldOcc n, maybeToList $ fmap unLoc doc, M.empty)+ fields = [ (extFieldOcc n, maybeToList $ fmap unLoc doc, IM.empty) | Just flds <- map getRecConArgs_maybe cons , (L _ (ConDeclField _ ns _ doc)) <- (unLoc flds) , (L _ n) <- ns ]- derivs = [ (instName, [unLoc doc], M.empty)+ derivs = [ (instName, [unLoc doc], IM.empty) | (l, doc) <- concatMap (extract_deriv_clause_tys . deriv_clause_tys . unLoc) $- unLoc $ dd_derivs dd+ -- unLoc $ dd_derivs dd+ dd_derivs dd , Just instName <- [lookupSrcSpan l instMap] ] extract_deriv_clause_tys :: LDerivClauseTys GhcRn -> [(SrcSpan, LHsDocString)]@@ -209,30 +230,30 @@ extract_deriv_ty (L l (HsSig{sig_body = L _ ty})) = case ty of -- deriving (C a {- ^ Doc comment -})- HsDocTy _ _ doc -> Just (l, doc)+ HsDocTy _ _ doc -> Just (locA l, doc) _ -> Nothing -- | Extract constructor argument docs from inside constructor decls.-conArgDocs :: ConDecl GhcRn -> Map Int HsDocString+conArgDocs :: ConDecl GhcRn -> IntMap HsDocString conArgDocs (ConDeclH98{con_args = args}) = h98ConArgDocs args conArgDocs (ConDeclGADT{con_g_args = args, con_res_ty = res_ty}) = gadtConArgDocs args (unLoc res_ty) -h98ConArgDocs :: HsConDeclH98Details GhcRn -> Map Int HsDocString+h98ConArgDocs :: HsConDeclH98Details GhcRn -> IntMap HsDocString h98ConArgDocs con_args = case con_args of PrefixCon _ args -> con_arg_docs 0 $ map (unLoc . hsScaledThing) args InfixCon arg1 arg2 -> con_arg_docs 0 [ unLoc (hsScaledThing arg1) , unLoc (hsScaledThing arg2) ]- RecCon _ -> M.empty+ RecCon _ -> IM.empty -gadtConArgDocs :: HsConDeclGADTDetails GhcRn -> HsType GhcRn -> Map Int HsDocString+gadtConArgDocs :: HsConDeclGADTDetails GhcRn -> HsType GhcRn -> IntMap HsDocString gadtConArgDocs con_args res_ty = case con_args of PrefixConGADT args -> con_arg_docs 0 $ map (unLoc . hsScaledThing) args ++ [res_ty] RecConGADT _ -> con_arg_docs 1 [res_ty] -con_arg_docs :: Int -> [HsType GhcRn] -> Map Int HsDocString-con_arg_docs n = M.fromList . catMaybes . zipWith f [n..]+con_arg_docs :: Int -> [HsType GhcRn] -> IntMap HsDocString+con_arg_docs n = IM.fromList . catMaybes . zipWith f [n..] where f n (HsDocTy _ _ lds) = Just (n, unLoc lds) f n (HsBangTy _ _ (L _ (HsDocTy _ _ lds))) = Just (n, unLoc lds)@@ -245,7 +266,7 @@ -- | All the sub declarations of a class (that we handle), ordered by -- source location, with documentation attached if it exists. classDecls :: TyClDecl GhcRn -> [(LHsDecl GhcRn, [HsDocString])]-classDecls class_ = filterDecls . collectDocs . sortLocated $ decls+classDecls class_ = filterDecls . collectDocs . sortLocatedA $ decls where decls = docs ++ defs ++ sigs ++ ats docs = mkDecls tcdDocs (DocD noExtField) class_@@ -254,14 +275,14 @@ ats = mkDecls tcdATs (TyClD noExtField . FamDecl noExtField) class_ -- | Extract function argument docs from inside top-level decls.-declTypeDocs :: HsDecl GhcRn -> Map Int (HsDocString)+declTypeDocs :: HsDecl GhcRn -> IntMap (HsDocString) declTypeDocs = \case SigD _ (TypeSig _ _ ty) -> sigTypeDocs (unLoc (dropWildCards ty)) SigD _ (ClassOpSig _ _ _ ty) -> sigTypeDocs (unLoc ty) SigD _ (PatSynSig _ _ ty) -> sigTypeDocs (unLoc ty) ForD _ (ForeignImport _ _ ty _) -> sigTypeDocs (unLoc ty) TyClD _ (SynDecl { tcdRhs = ty }) -> typeDocs (unLoc ty)- _ -> M.empty+ _ -> IM.empty nubByName :: (a -> Name) -> [a] -> [a] nubByName f ns = go emptyNameSet ns@@ -275,25 +296,25 @@ y = f x -- | Extract function argument docs from inside types.-typeDocs :: HsType GhcRn -> Map Int (HsDocString)+typeDocs :: HsType GhcRn -> IntMap HsDocString typeDocs = go 0 where go n = \case HsForAllTy { hst_body = ty } -> go n (unLoc ty) HsQualTy { hst_body = ty } -> go n (unLoc ty)- HsFunTy _ _ (unLoc->HsDocTy _ _ x) ty -> M.insert n (unLoc x) $ go (n+1) (unLoc ty)+ HsFunTy _ _ (unLoc->HsDocTy _ _ x) ty -> IM.insert n (unLoc x) $ go (n+1) (unLoc ty) HsFunTy _ _ _ ty -> go (n+1) (unLoc ty)- HsDocTy _ _ doc -> M.singleton n (unLoc doc)- _ -> M.empty+ HsDocTy _ _ doc -> IM.singleton n (unLoc doc)+ _ -> IM.empty -- | Extract function argument docs from inside types.-sigTypeDocs :: HsSigType GhcRn -> Map Int HsDocString+sigTypeDocs :: HsSigType GhcRn -> IntMap HsDocString sigTypeDocs (HsSig{sig_body = body}) = typeDocs (unLoc body) -- | The top-level declarations of a module that we care about, -- ordered by source location, with documentation attached if it exists. topDecls :: HsGroup GhcRn -> [(LHsDecl GhcRn, [HsDocString])]-topDecls = filterClasses . filterDecls . collectDocs . sortLocated . ungroup+topDecls = filterClasses . filterDecls . collectDocs . sortLocatedA . ungroup -- | Take all declarations except pragmas, infix decls, rules from an 'HsGroup'. ungroup :: HsGroup GhcRn -> [LHsDecl GhcRn]@@ -350,12 +371,12 @@ -- | Go through all class declarations and filter their sub-declarations-filterClasses :: forall p doc. (UnXRec p, MapXRec p) => [(LHsDecl p, doc)] -> [(LHsDecl p, doc)]-filterClasses = map (first (mapXRec @p filterClass))+filterClasses :: forall p doc. (IsPass p) => [(LHsDecl (GhcPass p), doc)] -> [(LHsDecl (GhcPass p), doc)]+filterClasses = map (first (mapLoc filterClass)) where filterClass (TyClD x c@(ClassDecl {})) = TyClD x $ c { tcdSigs =- filter (liftA2 (||) (isUserSig . unXRec @p) isMinimalLSig) (tcdSigs c) }+ filter (liftA2 (||) (isUserSig . unLoc) isMinimalLSig) (tcdSigs c) } filterClass d = d -- | Was this signature given by the user?@@ -367,8 +388,67 @@ -- | Take a field of declarations from a data structure and create HsDecls -- using the given constructor-mkDecls :: (struct -> [Located decl])+mkDecls :: (struct -> [GenLocated l decl]) -> (decl -> hsDecl) -> struct- -> [Located hsDecl]+ -> [GenLocated l hsDecl] mkDecls field con = map (mapLoc con) . field++-- | Extracts out individual maps of documentation added via Template Haskell's+-- @putDoc@.+extractTHDocs :: THDocs+ -> ExtractedTHDocs+extractTHDocs docs =+ -- Split up docs into separate maps for each 'DocLoc' type+ ExtractedTHDocs+ docHeader+ (DeclDocMap (searchDocs decl))+ (ArgDocMap (searchDocs args))+ (DeclDocMap (searchDocs insts))+ where+ docHeader :: Maybe HsDocString+ docHeader+ | ((_, s):_) <- filter isModDoc (M.toList docs) = Just (mkHsDocString s)+ | otherwise = Nothing++ isModDoc (ModuleDoc, _) = True+ isModDoc _ = False++ -- Folds over the docs, applying 'f' as the accumulating function.+ -- We use different accumulating functions to sift out the specific types of+ -- documentation+ searchDocs :: Monoid a => (a -> (DocLoc, String) -> a) -> a+ searchDocs f = foldl' f mempty $ M.toList docs++ -- Pick out the declaration docs+ decl acc ((DeclDoc name), s) = M.insert name (mkHsDocString s) acc+ decl acc _ = acc++ -- Pick out the instance docs+ insts acc ((InstDoc name), s) = M.insert name (mkHsDocString s) acc+ insts acc _ = acc++ -- Pick out the argument docs+ args :: Map Name (IntMap HsDocString)+ -> (DocLoc, String)+ -> Map Name (IntMap HsDocString)+ args acc ((ArgDoc name i), s) =+ -- Insert the doc for the arg into the argument map for the function. This+ -- means we have to search to see if an map already exists for the+ -- function, and insert the new argument if it exists, or create a new map+ let ds = mkHsDocString s+ in M.insertWith (\_ m -> IM.insert i ds m) name (IM.singleton i ds) acc+ args acc _ = acc++-- | Unions together two 'ArgDocMaps' (or ArgMaps in haddock-api), such that two+-- maps with values for the same key merge the inner map as well.+-- Left biased so @unionArgMaps a b@ prefers @a@ over @b@.+unionArgMaps :: Map Name (IntMap b)+ -> Map Name (IntMap b)+ -> Map Name (IntMap b)+unionArgMaps a b = M.foldlWithKey go b a+ where+ go acc n newArgMap+ | Just oldArgMap <- M.lookup n acc =+ M.insert n (newArgMap `IM.union` oldArgMap) acc+ | otherwise = M.insert n newArgMap acc
compiler/GHC/HsToCore/Expr.hs view
@@ -64,6 +64,7 @@ import GHC.Types.Basic import GHC.Data.Maybe import GHC.Types.SrcLoc+import GHC.Types.Tickish import GHC.Utils.Misc import GHC.Data.Bag import GHC.Utils.Outputable as Outputable@@ -80,11 +81,11 @@ ************************************************************************ -} -dsLocalBinds :: LHsLocalBinds GhcTc -> CoreExpr -> DsM CoreExpr-dsLocalBinds (L _ (EmptyLocalBinds _)) body = return body-dsLocalBinds (L loc (HsValBinds _ binds)) body = putSrcSpanDs loc $- dsValBinds binds body-dsLocalBinds (L _ (HsIPBinds _ binds)) body = dsIPBinds binds body+dsLocalBinds :: HsLocalBinds GhcTc -> CoreExpr -> DsM CoreExpr+dsLocalBinds (EmptyLocalBinds _) body = return body+dsLocalBinds b@(HsValBinds _ binds) body = putSrcSpanDs (spanHsLocaLBinds b) $+ dsValBinds binds body+dsLocalBinds (HsIPBinds _ binds) body = dsIPBinds binds body ------------------------- -- caller sets location@@ -121,7 +122,7 @@ -- could be dict binds in the 'binds'. (See the notes -- below. Then pattern-match would fail. Urk.) , isUnliftedHsBind bind- = putSrcSpanDs loc $+ = putSrcSpanDs (locA loc) $ -- see Note [Strict binds checks] in GHC.HsToCore.Binds if is_polymorphic bind then errDsCoreExpr (poly_bind_err bind)@@ -249,7 +250,7 @@ -- ; return core_expr } dsLExpr :: LHsExpr GhcTc -> DsM CoreExpr dsLExpr (L loc e) =- putSrcSpanDs loc $ dsExpr e+ putSrcSpanDsA loc $ dsExpr e -- | Variant of 'dsLExpr' that ensures that the result is not levity -- polymorphic. This should be used when the resulting expression will@@ -258,7 +259,7 @@ -- See Note [Levity polymorphism invariants] in "GHC.Core" dsLExprNoLP :: LHsExpr GhcTc -> DsM CoreExpr dsLExprNoLP (L loc e)- = putSrcSpanDs loc $+ = putSrcSpanDsA loc $ do { e' <- dsExpr e ; dsNoLevPolyExpr e' (text "In the type of expression:" <+> ppr e) ; return e' }@@ -276,6 +277,9 @@ dsExpr (HsConLikeOut _ con) = dsConLike con dsExpr (HsIPVar {}) = panic "dsExpr: HsIPVar" +dsExpr (HsGetField x _ _) = absurd x+dsExpr (HsProjection x _) = absurd x+ dsExpr (HsLit _ lit) = do { warnAboutOverflowedLit lit ; dsLit (convertLit lit) }@@ -284,31 +288,15 @@ = do { warnAboutOverflowedOverLit lit ; dsOverLit lit } -dsExpr (XExpr (ExpansionExpr (HsExpanded _ b)))- = dsExpr b--dsExpr hswrap@(XExpr (WrapExpr (HsWrap co_fn e)))- = do { e' <- case e of- HsVar _ (L _ var) -> return $ varToCoreExpr var- HsConLikeOut _ (RealDataCon dc) -> return $ varToCoreExpr (dataConWrapId dc)- XExpr (WrapExpr (HsWrap _ _)) -> pprPanic "dsExpr: HsWrap inside HsWrap" (ppr hswrap)- HsPar _ _ -> pprPanic "dsExpr: HsPar inside HsWrap" (ppr hswrap)- _ -> addTyCs FromSource (hsWrapDictBinders co_fn) $- dsExpr e- -- See Note [Detecting forced eta expansion]- ; wrap' <- dsHsWrapper co_fn- ; dflags <- getDynFlags- ; let wrapped_e = wrap' e'- wrapped_ty = exprType wrapped_e- ; checkForcedEtaExpansion e (ppr hswrap) wrapped_ty -- See Note [Detecting forced eta expansion]- -- Pass HsWrap, so that the user can see entire expression with -fprint-typechecker-elaboration- ; warnAboutIdentities dflags e' wrapped_ty- ; return wrapped_e }+dsExpr e@(XExpr expansion)+ = case expansion of+ ExpansionExpr (HsExpanded _ b) -> dsExpr b+ WrapExpr {} -> dsHsWrapped e dsExpr (NegApp _ (L loc (HsOverLit _ lit@(OverLit { ol_val = HsIntegral i}))) neg_expr)- = do { expr' <- putSrcSpanDs loc $ do+ = do { expr' <- putSrcSpanDsA loc $ do { warnAboutOverflowedOverLit (lit { ol_val = HsIntegral (negateIntegralLit i) }) ; dsOverLit lit }@@ -330,9 +318,7 @@ ; dsWhenNoErrs (dsLExprNoLP arg) (\arg' -> mkCoreAppDs (text "HsApp" <+> ppr e) fun' arg') } -dsExpr (HsAppType ty e _)- = do { e' <- dsLExpr e- ; return (App e' (Type ty)) }+dsExpr e@(HsAppType {}) = dsHsWrapped e {- Note [Desugaring vars]@@ -353,12 +339,12 @@ -} dsExpr (ExplicitTuple _ tup_args boxity)- = do { let go (lam_vars, args) (L _ (Missing (Scaled mult ty)))+ = do { let go (lam_vars, args) (Missing (Scaled mult ty)) -- For every missing expression, we need -- another lambda in the desugaring. = do { lam_var <- newSysLocalDsNoLP mult ty ; return (lam_var : lam_vars, Var lam_var : args) }- go (lam_vars, args) (L _ (Present _ expr))+ go (lam_vars, args) (Present _ expr) -- Expressions that are present don't generate -- lambdas, just arguments. = do { core_expr <- dsLExprNoLP expr@@ -408,7 +394,7 @@ = mkErrorExpr | otherwise- = do { let grhss = GRHSs noExtField alts (noLoc emptyLocalBinds)+ = do { let grhss = GRHSs noExtField alts emptyLocalBinds ; rhss_nablas <- pmcGRHSs IfAlt grhss ; match_result <- dsGRHSs IfAlt grhss res_ty rhss_nablas ; error_expr <- mkErrorExpr@@ -449,7 +435,7 @@ dflags <- getDynFlags let platform = targetPlatform dflags- let (line, col) = case loc of+ let (line, col) = case locA loc of RealSrcSpan r _ -> ( srcLocLine $ realSrcSpanStart r , srcLocCol $ realSrcSpanStart r@@ -460,7 +446,7 @@ , mkIntExprInt platform line, mkIntExprInt platform col ] - putSrcSpanDs loc $ return $+ putSrcSpanDsA loc $ return $ mkCoreApps (Var makeStaticId) [ Type ty, srcLoc, expr_ds ] {-@@ -603,7 +589,11 @@ -} -dsExpr expr@(RecordUpd { rupd_expr = record_expr, rupd_flds = fields+dsExpr RecordUpd { rupd_flds = Right _} =+ -- Not possible due to elimination in the renamer. See Note+ -- [Handling overloaded and rebindable constructs]+ panic "The impossible happened"+dsExpr expr@(RecordUpd { rupd_expr = record_expr, rupd_flds = Left fields , rupd_ext = RecordUpdTc { rupd_cons = cons_to_upd , rupd_in_tys = in_inst_tys@@ -626,7 +616,7 @@ ; alts <- mapM (mk_alt upd_fld_env) cons_to_upd ; ([discrim_var], matching_code) <- matchWrapper RecUpd (Just record_expr) -- See Note [Scrutinee in Record updates]- (MG { mg_alts = noLoc alts+ (MG { mg_alts = noLocA alts , mg_ext = MatchGroupTc [unrestricted in_ty] out_ty , mg_origin = FromSource })@@ -680,7 +670,7 @@ mk_val_arg fl pat_arg_id = nlHsVar (lookupNameEnv upd_fld_env (flSelector fl) `orElse` pat_arg_id) - inst_con = noLoc $ mkHsWrap wrap (HsConLikeOut noExtField con)+ inst_con = noLocA $ mkHsWrap wrap (HsConLikeOut noExtField con) -- Reconstruct with the WrapId so that unpacking happens wrap = mkWpEvVarApps theta_vars <.> dict_req_wrap <.>@@ -724,16 +714,16 @@ req_wrap = dict_req_wrap <.> mkWpTyApps in_inst_tys - pat = noLoc $ ConPat { pat_con = noLoc con- , pat_args = PrefixCon [] $ map nlVarPat arg_ids- , pat_con_ext = ConPatTc- { cpt_tvs = ex_tvs- , cpt_dicts = eqs_vars ++ theta_vars- , cpt_binds = emptyTcEvBinds- , cpt_arg_tys = in_inst_tys- , cpt_wrap = req_wrap- }- }+ pat = noLocA $ ConPat { pat_con = noLocA con+ , pat_args = PrefixCon [] $ map nlVarPat arg_ids+ , pat_con_ext = ConPatTc+ { cpt_tvs = ex_tvs+ , cpt_dicts = eqs_vars ++ theta_vars+ , cpt_binds = emptyTcEvBinds+ , cpt_arg_tys = in_inst_tys+ , cpt_wrap = req_wrap+ }+ } ; return (mkSimpleMatch RecUpd [pat] wrapped_rhs) } {- Note [Scrutinee in Record updates]@@ -806,7 +796,7 @@ count <- goptM Opt_ProfCountEntries let nm = sl_fs cc flavour <- ExprCC <$> getCCIndexDsM nm- Tick (ProfNote (mkUserCC nm mod_name (getLoc expr) flavour) count True)+ Tick (ProfNote (mkUserCC nm mod_name (getLocA expr) flavour) count True) <$> dsLExpr expr else dsLExpr expr @@ -944,7 +934,7 @@ = goL stmts where goL [] = panic "dsDo"- goL ((L loc stmt):lstmts) = putSrcSpanDs loc (go loc stmt lstmts)+ goL ((L loc stmt):lstmts) = putSrcSpanDsA loc (go loc stmt lstmts) go _ (LastStmt _ body _ _) stmts = ASSERT( null stmts ) dsLExpr body@@ -977,11 +967,11 @@ do_arg (ApplicativeArgOne fail_op pat expr _) = ((pat, fail_op), dsLExpr expr) do_arg (ApplicativeArgMany _ stmts ret pat _) =- ((pat, Nothing), dsDo ctx (stmts ++ [noLoc $ mkLastStmt (noLoc ret)]))+ ((pat, Nothing), dsDo ctx (stmts ++ [noLocA $ mkLastStmt (noLocA ret)])) ; rhss' <- sequence rhss - ; body' <- dsLExpr $ noLoc $ HsDo body_ty ctx (noLoc stmts)+ ; body' <- dsLExpr $ noLocA $ HsDo body_ty ctx (noLocA stmts) ; let match_args (pat, fail_op) (vs,body) = do { var <- selectSimpleMatchVarL Many pat@@ -999,7 +989,7 @@ Nothing -> return expr Just join_op -> dsSyntaxExpr join_op [expr] } - go loc (RecStmt { recS_stmts = rec_stmts, recS_later_ids = later_ids+ go loc (RecStmt { recS_stmts = L _ rec_stmts, recS_later_ids = later_ids , recS_rec_ids = rec_ids, recS_ret_fn = return_op , recS_mfix_fn = mfix_op, recS_bind_fn = bind_op , recS_ext = RecStmtTc@@ -1022,19 +1012,19 @@ tup_ty = mkBigCoreTupTy (map idType tup_ids) -- Deals with singleton case rec_tup_pats = map nlVarPat tup_ids later_pats = rec_tup_pats- rets = map noLoc rec_rets+ rets = map noLocA rec_rets mfix_app = nlHsSyntaxApps mfix_op [mfix_arg]- mfix_arg = noLoc $ HsLam noExtField- (MG { mg_alts = noLoc [mkSimpleMatch+ mfix_arg = noLocA $ HsLam noExtField+ (MG { mg_alts = noLocA [mkSimpleMatch LambdaExpr [mfix_pat] body] , mg_ext = MatchGroupTc [unrestricted tup_ty] body_ty , mg_origin = Generated })- mfix_pat = noLoc $ LazyPat noExtField $ mkBigLHsPatTupId rec_tup_pats- body = noLoc $ HsDo body_ty- ctx (noLoc (rec_stmts ++ [ret_stmt]))+ mfix_pat = noLocA $ LazyPat noExtField $ mkBigLHsPatTupId rec_tup_pats+ body = noLocA $ HsDo body_ty+ ctx (noLocA (rec_stmts ++ [ret_stmt])) ret_app = nlHsSyntaxApps return_op [mkBigLHsTupId rets]- ret_stmt = noLoc $ mkLastStmt ret_app+ ret_stmt = noLocA $ mkLastStmt ret_app -- This LastStmt will be desugared with dsDo, -- which ignores the return_op in the LastStmt, -- so we must apply the return_op explicitly@@ -1052,15 +1042,8 @@ dsHsVar :: Id -> DsM CoreExpr dsHsVar var- | let bad_tys = badUseOfLevPolyPrimop var ty- , not (null bad_tys)- = do { levPolyPrimopErr (ppr var) ty bad_tys- ; return unitExpr } -- return something eminently safe-- | otherwise- = return (varToCoreExpr var) -- See Note [Desugaring vars]- where- ty = idType var+ = do { checkLevPolyFunction (ppr var) var (idType var)+ ; return (varToCoreExpr var) } -- See Note [Desugaring vars] dsConLike :: ConLike -> DsM CoreExpr dsConLike (RealDataCon dc) = dsHsVar (dataConWrapId dc)@@ -1094,8 +1077,8 @@ -- Warn about discarding non-() things in 'monadic' binding ; if warn_unused && not (isUnitTy norm_elt_ty)- then warnDs (Reason Opt_WarnUnusedDoBind)- (badMonadBind rhs elt_ty)+ then diagnosticDs (WarningWithFlag Opt_WarnUnusedDoBind)+ (badMonadBind rhs elt_ty) else -- Warn about discarding m a things in 'monadic' binding of the same type,@@ -1104,8 +1087,8 @@ case tcSplitAppTy_maybe norm_elt_ty of Just (elt_m_ty, _) | m_ty `eqType` topNormaliseType fam_inst_envs elt_m_ty- -> warnDs (Reason Opt_WarnWrongDoBind)- (badMonadBind rhs elt_ty)+ -> diagnosticDs (WarningWithFlag Opt_WarnWrongDoBind)+ (badMonadBind rhs elt_ty) _ -> return () } } | otherwise -- RHS does have type of form (m ty), which is weird@@ -1122,36 +1105,37 @@ {- ************************************************************************ * *- Forced eta expansion and levity polymorphism+ Levity polymorphism checks * * ************************************************************************ -Note [Detecting forced eta expansion]-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+Note [Checking for levity-polymorphic functions]+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We cannot have levity polymorphic function arguments. See-Note [Levity polymorphism invariants] in GHC.Core. But we *can* have-functions that take levity polymorphic arguments, as long as these-functions are eta-reduced. (See #12708 for an example.)+Note [Levity polymorphism invariants] in GHC.Core. That is+checked by dsLExprNoLP. -However, we absolutely cannot do this for functions that have no-binding (i.e., say True to Id.hasNoBinding), like primops and unboxed-tuple constructors. These get eta-expanded in CorePrep.maybeSaturate.+But what about+ const True (unsafeCoerce# :: forall r1 r2 (a :: TYPE r1) (b :: TYPE r2). a -> b) -Detecting when this is about to happen is a bit tricky, though. When-the desugarer is looking at the Id itself (let's be concrete and-suppose we have (#,#)), we don't know whether it will be levity-polymorphic. So the right spot seems to be to look after the Id has-been applied to its type arguments. To make the algorithm efficient,-it's important to be able to spot ((#,#) @a @b @c @d) without looking-past all the type arguments. We thus require that- * The body of an HsWrap is not an HsWrap, nor an HsPar.-This invariant is checked in dsExpr.-With that representation invariant, we simply look inside every HsWrap-to see if its body is an HsVar whose Id hasNoBinding. Then, we look-at the wrapped type. If it has any levity polymorphic arguments, reject.-Because we might have an HsVar without a wrapper, we check in dsHsVar-as well. typecheck/should_fail/T17021 triggers this case.+Since `unsafeCoerce#` has no binding, it has a compulsory unfolding.+But that compulsory unfolding is a levity-polymorphic lambda, which+is no good. So we want to reject this. On the other hand+ const True (unsafeCoerce# @LiftedRep @UnliftedRep)+is absolutely fine. +We have to collect all the type-instantiation and *then* check. That+is what dsHsWrapped does. Because we might have an HsVar without a+wrapper, we check in dsHsVar as well. typecheck/should_fail/T17021+triggers this case.++Note that if `f :: forall r (a :: Type r). blah`, then+ const True f+is absolutely fine. Here `f` is a function, represented by a+pointer, and we can pass it to `const` (or anything else). (See+#12708 for an example.) It's only the Id.hasNoBinding functions+that are a problem.+ Interestingly, this approach does not look to see whether the Id in question will be eta expanded. The logic is this: * Either the Id in question is saturated or not.@@ -1163,39 +1147,53 @@ -} --- | Takes an expression and its instantiated type. If the expression is an--- HsVar with a hasNoBinding primop and the type has levity-polymorphic arguments,--- issue an error. See Note [Detecting forced eta expansion]-checkForcedEtaExpansion :: HsExpr GhcTc -> SDoc -> Type -> DsM ()-checkForcedEtaExpansion expr expr_doc ty- | Just var <- case expr of- HsVar _ (L _ var) -> Just var- HsConLikeOut _ (RealDataCon dc) -> Just (dataConWrapId dc)- _ -> Nothing- , let bad_tys = badUseOfLevPolyPrimop var ty- , not (null bad_tys)- = levPolyPrimopErr expr_doc ty bad_tys-checkForcedEtaExpansion _ _ _ = return ()---- | Is this a hasNoBinding Id with a levity-polymorphic type?--- Returns the arguments that are levity polymorphic if they are bad;--- or an empty list otherwise--- See Note [Detecting forced eta expansion]-badUseOfLevPolyPrimop :: Id -> Type -> [Type]-badUseOfLevPolyPrimop id ty- | hasNoBinding id- = filter isTypeLevPoly arg_tys- | otherwise- = []+------------------------------+dsHsWrapped :: HsExpr GhcTc -> DsM CoreExpr+-- Looks for a function 'f' wrapped in type applications (HsAppType)+-- or wrappers (HsWrap), and checks that any hasNoBinding function+-- is not levity polymorphic, *after* instantiation with those wrappers+dsHsWrapped orig_hs_expr+ = go id orig_hs_expr where- (binders, _) = splitPiTys ty- arg_tys = mapMaybe binderRelevantType_maybe binders+ go wrap (XExpr (WrapExpr (HsWrap co_fn hs_e)))+ = do { wrap' <- dsHsWrapper co_fn+ ; addTyCs FromSource (hsWrapDictBinders co_fn) $+ go (wrap . wrap') hs_e }+ go wrap (HsConLikeOut _ (RealDataCon dc))+ = go_head wrap (dataConWrapId dc)+ go wrap (HsAppType ty hs_e _) = go_l (wrap . (\e -> App e (Type ty))) hs_e+ go wrap (HsPar _ hs_e) = go_l wrap hs_e+ go wrap (HsVar _ (L _ var)) = go_head wrap var+ go wrap hs_e = do { e <- dsExpr hs_e; return (wrap e) } -levPolyPrimopErr :: SDoc -> Type -> [Type] -> DsM ()-levPolyPrimopErr expr_doc ty bad_tys+ go_l wrap (L _ hs_e) = go wrap hs_e++ go_head wrap var+ = do { let wrapped_e = wrap (Var var)+ wrapped_ty = exprType wrapped_e++ ; checkLevPolyFunction (ppr orig_hs_expr) var wrapped_ty+ -- See Note [Checking for levity-polymorphic functions]+ -- Pass orig_hs_expr, so that the user can see entire+ -- expression with -fprint-typechecker-elaboration++ ; dflags <- getDynFlags+ ; warnAboutIdentities dflags var wrapped_ty++ ; return wrapped_e }+++-- | Takes a (pretty-printed) expression, a function, and its+-- instantiated type. If the function is a hasNoBinding op, and the+-- type has levity-polymorphic arguments, issue an error.+-- Note [Checking for levity-polymorphic functions]+checkLevPolyFunction :: SDoc -> Id -> Type -> DsM ()+checkLevPolyFunction pp_hs_expr var ty+ | let bad_tys = isBadLevPolyFunction var ty+ , not (null bad_tys) = errDs $ vcat [ hang (text "Cannot use function with levity-polymorphic arguments:")- 2 (expr_doc <+> dcolon <+> pprWithTYPE ty)+ 2 (pp_hs_expr <+> dcolon <+> pprWithTYPE ty) , ppUnlessOption sdocPrintTypecheckerElaboration $ vcat [ text "(Note that levity-polymorphic primops such as 'coerce' and unboxed tuples" , text "are eta-expanded internally because they must occur fully saturated."@@ -1206,3 +1204,19 @@ (\t -> pprWithTYPE t <+> dcolon <+> pprWithTYPE (typeKind t)) bad_tys ]++checkLevPolyFunction _ _ _ = return ()++-- | Is this a hasNoBinding Id with a levity-polymorphic type?+-- Returns the arguments that are levity polymorphic if they are bad;+-- or an empty list otherwise+-- Note [Checking for levity-polymorphic functions]+isBadLevPolyFunction :: Id -> Type -> [Type]+isBadLevPolyFunction id ty+ | hasNoBinding id+ = filter isTypeLevPoly arg_tys+ | otherwise+ = []+ where+ (binders, _) = splitPiTys ty+ arg_tys = mapMaybe binderRelevantType_maybe binders
compiler/GHC/HsToCore/Expr.hs-boot view
@@ -1,5 +1,5 @@ module GHC.HsToCore.Expr where-import GHC.Hs ( HsExpr, LHsExpr, LHsLocalBinds, SyntaxExpr )+import GHC.Hs ( HsExpr, LHsExpr, HsLocalBinds, SyntaxExpr ) import GHC.HsToCore.Monad ( DsM ) import GHC.Core ( CoreExpr ) import GHC.Hs.Extension ( GhcTc)@@ -7,4 +7,4 @@ dsExpr :: HsExpr GhcTc -> DsM CoreExpr dsLExpr, dsLExprNoLP :: LHsExpr GhcTc -> DsM CoreExpr dsSyntaxExpr :: SyntaxExpr GhcTc -> [CoreExpr] -> DsM CoreExpr-dsLocalBinds :: LHsLocalBinds GhcTc -> CoreExpr -> DsM CoreExpr+dsLocalBinds :: HsLocalBinds GhcTc -> CoreExpr -> DsM CoreExpr
compiler/GHC/HsToCore/Foreign/Decl.hs view
@@ -102,13 +102,13 @@ fe_init_code = foreignExportsInitialiser mod fe_ids -- return (ForeignStubs- (vcat hs)- (vcat cs $$ fe_init_code),+ (mconcat hs)+ (mconcat cs `mappend` fe_init_code), foldr (appOL . toOL) nilOL bindss) where- do_ldecl (L loc decl) = putSrcSpanDs loc (do_decl decl)+ do_ldecl (L loc decl) = putSrcSpanDs (locA loc) (do_decl decl) - do_decl :: ForeignDecl GhcTc -> DsM (SDoc, SDoc, [Id], [Binding])+ do_decl :: ForeignDecl GhcTc -> DsM (CHeader, CStub, [Id], [Binding]) do_decl (ForeignImport { fd_name = id, fd_i_ext = co, fd_fi = spec }) = do traceIf (text "fi start" <+> ppr id) let id' = unLoc id@@ -152,7 +152,7 @@ dsFImport :: Id -> Coercion -> ForeignImport- -> DsM ([Binding], SDoc, SDoc)+ -> DsM ([Binding], CHeader, CStub) dsFImport id co (CImport cconv safety mHeader spec _) = dsCImport id co spec (unLoc cconv) (unLoc safety) mHeader @@ -162,7 +162,7 @@ -> CCallConv -> Safety -> Maybe Header- -> DsM ([Binding], SDoc, SDoc)+ -> DsM ([Binding], CHeader, CStub) dsCImport id co (CLabel cid) cconv _ _ = do dflags <- getDynFlags let ty = coercionLKind co@@ -179,7 +179,7 @@ rhs' = Cast rhs co stdcall_info = fun_type_arg_stdcall_info platform cconv ty in- return ([(id, rhs')], empty, empty)+ return ([(id, rhs')], mempty, mempty) dsCImport id co (CFunction target) cconv@PrimCallConv safety _ = dsPrimCall id co (CCall (CCallSpec target cconv safety))@@ -211,7 +211,7 @@ -} dsFCall :: Id -> Coercion -> ForeignCall -> Maybe Header- -> DsM ([(Id, Expr TyVar)], SDoc, SDoc)+ -> DsM ([(Id, Expr TyVar)], CHeader, CStub) dsFCall fn_id co fcall mDeclHeader = do let ty = coercionLKind co@@ -297,7 +297,7 @@ simpl_opts wrap_rhs' - return ([(work_id, work_rhs), (fn_id_w_inl, wrap_rhs')], empty, cDoc)+ return ([(work_id, work_rhs), (fn_id_w_inl, wrap_rhs')], mempty, CStub cDoc) {- ************************************************************************@@ -315,7 +315,7 @@ -} dsPrimCall :: Id -> Coercion -> ForeignCall- -> DsM ([(Id, Expr TyVar)], SDoc, SDoc)+ -> DsM ([(Id, Expr TyVar)], CHeader, CStub) dsPrimCall fn_id co fcall = do let ty = coercionLKind co@@ -330,7 +330,7 @@ call_app = mkFCall dflags ccall_uniq fcall (map Var args) io_res_ty rhs = mkLams tvs (mkLams args call_app) rhs' = Cast rhs co- return ([(fn_id, rhs')], empty, empty)+ return ([(fn_id, rhs')], mempty, mempty) {- ************************************************************************@@ -360,8 +360,8 @@ -> Bool -- True => foreign export dynamic -- so invoke IO action that's hanging off -- the first argument's stable pointer- -> DsM ( SDoc -- contents of Module_stub.h- , SDoc -- contents of Module_stub.c+ -> DsM ( CHeader -- contents of Module_stub.h+ , CStub -- contents of Module_stub.c , String -- string describing type to pass to createAdj. , Int -- size of args to stub function )@@ -430,7 +430,7 @@ dsFExportDynamic :: Id -> Coercion -> CCallConv- -> DsM ([Binding], SDoc, SDoc)+ -> DsM ([Binding], CHeader, CStub) dsFExportDynamic id co0 cconv = do mod <- getModule dflags <- getDynFlags@@ -520,8 +520,8 @@ -> Type -> Bool -- True <=> returns an IO type -> CCallConv- -> (SDoc,- SDoc,+ -> (CHeader,+ CStub, String, -- the argument reps Int -- total size of arguments )@@ -599,7 +599,7 @@ -- Now we can cook up the prototype for the exported function. pprCconv = ccallConvAttribute cc - header_bits = text "extern" <+> fun_proto <> semi+ header_bits = CHeader (text "extern" <+> fun_proto <> semi) fun_args | null aug_arg_info = text "void"@@ -646,7 +646,7 @@ -- finally, the whole darn thing- c_bits =+ c_bits = CStub $ space $$ extern_decl $$ fun_proto $$@@ -683,7 +683,7 @@ ] -foreignExportsInitialiser :: Module -> [Id] -> SDoc+foreignExportsInitialiser :: Module -> [Id] -> CStub foreignExportsInitialiser mod hs_fns = -- Initialise foreign exports by registering a stable pointer from an -- __attribute__((constructor)) function.@@ -695,7 +695,7 @@ -- (this is bad for big umbrella modules like Graphics.Rendering.OpenGL) -- -- See Note [Tracking foreign exports] in rts/ForeignExports.c- vcat+ CStub $ vcat [ text "static struct ForeignExportsList" <+> list_symbol <+> equals <+> braces ( text ".exports = " <+> export_list <> comma <+>
compiler/GHC/HsToCore/ListComp.hs view
@@ -88,7 +88,7 @@ list_ty = mkListTy bndrs_tuple_type -- really use original bndrs below!- ; expr <- dsListComp (stmts ++ [noLoc $ mkLastStmt (mkBigLHsVarTupId bndrs)]) list_ty+ ; expr <- dsListComp (stmts ++ [noLocA $ mkLastStmt (mkBigLHsVarTupId bndrs)]) list_ty ; return (expr, bndrs_tuple_type) } @@ -479,7 +479,7 @@ dsMcStmts :: [ExprLStmt GhcTc] -> DsM CoreExpr dsMcStmts [] = panic "dsMcStmts"-dsMcStmts ((L loc stmt) : lstmts) = putSrcSpanDs loc (dsMcStmt stmt lstmts)+dsMcStmts ((L loc stmt) : lstmts) = putSrcSpanDsA loc (dsMcStmt stmt lstmts) --------------- dsMcStmt :: ExprStmt GhcTc -> [ExprLStmt GhcTc] -> DsM CoreExpr@@ -632,7 +632,7 @@ -> DsM CoreExpr dsInnerMonadComp stmts bndrs ret_op = dsMcStmts (stmts ++- [noLoc (LastStmt noExtField (mkBigLHsVarTupId bndrs) Nothing ret_op)])+ [noLocA (LastStmt noExtField (mkBigLHsVarTupId bndrs) Nothing ret_op)]) -- The `unzip` function for `GroupStmt` in a monad comprehensions
compiler/GHC/HsToCore/Match.hs view
@@ -248,7 +248,7 @@ case p of PgView e _ -> e:acc _ -> acc) [] group) eqns maybeWarn [] = return ()- maybeWarn l = warnDs NoReason (vcat l)+ maybeWarn l = diagnosticDs WarningWithoutFlag (vcat l) in maybeWarn $ (map (\g -> text "Putting these view expressions into the same case:" <+> (ppr g)) (filter (not . null) gs))@@ -455,7 +455,7 @@ -- not fully know the zonked types yet. We sure do here. = do { let unlifted_bndrs = filter (isUnliftedType . idType) (collectPatBinders CollNoDictBinders pat) ; unless (null unlifted_bndrs) $- putSrcSpanDs (getLoc pat) $+ putSrcSpanDs (getLocA pat) $ errDs (hang (text "A lazy (~) pattern cannot bind variables of unlifted type." $$ text "Unlifted variables:") 2 (vcat (map (\id -> ppr id <+> dcolon <+> ppr (idType id))@@ -514,7 +514,7 @@ = return (idDsWrapper, non_interesting_pat) ---------------------tidy_bang_pat :: Id -> Origin -> SrcSpan -> Pat GhcTc+tidy_bang_pat :: Id -> Origin -> SrcSpanAnnA -> Pat GhcTc -> DsM (DsWrapper, Pat GhcTc) -- Discard par/sig under a bang@@ -567,7 +567,7 @@ tidy_bang_pat _ _ l p = return (idDsWrapper, BangPat noExtField (L l p)) --------------------push_bang_into_newtype_arg :: SrcSpan+push_bang_into_newtype_arg :: SrcSpanAnnA -> Type -- The type of the argument we are pushing -- onto -> HsConPatDetails GhcTc -> HsConPatDetails GhcTc@@ -584,7 +584,7 @@ = L l (BangPat noExtField arg) })] }) push_bang_into_newtype_arg l ty (RecCon rf) -- If a user writes !(T {}) | HsRecFields { rec_flds = [] } <- rf- = PrefixCon [] [L l (BangPat noExtField (noLoc (WildPat ty)))]+ = PrefixCon [] [L l (BangPat noExtField (noLocA (WildPat ty)))] push_bang_into_newtype_arg _ _ cd = pprPanic "push_bang_into_newtype_arg" (pprConArgs cd) @@ -812,11 +812,10 @@ -> [MatchId] -> [EquationInfo] -> Type -> DsM CoreExpr matchEquations ctxt vars eqns_info rhs_ty- = do { let error_doc = matchContextErrString ctxt+ = do { match_result <- match vars rhs_ty eqns_info - ; match_result <- match vars rhs_ty eqns_info+ ; fail_expr <- mkFailExpr ctxt rhs_ty - ; fail_expr <- mkErrorAppDs pAT_ERROR_ID rhs_ty error_doc ; extractMatchResult match_result fail_expr } -- | @matchSimply@ is a wrapper for 'match' which deals with the@@ -1112,8 +1111,8 @@ syn_exp _ _ = False ---------- tup_arg (L _ (Present _ e1)) (L _ (Present _ e2)) = lexp e1 e2- tup_arg (L _ (Missing (Scaled _ t1))) (L _ (Missing (Scaled _ t2))) = eqType t1 t2+ tup_arg (Present _ e1) (Present _ e2) = lexp e1 e2+ tup_arg (Missing (Scaled _ t1)) (Missing (Scaled _ t2)) = eqType t1 t2 tup_arg _ _ = False ---------
compiler/GHC/HsToCore/Match.hs-boot view
@@ -6,7 +6,7 @@ import GHC.HsToCore.Monad ( DsM, EquationInfo, MatchResult ) import GHC.Core ( CoreExpr ) import GHC.Hs ( LPat, HsMatchContext, MatchGroup, LHsExpr )-import GHC.Hs.Extension ( GhcRn, GhcTc )+import GHC.Hs.Extension ( GhcTc, GhcRn ) match :: [Id] -> Type
compiler/GHC/HsToCore/Match/Literal.hs view
@@ -258,16 +258,16 @@ same. Then it's probably (albeit not definitely) the identity -} -warnAboutIdentities :: DynFlags -> CoreExpr -> Type -> DsM ()-warnAboutIdentities dflags (Var conv_fn) type_of_conv+warnAboutIdentities :: DynFlags -> Id -> Type -> DsM ()+warnAboutIdentities dflags conv_fn type_of_conv | wopt Opt_WarnIdentities dflags , idName conv_fn `elem` conversionNames , Just (_, arg_ty, res_ty) <- splitFunTy_maybe type_of_conv , arg_ty `eqType` res_ty -- So we are converting ty -> ty- = warnDs (Reason Opt_WarnIdentities)- (vcat [ text "Call of" <+> ppr conv_fn <+> dcolon <+> ppr type_of_conv- , nest 2 $ text "can probably be omitted"- ])+ = diagnosticDs (WarningWithFlag Opt_WarnIdentities)+ (vcat [ text "Call of" <+> ppr conv_fn <+> dcolon <+> ppr type_of_conv+ , nest 2 $ text "can probably be omitted"+ ]) warnAboutIdentities _ _ _ = return () conversionNames :: [Name]@@ -348,19 +348,19 @@ checkPositive :: Integer -> Name -> DsM () checkPositive i tc = when (i < 0) $- warnDs (Reason Opt_WarnOverflowedLiterals)- (vcat [ text "Literal" <+> integer i- <+> text "is negative but" <+> ppr tc- <+> ptext (sLit "only supports positive numbers")- ])+ diagnosticDs (WarningWithFlag Opt_WarnOverflowedLiterals)+ (vcat [ text "Literal" <+> integer i+ <+> text "is negative but" <+> ppr tc+ <+> ptext (sLit "only supports positive numbers")+ ]) check i tc minB maxB = when (i < minB || i > maxB) $- warnDs (Reason Opt_WarnOverflowedLiterals)- (vcat [ text "Literal" <+> integer i- <+> text "is out of the" <+> ppr tc <+> ptext (sLit "range")- <+> integer minB <> text ".." <> integer maxB- , sug ])+ diagnosticDs (WarningWithFlag Opt_WarnOverflowedLiterals)+ (vcat [ text "Literal" <+> integer i+ <+> text "is out of the" <+> ppr tc <+> ptext (sLit "range")+ <+> integer minB <> text ".." <> integer maxB+ , sug ]) where sug | minB == -i -- Note [Suggest NegativeLiterals] , i > 0@@ -441,7 +441,8 @@ | otherwise = return () where- raiseWarning = warnDs (Reason Opt_WarnEmptyEnumerations) (text "Enumeration is empty")+ raiseWarning =+ diagnosticDs (WarningWithFlag Opt_WarnEmptyEnumerations) (text "Enumeration is empty") getLHsIntegralLit :: LHsExpr GhcTc -> Maybe (Integer, Type) -- ^ See if the expression is an 'Integral' literal.@@ -575,7 +576,7 @@ mk_con_pat :: DataCon -> HsLit GhcTc -> Pat GhcTc mk_con_pat con lit- = unLoc (mkPrefixConPat con [noLoc $ LitPat noExtField lit] [])+ = unLoc (mkPrefixConPat con [noLocA $ LitPat noExtField lit] []) mb_int_lit :: Maybe Integer mb_int_lit = case (mb_neg, val) of
compiler/GHC/HsToCore/Monad.hs view
@@ -22,7 +22,7 @@ duplicateLocalDs, newSysLocalDsNoLP, newSysLocalDs, newSysLocalsDsNoLP, newSysLocalsDs, newUniqueId, newFailLocalDs, newPredVarDs,- getSrcSpanDs, putSrcSpanDs,+ getSrcSpanDs, putSrcSpanDs, putSrcSpanDsA, mkPrintUnqualifiedDs, newUnique, UniqSupply, newUniqueSupply,@@ -40,7 +40,7 @@ dsGetCompleteMatches, -- Warnings and errors- DsWarning, warnDs, warnIfSetDs, errDs, errDsCoreExpr,+ DsWarning, diagnosticDs, warnIfSetDs, errDs, errDsCoreExpr, failWithDs, failDs, discardWarningsDs, askNoErrsDs, @@ -107,6 +107,7 @@ import GHC.Utils.Outputable import GHC.Utils.Panic+import GHC.Utils.Error import Data.IORef @@ -213,7 +214,7 @@ } -- | Run a 'DsM' action inside the 'IO' monad.-initDs :: HscEnv -> TcGblEnv -> DsM a -> IO (Messages DecoratedSDoc, Maybe a)+initDs :: HscEnv -> TcGblEnv -> DsM a -> IO (Messages DiagnosticMessage, Maybe a) initDs hsc_env tcg_env thing_inside = do { msg_var <- newIORef emptyMessages ; envs <- mkDsEnvsFromTcGbl hsc_env msg_var tcg_env@@ -222,7 +223,7 @@ -- | Build a set of desugarer environments derived from a 'TcGblEnv'. mkDsEnvsFromTcGbl :: MonadIO m- => HscEnv -> IORef (Messages DecoratedSDoc) -> TcGblEnv+ => HscEnv -> IORef (Messages DiagnosticMessage) -> TcGblEnv -> m (DsGblEnv, DsLclEnv) mkDsEnvsFromTcGbl hsc_env msg_var tcg_env = do { cc_st_var <- liftIO $ newIORef newCostCentreState@@ -239,7 +240,7 @@ msg_var cc_st_var complete_matches } -runDs :: HscEnv -> (DsGblEnv, DsLclEnv) -> DsM a -> IO (Messages DecoratedSDoc, Maybe a)+runDs :: HscEnv -> (DsGblEnv, DsLclEnv) -> DsM a -> IO (Messages DiagnosticMessage, Maybe a) runDs hsc_env (ds_gbl, ds_lcl) thing_inside = do { res <- initTcRnIf 'd' hsc_env ds_gbl ds_lcl (tryM thing_inside)@@ -252,7 +253,7 @@ } -- | Run a 'DsM' action in the context of an existing 'ModGuts'-initDsWithModGuts :: HscEnv -> ModGuts -> DsM a -> IO (Messages DecoratedSDoc, Maybe a)+initDsWithModGuts :: HscEnv -> ModGuts -> DsM a -> IO (Messages DiagnosticMessage, Maybe a) initDsWithModGuts hsc_env (ModGuts { mg_module = this_mod, mg_binds = binds , mg_tcs = tycons, mg_fam_insts = fam_insts , mg_patsyns = patsyns, mg_rdr_env = rdr_env@@ -278,7 +279,7 @@ ; runDs hsc_env envs thing_inside } -initTcDsForSolver :: TcM a -> DsM (Messages DecoratedSDoc, Maybe a)+initTcDsForSolver :: TcM a -> DsM a -- Spin up a TcM context so that we can run the constraint solver -- Returns any error messages generated by the constraint solver -- and (Just res) if no error happened; Nothing if an error happened@@ -303,13 +304,16 @@ DsLclEnv { dsl_loc = loc } = lcl - ; liftIO $ initTc hsc_env HsSrcFile False mod loc $+ ; (msgs, mb_ret) <- liftIO $ initTc hsc_env HsSrcFile False mod loc $ updGblEnv (\tc_gbl -> tc_gbl { tcg_fam_inst_env = fam_inst_env , tcg_rdr_env = rdr_env }) $- thing_inside }+ thing_inside+ ; case mb_ret of+ Just ret -> pure ret+ Nothing -> pprPanic "initTcDsForSolver" (vcat $ pprMsgEnvelopeBagWithLoc (getErrorMessages msgs)) } mkDsEnvs :: UnitEnv -> Module -> GlobalRdrEnv -> TypeEnv -> FamInstEnv- -> IORef (Messages DecoratedSDoc) -> IORef CostCentreState -> CompleteMatches+ -> IORef (Messages DiagnosticMessage) -> IORef CostCentreState -> CompleteMatches -> (DsGblEnv, DsLclEnv) mkDsEnvs unit_env mod rdr_env type_env fam_inst_env msg_var cc_st_var complete_matches@@ -447,27 +451,29 @@ putSrcSpanDs (RealSrcSpan real_span _) thing_inside = updLclEnv (\ env -> env {dsl_loc = real_span}) thing_inside --- | Emit a warning for the current source location+putSrcSpanDsA :: SrcSpanAnn' ann -> DsM a -> DsM a+putSrcSpanDsA loc = putSrcSpanDs (locA loc)++-- | Emit a diagnostic for the current source location -- NB: Warns whether or not -Wxyz is set-warnDs :: WarnReason -> SDoc -> DsM ()-warnDs reason warn+diagnosticDs :: DiagnosticReason -> SDoc -> DsM ()+diagnosticDs reason warn = do { env <- getGblEnv ; loc <- getSrcSpanDs- ; let msg = makeIntoWarning reason $- mkWarnMsg loc (ds_unqual env) warn+ ; let msg = mkShortMsgEnvelope reason loc (ds_unqual env) warn ; updMutVar (ds_msgs env) (\ msgs -> msg `addMessage` msgs) } --- | Emit a warning only if the correct WarnReason is set in the DynFlags+-- | Emit a warning only if the correct WarningWithoutFlag is set in the DynFlags warnIfSetDs :: WarningFlag -> SDoc -> DsM () warnIfSetDs flag warn = whenWOptM flag $- warnDs (Reason flag) warn+ diagnosticDs (WarningWithFlag flag) warn errDs :: SDoc -> DsM () errDs err = do { env <- getGblEnv ; loc <- getSrcSpanDs- ; let msg = mkMsgEnvelope loc (ds_unqual env) err+ ; let msg = mkShortMsgEnvelope ErrorWithoutFlag loc (ds_unqual env) err ; updMutVar (ds_msgs env) (\ msgs -> msg `addMessage` msgs) } -- | Issue an error, but return the expression for (), so that we can continue
compiler/GHC/HsToCore/Pmc.hs view
@@ -238,10 +238,6 @@ instance Monoid CIRB where mempty = CIRB mempty mempty mempty mempty -markAllRedundant :: CIRB -> CIRB-markAllRedundant CIRB { cirb_cov = cov, cirb_inacc = inacc, cirb_red = red } =- mempty { cirb_red = cov Semi.<> inacc Semi.<> red }- -- See Note [Determining inaccessible clauses] ensureOneNotRedundant :: CIRB -> CIRB ensureOneNotRedundant ci = case ci of@@ -279,12 +275,14 @@ cirbsMatch :: PmMatch Post -> DsM CIRB cirbsMatch PmMatch { pm_pats = red, pm_grhss = grhss } = do- (is_covered, may_diverge, red_bangs) <- testRedSets red+ (_is_covered, may_diverge, red_bangs) <- testRedSets red+ -- Don't look at is_covered: If it is True, all children are redundant anyway,+ -- unless there is a 'considerAccessible', which may break that rule+ -- intentionally. See Note [considerAccessible] in "GHC.HsToCore.Pmc.Check". cirb <- cirbsGRHSs grhss pure $ addRedundantBangs red_bangs -- See Note [Determining inaccessible clauses] $ applyWhen may_diverge ensureOneNotRedundant- $ applyWhen (not is_covered) markAllRedundant $ cirb cirbsGRHSs :: PmGRHSs Post -> DsM CIRB@@ -349,26 +347,26 @@ approx = precision == Approximate when (approx && (exists_u || exists_i)) $- putSrcSpanDs loc (warnDs NoReason approx_msg)+ putSrcSpanDs loc (diagnosticDs WarningWithoutFlag approx_msg) when exists_b $ forM_ redundant_bangs $ \(SrcInfo (L l q)) ->- putSrcSpanDs l (warnDs (Reason Opt_WarnRedundantBangPatterns)- (pprEqn q "has redundant bang"))+ putSrcSpanDs l (diagnosticDs (WarningWithFlag Opt_WarnRedundantBangPatterns)+ (pprEqn q "has redundant bang")) when exists_r $ forM_ redundant_rhss $ \(SrcInfo (L l q)) ->- putSrcSpanDs l (warnDs (Reason Opt_WarnOverlappingPatterns)- (pprEqn q "is redundant"))+ putSrcSpanDs l (diagnosticDs (WarningWithFlag Opt_WarnOverlappingPatterns)+ (pprEqn q "is redundant")) when exists_i $ forM_ inaccessible_rhss $ \(SrcInfo (L l q)) ->- putSrcSpanDs l (warnDs (Reason Opt_WarnOverlappingPatterns)- (pprEqn q "has inaccessible right hand side"))+ putSrcSpanDs l (diagnosticDs (WarningWithFlag Opt_WarnOverlappingPatterns)+ (pprEqn q "has inaccessible right hand side")) - when exists_u $ putSrcSpanDs loc $ warnDs flag_u_reason $+ when exists_u $ putSrcSpanDs loc $ diagnosticDs flag_u_reason $ pprEqns vars unc_examples where flag_i = overlapping dflags kind flag_u = exhaustive dflags kind flag_b = redundantBang dflags- flag_u_reason = maybe NoReason Reason (exhaustiveWarningFlag kind)+ flag_u_reason = maybe WarningWithoutFlag WarningWithFlag (exhaustiveWarningFlag kind) maxPatterns = maxUncoveredPatterns dflags
compiler/GHC/HsToCore/Pmc/Check.hs view
@@ -26,6 +26,7 @@ import GHC.Prelude +import GHC.Builtin.Names ( hasKey, considerAccessibleIdKey, trueDataConKey ) import GHC.HsToCore.Monad ( DsM ) import GHC.HsToCore.Pmc.Types import GHC.HsToCore.Pmc.Utils@@ -124,6 +125,13 @@ pure CheckResult { cr_ret = RedSets { rs_cov = matched, rs_div = div, rs_bangs = bangs } , cr_uncov = mempty , cr_approx = Precise }+ -- See point (3) of Note [considerAccessible]+ PmCon x (PmAltConLike con) _ _ _+ | x `hasKey` considerAccessibleIdKey+ , con `hasKey` trueDataConKey+ -> pure CheckResult { cr_ret = emptyRedSets { rs_cov = initNablas }+ , cr_uncov = mempty+ , cr_approx = Precise } -- Con: Fall through on x ≁ K and refine with x ~ K ys and type info PmCon x con tvs dicts args -> do !div <- if isPmAltConMatchStrict con@@ -269,4 +277,77 @@ dreadful example: Since their RHS are often pretty much unique, we split on a variable (the one representing the RHS) that doesn't occur anywhere else in the program, so we don't actually get useful information out of that split!++Note [considerAccessible]+~~~~~~~~~~~~~~~~~~~~~~~~~+Consider (T18610)++ f :: Bool -> Int+ f x = case (x, x) of+ (True, True) -> 1+ (False, False) -> 2+ (True, False) -> 3 -- Warning: Redundant++The third case is detected as redundant. But it may be the intent of the+programmer to keep the dead code, in order for it not to bitrot or to support+debugging scenarios. But there is no way to communicate that to the+pattern-match checker! The only way is to deactivate pattern-match checking+whole-sale, which is quite annoying. Hence, we define in "GHC.Exts":++ considerAccessible = True++'considerAccessible' is treated specially by the pattern-match checker in that a+guard with it as the scrutinee expression will keep its parent clause alive:++ g :: Bool -> Int+ g x = case (x, x) of+ (True, True) -> 1+ (False, False) -> 2+ (True, False) | GHC.Exts.considerAccessible -> 3 -- No warning++The key bits of the implementation are:++ 1. Its definition is recognised as known-key (see "GHC.Builtin.Names").+ 2. After "GHC.HsToCore.Pmc.Desugar", the guard will end up as a 'PmCon', where+ the match var is the known-key 'considerAccessible' and the constructor+ against which it matches is 'True'.+ 3. We recognise the 'PmCon' in 'GHC.HsToCore.Check.checkGrd' and inflate the+ incoming set of values for all guards downstream to the unconstrained+ 'initNablas' set, e.g. /all/ values.+ (The set of values that falls through that particular guard is empty, as+ matching 'considerAccessible' against 'True' can't fail.)++Note that 'considerAccessible' breaks the invariant that incoming sets of values+reaching syntactic children are subsets of that of the syntactic ancestor:+A whole match, like that of the third clause of the example, might have no+incoming value, but its single RHS has incoming values because of (3).++That means the 'is_covered' flag computed in 'GHC.HsToCore.Pmc.cirbsMatch'+is irrelevant and should not be used to flag all children as redundant (which is+what we used to do).++We achieve great benefits with a very simple implementation.+There are caveats, though:++ (A) Putting potentially failing guards /after/ the+ 'considerAccessible' guard might lead to weird check results, e.g.,++ h :: Bool -> Int+ h x = case (x, x) of+ (True, True) -> 1+ (False, False) -> 2+ (True, False) | GHC.Exts.considerAccessible, False <- x -> 3+ -- Warning: Not matched: (_, _)++ That *is* fixable, although we would pay with a much more complicated+ implementation.+ (B) If the programmer puts a 'considerAccessible' marker on an accessible+ clause, the checker doesn't warn about it. E.g.,++ f :: Bool -> Int+ f True | considerAccessible = 0+ f False = 1++ will not emit any warning whatsoever. We could implement code that warns+ here, but it wouldn't be as simple as it is now. -}
compiler/GHC/HsToCore/Pmc/Desugar.hs view
@@ -117,7 +117,7 @@ -- Add the bang in front of the list, because it will happen before any -- nested stuff. (PmBang x pm_loc :) <$> desugarLPat x p- where pm_loc = Just (SrcInfo (L l (ppr p')))+ where pm_loc = Just (SrcInfo (L (locA l) (ppr p'))) -- (x@pat) ==> Desugar pat with x as match var and handle impedance -- mismatch with incoming match var@@ -342,7 +342,7 @@ desugarMatch :: [Id] -> LMatch GhcTc (LHsExpr GhcTc) -> DsM (PmMatch Pre) desugarMatch vars (L match_loc (Match { m_pats = pats, m_grhss = grhss })) = do pats' <- concat <$> zipWithM desugarLPat vars pats- grhss' <- desugarGRHSs match_loc (sep (map ppr pats)) grhss+ grhss' <- desugarGRHSs (locA match_loc) (sep (map ppr pats)) grhss -- tracePm "desugarMatch" (vcat [ppr pats, ppr pats', ppr grhss']) return PmMatch { pm_pats = GrdVec pats', pm_grhss = grhss' } @@ -364,8 +364,8 @@ -- pp_pats is the space-separated pattern of the current Match this -- GRHS belongs to, so the @A B x@ part in @A B x | 0 <- x@. let rhs_info = case gs of- [] -> L match_loc pp_pats- (L grd_loc _):_ -> L grd_loc (pp_pats <+> vbar <+> interpp'SP gs)+ [] -> L match_loc pp_pats+ (L grd_loc _):_ -> L (locA grd_loc) (pp_pats <+> vbar <+> interpp'SP gs) grds <- concatMapM (desugarGuard . unLoc) gs pure PmGRHS { pg_grds = GrdVec grds, pg_rhs = SrcInfo rhs_info } @@ -385,8 +385,8 @@ -- Deals only with simple @let@ or @where@ bindings without any polymorphism, -- recursion, pattern bindings etc. -- See Note [Long-distance information for HsLocalBinds].-desugarLocalBinds :: LHsLocalBinds GhcTc -> DsM [PmGrd]-desugarLocalBinds (L _ (HsValBinds _ (XValBindsLR (NValBinds binds _)))) =+desugarLocalBinds :: HsLocalBinds GhcTc -> DsM [PmGrd]+desugarLocalBinds (HsValBinds _ (XValBindsLR (NValBinds binds _))) = concatMapM (concatMapM go . bagToList) (map snd binds) where go :: LHsBind GhcTc -> DsM [PmGrd]
compiler/GHC/HsToCore/Pmc/Solver.hs view
@@ -39,16 +39,16 @@ import GHC.Prelude import GHC.HsToCore.Pmc.Types-import GHC.HsToCore.Pmc.Utils ( tracePm, mkPmId )+import GHC.HsToCore.Pmc.Utils (tracePm, mkPmId) import GHC.Driver.Session import GHC.Driver.Config import GHC.Utils.Outputable-import GHC.Utils.Error ( pprMsgEnvelopeBagWithLoc ) import GHC.Utils.Misc+import GHC.Utils.Monad (allM) import GHC.Utils.Panic import GHC.Data.Bag-import GHC.Types.Error+import GHC.Types.CompleteMatch import GHC.Types.Unique.Set import GHC.Types.Unique.DSet import GHC.Types.Unique.SDFM@@ -75,8 +75,9 @@ import GHC.Builtin.Types import GHC.Builtin.Types.Prim (tYPETyCon) import GHC.Core.TyCo.Rep+import GHC.Core.TyCo.Subst (elemTCvSubst) import GHC.Core.Type-import GHC.Tc.Solver (tcNormalise, tcCheckSatisfiability)+import GHC.Tc.Solver (tcNormalise, tcCheckGivens, tcCheckWanteds) import GHC.Core.Unify (tcMatchTy) import GHC.Core.Coercion import GHC.HsToCore.Monad hiding (foldlM)@@ -84,7 +85,7 @@ import GHC.Core.FamInstEnv import Control.Applicative ((<|>))-import Control.Monad (foldM, forM, guard, mzero, when)+import Control.Monad (foldM, forM, guard, mzero, when, filterM) import Control.Monad.Trans.Class (lift) import Control.Monad.Trans.State.Strict import Data.Coerce@@ -147,7 +148,7 @@ -- special case. mb_dcs | tc == tYPETyCon = Just [] | otherwise = tyConDataCons_maybe tc- in mkUniqDSet . map RealDataCon <$> mb_dcs+ in vanillaCompleteMatch . mkUniqDSet . map RealDataCon <$> mb_dcs -- | Initialise from 'dsGetCompleteMatches' (containing all COMPLETE pragmas) -- if the given 'ResidualCompleteMatches' were empty.@@ -180,9 +181,9 @@ markMatched (PmAltLit _) _ = pure Nothing -- lits are never part of a COMPLETE set markMatched (PmAltConLike cl) rcm = do rcm' <- addConLikeMatches cl rcm- let go cm = case lookupUniqDSet cm cl of+ let go cm = case lookupUniqDSet (cmConLikes cm) cl of Nothing -> (False, cm)- Just _ -> (True, delOneFromUniqDSet cm cl)+ Just _ -> (True, cm { cmConLikes = delOneFromUniqDSet (cmConLikes cm) cl }) pure $ updRcm go rcm' {-@@ -203,11 +204,35 @@ booleanToInt F = 0 booleanToInt T = 1 -COMPLETE sets are represented internally in GHC a set of 'ConLike's. For+COMPLETE sets are represented internally in GHC as a set of 'ConLike's. For example, the pragma {-# COMPLETE F, T #-} would be represented as: - {F, T}+ CompleteMatch {F, T} Nothing +What is the Maybe for? Answer: COMPLETE pragmas may optionally specify a+result *type constructor* (cf. T14422):++ class C f where+ foo :: f a -> ()+ pattern P :: C f => f a+ pattern P <- (foo -> ())++ instance C State where+ foo _ = ()+ {-# COMPLETE P :: State #-}++ f :: State a -> ()+ f P = ()+ g :: C f => f a -> ()+ g P = ()++The @:: State@ here means that the types at which the COMPLETE pragma *applies*+is restricted to scrutinee types that are applications of the 'State' TyCon. So+it applies to the match in @f@ but not in @g@ above, resulting in a warning for+the latter but not for the former. The pragma is represented as++ CompleteMatch {P} (Just State)+ GHC collects all COMPLETE pragmas from the current module and from imports into a field in the DsM environment, which can be accessed with dsGetCompleteMatches from "GHC.HsToCore.Monad".@@ -228,18 +253,20 @@ testing). If *any* of the COMPLETE sets become empty, we know that the match was exhaustive. -We assume that a COMPLETE set is non-empty if for one of its ConLikes-we fail to 'guessConLikeUnivTyArgsFromResTy'. That accounts for ill-typed-COMPLETE sets. So why don't we simply prune those ill-typed COMPLETE sets from-'ResidualCompleteMatches'? The answer is that additional type constraints might-make more COMPLETE sets applicable! Example:+We assume that a COMPLETE set does not apply if for one of its+ConLikes we fail to 'matchConLikeResTy' or the+type of the match variable isn't an application of the optional+result type constructor from the pragma. Why don't we simply+prune inapplicable COMPLETE sets from 'ResidualCompleteMatches'?+The answer is that additional type constraints might make more+COMPLETE sets applicable! Example: - f :: a -> a :~: Boolean -> ()- f x Refl | T <- x = ()+ h :: a -> a :~: Boolean -> ()+ h x Refl | T <- x = () | F <- x = () If we eagerly prune {F,T} from the residual matches of @x@, then we don't see-that the match in the guards of @f@ is exhaustive, where the COMPLETE set+that the match in the guards of @h@ is exhaustive, where the COMPLETE set applies due to refined type information. -} @@ -248,11 +275,7 @@ -- | The return value of 'pmTopNormaliseType' data TopNormaliseTypeResult- = NoChange Type- -- ^ 'tcNormalise' failed to simplify the type and 'topNormaliseTypeX' was- -- unable to reduce the outermost type application, so the type came out- -- unchanged.- | NormalisedByConstraints Type+ = NormalisedByConstraints Type -- ^ 'tcNormalise' was able to simplify the type with some local constraint -- from the type oracle, but 'topNormaliseTypeX' couldn't identify a type -- redex.@@ -276,12 +299,10 @@ -- | Return the fields of 'HadRedexes'. Returns appropriate defaults in the -- other cases. tntrGuts :: TopNormaliseTypeResult -> (Type, [(Type, DataCon, Type)], Type)-tntrGuts (NoChange ty) = (ty, [], ty) tntrGuts (NormalisedByConstraints ty) = (ty, [], ty) tntrGuts (HadRedexes src_ty ds core_ty) = (src_ty, ds, core_ty) instance Outputable TopNormaliseTypeResult where- ppr (NoChange ty) = text "NoChange" <+> ppr ty ppr (NormalisedByConstraints ty) = text "NormalisedByConstraints" <+> ppr ty ppr (HadRedexes src_ty ds core_ty) = text "HadRedexes" <+> braces fields where@@ -311,17 +332,12 @@ -- Before proceeding, we chuck typ into the constraint solver, in case -- solving for given equalities may reduce typ some. See -- "Wrinkle: local equalities" in Note [Type normalisation].- (_, mb_typ') <- initTcDsForSolver $ tcNormalise inert typ- -- If tcNormalise didn't manage to simplify the type, continue anyway.- -- We might be able to reduce type applications nonetheless!- let typ' = fromMaybe typ mb_typ'+ typ' <- initTcDsForSolver $ tcNormalise inert typ -- Now we look with topNormaliseTypeX through type and data family -- applications and newtypes, which tcNormalise does not do. -- See also 'TopNormaliseTypeResult'. pure $ case topNormaliseTypeX (stepper env) comb typ' of- Nothing- | Nothing <- mb_typ' -> NoChange typ- | otherwise -> NormalisedByConstraints typ'+ Nothing -> NormalisedByConstraints typ' Just ((ty_f,tm_f), ty) -> HadRedexes src_ty newtype_dcs core_ty where src_ty = eq_src_ty ty (typ' : ty_f [ty])@@ -410,7 +426,6 @@ normaliseSourceTypeWHNF _ ty | isSourceTypeInWHNF ty = pure ty normaliseSourceTypeWHNF ty_st ty = pmTopNormaliseType ty_st ty >>= \case- NoChange ty -> pure ty NormalisedByConstraints ty -> pure ty HadRedexes ty _ _ -> pure ty @@ -424,7 +439,7 @@ | otherwise = False {- Note [Type normalisation]-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Constructs like -XEmptyCase or a previous unsuccessful pattern match on a data constructor place a non-void constraint on the matched thing. This means that it boils down to checking whether the type of the scrutinee is inhabited. Function@@ -680,11 +695,9 @@ | otherwise = do { evs <- traverse nameTyCt cts ; tracePm "tyOracle" (ppr cts $$ ppr inert)- ; (msgs, res) <- initTcDsForSolver $ tcCheckSatisfiability inert evs- ; case res of- -- return the new inert set and increment the sequence number n- Just mb_new_inert -> return (TySt (n+1) <$> mb_new_inert)- Nothing -> pprPanic "tyOracle" (vcat $ pprMsgEnvelopeBagWithLoc (getErrorMessages msgs)) }+ ; mb_new_inert <- initTcDsForSolver $ tcCheckGivens inert evs+ -- return the new inert set and increment the sequence number n+ ; return (TySt (n+1) <$> mb_new_inert) } -- | Allocates a fresh 'EvVar' name for 'PredTy's. nameTyCt :: PredType -> DsM EvVar@@ -1338,7 +1351,7 @@ go (PmAltConLike cl) = p cl go _ = False --- | @instCompleteSet fuel nabla nabla cls@ iterates over @cls@ until it finds+-- | @instCompleteSet fuel nabla x cls@ iterates over @cls@ until it finds -- the first inhabited ConLike (as per 'instCon'). Any failed instantiation -- attempts of a ConLike are recorded as negative information in the returned -- 'Nabla', so that later calls to this function can skip repeatedly fruitless@@ -1350,23 +1363,26 @@ -- entirely as an optimisation. instCompleteSet :: Int -> Nabla -> Id -> CompleteMatch -> MaybeT DsM Nabla instCompleteSet fuel nabla x cs- | anyConLikeSolution (`elementOfUniqDSet` cs) (vi_pos vi)+ | anyConLikeSolution (`elementOfUniqDSet` (cmConLikes cs)) (vi_pos vi) -- No need to instantiate a constructor of this COMPLETE set if we already -- have a solution! = pure nabla+ | not (completeMatchAppliesAtType (varType x) cs)+ = pure nabla | otherwise = go nabla (sorted_candidates cs) where vi = lookupVarInfo (nabla_tm_st nabla) x sorted_candidates :: CompleteMatch -> [ConLike]- sorted_candidates cs+ sorted_candidates cm -- If there aren't many candidates, we can try to sort them by number of -- strict fields, type constraints, etc., so that we are fast in the -- common case -- (either many simple constructors *or* few "complicated" ones). | sizeUniqDSet cs <= 5 = sortBy compareConLikeTestability (uniqDSetToList cs) | otherwise = uniqDSetToList cs+ where cs = cmConLikes cm go :: Nabla -> [ConLike] -> MaybeT DsM Nabla go _ [] = mzero@@ -1436,66 +1452,40 @@ unlifted_or_strict_fields dc = fast_length (dataConImplBangs dc) + fast_length (dataConUnliftedFieldTys dc) --- | @instCon fuel nabla (x::res_ty) K@ tries to instantiate @x@ to @K@.--- This is the \(Inst\) function from Figure 8 of the LYG paper.------ As a first step, it tries to guess the universal type arguments of @K@ from--- the @res_ty@ and @K@'s result type, so that we have------ K @arg_tys :: forall es. Q => t1 -> ... -> tn -> res_ty------ See 'guessConLikeUnivTyArgsFromResTy' for when it might fail to guess (only--- for certain pattern synonyms).--- If the function /fails/ to guess, 'instCon' trivially succeeds, because it--- can't be sure if @x@ could be instantiated to @K@ and has to be--- conservative).--- If the function /succeeds/ in guessing @arg_tys@, it does the necessary--- substitution and instantiation dance for @K@'s field types, which may still--- reference existential type variables of @K@. So it performs the following steps:------ * It accumulates a substitution mapping @K@'s universal type variables,--- which are substituted for @arg_tys@.--- * It instantiates fresh binders for the other type variables @es@ bound by--- @K@ and adds it to the substitution, so that we have--- @K \@arg_tys \@ex_tvs :: Q => t1' -> ... -> tn' -> res_ty@--- * It substitutes the 'ThetaType' @Q@ for type constraints @gammas@ to add--- * It substitutes and conjures new binders @arg_ids@ for the argument types--- @t1' ... tn'@.+-- | @instCon fuel nabla (x::match_ty) K@ tries to instantiate @x@ to @K@ by+-- adding the proper constructor constraint. ----- Finally, it adds a 'PhiConCt' constructor constraint--- @K ex_tvs gammas arg_ids <- x@ which handles the details regarding type--- constraints and unlifted fields.+-- See Note [Instantiating a ConLike]. instCon :: Int -> Nabla -> Id -> ConLike -> MaybeT DsM Nabla instCon fuel nabla@MkNabla{nabla_ty_st = ty_st} x con = MaybeT $ do env <- dsGetFamInstEnvs- let res_ty = idType x- norm_res_ty <- normaliseSourceTypeWHNF ty_st res_ty- let mb_arg_tys = guessConLikeUnivTyArgsFromResTy env norm_res_ty con- case mb_arg_tys of- Just arg_tys -> do- let (univ_tvs, ex_tvs, eq_spec, thetas, _req_theta, field_tys, _con_res_ty)+ let match_ty = idType x+ norm_match_ty <- normaliseSourceTypeWHNF ty_st match_ty+ mb_sigma_univ <- matchConLikeResTy env ty_st norm_match_ty con+ case mb_sigma_univ of+ Just sigma_univ -> do+ let (_univ_tvs, ex_tvs, eq_spec, thetas, _req_theta, field_tys, _con_res_ty) = conLikeFullSig con- -- (1) Substitute universals for type arguments- let subst_univ = zipTvSubst univ_tvs arg_tys- -- (2) Instantiate fresh existentials as arguments to the constructor.- -- This is important for instantiating the Thetas and field types.- (subst, _) <- cloneTyVarBndrs subst_univ ex_tvs <$> getUniqueSupplyM- let field_tys' = substTys subst $ map scaledThing field_tys- -- (3) All constraints bound by the constructor (alpha-renamed), these are added- -- to the type oracle- let gammas = substTheta subst (eqSpecPreds eq_spec ++ thetas)+ -- Following Note [Instantiating a ConLike]:+ -- (1) _req_theta has been tested in 'matchConLikeResTy'+ -- (2) Instantiate fresh existentials+ (sigma_ex, _) <- cloneTyVarBndrs sigma_univ ex_tvs <$> getUniqueSupplyM+ -- (3) Substitute provided constraints bound by the constructor.+ -- These are added to the type oracle as new facts (in a moment)+ let gammas = substTheta sigma_ex (eqSpecPreds eq_spec ++ thetas) -- (4) Instantiate fresh term variables as arguments to the constructor+ let field_tys' = substTys sigma_ex $ map scaledThing field_tys arg_ids <- mapM mkPmId field_tys' tracePm "instCon" $ vcat- [ ppr x <+> dcolon <+> ppr res_ty- , text "In WHNF:" <+> ppr (isSourceTypeInWHNF res_ty) <+> ppr norm_res_ty+ [ ppr x <+> dcolon <+> ppr match_ty+ , text "In WHNF:" <+> ppr (isSourceTypeInWHNF match_ty) <+> ppr norm_match_ty , ppr con <+> dcolon <+> text "... ->" <+> ppr _con_res_ty- , ppr (zipWith (\tv ty -> ppr tv <+> char '↦' <+> ppr ty) univ_tvs arg_tys)+ , ppr (map (\tv -> ppr tv <+> char '↦' <+> ppr (substTyVar sigma_univ tv)) _univ_tvs) , ppr gammas , ppr (map (\x -> ppr x <+> dcolon <+> ppr (idType x)) arg_ids) , ppr fuel ]- -- Finally add the constraint+ -- (5) Finally add the new constructor constraint runMaybeT $ do -- Case (2) of Note [Strict fields and variables of unlifted type] let alt = PmAltConLike con@@ -1506,38 +1496,34 @@ | branching_factor <= 1 = fuel | otherwise = min fuel 2 inhabitationTest new_fuel (nabla_ty_st nabla) nabla'- Nothing -> pure (Just nabla) -- Could not guess arg_tys. Just assume inhabited+ Nothing -> pure (Just nabla) -- Matching against match_ty failed. Inhabited!+ -- See Note [Instantiating a ConLike]. --- | Guess the universal argument types of a ConLike from an instantiation of--- its (normalised!) result type. So, given------ K :: forall us. forall es. Q => t1 -> ... -> tn -> con_res_ty------ It tries to guess @arg_tys@ by matching @norm_res_ty@ and @con_res_ty@, such that+-- | @matchConLikeResTy _ _ ty K@ tries to match @ty@ against the result+-- type of @K@, @res_ty@. It returns a substitution @s@ for @K@'s universal+-- tyvars such that @s(res_ty)@ equals @ty@ if successful. ----- K @arg_tys :: forall es. Q' => t1' -> ... -> tn' -> norm_res_ty+-- Make sure that @ty@ is normalised before. ----- Rather easy for DataCons, but not so much for PatSynCons. See Note [Pattern--- synonym result type] in "GHC.Core.PatSyn".-guessConLikeUnivTyArgsFromResTy :: FamInstEnvs -> Type -> ConLike -> Maybe [Type]-guessConLikeUnivTyArgsFromResTy env norm_res_ty (RealDataCon dc) = do- -- splitReprTyConApp_maybe rather than splitTyConApp_maybe because of data families.- (rep_tc, tc_args, _co) <- splitReprTyConApp_maybe env norm_res_ty+-- See Note [Matching against a ConLike result type].+matchConLikeResTy :: FamInstEnvs -> TyState -> Type -> ConLike -> DsM (Maybe TCvSubst)+matchConLikeResTy env _ ty (RealDataCon dc) = pure $ do+ (rep_tc, tc_args, _co) <- splitReprTyConApp_maybe env ty if rep_tc == dataConTyCon dc- then Just tc_args+ then Just (zipTCvSubst (dataConUnivTyVars dc) tc_args) else Nothing-guessConLikeUnivTyArgsFromResTy _ norm_res_ty (PatSynCon ps) = do- -- We are successful if we managed to instantiate *every* univ_tv of con.- -- This is difficult and bound to fail in some cases, see- -- Note [Pattern synonym result type] in GHC.Core.PatSyn. So we just try our best- -- here and be sure to return an instantiation when we can substitute every- -- universally quantified type variable.- -- We *could* instantiate all the other univ_tvs just to fresh variables, I- -- suppose, but that means we get weird field types for which we don't know- -- anything. So we prefer to keep it simple here.- let (univ_tvs,_,_,_,_,con_res_ty) = patSynSig ps- subst <- tcMatchTy con_res_ty norm_res_ty- traverse (lookupTyVar subst) univ_tvs+matchConLikeResTy _ (TySt _ inert) ty (PatSynCon ps) = runMaybeT $ do+ let (univ_tvs,req_theta,_,_,_,con_res_ty) = patSynSig ps+ subst <- MaybeT $ pure $ tcMatchTy con_res_ty ty+ guard $ all (`elemTCvSubst` subst) univ_tvs -- See the Note about T11336b+ if null req_theta+ then pure subst+ else do+ let req_theta' = substTys subst req_theta+ satisfiable <- lift $ initTcDsForSolver $ tcCheckWanteds inert req_theta'+ if satisfiable+ then pure subst+ else mzero {- Note [Soundness and completeness] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~@@ -1722,6 +1708,109 @@ on a constructor of a COMPLETE set, we filter out all of the DI ones. This fast path shaves down -7% allocations for PmSeriesG, for example.++Note [Matching against a ConLike result type]+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+Given a ConLike++> C :: forall us. R => ... -> res_ty++is a pattern `C ...` compatible with the type `ty`? Clearly that is the case if+`res_ty` /subsumes/ `ty` and the required constraints `R` (strictly a feature of+pattern synonyms) are satisfiable. In that case, 'matchConLikeResTy' returns a+substitution σ over `us` such that `σ(res_ty) == ty`.++It's surprisingly tricky to implement correctly, and works quite different for+DataCons and PatSynCons:++ * For data cons, we look at `ty` and see if it's a TyCon app `T t1 ... tn`.+ If that is the case, we make sure that `C` is a DataCon of `T` and return+ a substitution mapping `C`'s universal tyvars `us` to `t1`...`tn`.++ Wrinkle: Since `T` might be a data family TyCon, we have to look up its+ representation TyCon before we compare to `C`'s TyCon.+ So we use 'splitReprTyConApp_maybe' instead of 'splitTyConApp_maybe'.++ * For pattern synonyms, we directly match `ty` against `res_ty` to get the+ substitution σ. See Note [Pattern synonym result type] in "GHC.Core.PatSyn".++ Fortunately, we don't have to treat data family TyCons specially:+ Pattern synonyms /never/ apply to a data family representation TyCon.+ We do have to consider the required constraints `σ(R)`, though, as we have+ seen in #19475. That is done by solving them as Wanted constraints given the+ inert set of the current type state (which is part of a Nabla's TySt). Since+ spinning up a constraint solver session is costly, we only do so in the rare+ cases that a pattern synonym actually carries any required constraints.++ We can get into the strange situation that not all universal type variables+ `us` occur in `res_ty`. Example from T11336b:++ instance C Proxy where ... -- impl uninteresting+ pattern P :: forall f a. C f => f a -> Proxy a -- impl uninteresting++ fun :: Proxy a -> ()+ fun (P Proxy) = ()+ fun (P Proxy) = () -- ideally detected as redundant++ `f` is a universal type variable and `C f` the required constraint of+ pattern synonym `P`. But `f` doesn't occur in the result type `Proxy a` of+ `P`, so σ will not even have `f` in its in-scope set. It's a bit unclear+ what to do here; we might want to freshen `f` to `f'` and see if we can+ solve `C f'` as a Wanted constraint, which we most likely can't.+ Hence, we simply skip the freshening and declare the match as failed when+ there is a variable like `f`. For the definition of `fun`, that+ means we will not remember that we matched on `P` and thus will+ not detect its second clause as redundant.++ See Note [Pattern synonym result type] in "GHC.Core.PatSyn" for similar+ oddities.++Note [Instantiating a ConLike]+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+`instCon` implements the the \(Inst\) function from Figure 8 of the LYG paper.++Given the following type of ConLike `K`++> K :: forall us. R => forall es. P => t1 -> ... -> tn -> res_ty++and a variable `x::match_ty`, it tries to find an instantiation+`K ex_tvs gammas arg_ids :: match_ty` (for fresh `arg_ids`) and ultimately adds+a constructor constraint `K ex_tvs gammas arg_ids <- x` to the given Nabla.++As a first step, it tries (via 'matchConLikeResTy') to match `match_ty` against+`res_ty` and checks that that the required constraints @R@ are satisfiable.+See Note [Matching against a ConLike result type].++If matching /fails/, it trivially (and conservatively) reports "inhabited" by+returning the unrefined input Nabla. After all, the match might have failed due+to incomplete type information in Nabla.+(Type refinement from unpacking GADT constructors might monomorphise `match_ty`+so much that `res_ty` ultimately subsumes it.)++If matching /succeeds/, we get a substitution σ for the (universal)+tyvars `us`. After applying σ, we get++> K @σ(us) :: σ(R) => forall σ(es). σ(P) => σ(t1) -> ... -> σ(tn) -> match_ty++The existentials `es` might still occur in argument types `σ(tn)`, though.+Now 'instCon' performs the following steps:++ 1. It drops the required constraints `σ(R)`, as they have already been+ discharged by 'matchConLikeResTy'.+ 2. It instantiates fresh binders `es'` for the other type variables `es`+ bound by `K` and adds the mapping to σ to get σ', so that we have++ > K @σ(us) @es' :: σ'(P) => σ'(t1) -> ... -> σ'(tn) -> match_ty++ 3. It adds new type constraints from the substituted+ provided constraints @σ'(P)@.+ 4. It substitutes and conjures new binders @arg_ids@ for the argument types+ @σ'(t1) ... σ'(tn)@.+ 5. It adds a term constraint @K es' σ'(P) arg_ids <- x@, which handles+ the details regarding type constraints and unlifted fields.++And finally the extended 'Nabla' is returned if all the constraints were+compatible. -} --------------------------------------@@ -1779,8 +1868,8 @@ Nothing -> addCompleteMatches (vi_rcm vi) -- Test all COMPLETE sets for inhabitants (n inhs at max). Take care of ⊥.- clss <- pickApplicableCompleteSets rep_ty rcm- case NE.nonEmpty (uniqDSetToList <$> clss) of+ clss <- pickApplicableCompleteSets (nabla_ty_st nabla) rep_ty rcm+ case NE.nonEmpty (uniqDSetToList . cmConLikes <$> clss) of Nothing -> -- No COMPLETE sets ==> inhabited generateInhabitingPatterns xs n newty_nabla@@ -1830,13 +1919,26 @@ other_cons_nablas <- instantiate_cons x ty xs (n - length con_nablas) nabla cls pure (con_nablas ++ other_cons_nablas) -pickApplicableCompleteSets :: Type -> ResidualCompleteMatches -> DsM [CompleteMatch]-pickApplicableCompleteSets ty rcm = do- env <- dsGetFamInstEnvs- pure $ filter (all (is_valid env) . uniqDSetToList) (getRcm rcm)- where- is_valid :: FamInstEnvs -> ConLike -> Bool- is_valid env cl = isJust (guessConLikeUnivTyArgsFromResTy env ty cl)+pickApplicableCompleteSets :: TyState -> Type -> ResidualCompleteMatches -> DsM [CompleteMatch]+-- See Note [Implementation of COMPLETE pragmas] on what "applicable" means+pickApplicableCompleteSets ty_st ty rcm = do+ let cl_res_ty_ok :: ConLike -> DsM Bool+ cl_res_ty_ok cl = do+ env <- dsGetFamInstEnvs+ isJust <$> matchConLikeResTy env ty_st ty cl+ let cm_applicable :: CompleteMatch -> DsM Bool+ cm_applicable cm = do+ cls_ok <- allM cl_res_ty_ok (uniqDSetToList (cmConLikes cm))+ let match_ty_ok = completeMatchAppliesAtType ty cm+ pure (cls_ok && match_ty_ok)+ applicable_cms <- filterM cm_applicable (getRcm rcm)+ tracePm "pickApplicableCompleteSets:" $+ vcat+ [ ppr ty+ , ppr rcm+ , ppr applicable_cms+ ]+ return applicable_cms {- Note [Why inhabitationTest doesn't call generateInhabitingPatterns] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
compiler/GHC/HsToCore/Pmc/Solver/Types.hs view
@@ -61,10 +61,10 @@ import GHC.Builtin.Types.Prim import GHC.Tc.Solver.Monad (InertSet, emptyInert) import GHC.Tc.Utils.TcType (isStringTy)-import GHC.Types.CompleteMatch (CompleteMatch)-import GHC.Types.SourceText (mkFractionalLit, FractionalLit, fractionalLitFromRational,- FractionalExponentBase(..), SourceText(..))-+import GHC.Types.CompleteMatch (CompleteMatch(..))+import GHC.Types.SourceText (SourceText(..), mkFractionalLit, FractionalLit+ , fractionalLitFromRational+ , FractionalExponentBase(..)) import Numeric (fromRat) import Data.Foldable (find) import Data.Ratio@@ -368,7 +368,7 @@ data PmAltCon = PmAltConLike ConLike | PmAltLit PmLit -data PmAltConSet = PACS !CompleteMatch ![PmLit]+data PmAltConSet = PACS !(UniqDSet ConLike) ![PmLit] emptyPmAltConSet :: PmAltConSet emptyPmAltConSet = PACS emptyUniqDSet []
compiler/GHC/HsToCore/Quote.hs view
@@ -180,7 +180,7 @@ new_bit = mkNameEnv [(n, DsSplice (unLoc e)) | PendingTcSplice n e <- splices] - do_brack (VarBr _ _ n) = do { MkC e1 <- lookupOccDsM n ; return e1 }+ do_brack (VarBr _ _ n) = do { MkC e1 <- lookupOccDsM (unLoc n) ; return e1 } do_brack (ExpBr _ e) = runOverloaded $ do { MkC e1 <- repLE e ; return e1 } do_brack (PatBr _ p) = runOverloaded $ do { MkC p1 <- repTopP p ; return p1 } do_brack (TypBr _ t) = runOverloaded $ do { MkC t1 <- repLTy t ; return t1 }@@ -331,15 +331,15 @@ } where no_splice (L loc _)- = notHandledL loc "Splices within declaration brackets" empty+ = notHandledL (locA loc) "Splices within declaration brackets" empty no_default_decl (L loc decl)- = notHandledL loc "Default declarations" (ppr decl)+ = notHandledL (locA loc) "Default declarations" (ppr decl) no_warn :: LWarnDecl GhcRn -> MetaM a no_warn (L loc (Warning _ thing _))- = notHandledL loc "WARNING and DEPRECATION pragmas" $+ = notHandledL (locA loc) "WARNING and DEPRECATION pragmas" $ text "Pragma for declaration of" <+> ppr thing no_doc (L loc _)- = notHandledL loc "Haddock documentation" empty+ = notHandledL (locA loc) "Haddock documentation" empty hsScopedTvBinders :: HsValBinds GhcRn -> [Name] -- See Note [Scoped type variables in quotes]@@ -466,7 +466,7 @@ = do { tc1 <- lookupLOcc tc -- See note [Binders and occurrences] ; dec <- addTyClTyVarBinds tvs $ \bndrs -> repSynDecl tc1 bndrs rhs- ; return (Just (loc, dec)) }+ ; return (Just (locA loc, dec)) } repTyClD (L loc (DataDecl { tcdLName = tc , tcdTyVars = tvs@@ -474,7 +474,7 @@ = do { tc1 <- lookupLOcc tc -- See note [Binders and occurrences] ; dec <- addTyClTyVarBinds tvs $ \bndrs -> repDataDefn tc1 (Left bndrs) defn- ; return (Just (loc, dec)) }+ ; return (Just (locA loc, dec)) } repTyClD (L loc (ClassDecl { tcdCtxt = cxt, tcdLName = cls, tcdTyVars = tvs, tcdFDs = fds,@@ -491,7 +491,7 @@ ; decls1 <- repListM decTyConName return (ats1 ++ atds1 ++ sigs_binds) ; decls2 <- repClass cxt1 cls1 bndrs fds1 decls1 ; wrapGenSyms ss decls2 }- ; return $ Just (loc, dec)+ ; return $ Just (locA loc, dec) } -------------------------@@ -501,7 +501,7 @@ ; roles1 <- mapM repRole roles ; roles2 <- coreList roleTyConName roles1 ; dec <- repRoleAnnotD tycon1 roles2- ; return (loc, dec) }+ ; return (locA loc, dec) } ------------------------- repKiSigD :: LStandaloneKindSig GhcRn -> MetaM (SrcSpan, Core (M TH.Dec))@@ -511,7 +511,7 @@ MkC th_v <- lookupLOcc v MkC th_ki <- repHsSigType ki dec <- rep2 kiSigDName [th_v, th_ki]- pure (loc, dec)+ pure (locA loc, dec) ------------------------- repDataDefn :: Core TH.Name@@ -579,7 +579,7 @@ DataFamily -> do { kind <- repFamilyResultSigToMaybeKind resultSig ; repDataFamilyD tc1 bndrs kind }- ; return (loc, dec)+ ; return (locA loc, dec) } -- | Represent result signature of a type family@@ -607,7 +607,7 @@ -> MetaM (Core (Maybe TH.InjectivityAnn)) repInjectivityAnn Nothing = coreNothing injAnnTyConName-repInjectivityAnn (Just (L _ (InjectivityAnn lhs rhs))) =+repInjectivityAnn (Just (L _ (InjectivityAnn _ lhs rhs))) = do { lhs' <- lookupBinder (unLoc lhs) ; rhs1 <- mapM (lookupBinder . unLoc) rhs ; rhs2 <- coreList nameTyConName rhs1@@ -627,7 +627,7 @@ repLFunDeps fds = repList funDepTyConName repLFunDep fds repLFunDep :: LHsFunDep GhcRn -> MetaM (Core TH.FunDep)-repLFunDep (L _ (xs, ys))+repLFunDep (L _ (FunDep _ xs ys)) = do xs' <- repList nameTyConName (lookupBinder . unLoc) xs ys' <- repList nameTyConName (lookupBinder . unLoc) ys repFunDep xs' ys'@@ -637,13 +637,13 @@ repInstD :: LInstDecl GhcRn -> MetaM (SrcSpan, Core (M TH.Dec)) repInstD (L loc (TyFamInstD { tfid_inst = fi_decl })) = do { dec <- repTyFamInstD fi_decl- ; return (loc, dec) }+ ; return (locA loc, dec) } repInstD (L loc (DataFamInstD { dfid_inst = fi_decl })) = do { dec <- repDataFamInstD fi_decl- ; return (loc, dec) }+ ; return (locA loc, dec) } repInstD (L loc (ClsInstD { cid_inst = cls_decl })) = do { dec <- repClsInstD cls_decl- ; return (loc, dec) }+ ; return (locA loc, dec) } repClsInstD :: ClsInstDecl GhcRn -> MetaM (Core (M TH.Dec)) repClsInstD (ClsInstDecl { cid_poly_ty = ty, cid_binds = binds@@ -682,7 +682,7 @@ do { cxt' <- repLContext cxt ; inst_ty' <- repLTy inst_ty ; repDeriv strat' cxt' inst_ty' }- ; return (loc, dec) }+ ; return (locA loc, dec) } where (tvs, cxt, inst_ty) = splitLHsInstDeclTy (dropWildCards ty) @@ -742,7 +742,7 @@ checkTys tys@(HsValArg _: HsValArg _: _) = return tys checkTys _ = panic "repDataFamInstD:checkTys" -repForD :: Located (ForeignDecl GhcRn) -> MetaM (SrcSpan, Core (M TH.Dec))+repForD :: LForeignDecl GhcRn -> MetaM (SrcSpan, Core (M TH.Dec)) repForD (L loc (ForeignImport { fd_name = name, fd_sig_ty = typ , fd_fi = CImport (L _ cc) (L _ s) mch cis _ }))@@ -753,7 +753,7 @@ cis' <- conv_cimportspec cis MkC str <- coreStringLit (static ++ chStr ++ cis') dec <- rep2 forImpDName [cc', s', str, name', typ']- return (loc, dec)+ return (locA loc, dec) where conv_cimportspec (CLabel cls) = notHandled "Foreign label" (doubleQuotes (ppr cls))@@ -786,7 +786,7 @@ repSafety PlaySafe = rep2_nw safeName [] repLFixD :: LFixitySig GhcRn -> MetaM [(SrcSpan, Core (M TH.Dec))]-repLFixD (L loc fix_sig) = rep_fix_d loc fix_sig+repLFixD (L loc fix_sig) = rep_fix_d (locA loc) fix_sig rep_fix_d :: SrcSpan -> FixitySig GhcRn -> MetaM [(SrcSpan, Core (M TH.Dec))] rep_fix_d loc (FixitySig _ names (Fixity _ prec dir))@@ -825,7 +825,7 @@ ; rhs' <- repLE rhs ; repPragRule n' ty_bndrs' tm_bndrs' lhs' rhs' act' } ; wrapGenSyms ss rule }- ; return (loc, rule) }+ ; return (locA loc, rule) } ruleBndrNames :: LRuleBndr GhcRn -> [Name] ruleBndrNames (L _ (RuleBndr _ n)) = [unLoc n]@@ -835,10 +835,10 @@ repRuleBndr :: LRuleBndr GhcRn -> MetaM (Core (M TH.RuleBndr)) repRuleBndr (L _ (RuleBndr _ n))- = do { MkC n' <- lookupLBinder n+ = do { MkC n' <- lookupNBinder n ; rep2 ruleVarName [n'] } repRuleBndr (L _ (RuleBndrSig _ n sig))- = do { MkC n' <- lookupLBinder n+ = do { MkC n' <- lookupNBinder n ; MkC ty' <- repLTy (hsPatSigType sig) ; rep2 typedRuleVarName [n', ty'] } @@ -847,9 +847,9 @@ = do { target <- repAnnProv ann_prov ; exp' <- repE exp ; dec <- repPragAnn target exp'- ; return (loc, dec) }+ ; return (locA loc, dec) } -repAnnProv :: AnnProvenance Name -> MetaM (Core TH.AnnTarget)+repAnnProv :: AnnProvenance GhcRn -> MetaM (Core TH.AnnTarget) repAnnProv (ValueAnnProvenance n) = do { -- An ANN references an identifier bound elsewhere in the module, so -- we must look it up using lookupLOcc (#19377).@@ -868,13 +868,13 @@ repC :: LConDecl GhcRn -> MetaM (Core (M TH.Con)) repC (L _ (ConDeclH98 { con_name = con- , con_forall = (L _ False)+ , con_forall = False , con_mb_cxt = Nothing , con_args = args })) = repH98DataCon con args repC (L _ (ConDeclH98 { con_name = con- , con_forall = L _ is_existential+ , con_forall = is_existential , con_ex_tvs = con_tvs , con_mb_cxt = mcxt , con_args = args }))@@ -940,7 +940,7 @@ ------------------------------------------------------- repDerivs :: HsDeriving GhcRn -> MetaM (Core [M TH.DerivClause])-repDerivs (L _ clauses)+repDerivs clauses = repListM derivClauseTyConName repDerivClause clauses repDerivClause :: LHsDerivingClause GhcRn@@ -986,22 +986,22 @@ rep_sig :: LSig GhcRn -> MetaM [(SrcSpan, Core (M TH.Dec))] rep_sig (L loc (TypeSig _ nms ty))- = mapM (rep_wc_ty_sig sigDName loc ty) nms+ = mapM (rep_wc_ty_sig sigDName (locA loc) ty) nms rep_sig (L loc (PatSynSig _ nms ty))- = mapM (rep_patsyn_ty_sig loc ty) nms+ = mapM (rep_patsyn_ty_sig (locA loc) ty) nms rep_sig (L loc (ClassOpSig _ is_deflt nms ty))- | is_deflt = mapM (rep_ty_sig defaultSigDName loc ty) nms- | otherwise = mapM (rep_ty_sig sigDName loc ty) nms+ | is_deflt = mapM (rep_ty_sig defaultSigDName (locA loc) ty) nms+ | otherwise = mapM (rep_ty_sig sigDName (locA loc) ty) nms rep_sig d@(L _ (IdSig {})) = pprPanic "rep_sig IdSig" (ppr d)-rep_sig (L loc (FixSig _ fix_sig)) = rep_fix_d loc fix_sig-rep_sig (L loc (InlineSig _ nm ispec))= rep_inline nm ispec loc+rep_sig (L loc (FixSig _ fix_sig)) = rep_fix_d (locA loc) fix_sig+rep_sig (L loc (InlineSig _ nm ispec))= rep_inline nm ispec (locA loc) rep_sig (L loc (SpecSig _ nm tys ispec))- = concatMapM (\t -> rep_specialise nm t ispec loc) tys-rep_sig (L loc (SpecInstSig _ _ ty)) = rep_specialiseInst ty loc+ = concatMapM (\t -> rep_specialise nm t ispec (locA loc)) tys+rep_sig (L loc (SpecInstSig _ _ ty)) = rep_specialiseInst ty (locA loc) rep_sig (L _ (MinimalSig {})) = notHandled "MINIMAL pragmas" empty rep_sig (L _ (SCCFunSig {})) = notHandled "SCC pragmas" empty rep_sig (L loc (CompleteMatchSig _ _st cls mty))- = rep_complete_sig cls mty loc+ = rep_complete_sig cls mty (locA loc) -- Desugar the explicit type variable binders in an 'LHsSigType', making -- sure not to gensym them.@@ -1028,7 +1028,7 @@ -- deliberately avoids gensymming the type variables. -- See Note [Scoped type variables in quotes] -- and Note [Don't quantify implicit type variables in quotes]-rep_ty_sig :: Name -> SrcSpan -> LHsSigType GhcRn -> Located Name+rep_ty_sig :: Name -> SrcSpan -> LHsSigType GhcRn -> LocatedN Name -> MetaM (SrcSpan, Core (M TH.Dec)) rep_ty_sig mk_sig loc sig_ty nm = do { nm1 <- lookupLOcc nm@@ -1047,11 +1047,11 @@ = do { th_explicit_tvs <- rep_ty_sig_outer_tvs outer_bndrs ; th_ctxt <- repLContext ctxt ; th_tau <- repLTy tau- ; if nullOuterExplicit outer_bndrs && null (unLoc ctxt)+ ; if nullOuterExplicit outer_bndrs && null (fromMaybeContext ctxt) then return th_tau else repTForall th_explicit_tvs th_ctxt th_tau } -rep_patsyn_ty_sig :: SrcSpan -> LHsSigType GhcRn -> Located Name+rep_patsyn_ty_sig :: SrcSpan -> LHsSigType GhcRn -> LocatedN Name -> MetaM (SrcSpan, Core (M TH.Dec)) -- represents a pattern synonym type signature; -- see Note [Pattern synonym type signatures and Template Haskell] in "GHC.ThToHs"@@ -1073,12 +1073,12 @@ ; sig <- repProto patSynSigDName nm1 ty1 ; return (loc, sig) } -rep_wc_ty_sig :: Name -> SrcSpan -> LHsSigWcType GhcRn -> Located Name+rep_wc_ty_sig :: Name -> SrcSpan -> LHsSigWcType GhcRn -> LocatedN Name -> MetaM (SrcSpan, Core (M TH.Dec)) rep_wc_ty_sig mk_sig loc sig_ty nm = rep_ty_sig mk_sig loc (hswc_body sig_ty) nm -rep_inline :: Located Name+rep_inline :: LocatedN Name -> InlinePragma -- Never defaultInlinePragma -> SrcSpan -> MetaM [(SrcSpan, Core (M TH.Dec))]@@ -1091,7 +1091,7 @@ ; return [(loc, pragma)] } -rep_specialise :: Located Name -> LHsSigType GhcRn -> InlinePragma+rep_specialise :: LocatedN Name -> LHsSigType GhcRn -> InlinePragma -> SrcSpan -> MetaM [(SrcSpan, Core (M TH.Dec))] rep_specialise nm ty ispec loc@@ -1132,8 +1132,8 @@ ; dataCon' fromPhaseDataConName [arg] } repPhases _ = dataCon allPhasesDataConName -rep_complete_sig :: Located [Located Name]- -> Maybe (Located Name)+rep_complete_sig :: Located [LocatedN Name]+ -> Maybe (LocatedN Name) -> SrcSpan -> MetaM [(SrcSpan, Core (M TH.Dec))] rep_complete_sig (L _ cls) mty loc@@ -1294,8 +1294,9 @@ -- represent a type context ---repLContext :: LHsContext GhcRn -> MetaM (Core (M TH.Cxt))-repLContext ctxt = repContext (unLoc ctxt)+repLContext :: Maybe (LHsContext GhcRn) -> MetaM (Core (M TH.Cxt))+repLContext Nothing = repContext []+repLContext (Just ctxt) = repContext (unLoc ctxt) repContext :: HsContext GhcRn -> MetaM (Core (M TH.Cxt)) repContext ctxt = do preds <- repListM typeTyConName repLTy ctxt@@ -1307,7 +1308,7 @@ = addHsOuterSigTyVarBinds outer_bndrs $ \ th_outer_bndrs -> do { th_ctxt <- repLContext ctxt ; th_tau <- repLTy tau- ; if nullOuterExplicit outer_bndrs && null (unLoc ctxt)+ ; if nullOuterExplicit outer_bndrs && null (fromMaybeContext ctxt) then pure th_tau else repTForall th_outer_bndrs th_ctxt th_tau } @@ -1327,7 +1328,7 @@ -- handled separately in repTy. repForallT :: HsType GhcRn -> MetaM (Core (M TH.Type)) repForallT ty- | (tvs, ctxt, tau) <- splitLHsSigmaTyInvis (noLoc ty)+ | (tvs, ctxt, tau) <- splitLHsSigmaTyInvis (noLocA ty) = addHsTyVarBinds tvs $ \bndrs -> do { ctxt1 <- repLContext ctxt ; tau1 <- repLTy tau@@ -1472,7 +1473,7 @@ -- unless we can make sure that constructs, which are plainly not -- supported in TH already lead to error messages at an earlier stage repLE :: LHsExpr GhcRn -> MetaM (Core (M TH.Exp))-repLE (L loc e) = mapReaderT (putSrcSpanDs loc) (repE e)+repLE (L loc e) = mapReaderT (putSrcSpanDs (locA loc)) (repE e) repE :: HsExpr GhcRn -> MetaM (Core (M TH.Exp)) repE (HsVar _ (L _ x)) =@@ -1487,7 +1488,7 @@ repE (HsOverLabel _ s) = repOverLabel s repE e@(HsRecFld _ f) = case f of- Unambiguous x _ -> repE (HsVar noExtField (noLoc x))+ Unambiguous x _ -> repE (HsVar noExtField (noLocA x)) Ambiguous{} -> notHandled "Ambiguous record selectors" (ppr e) -- Remember, we're desugaring renamer output here, so@@ -1530,7 +1531,7 @@ = do { (binds, alts') <- liftM unzip $ mapM repLGRHS alts ; expr' <- repMultiIf (nonEmptyCoreList alts') ; wrapGenSyms (concat binds) expr' }-repE (HsLet _ (L _ bs) e) = do { (ss,ds) <- repBinds bs+repE (HsLet _ bs e) = do { (ss,ds) <- repBinds bs ; e2 <- addBinds ss (repLE e) ; z <- repLetE ds e2 ; wrapGenSyms ss z }@@ -1558,8 +1559,8 @@ repE (ExplicitList _ es) = do { xs <- repLEs es; repListExp xs } repE (ExplicitTuple _ es boxity) =- let tupArgToCoreExp :: LHsTupArg GhcRn -> MetaM (Core (Maybe (M TH.Exp)))- tupArgToCoreExp (L _ a)+ let tupArgToCoreExp :: HsTupArg GhcRn -> MetaM (Core (Maybe (M TH.Exp)))+ tupArgToCoreExp a | (Present _ e) <- a = do { e' <- repLE e ; coreJustM expTyConName e' } | otherwise = coreNothingM expTyConName@@ -1580,10 +1581,15 @@ = do { x <- lookupLOcc c; fs <- repFields flds; repRecCon x fs }-repE (RecordUpd { rupd_expr = e, rupd_flds = flds })+repE (RecordUpd { rupd_expr = e, rupd_flds = Left flds }) = do { x <- repLE e; fs <- repUpdFields flds; repRecUpd x fs }+repE (RecordUpd { rupd_flds = Right _ })+ = do+ -- Not possible due to elimination in the renamer. See Note+ -- [Handling overloaded and rebindable constructs]+ panic "The impossible has happened!" repE (ExprWithTySig _ e wc_ty) = addSimpleTyVarBinds (get_scoped_tvs_from_sig sig_ty) $@@ -1653,7 +1659,7 @@ repMatchTup :: LMatch GhcRn (LHsExpr GhcRn) -> MetaM (Core (M TH.Match)) repMatchTup (L _ (Match { m_pats = [p]- , m_grhss = GRHSs _ guards (L _ wheres) })) =+ , m_grhss = GRHSs _ guards wheres })) = do { ss1 <- mkGenSyms (collectPatBinders CollNoDictBinders p) ; addBinds ss1 $ do { ; p1 <- repLP p@@ -1666,7 +1672,7 @@ repClauseTup :: LMatch GhcRn (LHsExpr GhcRn) -> MetaM (Core (M TH.Clause)) repClauseTup (L _ (Match { m_pats = ps- , m_grhss = GRHSs _ guards (L _ wheres) })) =+ , m_grhss = GRHSs _ guards wheres })) = do { ss1 <- mkGenSyms (collectPatsBinders CollNoDictBinders ps) ; addBinds ss1 $ do { ps1 <- repLPs ps@@ -1756,7 +1762,7 @@ ; (ss2,zs) <- repSts ss ; z <- repBindSt p1 e2 ; return (ss1++ss2, z : zs) }}-repSts (LetStmt _ (L _ bs) : ss) =+repSts (LetStmt _ bs : ss) = do { (ss1,ds) <- repBinds bs ; z <- repLetSt ds ; (ss2,zs) <- addBinds ss1 (repSts ss)@@ -1785,11 +1791,11 @@ ; z <- repNoBindSt e2 ; return ([], [z]) } repSts (stmt@RecStmt{} : ss)- = do { let binders = collectLStmtsBinders CollNoDictBinders (recS_stmts stmt)+ = do { let binders = collectLStmtsBinders CollNoDictBinders (unLoc $ recS_stmts stmt) ; ss1 <- mkGenSyms binders -- Bring all of binders in the recursive group into scope for the -- whole group.- ; (ss1_other,rss) <- addBinds ss1 $ repSts (map unLoc (recS_stmts stmt))+ ; (ss1_other,rss) <- addBinds ss1 $ repSts (map unLoc (unLoc $ recS_stmts stmt)) ; MASSERT(sort ss1 == sort ss1_other) ; z <- repRecSt (nonEmptyCoreList rss) ; (ss2,zs) <- addBinds ss1 (repSts ss)@@ -1835,7 +1841,7 @@ panic "rep_implicit_param_bind: post typechecking" ; rhs' <- repE rhs ; ipb <- repImplicitParamBind name rhs'- ; return (loc, ipb) }+ ; return (locA loc, ipb) } rep_implicit_param_name :: HsIPName -> MetaM (Core String) rep_implicit_param_name (HsIPName name) = coreStringLit (unpackFS name)@@ -1863,31 +1869,31 @@ fun_matches = MG { mg_alts = (L _ [L _ (Match { m_pats = []- , m_grhss = GRHSs _ guards (L _ wheres) }+ , m_grhss = GRHSs _ guards wheres } )]) } })) = do { (ss,wherecore) <- repBinds wheres ; guardcore <- addBinds ss (repGuards guards)- ; fn' <- lookupLBinder fn+ ; fn' <- lookupNBinder fn ; p <- repPvar fn' ; ans <- repVal p guardcore wherecore ; ans' <- wrapGenSyms ss ans- ; return (loc, ans') }+ ; return (locA loc, ans') } rep_bind (L loc (FunBind { fun_id = fn , fun_matches = MG { mg_alts = L _ ms } })) = do { ms1 <- mapM repClauseTup ms- ; fn' <- lookupLBinder fn+ ; fn' <- lookupNBinder fn ; ans <- repFun fn' (nonEmptyCoreList ms1)- ; return (loc, ans) }+ ; return (locA loc, ans) } rep_bind (L loc (PatBind { pat_lhs = pat- , pat_rhs = GRHSs _ guards (L _ wheres) }))+ , pat_rhs = GRHSs _ guards wheres })) = do { patcore <- repLP pat ; (ss,wherecore) <- repBinds wheres ; guardcore <- addBinds ss (repGuards guards) ; ans <- repVal patcore guardcore wherecore ; ans' <- wrapGenSyms ss ans- ; return (loc, ans') }+ ; return (locA loc, ans') } rep_bind (L _ (VarBind { var_id = v, var_rhs = e})) = do { v' <- lookupBinder v@@ -1903,7 +1909,7 @@ , psb_args = args , psb_def = pat , psb_dir = dir })))- = do { syn' <- lookupLBinder syn+ = do { syn' <- lookupNBinder syn ; dir' <- repPatSynDir dir ; ss <- mkGenArgSyms args ; patSynD' <- addBinds ss (@@ -1911,7 +1917,7 @@ ; pat' <- repLP pat ; repPatSynD syn' args' dir' pat' }) ; patSynD'' <- wrapGenArgSyms args ss patSynD'- ; return (loc, patSynD'') }+ ; return (locA loc, patSynD'') } where mkGenArgSyms :: HsPatSynDetails GhcRn -> MetaM [GenSymBind] -- for Record Pattern Synonyms we want to conflate the selector@@ -2006,7 +2012,7 @@ repLambda :: LMatch GhcRn (LHsExpr GhcRn) -> MetaM (Core (M TH.Exp)) repLambda (L _ (Match { m_pats = ps , m_grhss = GRHSs _ [L _ (GRHS _ [] e)]- (L _ (EmptyLocalBinds _)) } ))+ (EmptyLocalBinds _) } )) = do { let bndrs = collectPatsBinders CollNoDictBinders ps ; ; ss <- mkGenSyms bndrs ; lam <- addBinds ss (@@ -2036,7 +2042,7 @@ repP (VarPat _ x) = do { x' <- lookupBinder (unLoc x); repPvar x' } repP (LazyPat _ p) = do { p1 <- repLP p; repPtilde p1 } repP (BangPat _ p) = do { p1 <- repLP p; repPbang p1 }-repP (AsPat _ x p) = do { x' <- lookupLBinder x; p1 <- repLP p+repP (AsPat _ x p) = do { x' <- lookupNBinder x; p1 <- repLP p ; repPaspat x' p1 } repP (ParPat _ p) = repLP p repP (ListPat Nothing ps) = do { qs <- repLPs ps; repPlist qs }@@ -2118,8 +2124,8 @@ -- Look up a locally bound name ---lookupLBinder :: Located Name -> MetaM (Core TH.Name)-lookupLBinder n = lookupBinder (unLoc n)+lookupNBinder :: LocatedN Name -> MetaM (Core TH.Name)+lookupNBinder n = lookupBinder (unLoc n) lookupBinder :: Name -> MetaM (Core TH.Name) lookupBinder = lookupOcc@@ -2133,7 +2139,7 @@ -- * If it is a global name, generate the "original name" representation (ie, -- the <module>:<name> form) for the associated entity ---lookupLOcc :: Located Name -> MetaM (Core TH.Name)+lookupLOcc :: GenLocated l Name -> MetaM (Core TH.Name) -- Lookup an occurrence; it can't be a splice. -- Use the in-scope bindings if they exist lookupLOcc n = lookupOcc (unLoc n)@@ -2524,14 +2530,14 @@ Nothing -> thing_inside =<< nothing Just ds -> case unLoc ds of- StockStrategy -> thing_inside =<< just =<< repStockStrategy- AnyclassStrategy -> thing_inside =<< just =<< repAnyclassStrategy- NewtypeStrategy -> thing_inside =<< just =<< repNewtypeStrategy- ViaStrategy ty -> addSimpleTyVarBinds (get_scoped_tvs_from_sig ty) $- do ty' <- rep_ty_sig' ty- via_strat <- repViaStrategy ty'- m_via_strat <- just via_strat- thing_inside m_via_strat+ StockStrategy _ -> thing_inside =<< just =<< repStockStrategy+ AnyclassStrategy _ -> thing_inside =<< just =<< repAnyclassStrategy+ NewtypeStrategy _ -> thing_inside =<< just =<< repNewtypeStrategy+ ViaStrategy ty -> addSimpleTyVarBinds (get_scoped_tvs_from_sig ty) $+ do ty' <- rep_ty_sig' ty+ via_strat <- repViaStrategy ty'+ m_via_strat <- just via_strat+ thing_inside m_via_strat where nothing = coreNothingM derivStrategyTyConName just = coreJustM derivStrategyTyConName@@ -2652,7 +2658,7 @@ repCtxt :: Core [(M TH.Pred)] -> MetaM (Core (M TH.Cxt)) repCtxt (MkC tys) = rep2 cxtName [tys] -repH98DataCon :: Located Name+repH98DataCon :: LocatedN Name -> HsConDeclH98Details GhcRn -> MetaM (Core (M TH.Con)) repH98DataCon con details@@ -2669,7 +2675,7 @@ arg_vtys <- repRecConArgs ips rep2 recCName [unC con', unC arg_vtys] -repGadtDataCons :: [Located Name]+repGadtDataCons :: [LocatedN Name] -> HsConDeclGADTDetails GhcRn -> LHsType GhcRn -> MetaM (Core (M TH.Con))@@ -2692,7 +2698,7 @@ repPrefixConArgs ps = repListM bangTypeTyConName repBangTy (map hsScaledThing ps) -- Desugar the arguments in a data constructor declared with record syntax.-repRecConArgs :: Located [LConDeclField GhcRn]+repRecConArgs :: LocatedL [LConDeclField GhcRn] -> MetaM (Core [M TH.VarBangType]) repRecConArgs ips = do args <- concatMapM rep_ip (unLoc ips)
compiler/GHC/HsToCore/Types.hs view
@@ -9,6 +9,7 @@ import Data.IORef import GHC.Types.CostCentre.State+import GHC.Types.Error import GHC.Types.Name.Env import GHC.Types.SrcLoc import GHC.Types.Var@@ -18,7 +19,6 @@ import GHC.HsToCore.Pmc.Types (Nablas) import GHC.Core (CoreExpr) import GHC.Core.FamInstEnv-import GHC.Utils.Error import GHC.Utils.Outputable as Outputable import GHC.Unit.Module import GHC.Driver.Hooks (DsForeignsHook)@@ -47,7 +47,7 @@ -- constructors are in scope during -- pattern-match satisfiability checking , ds_unqual :: PrintUnqualified- , ds_msgs :: IORef (Messages DecoratedSDoc) -- Warning messages+ , ds_msgs :: IORef (Messages DiagnosticMessage) -- Diagnostic messages , ds_if_env :: (IfGblEnv, IfLclEnv) -- Used for looking up global, -- possibly-imported things , ds_complete_matches :: CompleteMatches
compiler/GHC/HsToCore/Usage.hs view
@@ -213,7 +213,11 @@ (ppr pNm) _ -> mapM hashFile (nub files) _ -> do- foundM <- findPluginModule hsc_env pNm+ let fc = hsc_FC hsc_env+ let units = hsc_units hsc_env+ let home_unit = hsc_home_unit hsc_env+ let dflags = hsc_dflags hsc_env+ foundM <- findPluginModule fc units home_unit dflags pNm case foundM of -- The plugin was built locally: look up the object file containing -- the `plugin` binder, and all object files belong to modules that are@@ -225,6 +229,9 @@ _ -> pprPanic "mkPluginUsage: no object file found" (ppr pNm) where dflags = hsc_dflags hsc_env+ fc = hsc_FC hsc_env+ home_unit = hsc_home_unit hsc_env+ units = hsc_units hsc_env platform = targetPlatform dflags pkgs = hsc_units hsc_env pNm = moduleName $ mi_module pluginModule@@ -235,7 +242,7 @@ -- Lookup object file for a plugin dependency, -- from the same package as the plugin. lookupObjectFile nm = do- foundM <- findImportedModule hsc_env nm Nothing+ foundM <- findImportedModule fc units home_unit dflags nm Nothing case foundM of Found ml m | moduleUnit m == pPkg -> Just <$> hashFile (ml_obj_file ml)
compiler/GHC/HsToCore/Utils.hs view
@@ -30,6 +30,7 @@ wrapBind, wrapBinds, mkErrorAppDs, mkCoreAppDs, mkCoreAppsDs, mkCastDs,+ mkFailExpr, seqVar, @@ -78,6 +79,7 @@ import GHC.Utils.Outputable import GHC.Utils.Panic import GHC.Types.SrcLoc+import GHC.Types.Tickish import GHC.Utils.Misc import GHC.Driver.Session import GHC.Driver.Ppr@@ -411,6 +413,57 @@ return (mkApps (Var err_id) [Type (getRuntimeRep ty), Type ty, core_msg]) {-+Note [Incompleteness and linearity]+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+The default branch of an incomplete pattern match is compiled to a call+to 'error'.+Because of linearity, we wrap it with an empty case. Example:++f :: a %1 -> Bool -> a+f x True = False++Adding 'f x False = error "Non-exhaustive pattern..."' would violate+the linearity of x.+Instead, we use 'f x False = case error "Non-exhausive pattern..." :: () of {}'.+This case expression accounts for linear variables by assigning bottom usage+(See Note [Bottom as a usage] in GHC.Core.Multiplicity).+This is done in mkFailExpr.+We use '()' instead of the original return type ('a' in this case)+because there might be levity polymorphism, e.g. in++g :: forall (a :: TYPE r). (() -> a) %1 -> Bool -> a+g x True = x ()++adding 'g x False = case error "Non-exhaustive pattern" :: a of {}'+would create an illegal levity-polymorphic case binder.+This is important for pattern synonym matchers, which often look like this 'g'.++Similarly, a hole+h :: a %1 -> a+h x = _+is desugared to 'case error "Hole" :: () of {}'. Test: LinearHole.++Instead of () we could use Data.Void.Void, but that would require+moving Void to GHC.Types: partial pattern matching is used in modules+that are compiled before Data.Void.+We can use () even though it has a constructor, because+Note [Case expression invariants] point 4 in GHC.Core is satisfied+when the scrutinee is bottoming.++You might wonder if this change slows down compilation, but the+performance testsuite did not show up any regressions.++For uniformity, calls to 'error' in both cases are wrapped even if -XLinearTypes+is disabled.+-}++mkFailExpr :: HsMatchContext GhcRn -> Type -> DsM CoreExpr+mkFailExpr ctxt ty+ = do fail_expr <- mkErrorAppDs pAT_ERROR_ID unitTy (matchContextErrString ctxt)+ return $ mkWildCase fail_expr (unrestricted unitTy) ty []+ -- See Note [Incompleteness and linearity]++{- 'mkCoreAppDs' and 'mkCoreAppsDs' handle the special-case desugaring of 'seq'. Note [Desugaring seq]@@ -676,9 +729,9 @@ -} -- Remark: pattern selectors only occur in unrestricted patterns so we are free -- to select Many as the multiplicity of every let-expression introduced.-mkSelectorBinds :: [[Tickish Id]] -- ^ ticks to add, possibly- -> LPat GhcTc -- ^ The pattern- -> CoreExpr -- ^ Expression to which the pattern is bound+mkSelectorBinds :: [[CoreTickish]] -- ^ ticks to add, possibly+ -> LPat GhcTc -- ^ The pattern+ -> CoreExpr -- ^ Expression to which the pattern is bound -> DsM (Id,[(Id,CoreExpr)]) -- ^ Id the rhs is bound to, for desugaring strict -- binds (see Note [Desugar Strict binds] in "GHC.HsToCore.Binds")@@ -768,7 +821,7 @@ ********************************************************************* -} mkLHsPatTup :: [LPat GhcTc] -> LPat GhcTc-mkLHsPatTup [] = noLoc $ mkVanillaTuplePat [] Boxed+mkLHsPatTup [] = noLocA $ mkVanillaTuplePat [] Boxed mkLHsPatTup [lpat] = lpat mkLHsPatTup lpats = L (getLoc (head lpats)) $ mkVanillaTuplePat lpats Boxed@@ -782,7 +835,7 @@ mkBigLHsVarTupId ids = mkBigLHsTupId (map nlHsVar ids) mkBigLHsTupId :: [LHsExpr GhcTc] -> LHsExpr GhcTc-mkBigLHsTupId = mkChunkified mkLHsTupleExpr+mkBigLHsTupId = mkChunkified (\e -> mkLHsTupleExpr e noExtField) -- The Big equivalents for the source tuple patterns mkBigLHsVarPatTupId :: [Id] -> LPat GhcTc@@ -928,9 +981,10 @@ fail_expr <- dsSyntaxExpr fail_op [fail_msg] body fail_expr -mk_fail_msg :: DynFlags -> HsStmtContext GhcRn -> Located e -> String+mk_fail_msg :: DynFlags -> HsStmtContext GhcRn -> LocatedA e -> String mk_fail_msg dflags ctx pat- = showPpr dflags $ text "Pattern match failure in" <+> pprStmtContext ctx <+> text "at" <+> ppr (getLoc pat)+ = showPpr dflags $ text "Pattern match failure in" <+> pprStmtContext ctx+ <+> text "at" <+> ppr (getLocA pat) {- ********************************************************************* * *@@ -938,7 +992,7 @@ * * ********************************************************************* -} -mkOptTickBox :: [Tickish Id] -> CoreExpr -> CoreExpr+mkOptTickBox :: [CoreTickish] -> CoreExpr -> CoreExpr mkOptTickBox = flip (foldr Tick) mkBinaryTickBox :: Int -> Int -> CoreExpr -> DsM CoreExpr
compiler/GHC/Iface/Binary.hs view
@@ -13,7 +13,6 @@ -- * Public API for interface file serialisation writeBinIface, readBinIface,- readBinIface_, getSymtabName, getDictFastString, CheckHiWay(..),@@ -29,7 +28,6 @@ putSymbolTable, BinSymbolTable(..), BinDictionary(..)- ) where #include "GhclibHsVersions.h"@@ -38,38 +36,31 @@ import GHC.Tc.Utils.Monad import GHC.Builtin.Utils ( isKnownKeyName, lookupKnownKeyName )-import GHC.Iface.Env import GHC.Unit import GHC.Unit.Module.ModIface import GHC.Types.Name-import GHC.Driver.Session import GHC.Platform.Profile import GHC.Types.Unique.FM-import GHC.Types.Unique.Supply import GHC.Utils.Panic import GHC.Utils.Binary as Binary-import GHC.Types.SrcLoc import GHC.Data.FastMutInt import GHC.Types.Unique import GHC.Utils.Outputable import GHC.Types.Name.Cache+import GHC.Types.SrcLoc import GHC.Platform import GHC.Data.FastString import GHC.Settings.Constants import GHC.Utils.Misc import Data.Array-import Data.Array.ST+import Data.Array.IO import Data.Array.Unsafe import Data.Bits import Data.Char import Data.Word import Data.IORef-import Data.Foldable import Control.Monad-import Control.Monad.ST-import Control.Monad.Trans.Class-import qualified Control.Monad.Trans.State.Strict as State -- --------------------------------------------------------------------------- -- Reading and writing binary interface files@@ -82,20 +73,15 @@ = TraceBinIFace (SDoc -> IO ()) | QuietBinIFace --- | Read an interface file-readBinIface :: CheckHiWay -> TraceBinIFace -> FilePath- -> TcRnIf a b ModIface-readBinIface checkHiWay traceBinIFaceReading hi_path = do- ncu <- mkNameCacheUpdater- dflags <- getDynFlags- let profile = targetProfile dflags- liftIO $ readBinIface_ profile checkHiWay traceBinIFaceReading hi_path ncu---- | Read an interface file in 'IO'.-readBinIface_ :: Profile -> CheckHiWay -> TraceBinIFace -> FilePath- -> NameCacheUpdater- -> IO ModIface-readBinIface_ profile checkHiWay traceBinIFace hi_path ncu = do+-- | Read an interface file.+readBinIface+ :: Profile+ -> NameCache+ -> CheckHiWay+ -> TraceBinIFace+ -> FilePath+ -> IO ModIface+readBinIface profile name_cache checkHiWay traceBinIFace hi_path = do let platform = profilePlatform profile wantedGot :: String -> a -> a -> (a -> SDoc) -> IO ()@@ -138,7 +124,7 @@ extFields_p <- get bh - mod_iface <- getWithUserData ncu bh+ mod_iface <- getWithUserData name_cache bh seekBin bh extFields_p extFields <- get bh@@ -149,8 +135,8 @@ -- | This performs a get action after reading the dictionary and symbol -- table. It is necessary to run this before trying to deserialise any -- Names or FastStrings.-getWithUserData :: Binary a => NameCacheUpdater -> BinHandle -> IO a-getWithUserData ncu bh = do+getWithUserData :: Binary a => NameCache -> BinHandle -> IO a+getWithUserData name_cache bh = do -- Read the dictionary -- The next word in the file is a pointer to where the dictionary is -- (probably at the end of the file)@@ -167,11 +153,11 @@ symtab_p <- Binary.get bh -- Get the symtab ptr data_p <- tellBin bh -- Remember where we are now seekBin bh symtab_p- symtab <- getSymbolTable bh ncu+ symtab <- getSymbolTable bh name_cache seekBin bh data_p -- Back to where we were before -- It is only now that we know how to get a Name- return $ setUserData bh $ newReadState (getSymtabName ncu dict symtab)+ return $ setUserData bh $ newReadState (getSymtabName name_cache dict symtab) (getDictFastString dict) -- Read the interface file@@ -217,14 +203,12 @@ symtab_p_p <- tellBin bh put_ bh symtab_p_p -- Make some initial state- symtab_next <- newFastMutInt- writeFastMutInt symtab_next 0+ symtab_next <- newFastMutInt 0 symtab_map <- newIORef emptyUFM let bin_symtab = BinSymbolTable { bin_symtab_next = symtab_next, bin_symtab_map = symtab_map }- dict_next_ref <- newFastMutInt- writeFastMutInt dict_next_ref 0+ dict_next_ref <- newFastMutInt 0 dict_map_ref <- newIORef emptyUFM let bin_dict = BinDictionary { bin_dict_next = dict_next_ref,@@ -293,38 +277,27 @@ -- indices that array uses to create order mapM_ (\n -> serialiseName bh n symtab) names -getSymbolTable :: BinHandle -> NameCacheUpdater -> IO SymbolTable-getSymbolTable bh ncu = do- sz <- get bh- od_names <- sequence (replicate sz (get bh))- updateNameCache ncu $ \namecache ->- runST $ flip State.evalStateT namecache $ do- mut_arr <- lift $ newSTArray_ (0, sz-1)- for_ (zip [0..] od_names) $ \(i, odn) -> do- (nc, !n) <- State.gets $ \nc -> fromOnDiskName nc odn- lift $ writeArray mut_arr i n- State.put nc- arr <- lift $ unsafeFreeze mut_arr- namecache' <- State.get- return (namecache', arr)- where- -- This binding is required because the type of newArray_ cannot be inferred- newSTArray_ :: forall s. (Int, Int) -> ST s (STArray s Int Name)- newSTArray_ = newArray_ -type OnDiskName = (Unit, ModuleName, OccName)--fromOnDiskName :: NameCache -> OnDiskName -> (NameCache, Name)-fromOnDiskName nc (pid, mod_name, occ) =- let mod = mkModule pid mod_name- cache = nsNames nc- in case lookupOrigNameCache cache mod occ of- Just name -> (nc, name)- Nothing ->- let (uniq, us) = takeUniqFromSupply (nsUniqs nc)- name = mkExternalName uniq mod occ noSrcSpan- new_cache = extendNameCache cache mod occ name- in ( nc{ nsUniqs = us, nsNames = new_cache }, name )+getSymbolTable :: BinHandle -> NameCache -> IO SymbolTable+getSymbolTable bh name_cache = do+ sz <- get bh :: IO Int+ -- create an array of Names for the symbols and add them to the NameCache+ updateNameCache' name_cache $ \cache0 -> do+ mut_arr <- newArray_ (0, sz-1) :: IO (IOArray Int Name)+ cache <- foldGet (fromIntegral sz) bh cache0 $ \i (uid, mod_name, occ) cache -> do+ let mod = mkModule uid mod_name+ case lookupOrigNameCache cache mod occ of+ Just name -> do+ writeArray mut_arr (fromIntegral i) name+ return cache+ Nothing -> do+ uniq <- takeUniqFromNameCache name_cache+ let name = mkExternalName uniq mod occ noSrcSpan+ new_cache = extendOrigNameCache cache mod occ name+ writeArray mut_arr (fromIntegral i) name+ return new_cache+ arr <- unsafeFreeze mut_arr+ return (cache, arr) serialiseName :: BinHandle -> Name -> UniqFM key (Int,Name) -> IO () serialiseName bh name _ = do@@ -375,10 +348,10 @@ put_ bh (fromIntegral off :: Word32) -- See Note [Symbol table representation of names]-getSymtabName :: NameCacheUpdater+getSymtabName :: NameCache -> Dictionary -> SymbolTable -> BinHandle -> IO Name-getSymtabName _ncu _dict symtab bh = do+getSymtabName _name_cache _dict symtab bh = do i :: Word32 <- get bh case i .&. 0xC0000000 of 0x00000000 -> return $! symtab ! fromIntegral i
compiler/GHC/Iface/Env.hs view
@@ -1,12 +1,12 @@ -- (c) The University of Glasgow 2002-2006 -{-# LANGUAGE CPP, RankNTypes, BangPatterns #-}+{-# LANGUAGE CPP, RankNTypes #-} module GHC.Iface.Env ( newGlobalBinder, newInteractiveBinder, externaliseName, lookupIfaceTop,- lookupOrig, lookupOrigIO, lookupOrigNameCache, extendNameCache,+ lookupOrig, lookupOrigIO, lookupOrigNameCache, newIfaceName, newIfaceNames, extendIfaceIdEnv, extendIfaceTyVarEnv, tcIfaceLclId, tcIfaceTyVar, lookupIfaceVar,@@ -15,9 +15,10 @@ ifaceExportNames, + trace_if, trace_hi_diffs,+ -- Name-cache stuff- allocateGlobalBinder, updNameCacheTc, updNameCache,- mkNameCacheUpdater, NameCacheUpdater(..),+ allocateGlobalBinder, ) where #include "GhclibHsVersions.h"@@ -25,6 +26,7 @@ import GHC.Prelude import GHC.Driver.Env+import GHC.Driver.Session import GHC.Tc.Utils.Monad import GHC.Core.Type@@ -45,8 +47,11 @@ import GHC.Types.SrcLoc import GHC.Utils.Outputable+import GHC.Utils.Error+import GHC.Utils.Logger+ import Data.List ( partition )-import Data.IORef+import Control.Monad {- *********************************************************@@ -68,8 +73,8 @@ -- moment when we know its Module and SrcLoc in their full glory newGlobalBinder mod occ loc- = do { name <- updNameCacheTc mod occ $ \name_cache ->- allocateGlobalBinder name_cache mod occ loc+ = do { hsc_env <- getTopEnv+ ; name <- liftIO $ allocateGlobalBinder (hsc_NC hsc_env) mod occ loc ; traceIf (text "newGlobalBinder" <+> (vcat [ ppr mod <+> ppr occ <+> ppr loc, ppr name])) ; return name }@@ -77,18 +82,18 @@ newInteractiveBinder :: HscEnv -> OccName -> SrcSpan -> IO Name -- Works in the IO monad, and gets the Module -- from the interactive context-newInteractiveBinder hsc_env occ loc- = do { let mod = icInteractiveModule (hsc_IC hsc_env)- ; updNameCacheIO hsc_env mod occ $ \name_cache ->- allocateGlobalBinder name_cache mod occ loc }+newInteractiveBinder hsc_env occ loc = do+ let mod = icInteractiveModule (hsc_IC hsc_env)+ allocateGlobalBinder (hsc_NC hsc_env) mod occ loc allocateGlobalBinder :: NameCache -> Module -> OccName -> SrcSpan- -> (NameCache, Name)+ -> IO Name -- See Note [The Name Cache] in GHC.Types.Name.Cache-allocateGlobalBinder name_supply mod occ loc- = case lookupOrigNameCache (nsNames name_supply) mod occ of+allocateGlobalBinder nc mod occ loc+ = updateNameCache nc mod occ $ \cache0 -> do+ case lookupOrigNameCache cache0 mod occ of -- A hit in the cache! We are at the binding site of the name. -- This is the moment when we know the SrcLoc -- of the Name, so we set this field in the Name we return.@@ -106,62 +111,26 @@ -- and their Module is correct. Just name | isWiredInName name- -> (name_supply, name)+ -> pure (cache0, name) | otherwise- -> (new_name_supply, name')+ -> pure (new_cache, name') where- uniq = nameUnique name- name' = mkExternalName uniq mod occ loc- -- name' is like name, but with the right SrcSpan- new_cache = extendNameCache (nsNames name_supply) mod occ name'- new_name_supply = name_supply {nsNames = new_cache}+ uniq = nameUnique name+ name' = mkExternalName uniq mod occ loc+ -- name' is like name, but with the right SrcSpan+ new_cache = extendOrigNameCache cache0 mod occ name' -- Miss in the cache! -- Build a completely new Name, and put it in the cache- _ -> (new_name_supply, name)- where- (uniq, us') = takeUniqFromSupply (nsUniqs name_supply)- name = mkExternalName uniq mod occ loc- new_cache = extendNameCache (nsNames name_supply) mod occ name- new_name_supply = name_supply {nsUniqs = us', nsNames = new_cache}+ _ -> do+ uniq <- takeUniqFromNameCache nc+ let name = mkExternalName uniq mod occ loc+ let new_cache = extendOrigNameCache cache0 mod occ name+ pure (new_cache, name) ifaceExportNames :: [IfaceExport] -> TcRnIf gbl lcl [AvailInfo] ifaceExportNames exports = return exports --- | A function that atomically updates the name cache given a modifier--- function. The second result of the modifier function will be the result--- of the IO action.-newtype NameCacheUpdater- = NCU { updateNameCache :: forall c. (NameCache -> (NameCache, c)) -> IO c }--mkNameCacheUpdater :: TcRnIf a b NameCacheUpdater-mkNameCacheUpdater = do { hsc_env <- getTopEnv- ; let !ncRef = hsc_NC hsc_env- ; return (NCU (updNameCache ncRef)) }--updNameCacheTc :: Module -> OccName -> (NameCache -> (NameCache, c))- -> TcRnIf a b c-updNameCacheTc mod occ upd_fn = do {- hsc_env <- getTopEnv- ; liftIO $ updNameCacheIO hsc_env mod occ upd_fn }---updNameCacheIO :: HscEnv -> Module -> OccName- -> (NameCache -> (NameCache, c))- -> IO c-updNameCacheIO hsc_env mod occ upd_fn = do {-- -- First ensure that mod and occ are evaluated- -- If not, chaos can ensue:- -- we read the name-cache- -- then pull on mod (say)- -- which does some stuff that modifies the name cache- -- This did happen, with tycon_mod in GHC.IfaceToCore.tcIfaceAlt (DataAlt..)-- mod `seq` occ `seq` return ()- ; updNameCache (hsc_NC hsc_env) upd_fn }-- {- ************************************************************************ * *@@ -174,32 +143,30 @@ -- Consider alternatively using 'lookupIfaceTop' if you're in the 'IfL' monad -- and 'Module' is simply that of the 'ModIface' you are typechecking. lookupOrig :: Module -> OccName -> TcRnIf a b Name-lookupOrig mod occ- = do { traceIf (text "lookup_orig" <+> ppr mod <+> ppr occ)-- ; updNameCacheTc mod occ $ lookupNameCache mod occ }+lookupOrig mod occ = do+ hsc_env <- getTopEnv+ traceIf (text "lookup_orig" <+> ppr mod <+> ppr occ)+ liftIO $ lookupNameCache (hsc_NC hsc_env) mod occ lookupOrigIO :: HscEnv -> Module -> OccName -> IO Name lookupOrigIO hsc_env mod occ- = updNameCacheIO hsc_env mod occ $ lookupNameCache mod occ+ = lookupNameCache (hsc_NC hsc_env) mod occ -lookupNameCache :: Module -> OccName -> NameCache -> (NameCache, Name)+lookupNameCache :: NameCache -> Module -> OccName -> IO Name -- Lookup up the (Module,OccName) in the NameCache -- If you find it, return it; if not, allocate a fresh original name and extend -- the NameCache. -- Reason: this may the first occurrence of (say) Foo.bar we have encountered. -- If we need to explore its value we will load Foo.hi; but meanwhile all we -- need is a Name for it.-lookupNameCache mod occ name_cache =- case lookupOrigNameCache (nsNames name_cache) mod occ of {- Just name -> (name_cache, name);- Nothing ->- case takeUniqFromSupply (nsUniqs name_cache) of {- (uniq, us) ->- let- name = mkExternalName uniq mod occ noSrcSpan- new_cache = extendNameCache (nsNames name_cache) mod occ name- in (name_cache{ nsUniqs = us, nsNames = new_cache }, name) }}+lookupNameCache nc mod occ = updateNameCache nc mod occ $ \cache0 ->+ case lookupOrigNameCache cache0 mod occ of+ Just name -> pure (cache0, name)+ Nothing -> do+ uniq <- takeUniqFromNameCache nc+ let name = mkExternalName uniq mod occ noSrcSpan+ let new_cache = extendOrigNameCache cache0 mod occ name+ pure (new_cache, name) externaliseName :: Module -> Name -> TcRnIf m n Name -- Take an Internal Name and make it an External one,@@ -209,10 +176,11 @@ loc = nameSrcSpan name uniq = nameUnique name ; occ `seq` return () -- c.f. seq in newGlobalBinder- ; updNameCacheTc mod occ $ \ ns ->- let name' = mkExternalName uniq mod occ loc- ns' = ns { nsNames = extendNameCache (nsNames ns) mod occ name' }- in (ns', name') }+ ; hsc_env <- getTopEnv+ ; liftIO $ updateNameCache (hsc_NC hsc_env) mod occ $ \cache -> do+ let name' = mkExternalName uniq mod occ loc+ cache' = extendOrigNameCache cache mod occ name'+ pure (cache', name') } -- | Set the 'Module' of a 'Name'. setNameModule :: Maybe Module -> Name -> TcRnIf m n Name@@ -304,19 +272,10 @@ ; return [ mkInternalName uniq occ noSrcSpan | (occ,uniq) <- occs `zip` uniqsFromSupply uniqs] } -{--Names in a NameCache are always stored as a Global, and have the SrcLoc-of their binding locations.--Actually that's not quite right. When we first encounter the original-name, we might not be at its binding site (e.g. we are reading an-interface file); so we give it 'noSrcLoc' then. Later, when we find-its binding site, we fix it up.--}--updNameCache :: IORef NameCache- -> (NameCache -> (NameCache, c)) -- The updating function- -> IO c-updNameCache ncRef upd_fn- = atomicModifyIORef' ncRef upd_fn+trace_if :: Logger -> DynFlags -> SDoc -> IO ()+{-# INLINE trace_if #-}+trace_if logger dflags doc = when (dopt Opt_D_dump_if_trace dflags) $ putMsg logger dflags doc +trace_hi_diffs :: Logger -> DynFlags -> SDoc -> IO ()+{-# INLINE trace_hi_diffs #-}+trace_hi_diffs logger dflags doc = when (dopt Opt_D_dump_hi_diffs dflags) $ putMsg logger dflags doc
compiler/GHC/Iface/Ext/Ast.hs view
@@ -1,5 +1,6 @@ {-# LANGUAGE AllowAmbiguousTypes #-} {-# LANGUAGE CPP #-}+{-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE FlexibleContexts #-}@@ -30,7 +31,7 @@ import GHC.Data.Bag ( Bag, bagToList ) import GHC.Types.Basic import GHC.Data.BooleanFormula-import GHC.Core.Class ( FunDep, className, classSCSelIds )+import GHC.Core.Class ( className, classSCSelIds ) import GHC.Core.Utils ( exprType ) import GHC.Core.ConLike ( conLikeName, ConLike(RealDataCon) ) import GHC.Core.TyCon ( TyCon, tyConClass_maybe )@@ -348,10 +349,12 @@ modulify (HiePath file) xs' = do - top_ev_asts <-+ top_ev_asts :: [HieAST Type] <- do+ let+ l :: SrcSpanAnnA+ l = noAnnSrcSpan (RealSrcSpan (realSrcLocSpan $ mkRealSrcLoc file 1 1) Nothing) toHie $ EvBindContext ModuleScope Nothing- $ L (RealSrcSpan (realSrcLocSpan $ mkRealSrcLoc file 1 1) Nothing)- $ EvBinds ev_bs+ $ L l (EvBinds ev_bs) (uloc_evs,more_ev_asts) <- getUnlocatedEvBinds file @@ -390,12 +393,17 @@ , toHie $ hs_ruleds grp ] +getRealSpanA :: SrcSpanAnn' ann -> Maybe Span+getRealSpanA la = getRealSpan (locA la)+ getRealSpan :: SrcSpan -> Maybe Span getRealSpan (RealSrcSpan sp _) = Just sp getRealSpan _ = Nothing -grhss_span :: GRHSs (GhcPass p) body -> SrcSpan-grhss_span (GRHSs _ xs bs) = foldl' combineSrcSpans (getLoc bs) (map getLoc xs)+grhss_span :: (Anno (GRHS (GhcPass p) (LocatedA (body (GhcPass p)))) ~ SrcSpan+ , Data (HsLocalBinds (GhcPass p)))+ => GRHSs (GhcPass p) (LocatedA (body (GhcPass p))) -> SrcSpan+grhss_span (GRHSs _ xs bs) = foldl' combineSrcSpans (spanHsLocaLBinds bs) (map getLoc xs) bindingsOnly :: [Context Name] -> HieM [HieAST a] bindingsOnly [] = pure []@@ -468,13 +476,13 @@ -- things to its right, ala RScoped -- | Each element scopes over the elements to the right-listScopes :: Scope -> [Located a] -> [RScoped (Located a)]+listScopes :: Scope -> [LocatedA a] -> [RScoped (LocatedA a)] listScopes _ [] = [] listScopes rhsScope [pat] = [RS rhsScope pat] listScopes rhsScope (pat : pats) = RS sc pat : pats' where pats'@((RS scope p):_) = listScopes rhsScope pats- sc = combineScopes scope $ mkScope $ getLoc p+ sc = combineScopes scope $ mkScope $ getLocA p -- | 'listScopes' specialised to 'PScoped' things patScopes@@ -536,11 +544,17 @@ instance HasLoc (Located a) where loc (L l _) = l +instance HasLoc (LocatedA a) where+ loc (L la _) = locA la++instance HasLoc (LocatedN a) where+ loc (L la _) = locA la+ instance HasLoc a => HasLoc [a] where loc [] = noSrcSpan loc xs = foldl1' combineSrcSpans $ map loc xs -instance HasLoc a => HasLoc (FamEqn (GhcPass s) a) where+instance (HasLoc a, HiePass p) => HasLoc (FamEqn (GhcPass p) a) where loc (FamEqn _ a outer_bndrs b _ c) = case outer_bndrs of HsOuterImplicit{} -> foldl1' combineSrcSpans [loc a, loc b, loc c]@@ -587,6 +601,12 @@ idents = M.singleton (Left mname) details toHie _ = pure [] +instance ToHie (Context (Located a)) => ToHie (Context (LocatedN a)) where+ toHie (C c (L l a)) = toHie (C c (L (locA l) a))++instance ToHie (Context (Located a)) => ToHie (Context (LocatedA a)) where+ toHie (C c (L l a)) = toHie (C c (L (locA l) a))+ instance ToHie (Context (Located Var)) where toHie c = case c of C context (L (RealSrcSpan span _) name')@@ -645,7 +665,7 @@ EvTypeableTyLit e -> evVarsOfTermList e evVarsOfTermList (EvFun{}) = [] -instance ToHie (EvBindContext (Located TcEvBinds)) where+instance ToHie (EvBindContext (LocatedA TcEvBinds)) where toHie (EvBindContext sc sp (L span (EvBinds bs))) = concatMapM go $ bagToList bs where@@ -653,40 +673,40 @@ let evDeps = evVarsOfTermList $ eb_rhs evbind depNames = EvBindDeps $ map varName evDeps concatM $- [ toHie (C (EvidenceVarBind (EvLetBind depNames) (combineScopes sc (mkScope span)) sp)+ [ toHie (C (EvidenceVarBind (EvLetBind depNames) (combineScopes sc (mkScopeA span)) sp) (L span $ eb_lhs evbind)) , toHie $ map (C EvidenceVarUse . L span) $ evDeps ] toHie _ = pure [] -instance ToHie (Located HsWrapper) where+instance ToHie (LocatedA HsWrapper) where toHie (L osp wrap) = case wrap of- (WpLet bs) -> toHie $ EvBindContext (mkScope osp) (getRealSpan osp) (L osp bs)+ (WpLet bs) -> toHie $ EvBindContext (mkScopeA osp) (getRealSpanA osp) (L osp bs) (WpCompose a b) -> concatM $ [toHie (L osp a), toHie (L osp b)] (WpFun a b _ _) -> concatM $ [toHie (L osp a), toHie (L osp b)] (WpEvLam a) ->- toHie $ C (EvidenceVarBind EvWrapperBind (mkScope osp) (getRealSpan osp))+ toHie $ C (EvidenceVarBind EvWrapperBind (mkScopeA osp) (getRealSpanA osp)) $ L osp a (WpEvApp a) -> concatMapM (toHie . C EvidenceVarUse . L osp) $ evVarsOfTermList a _ -> pure [] -instance HiePass p => HasType (Located (HsBind (GhcPass p))) where+instance HiePass p => HasType (LocatedA (HsBind (GhcPass p))) where getTypeNode (L spn bind) = case hiePass @p of- HieRn -> makeNode bind spn+ HieRn -> makeNode bind (locA spn) HieTc -> case bind of- FunBind{fun_id = name} -> makeTypeNode bind spn (varType $ unLoc name)- _ -> makeNode bind spn+ FunBind{fun_id = name} -> makeTypeNode bind (locA spn) (varType $ unLoc name)+ _ -> makeNode bind (locA spn) -instance HiePass p => HasType (Located (Pat (GhcPass p))) where+instance HiePass p => HasType (LocatedA (Pat (GhcPass p))) where getTypeNode (L spn pat) = case hiePass @p of- HieRn -> makeNode pat spn- HieTc -> makeTypeNode pat spn (hsPatType pat)+ HieRn -> makeNodeA pat spn+ HieTc -> makeTypeNodeA pat spn (hsPatType pat) -- | This instance tries to construct 'HieAST' nodes which include the type of -- the expression. It is not yet possible to do this efficiently for all@@ -703,10 +723,10 @@ -- expression's type is going to be expensive. -- -- See #16233-instance HiePass p => HasType (Located (HsExpr (GhcPass p))) where+instance HiePass p => HasType (LocatedA (HsExpr (GhcPass p))) where getTypeNode e@(L spn e') = case hiePass @p of- HieRn -> makeNode e' spn+ HieRn -> makeNodeA e' spn HieTc -> -- Some expression forms have their type immediately available let tyOpt = case e' of@@ -729,15 +749,15 @@ in case tyOpt of- Just t -> makeTypeNode e' spn t+ Just t -> makeTypeNodeA e' spn t Nothing | skipDesugaring e' -> fallback | otherwise -> do hs_env <- lift $ lift $ Hsc $ \e w -> return (e,w) (_,mbe) <- liftIO $ deSugarExpr hs_env e- maybe fallback (makeTypeNode e' spn . exprType) mbe+ maybe fallback (makeTypeNodeA e' spn . exprType) mbe where- fallback = makeNode e' spn+ fallback = makeNodeA e' spn matchGroupType :: MatchGroupTc -> Type matchGroupType (MatchGroupTc args res) = mkVisFunTys args res@@ -764,12 +784,16 @@ class ( IsPass p , HiePass (NoGhcTcPass p) , ModifyState (IdGhcP p)- , Data (GRHS (GhcPass p) (Located (HsExpr (GhcPass p))))+ , Data (GRHS (GhcPass p) (LocatedA (HsExpr (GhcPass p))))+ , Data (Match (GhcPass p) (LocatedA (HsExpr (GhcPass p))))+ , Data (Match (GhcPass p) (LocatedA (HsCmd (GhcPass p))))+ , Data (Stmt (GhcPass p) (LocatedA (HsExpr (GhcPass p))))+ , Data (Stmt (GhcPass p) (LocatedA (HsCmd (GhcPass p)))) , Data (HsExpr (GhcPass p))- , Data (HsCmd (GhcPass p))+ , Data (HsCmd (GhcPass p)) , Data (AmbiguousFieldOcc (GhcPass p)) , Data (HsCmdTop (GhcPass p))- , Data (GRHS (GhcPass p) (Located (HsCmd (GhcPass p))))+ , Data (GRHS (GhcPass p) (LocatedA (HsCmd (GhcPass p)))) , Data (HsSplice (GhcPass p)) , Data (HsLocalBinds (GhcPass p)) , Data (FieldOcc (GhcPass p))@@ -780,6 +804,7 @@ , ToHie (RFContext (Located (FieldOcc (GhcPass p)))) , ToHie (TScoped (LHsWcType (GhcPass (NoGhcTcPass p)))) , ToHie (TScoped (LHsSigWcType (GhcPass (NoGhcTcPass p))))+ , Anno (IdGhcP p) ~ SrcSpanAnnN ) => HiePass p where hiePass :: HiePassEv p@@ -792,18 +817,35 @@ instance ToHie (Context (Located NoExtField)) where toHie _ = pure [] -instance HiePass p => ToHie (BindContext (Located (HsBind (GhcPass p)))) where+type AnnoBody p body+ = ( Anno (Match (GhcPass p) (LocatedA (body (GhcPass p))))+ ~ SrcSpanAnnA+ , Anno [LocatedA (Match (GhcPass p) (LocatedA (body (GhcPass p))))]+ ~ SrcSpanAnnL+ , Anno (GRHS (GhcPass p) (LocatedA (body (GhcPass p))))+ ~ SrcSpan+ , Anno (StmtLR (GhcPass p) (GhcPass p) (LocatedA (body (GhcPass p)))) ~ SrcSpanAnnA++ , Data (body (GhcPass p))+ , Data (Match (GhcPass p) (LocatedA (body (GhcPass p))))+ , Data (GRHS (GhcPass p) (LocatedA (body (GhcPass p))))+ , Data (Stmt (GhcPass p) (LocatedA (body (GhcPass p))))++ , IsPass p+ )++instance HiePass p => ToHie (BindContext (LocatedA (HsBind (GhcPass p)))) where toHie (BC context scope b@(L span bind)) = concatM $ getTypeNode b : case bind of FunBind{fun_id = name, fun_matches = matches, fun_ext = wrap} ->- [ toHie $ C (ValBind context scope $ getRealSpan span) name+ [ toHie $ C (ValBind context scope $ getRealSpanA span) name , toHie matches , case hiePass @p of HieTc -> toHie $ L span wrap _ -> pure [] ] PatBind{pat_lhs = lhs, pat_rhs = rhs} ->- [ toHie $ PS (getRealSpan span) scope NoScope lhs+ [ toHie $ PS (getRealSpan (locA span)) scope NoScope lhs , toHie rhs ] VarBind{var_rhs = expr} ->@@ -816,26 +858,26 @@ (toHie $ fmap (BC context scope) binds) , toHie $ map (L span . abe_wrap) xs , toHie $- map (EvBindContext (mkScope span) (getRealSpan span)+ map (EvBindContext (mkScopeA span) (getRealSpanA span) . L span) ev_binds , toHie $ map (C (EvidenceVarBind EvSigBind- (mkScope span)- (getRealSpan span))+ (mkScopeA span)+ (getRealSpanA span)) . L span) ev_vars ] PatSynBind _ psb ->- [ toHie $ L span psb -- PatSynBinds only occur at the top level+ [ toHie $ L (locA span) psb -- PatSynBinds only occur at the top level ] instance ( HiePass p- , ToHie (Located body)- , Data body- ) => ToHie (MatchGroup (GhcPass p) (Located body)) where+ , AnnoBody p body+ , ToHie (LocatedA (body (GhcPass p)))+ ) => ToHie (MatchGroup (GhcPass p) (LocatedA (body (GhcPass p)))) where toHie mg = case mg of MG{ mg_alts = (L span alts) , mg_origin = origin} -> local (setOrigin origin) $ concatM- [ locOnly span+ [ locOnly (locA span) , toHie alts ] @@ -853,14 +895,14 @@ ] where lhsScope = combineScopes varScope detScope- varScope = mkLScope var- patScope = mkScope $ getLoc pat+ varScope = mkLScopeN var+ patScope = mkScopeA $ getLoc pat detScope = case dets of- (PrefixCon _ args) -> foldr combineScopes NoScope $ map mkLScope args- (InfixCon a b) -> combineScopes (mkLScope a) (mkLScope b)+ (PrefixCon _ args) -> foldr combineScopes NoScope $ map mkLScopeN args+ (InfixCon a b) -> combineScopes (mkLScopeN a) (mkLScopeN b) (RecCon r) -> foldr go NoScope r go (RecordPatSynField a b) c = combineScopes c- $ combineScopes (mkLScope (rdrNameFieldOcc a)) (mkLScope b)+ $ combineScopes (mkLScopeN (rdrNameFieldOcc a)) (mkLScopeN b) detSpan = case detScope of LocalScope a -> Just a _ -> Nothing@@ -874,9 +916,10 @@ _ -> pure [] instance ( HiePass p- , Data body- , ToHie (Located body)- ) => ToHie (Located (Match (GhcPass p) (Located body))) where+ , Data (body (GhcPass p))+ , AnnoBody p body+ , ToHie (LocatedA (body (GhcPass p)))+ ) => ToHie (LocatedA (Match (GhcPass p) (LocatedA (body (GhcPass p))))) where toHie (L span m ) = concatM $ node : case m of Match{m_ctxt=mctx, m_pats = pats, m_grhss = grhss } -> [ toHie mctx@@ -886,8 +929,8 @@ ] where node = case hiePass @p of- HieTc -> makeNode m span- HieRn -> makeNode m span+ HieTc -> makeNodeA m span+ HieRn -> makeNodeA m span instance HiePass p => ToHie (HsMatchContext (GhcPass p)) where toHie (FunRhs{mc_fun=name}) = toHie $ C MatchBind name@@ -900,7 +943,7 @@ toHie (TransStmtCtxt a) = toHie a toHie _ = pure [] -instance HiePass p => ToHie (PScoped (Located (Pat (GhcPass p)))) where+instance HiePass p => ToHie (PScoped (LocatedA (Pat (GhcPass p)))) where toHie (PS rsp scope pscope lpat@(L ospan opat)) = concatM $ getTypeNode lpat : case opat of WildPat _ ->@@ -913,7 +956,7 @@ ] AsPat _ lname pat -> [ toHie $ C (PatternBind scope- (combineScopes (mkLScope pat) pscope)+ (combineScopes (mkLScopeA pat) pscope) rsp) lname , toHie $ PS rsp scope pscope pat@@ -941,7 +984,7 @@ , let ev_binds = cpt_binds ext ev_vars = cpt_dicts ext wrap = cpt_wrap ext- evscope = mkScope ospan `combineScopes` scope `combineScopes` pscope+ evscope = mkScopeA ospan `combineScopes` scope `combineScopes` pscope in concatM [ toHie $ EvBindContext scope rsp $ L ospan ev_binds , toHie $ L ospan wrap , toHie $ map (C (EvidenceVarBind EvPatternBind evscope rsp)@@ -970,7 +1013,7 @@ [ toHie $ PS rsp scope pscope pat , case hiePass @p of HieTc ->- let cscope = mkLScope pat in+ let cscope = mkLScopeA pat in toHie $ TS (ResolvedScopes [cscope, scope, pscope]) sig HieRn -> pure []@@ -989,48 +1032,50 @@ contextify :: a ~ LPat (GhcPass p) => HsConDetails (HsPatSigType (NoGhcTc (GhcPass p))) a (HsRecFields (GhcPass p) a) -> HsConDetails (TScoped (HsPatSigType (NoGhcTc (GhcPass p)))) (PScoped a) (RContext (HsRecFields (GhcPass p) (PScoped a))) contextify (PrefixCon tyargs args) = PrefixCon (tScopes scope argscope tyargs) (patScopes rsp scope pscope args)- where argscope = foldr combineScopes NoScope $ map mkLScope args+ where argscope = foldr combineScopes NoScope $ map mkLScopeA args contextify (InfixCon a b) = InfixCon a' b' where [a', b'] = patScopes rsp scope pscope [a,b] contextify (RecCon r) = RecCon $ RC RecFieldMatch $ contextify_rec r contextify_rec (HsRecFields fds a) = HsRecFields (map go scoped_fds) a where- go (RS fscope (L spn (HsRecField lbl pat pun))) =- L spn $ HsRecField lbl (PS rsp scope fscope pat) pun+ go :: RScoped (LocatedA (HsRecField' id a1))+ -> LocatedA (HsRecField' id (PScoped a1)) -- AZ+ go (RS fscope (L spn (HsRecField x lbl pat pun))) =+ L spn $ HsRecField x lbl (PS rsp scope fscope pat) pun scoped_fds = listScopes pscope fds instance ToHie (TScoped (HsPatSigType GhcRn)) where toHie (TS sc (HsPS (HsPSRn wcs tvs) body@(L span _))) = concatM $- [ bindingsOnly $ map (C $ TyVarBind (mkScope span) sc) (wcs++tvs)+ [ bindingsOnly $ map (C $ TyVarBind (mkScopeA span) sc) (wcs++tvs) , toHie body ] -- See Note [Scoping Rules for SigPat] -instance ( ToHie (Located body)+instance ( ToHie (LocatedA (body (GhcPass p))) , HiePass p- , Data body- ) => ToHie (GRHSs (GhcPass p) (Located body)) where+ , AnnoBody p body+ ) => ToHie (GRHSs (GhcPass p) (LocatedA (body (GhcPass p)))) where toHie grhs = concatM $ case grhs of GRHSs _ grhss binds -> [ toHie grhss , toHie $ RS (mkScope $ grhss_span grhs) binds ] -instance ( ToHie (Located body)- , HiePass a- , Data body- ) => ToHie (Located (GRHS (GhcPass a) (Located body))) where+instance ( ToHie (LocatedA (body (GhcPass p)))+ , HiePass p+ , AnnoBody p body+ ) => ToHie (Located (GRHS (GhcPass p) (LocatedA (body (GhcPass p))))) where toHie (L span g) = concatM $ node : case g of GRHS _ guards body ->- [ toHie $ listScopes (mkLScope body) guards+ [ toHie $ listScopes (mkLScopeA body) guards , toHie body ] where- node = case hiePass @a of+ node = case hiePass @p of HieRn -> makeNode g span HieTc -> makeNode g span -instance HiePass p => ToHie (Located (HsExpr (GhcPass p))) where+instance HiePass p => ToHie (LocatedA (HsExpr (GhcPass p))) where toHie e@(L mspan oexpr) = concatM $ getTypeNode e : case oexpr of HsVar _ (L _ var) -> [ toHie $ C Use (L mspan var)@@ -1041,7 +1086,7 @@ [ toHie $ C Use $ L mspan $ conLikeName con ] HsRecFld _ fld ->- [ toHie $ RFC RecFieldOcc Nothing (L mspan fld)+ [ toHie $ RFC RecFieldOcc Nothing (L (locA mspan) fld) ] HsOverLabel {} -> [] HsIPVar _ _ -> []@@ -1099,11 +1144,11 @@ [ toHie grhss ] HsLet _ binds expr ->- [ toHie $ RS (mkLScope expr) binds+ [ toHie $ RS (mkLScopeA expr) binds , toHie expr ] HsDo _ _ (L ispan stmts) ->- [ locOnly ispan+ [ locOnly (locA ispan) , toHie $ listScopes NoScope stmts ] ExplicitList _ exprs ->@@ -1114,17 +1159,20 @@ , toHie $ RC RecFieldAssign $ binds ] where- con_name :: Located Name+ con_name :: LocatedN Name con_name = case hiePass @p of -- Like ConPat HieRn -> con HieTc -> fmap conLikeName con- RecordUpd {rupd_expr = expr, rupd_flds = upds}->+ RecordUpd {rupd_expr = expr, rupd_flds = Left upds}-> [ toHie expr , toHie $ map (RC RecFieldAssign) upds ]+ RecordUpd {rupd_expr = expr, rupd_flds = Right _}->+ [ toHie expr+ ] ExprWithTySig _ expr sig -> [ toHie expr- , toHie $ TS (ResolvedScopes [mkLScope expr]) sig+ , toHie $ TS (ResolvedScopes [mkLScopeA expr]) sig ] ArithSeq _ _ info -> [ toHie info@@ -1159,6 +1207,8 @@ HsSpliceE _ x -> [ toHie $ L mspan x ]+ HsGetField {} -> []+ HsProjection {} -> [] XExpr x | GhcTc <- ghcPass @p , WrapExpr (HsWrap w a) <- x@@ -1171,23 +1221,24 @@ ] | otherwise -> [] -instance HiePass p => ToHie (Located (HsTupArg (GhcPass p))) where- toHie (L span arg) = concatM $ makeNode arg span : case arg of+-- NOTE: no longer have the location+instance HiePass p => ToHie (HsTupArg (GhcPass p)) where+ toHie arg = concatM $ case arg of Present _ expr -> [ toHie expr ] Missing _ -> [] -instance ( ToHie (Located body)- , Data body+instance ( ToHie (LocatedA (body (GhcPass p)))+ , AnnoBody p body , HiePass p- ) => ToHie (RScoped (Located (Stmt (GhcPass p) (Located body)))) where+ ) => ToHie (RScoped (LocatedA (Stmt (GhcPass p) (LocatedA (body (GhcPass p)))))) where toHie (RS scope (L span stmt)) = concatM $ node : case stmt of LastStmt _ body _ _ -> [ toHie body ] BindStmt _ pat body ->- [ toHie $ PS (getRealSpan $ getLoc body) scope NoScope pat+ [ toHie $ PS (getRealSpan $ getLocA body) scope NoScope pat , toHie body ] ApplicativeStmt _ stmts _ ->@@ -1209,34 +1260,60 @@ , toHie using , toHie by ]- RecStmt {recS_stmts = stmts} ->- [ toHie $ map (RS $ combineScopes scope (mkScope span)) stmts+ RecStmt {recS_stmts = L _ stmts} ->+ [ toHie $ map (RS $ combineScopes scope (mkScope (locA span))) stmts ] where node = case hiePass @p of- HieTc -> makeNode stmt span- HieRn -> makeNode stmt span+ HieTc -> makeNodeA stmt span+ HieRn -> makeNodeA stmt span -instance HiePass p => ToHie (RScoped (Located (HsLocalBinds (GhcPass p)))) where- toHie (RS scope (L sp binds)) = concatM $ makeNode binds sp : case binds of+instance HiePass p => ToHie (RScoped (HsLocalBinds (GhcPass p))) where+ toHie (RS scope binds) = concatM $ makeNode binds (spanHsLocaLBinds binds) : case binds of EmptyLocalBinds _ -> [] HsIPBinds _ ipbinds -> case ipbinds of- IPBinds evbinds xs -> let sc = combineScopes scope $ mkScope sp in- [ case hiePass @p of- HieTc -> toHie $ EvBindContext sc (getRealSpan sp) $ L sp evbinds+ IPBinds evbinds xs -> let sc = combineScopes scope $ scopeHsLocaLBinds binds+ sp :: SrcSpanAnnA+ sp = noAnnSrcSpan $ spanHsLocaLBinds binds in+ [+ case hiePass @p of+ HieTc -> toHie $ EvBindContext sc (getRealSpan $ locA sp) $ L sp evbinds HieRn -> pure [] , toHie $ map (RS sc) xs ] HsValBinds _ valBinds ->- [ toHie $ RS (combineScopes scope $ mkScope sp)+ [+ toHie $ RS (combineScopes scope (scopeHsLocaLBinds binds)) valBinds ] -instance HiePass p => ToHie (RScoped (Located (IPBind (GhcPass p)))) where- toHie (RS scope (L sp bind)) = concatM $ makeNode bind sp : case bind of++scopeHsLocaLBinds :: HsLocalBinds (GhcPass p) -> Scope+scopeHsLocaLBinds (HsValBinds _ (ValBinds _ bs sigs))+ = foldr combineScopes NoScope (bsScope ++ sigsScope)+ where+ bsScope :: [Scope]+ bsScope = map (mkScopeA . getLoc) $ bagToList bs+ sigsScope :: [Scope]+ sigsScope = map (mkScope . getLocA) sigs+scopeHsLocaLBinds (HsValBinds _ (XValBindsLR (NValBinds bs sigs)))+ = foldr combineScopes NoScope (bsScope ++ sigsScope)+ where+ bsScope :: [Scope]+ bsScope = map (mkScopeA . getLoc) $ concatMap (bagToList . snd) bs+ sigsScope :: [Scope]+ sigsScope = map (mkScope . getLocA) sigs++scopeHsLocaLBinds (HsIPBinds _ (IPBinds _ bs))+ = foldr combineScopes NoScope (map (mkScopeA . getLoc) bs)+scopeHsLocaLBinds (EmptyLocalBinds _) = NoScope+++instance HiePass p => ToHie (RScoped (LocatedA (IPBind (GhcPass p)))) where+ toHie (RS scope (L sp bind)) = concatM $ makeNodeA bind sp : case bind of IPBind _ (Left _) expr -> [toHie expr] IPBind _ (Right v) expr ->- [ toHie $ C (EvidenceVarBind EvImplicitBind scope (getRealSpan sp))+ [ toHie $ C (EvidenceVarBind EvImplicitBind scope (getRealSpanA sp)) $ L sp v , toHie expr ]@@ -1260,11 +1337,11 @@ toHie (RC c (HsRecFields fields _)) = toHie $ map (RC c) fields instance ( ToHie (RFContext (Located label))- , ToHie arg , HasLoc arg , Data arg+ , ToHie arg, HasLoc arg, Data arg , Data label- ) => ToHie (RContext (LHsRecField' label arg)) where- toHie (RC c (L span recfld)) = concatM $ makeNode recfld span : case recfld of- HsRecField label expr _ ->+ ) => ToHie (RContext (LocatedA (HsRecField' label arg))) where+ toHie (RC c (L span recfld)) = concatM $ makeNode recfld (locA span) : case recfld of+ HsRecField _ label expr _ -> [ toHie $ RFC c (getRealSpan $ loc expr) label , toHie expr ]@@ -1323,8 +1400,8 @@ [ toHie cmd ] -instance HiePass p => ToHie (Located (HsCmd (GhcPass p))) where- toHie (L span cmd) = concatM $ makeNode cmd span : case cmd of+instance HiePass p => ToHie (LocatedA (HsCmd (GhcPass p))) where+ toHie (L span cmd) = concatM $ makeNodeA cmd span : case cmd of HsCmdArrApp _ a b _ _ -> [ toHie a , toHie b@@ -1356,11 +1433,11 @@ , toHie c ] HsCmdLet _ binds cmd' ->- [ toHie $ RS (mkLScope cmd') binds+ [ toHie $ RS (mkLScopeA cmd') binds , toHie cmd' ] HsCmdDo _ (L ispan stmts) ->- [ locOnly ispan+ [ locOnly (locA ispan) , toHie $ listScopes NoScope stmts ] XCmd _ -> []@@ -1377,27 +1454,27 @@ , toHie instances ] -instance ToHie (Located (TyClDecl GhcRn)) where- toHie (L span decl) = concatM $ makeNode decl span : case decl of+instance ToHie (LocatedA (TyClDecl GhcRn)) where+ toHie (L span decl) = concatM $ makeNodeA decl span : case decl of FamDecl {tcdFam = fdecl} ->- [ toHie (L span fdecl)+ [ toHie ((L span fdecl) :: LFamilyDecl GhcRn) ] SynDecl {tcdLName = name, tcdTyVars = vars, tcdRhs = typ} ->- [ toHie $ C (Decl SynDec $ getRealSpan span) name- , toHie $ TS (ResolvedScopes [mkScope $ getLoc typ]) vars+ [ toHie $ C (Decl SynDec $ getRealSpanA span) name+ , toHie $ TS (ResolvedScopes [mkScope $ getLocA typ]) vars , toHie typ ] DataDecl {tcdLName = name, tcdTyVars = vars, tcdDataDefn = defn} ->- [ toHie $ C (Decl DataDec $ getRealSpan span) name+ [ toHie $ C (Decl DataDec $ getRealSpanA span) name , toHie $ TS (ResolvedScopes [quant_scope, rhs_scope]) vars , toHie defn ] where- quant_scope = mkLScope $ dd_ctxt defn+ quant_scope = mkLScopeA $ fromMaybe (noLocA []) $ dd_ctxt defn rhs_scope = sig_sc `combineScopes` con_sc `combineScopes` deriv_sc- sig_sc = maybe NoScope mkLScope $ dd_kindSig defn- con_sc = foldr combineScopes NoScope $ map mkLScope $ dd_cons defn- deriv_sc = mkLScope $ dd_derivs defn+ sig_sc = maybe NoScope mkLScopeA $ dd_kindSig defn+ con_sc = foldr combineScopes NoScope $ map mkLScopeA $ dd_cons defn+ deriv_sc = foldr combineScopes NoScope $ map mkLScope $ dd_derivs defn ClassDecl { tcdCtxt = context , tcdLName = name , tcdTyVars = vars@@ -1407,25 +1484,25 @@ , tcdATs = typs , tcdATDefs = deftyps } ->- [ toHie $ C (Decl ClassDec $ getRealSpan span) name+ [ toHie $ C (Decl ClassDec $ getRealSpanA span) name , toHie context , toHie $ TS (ResolvedScopes [context_scope, rhs_scope]) vars , toHie deps- , toHie $ map (SC $ SI ClassSig $ getRealSpan span) sigs+ , toHie $ map (SC $ SI ClassSig $ getRealSpanA span) sigs , toHie $ fmap (BC InstanceBind ModuleScope) meths , toHie typs- , concatMapM (locOnly . getLoc) deftyps+ , concatMapM (locOnly . getLocA) deftyps , toHie deftyps ] where- context_scope = mkLScope context+ context_scope = mkLScopeA $ fromMaybe (noLocA []) context rhs_scope = foldl1' combineScopes $ map mkScope [ loc deps, loc sigs, loc (bagToList meths), loc typs, loc deftyps] -instance ToHie (Located (FamilyDecl GhcRn)) where- toHie (L span decl) = concatM $ makeNode decl span : case decl of- FamilyDecl _ info name vars _ sig inj ->- [ toHie $ C (Decl FamDec $ getRealSpan span) name+instance ToHie (LocatedA (FamilyDecl GhcRn)) where+ toHie (L span decl) = concatM $ makeNodeA decl span : case decl of+ FamilyDecl _ info _ name vars _ sig inj ->+ [ toHie $ C (Decl FamDec $ getRealSpanA span) name , toHie $ TS (ResolvedScopes [rhsSpan]) vars , toHie info , toHie $ RS injSpan sig@@ -1438,11 +1515,11 @@ instance ToHie (FamilyInfo GhcRn) where toHie (ClosedTypeFamily (Just eqns)) = concatM $- [ concatMapM (locOnly . getLoc) eqns+ [ concatMapM (locOnly . getLocA) eqns , toHie $ map go eqns ] where- go (L l ib) = TS (ResolvedScopes [mkScope l]) ib+ go (L l ib) = TS (ResolvedScopes [mkScopeA l]) ib toHie _ = pure [] instance ToHie (RScoped (Located (FamilyResultSig GhcRn))) where@@ -1456,17 +1533,20 @@ [ toHie $ TVS (ResolvedScopes [sc]) NoScope bndr ] -instance ToHie (Located (FunDep (Located Name))) where- toHie (L span fd@(lhs, rhs)) = concatM $- [ makeNode fd span+instance ToHie (LocatedA (FunDep GhcRn)) where+ toHie (L span fd@(FunDep _ lhs rhs)) = concatM $+ [ makeNode fd (locA span) , toHie $ map (C Use) lhs , toHie $ map (C Use) rhs ] -instance (ToHie rhs, HasLoc rhs)- => ToHie (TScoped (FamEqn GhcRn rhs)) where++instance ToHie (TScoped (FamEqn GhcRn (HsDataDefn GhcRn))) where toHie (TS _ f) = toHie f +instance ToHie (TScoped (FamEqn GhcRn (LocatedA (HsType GhcRn)))) where+ toHie (TS _ f) = toHie f+ instance (ToHie rhs, HasLoc rhs) => ToHie (FamEqn GhcRn rhs) where toHie fe@(FamEqn _ var outer_bndrs pats _ rhs) = concatM $@@ -1481,7 +1561,7 @@ instance ToHie (Located (InjectivityAnn GhcRn)) where toHie (L span ann) = concatM $ makeNode ann span : case ann of- InjectivityAnn lhs rhs ->+ InjectivityAnn _ lhs rhs -> [ toHie $ C Use lhs , toHie $ map (C Use) rhs ]@@ -1507,32 +1587,32 @@ , toHie dct ] -instance ToHie (Located (DerivClauseTys GhcRn)) where- toHie (L span dct) = concatM $ makeNode dct span : case dct of+instance ToHie (LocatedC (DerivClauseTys GhcRn)) where+ toHie (L span dct) = concatM $ makeNodeA dct span : case dct of DctSingle _ ty -> [ toHie $ TS (ResolvedScopes []) ty ] DctMulti _ tys -> [ toHie $ map (TS (ResolvedScopes [])) tys ] instance ToHie (Located (DerivStrategy GhcRn)) where toHie (L span strat) = concatM $ makeNode strat span : case strat of- StockStrategy -> []- AnyclassStrategy -> []- NewtypeStrategy -> []+ StockStrategy _ -> []+ AnyclassStrategy _ -> []+ NewtypeStrategy _ -> [] ViaStrategy s -> [ toHie (TS (ResolvedScopes []) s) ] -instance ToHie (Located OverlapMode) where- toHie (L span _) = locOnly span+instance ToHie (LocatedP OverlapMode) where+ toHie (L span _) = locOnly (locA span) instance ToHie a => ToHie (HsScaled GhcRn a) where toHie (HsScaled w t) = concatM [toHie (arrowToHsType w), toHie t] -instance ToHie (Located (ConDecl GhcRn)) where- toHie (L span decl) = concatM $ makeNode decl span : case decl of+instance ToHie (LocatedA (ConDecl GhcRn)) where+ toHie (L span decl) = concatM $ makeNode decl (locA span) : case decl of ConDeclGADT { con_names = names, con_bndrs = L outer_bndrs_loc outer_bndrs , con_mb_cxt = ctx, con_g_args = args, con_res_ty = typ } ->- [ toHie $ map (C (Decl ConDec $ getRealSpan span)) names+ [ toHie $ map (C (Decl ConDec $ getRealSpanA span)) names , case outer_bndrs of HsOuterImplicit{hso_ximplicit = imp_vars} ->- bindingsOnly $ map (C $ TyVarBind (mkScope outer_bndrs_loc) resScope)+ bindingsOnly $ map (C $ TyVarBind (mkScopeA outer_bndrs_loc) resScope) imp_vars HsOuterExplicit{hso_bndrs = exp_bndrs} -> toHie $ tvScopes resScope NoScope exp_bndrs@@ -1542,51 +1622,51 @@ ] where rhsScope = combineScopes argsScope tyScope- ctxScope = maybe NoScope mkLScope ctx+ ctxScope = maybe NoScope mkLScopeA ctx argsScope = case args of PrefixConGADT xs -> scaled_args_scope xs- RecConGADT x -> mkLScope x- tyScope = mkLScope typ+ RecConGADT x -> mkLScopeA x+ tyScope = mkLScopeA typ resScope = ResolvedScopes [ctxScope, rhsScope] ConDeclH98 { con_name = name, con_ex_tvs = qvars , con_mb_cxt = ctx, con_args = dets } ->- [ toHie $ C (Decl ConDec $ getRealSpan span) name+ [ toHie $ C (Decl ConDec $ getRealSpan (locA span)) name , toHie $ tvScopes (ResolvedScopes []) rhsScope qvars , toHie ctx , toHie dets ] where rhsScope = combineScopes ctxScope argsScope- ctxScope = maybe NoScope mkLScope ctx+ ctxScope = maybe NoScope mkLScopeA ctx argsScope = case dets of PrefixCon _ xs -> scaled_args_scope xs InfixCon a b -> scaled_args_scope [a, b]- RecCon x -> mkLScope x+ RecCon x -> mkLScopeA x where scaled_args_scope :: [HsScaled GhcRn (LHsType GhcRn)] -> Scope- scaled_args_scope = foldr combineScopes NoScope . map (mkLScope . hsScaledThing)+ scaled_args_scope = foldr combineScopes NoScope . map (mkLScopeA . hsScaledThing) -instance ToHie (Located [Located (ConDeclField GhcRn)]) where+instance ToHie (LocatedL [LocatedA (ConDeclField GhcRn)]) where toHie (L span decls) = concatM $- [ locOnly span+ [ locOnly (locA span) , toHie decls ] -instance ToHie (TScoped (HsWildCardBndrs GhcRn (Located (HsSigType GhcRn)))) where+instance ToHie (TScoped (HsWildCardBndrs GhcRn (LocatedA (HsSigType GhcRn)))) where toHie (TS sc (HsWC names a)) = concatM $ [ bindingsOnly $ map (C $ TyVarBind (mkScope span) sc) names , toHie $ TS sc a ] where span = loc a -instance ToHie (TScoped (HsWildCardBndrs GhcRn (Located (HsType GhcRn)))) where+instance ToHie (TScoped (HsWildCardBndrs GhcRn (LocatedA (HsType GhcRn)))) where toHie (TS sc (HsWC names a)) = concatM $ [ bindingsOnly $ map (C $ TyVarBind (mkScope span) sc) names , toHie a ] where span = loc a -instance ToHie (Located (StandaloneKindSig GhcRn)) where- toHie (L sp sig) = concatM [makeNode sig sp, toHie sig]+instance ToHie (LocatedA (StandaloneKindSig GhcRn)) where+ toHie (L sp sig) = concatM [makeNodeA sig sp, toHie sig] instance ToHie (StandaloneKindSig GhcRn) where toHie sig = concatM $ case sig of@@ -1595,11 +1675,11 @@ , toHie $ TS (ResolvedScopes []) typ ] -instance HiePass p => ToHie (SigContext (Located (Sig (GhcPass p)))) where+instance HiePass p => ToHie (SigContext (LocatedA (Sig (GhcPass p)))) where toHie (SC (SI styp msp) (L sp sig)) = case hiePass @p of HieTc -> pure []- HieRn -> concatM $ makeNode sig sp : case sig of+ HieRn -> concatM $ makeNodeA sig sp : case sig of TypeSig _ names typ -> [ toHie $ map (C TyDecl) names , toHie $ TS (UnresolvedScope (map unLoc names) Nothing) typ@@ -1610,7 +1690,7 @@ ] ClassOpSig _ _ names typ -> [ case styp of- ClassSig -> toHie $ map (C $ ClassTyDecl $ getRealSpan sp) names+ ClassSig -> toHie $ map (C $ ClassTyDecl $ getRealSpanA sp) names _ -> toHie $ map (C $ TyDecl) names , toHie $ TS (UnresolvedScope (map unLoc names) msp) typ ]@@ -1641,21 +1721,22 @@ , toHie $ fmap (C Use) typ ] -instance ToHie (TScoped (Located (HsSigType GhcRn))) where- toHie (TS tsc (L span t@HsSig{sig_bndrs=bndrs,sig_body=body})) = concatM $ makeNode t span :- [ toHie (TVS tsc (mkScope span) bndrs)+instance ToHie (TScoped (LocatedA (HsSigType GhcRn))) where+ toHie (TS tsc (L span t@HsSig{sig_bndrs=bndrs,sig_body=body})) = concatM $ makeNodeA t span :+ [ toHie (TVS tsc (mkScopeA span) bndrs) , toHie body ] +-- Check this instance Data flag => ToHie (TVScoped (HsOuterTyVarBndrs flag GhcRn)) where toHie (TVS tsc sc bndrs) = case bndrs of HsOuterImplicit xs -> bindingsOnly $ map (C $ TyVarBind sc tsc) xs HsOuterExplicit _ xs -> toHie $ tvScopes tsc sc xs -instance ToHie (Located (HsType GhcRn)) where- toHie (L span t) = concatM $ makeNode t span : case t of+instance ToHie (LocatedA (HsType GhcRn)) where+ toHie (L span t) = concatM $ makeNode t (locA span) : case t of HsForAllTy _ tele body ->- let scope = mkScope $ getLoc body in+ let scope = mkScope $ getLocA body in [ case tele of HsForAllVis { hsf_vis_bndrs = bndrs } -> toHie $ tvScopes (ResolvedScopes []) scope bndrs@@ -1736,8 +1817,8 @@ toHie (HsTypeArg _ ty) = toHie ty toHie (HsArgPar sp) = locOnly sp -instance Data flag => ToHie (TVScoped (Located (HsTyVarBndr flag GhcRn))) where- toHie (TVS tsc sc (L span bndr)) = concatM $ makeNode bndr span : case bndr of+instance Data flag => ToHie (TVScoped (LocatedA (HsTyVarBndr flag GhcRn))) where+ toHie (TVS tsc sc (L span bndr)) = concatM $ makeNodeA bndr span : case bndr of UserTyVar _ _ var -> [ toHie $ C (TyVarBind sc tsc) var ]@@ -1755,14 +1836,14 @@ varLoc = loc vars bindings = map (C $ TyVarBind (mkScope varLoc) sc) implicits -instance ToHie (Located [Located (HsType GhcRn)]) where+instance ToHie (LocatedC [LocatedA (HsType GhcRn)]) where toHie (L span tys) = concatM $- [ locOnly span+ [ locOnly (locA span) , toHie tys ] -instance ToHie (Located (ConDeclField GhcRn)) where- toHie (L span field) = concatM $ makeNode field span : case field of+instance ToHie (LocatedA (ConDeclField GhcRn)) where+ toHie (L span field) = concatM $ makeNode field (locA span) : case field of ConDeclField _ fields typ _ -> [ toHie $ map (RFC RecFieldDecl (getRealSpan $ loc typ)) fields , toHie typ@@ -1784,8 +1865,8 @@ , toHie c ] -instance ToHie (Located (SpliceDecl GhcRn)) where- toHie (L span decl) = concatM $ makeNode decl span : case decl of+instance ToHie (LocatedA (SpliceDecl GhcRn)) where+ toHie (L span decl) = concatM $ makeNodeA decl span : case decl of SpliceDecl _ splice _ -> [ toHie splice ]@@ -1799,8 +1880,8 @@ instance ToHie PendingTcSplice where toHie _ = pure [] -instance ToHie (LBooleanFormula (Located Name)) where- toHie (L span form) = concatM $ makeNode form span : case form of+instance ToHie (LBooleanFormula (LocatedN Name)) where+ toHie (L span form) = concatM $ makeNode form (locA span) : case form of Var a -> [ toHie $ C Use a ]@@ -1817,8 +1898,8 @@ instance ToHie (Located HsIPName) where toHie (L span e) = makeNode e span -instance HiePass p => ToHie (Located (HsSplice (GhcPass p))) where- toHie (L span sp) = concatM $ makeNode sp span : case sp of+instance HiePass p => ToHie (LocatedA (HsSplice (GhcPass p))) where+ toHie (L span sp) = concatM $ makeNodeA sp span : case sp of HsTypedSplice _ _ _ expr -> [ toHie expr ]@@ -1838,15 +1919,15 @@ GhcTc -> case x of HsSplicedT _ -> [] -instance ToHie (Located (RoleAnnotDecl GhcRn)) where- toHie (L span annot) = concatM $ makeNode annot span : case annot of+instance ToHie (LocatedA (RoleAnnotDecl GhcRn)) where+ toHie (L span annot) = concatM $ makeNodeA annot span : case annot of RoleAnnotDecl _ var roles -> [ toHie $ C Use var , concatMapM (locOnly . getLoc) roles ] -instance ToHie (Located (InstDecl GhcRn)) where- toHie (L span decl) = concatM $ makeNode decl span : case decl of+instance ToHie (LocatedA (InstDecl GhcRn)) where+ toHie (L span decl) = concatM $ makeNodeA decl span : case decl of ClsInstD _ d -> [ toHie $ L span d ]@@ -1857,23 +1938,23 @@ [ toHie $ L span d ] -instance ToHie (Located (ClsInstDecl GhcRn)) where+instance ToHie (LocatedA (ClsInstDecl GhcRn)) where toHie (L span decl) = concatM- [ toHie $ TS (ResolvedScopes [mkScope span]) $ cid_poly_ty decl+ [ toHie $ TS (ResolvedScopes [mkScopeA span]) $ cid_poly_ty decl , toHie $ fmap (BC InstanceBind ModuleScope) $ cid_binds decl- , toHie $ map (SC $ SI InstSig $ getRealSpan span) $ cid_sigs decl- , concatMapM (locOnly . getLoc) $ cid_tyfam_insts decl+ , toHie $ map (SC $ SI InstSig $ getRealSpanA span) $ cid_sigs decl+ , concatMapM (locOnly . getLocA) $ cid_tyfam_insts decl , toHie $ cid_tyfam_insts decl- , concatMapM (locOnly . getLoc) $ cid_datafam_insts decl+ , concatMapM (locOnly . getLocA) $ cid_datafam_insts decl , toHie $ cid_datafam_insts decl , toHie $ cid_overlap_mode decl ] -instance ToHie (Located (DataFamInstDecl GhcRn)) where- toHie (L sp (DataFamInstDecl d)) = toHie $ TS (ResolvedScopes [mkScope sp]) d+instance ToHie (LocatedA (DataFamInstDecl GhcRn)) where+ toHie (L sp (DataFamInstDecl d)) = toHie $ TS (ResolvedScopes [mkScopeA sp]) d -instance ToHie (Located (TyFamInstDecl GhcRn)) where- toHie (L sp (TyFamInstDecl d)) = toHie $ TS (ResolvedScopes [mkScope sp]) d+instance ToHie (LocatedA (TyFamInstDecl GhcRn)) where+ toHie (L sp (TyFamInstDecl _ d)) = toHie $ TS (ResolvedScopes [mkScopeA sp]) d instance HiePass p => ToHie (Context (FieldOcc (GhcPass p))) where toHie (C c (FieldOcc n (L l _))) = case hiePass @p of@@ -1886,30 +1967,30 @@ , toHie $ C Use b ] -instance ToHie (Located (DerivDecl GhcRn)) where- toHie (L span decl) = concatM $ makeNode decl span : case decl of+instance ToHie (LocatedA (DerivDecl GhcRn)) where+ toHie (L span decl) = concatM $ makeNodeA decl span : case decl of DerivDecl _ typ strat overlap -> [ toHie $ TS (ResolvedScopes []) typ , toHie strat , toHie overlap ] -instance ToHie (Located (FixitySig GhcRn)) where- toHie (L span sig) = concatM $ makeNode sig span : case sig of+instance ToHie (LocatedA (FixitySig GhcRn)) where+ toHie (L span sig) = concatM $ makeNodeA sig span : case sig of FixitySig _ vars _ -> [ toHie $ map (C Use) vars ] -instance ToHie (Located (DefaultDecl GhcRn)) where- toHie (L span decl) = concatM $ makeNode decl span : case decl of+instance ToHie (LocatedA (DefaultDecl GhcRn)) where+ toHie (L span decl) = concatM $ makeNodeA decl span : case decl of DefaultDecl _ typs -> [ toHie typs ] -instance ToHie (Located (ForeignDecl GhcRn)) where- toHie (L span decl) = concatM $ makeNode decl span : case decl of+instance ToHie (LocatedA (ForeignDecl GhcRn)) where+ toHie (L span decl) = concatM $ makeNodeA decl span : case decl of ForeignImport {fd_name = name, fd_sig_ty = sig, fd_fi = fi} ->- [ toHie $ C (ValBind RegularBind ModuleScope $ getRealSpan span) name+ [ toHie $ C (ValBind RegularBind ModuleScope $ getRealSpanA span) name , toHie $ TS (ResolvedScopes []) sig , toHie fi ]@@ -1932,49 +2013,49 @@ , locOnly b ] -instance ToHie (Located (WarnDecls GhcRn)) where- toHie (L span decl) = concatM $ makeNode decl span : case decl of+instance ToHie (LocatedA (WarnDecls GhcRn)) where+ toHie (L span decl) = concatM $ makeNodeA decl span : case decl of Warnings _ _ warnings -> [ toHie warnings ] -instance ToHie (Located (WarnDecl GhcRn)) where- toHie (L span decl) = concatM $ makeNode decl span : case decl of+instance ToHie (LocatedA (WarnDecl GhcRn)) where+ toHie (L span decl) = concatM $ makeNode decl (locA span) : case decl of Warning _ vars _ -> [ toHie $ map (C Use) vars ] -instance ToHie (Located (AnnDecl GhcRn)) where- toHie (L span decl) = concatM $ makeNode decl span : case decl of+instance ToHie (LocatedA (AnnDecl GhcRn)) where+ toHie (L span decl) = concatM $ makeNodeA decl span : case decl of HsAnnotation _ _ prov expr -> [ toHie prov , toHie expr ] -instance ToHie (Context (Located a)) => ToHie (AnnProvenance a) where+instance ToHie (AnnProvenance GhcRn) where toHie (ValueAnnProvenance a) = toHie $ C Use a toHie (TypeAnnProvenance a) = toHie $ C Use a toHie ModuleAnnProvenance = pure [] -instance ToHie (Located (RuleDecls GhcRn)) where- toHie (L span decl) = concatM $ makeNode decl span : case decl of+instance ToHie (LocatedA (RuleDecls GhcRn)) where+ toHie (L span decl) = concatM $ makeNodeA decl span : case decl of HsRules _ _ rules -> [ toHie rules ] -instance ToHie (Located (RuleDecl GhcRn)) where+instance ToHie (LocatedA (RuleDecl GhcRn)) where toHie (L span r@(HsRule _ rname _ tybndrs bndrs exprA exprB)) = concatM- [ makeNode r span+ [ makeNodeA r span , locOnly $ getLoc rname , toHie $ fmap (tvScopes (ResolvedScopes []) scope) tybndrs- , toHie $ map (RS $ mkScope span) bndrs+ , toHie $ map (RS $ mkScope (locA span)) bndrs , toHie exprA , toHie exprB ] where scope = bndrs_sc `combineScopes` exprA_sc `combineScopes` exprB_sc bndrs_sc = maybe NoScope mkLScope (listToMaybe bndrs)- exprA_sc = mkLScope exprA- exprB_sc = mkLScope exprB+ exprA_sc = mkLScopeA exprA+ exprB_sc = mkLScopeA exprB instance ToHie (RScoped (Located (RuleBndr GhcRn))) where toHie (RS sc (L span bndr)) = concatM $ makeNode bndr span : case bndr of@@ -1986,8 +2067,8 @@ , toHie $ TS (ResolvedScopes [sc]) typ ] -instance ToHie (Located (ImportDecl GhcRn)) where- toHie (L span decl) = concatM $ makeNode decl span : case decl of+instance ToHie (LocatedA (ImportDecl GhcRn)) where+ toHie (L span decl) = concatM $ makeNode decl (locA span) : case decl of ImportDecl { ideclName = name, ideclAs = as, ideclHiding = hidden } -> [ toHie $ IEC Import name , toHie $ fmap (IEC ImportAs) as@@ -1995,14 +2076,14 @@ ] where goIE (hiding, (L sp liens)) = concatM $- [ locOnly sp+ [ locOnly (locA sp) , toHie $ map (IEC c) liens ] where c = if hiding then ImportHiding else Import -instance ToHie (IEContext (Located (IE GhcRn))) where- toHie (IEC c (L span ie)) = concatM $ makeNode ie span : case ie of+instance ToHie (IEContext (LocatedA (IE GhcRn))) where+ toHie (IEC c (L span ie)) = concatM $ makeNode ie (locA span) : case ie of IEVar _ n -> [ toHie $ IEC c n ]@@ -2025,14 +2106,14 @@ IEDocNamed _ _ -> [] instance ToHie (IEContext (LIEWrappedName Name)) where- toHie (IEC c (L span iewn)) = concatM $ makeNode iewn span : case iewn of+ toHie (IEC c (L span iewn)) = concatM $ makeNodeA iewn span : case iewn of IEName n -> [ toHie $ C (IEThing c) n ]- IEPattern p ->+ IEPattern _ p -> [ toHie $ C (IEThing c) p ]- IEType n ->+ IEType _ n -> [ toHie $ C (IEThing c) n ]
compiler/GHC/Iface/Ext/Binary.hs view
@@ -14,7 +14,6 @@ , HieFileResult(..) , hieMagic , hieNameOcc- , NameCacheUpdater(..) ) where @@ -31,19 +30,18 @@ import GHC.Utils.Panic import GHC.Builtin.Utils import GHC.Types.SrcLoc as SrcLoc-import GHC.Types.Unique.Supply ( takeUniqFromSupply ) import GHC.Types.Unique import GHC.Types.Unique.FM-import GHC.Iface.Env (NameCacheUpdater(..)) -import qualified Data.Array as A+import qualified Data.Array as A+import qualified Data.Array.IO as A+import qualified Data.Array.Unsafe as A import Data.IORef import Data.ByteString ( ByteString ) import qualified Data.ByteString as BS import qualified Data.ByteString.Char8 as BSC-import Data.List ( mapAccumR ) import Data.Word ( Word8, Word32 )-import Control.Monad ( replicateM, when )+import Control.Monad ( replicateM, when, forM_ ) import System.Directory ( createDirectoryIfMissing ) import System.FilePath ( takeDirectory ) @@ -98,14 +96,12 @@ put_ bh0 symtab_p_p -- Make some initial state- symtab_next <- newFastMutInt- writeFastMutInt symtab_next 0+ symtab_next <- newFastMutInt 0 symtab_map <- newIORef emptyUFM :: IO (IORef (UniqFM Name (Int, HieName))) let hie_symtab = HieSymbolTable { hie_symtab_next = symtab_next, hie_symtab_map = symtab_map }- dict_next_ref <- newFastMutInt- writeFastMutInt dict_next_ref 0+ dict_next_ref <- newFastMutInt 0 dict_map_ref <- newIORef emptyUFM let hie_dict = HieDictionary { hie_dict_next = dict_next_ref,@@ -155,23 +151,23 @@ -- an existing `NameCache`. Allows you to specify -- which versions of hieFile to attempt to read. -- `Left` case returns the failing header versions.-readHieFileWithVersion :: (HieHeader -> Bool) -> NameCacheUpdater -> FilePath -> IO (Either HieHeader HieFileResult)-readHieFileWithVersion readVersion ncu file = do+readHieFileWithVersion :: (HieHeader -> Bool) -> NameCache -> FilePath -> IO (Either HieHeader HieFileResult)+readHieFileWithVersion readVersion name_cache file = do bh0 <- readBinMem file (hieVersion, ghcVersion) <- readHieFileHeader file bh0 if readVersion (hieVersion, ghcVersion) then do- hieFile <- readHieFileContents bh0 ncu+ hieFile <- readHieFileContents bh0 name_cache return $ Right (HieFileResult hieVersion ghcVersion hieFile) else return $ Left (hieVersion, ghcVersion) -- | Read a `HieFile` from a `FilePath`. Can use -- an existing `NameCache`.-readHieFile :: NameCacheUpdater -> FilePath -> IO HieFileResult-readHieFile ncu file = do+readHieFile :: NameCache -> FilePath -> IO HieFileResult+readHieFile name_cache file = do bh0 <- readBinMem file @@ -185,7 +181,7 @@ , show hieVersion , "but got", show readHieVersion ]- hieFile <- readHieFileContents bh0 ncu+ hieFile <- readHieFileContents bh0 name_cache return $ HieFileResult hieVersion ghcVersion hieFile readBinLine :: BinHandle -> IO ByteString@@ -220,8 +216,8 @@ ] return (readHieVersion, ghcVersion) -readHieFileContents :: BinHandle -> NameCacheUpdater -> IO HieFile-readHieFileContents bh0 ncu = do+readHieFileContents :: BinHandle -> NameCache -> IO HieFile+readHieFileContents bh0 name_cache = do dict <- get_dictionary bh0 -- read the symbol table so we are capable of reading the actual data bh1 <- do@@ -248,7 +244,7 @@ symtab_p <- get bh1 data_p' <- tellBin bh1 seekBin bh1 symtab_p- symtab <- getSymbolTable bh1 ncu+ symtab <- getSymbolTable bh1 name_cache seekBin bh1 data_p' return symtab @@ -272,14 +268,15 @@ let names = A.elems (A.array (0,next_off-1) (nonDetEltsUFM symtab)) mapM_ (putHieName bh) names -getSymbolTable :: BinHandle -> NameCacheUpdater -> IO SymbolTable-getSymbolTable bh ncu = do+getSymbolTable :: BinHandle -> NameCache -> IO SymbolTable+getSymbolTable bh name_cache = do sz <- get bh- od_names <- replicateM sz (getHieName bh)- updateNameCache ncu $ \nc ->- let arr = A.listArray (0,sz-1) names- (nc', names) = mapAccumR fromHieName nc od_names- in (nc',arr)+ mut_arr <- A.newArray_ (0, sz-1) :: IO (A.IOArray Int Name)+ forM_ [0..(sz-1)] $ \i -> do+ od_name <- getHieName bh+ name <- fromHieName name_cache od_name+ A.writeArray mut_arr i name+ A.unsafeFreeze mut_arr getSymTabName :: SymbolTable -> BinHandle -> IO Name getSymTabName st bh = do@@ -314,24 +311,28 @@ -- ** Converting to and from `HieName`'s -fromHieName :: NameCache -> HieName -> (NameCache, Name)-fromHieName nc (ExternalName mod occ span) =- let cache = nsNames nc- in case lookupOrigNameCache cache mod occ of- Just name -> (nc, name)- Nothing ->- let (uniq, us) = takeUniqFromSupply (nsUniqs nc)- name = mkExternalName uniq mod occ span- new_cache = extendNameCache cache mod occ name- in ( nc{ nsUniqs = us, nsNames = new_cache }, name )-fromHieName nc (LocalName occ span) =- let (uniq, us) = takeUniqFromSupply (nsUniqs nc)- name = mkInternalName uniq occ span- in ( nc{ nsUniqs = us }, name )-fromHieName nc (KnownKeyName u) = case lookupKnownKeyName u of- Nothing -> pprPanic "fromHieName:unknown known-key unique"- (ppr (unpkUnique u))- Just n -> (nc, n)+fromHieName :: NameCache -> HieName -> IO Name+fromHieName nc hie_name = do++ case hie_name of+ ExternalName mod occ span -> updateNameCache nc mod occ $ \cache -> do+ case lookupOrigNameCache cache mod occ of+ Just name -> pure (cache, name)+ Nothing -> do+ uniq <- takeUniqFromNameCache nc+ let name = mkExternalName uniq mod occ span+ new_cache = extendOrigNameCache cache mod occ name+ pure (new_cache, name)++ LocalName occ span -> do+ uniq <- takeUniqFromNameCache nc+ -- don't update the NameCache for local names+ pure $ mkInternalName uniq occ span++ KnownKeyName u -> case lookupKnownKeyName u of+ Nothing -> pprPanic "fromHieName:unknown known-key unique"+ (ppr (unpkUnique u))+ Just n -> pure n -- ** Reading and writing `HieName`'s
compiler/GHC/Iface/Ext/Utils.hs view
@@ -25,6 +25,7 @@ import GHC.Core.Type import GHC.Types.Var import GHC.Types.Var.Env+import GHC.Parser.Annotation import GHC.Iface.Ext.Types @@ -523,6 +524,9 @@ pure [Node e span []] locOnly _ = pure [] +mkScopeA :: SrcSpanAnn' ann -> Scope+mkScopeA l = mkScope (locA l)+ mkScope :: SrcSpan -> Scope mkScope (RealSrcSpan sp _) = LocalScope sp mkScope _ = NoScope@@ -530,6 +534,12 @@ mkLScope :: Located a -> Scope mkLScope = mkScope . getLoc +mkLScopeA :: GenLocated (SrcSpanAnn' a) e -> Scope+mkLScopeA = mkScope . locA . getLoc++mkLScopeN :: LocatedN a -> Scope+mkLScopeN = mkScope . getLocA+ combineScopes :: Scope -> Scope -> Scope combineScopes ModuleScope _ = ModuleScope combineScopes _ ModuleScope = ModuleScope@@ -541,6 +551,14 @@ mkSourcedNodeInfo :: NodeOrigin -> NodeInfo a -> SourcedNodeInfo a mkSourcedNodeInfo org ni = SourcedNodeInfo $ M.singleton org ni +{-# INLINEABLE makeNodeA #-}+makeNodeA+ :: (Monad m, Data a)+ => a -- ^ helps fill in 'nodeAnnotations' (with 'Data')+ -> SrcSpanAnn' ann -- ^ return an empty list if this is unhelpful+ -> ReaderT NodeOrigin m [HieAST b]+makeNodeA x spn = makeNode x (locA spn)+ {-# INLINEABLE makeNode #-} makeNode :: (Monad m, Data a)@@ -555,6 +573,15 @@ where cons = mkFastString . show . toConstr $ x typ = mkFastString . show . typeRepTyCon . typeOf $ x++{-# INLINEABLE makeTypeNodeA #-}+makeTypeNodeA+ :: (Monad m, Data a)+ => a -- ^ helps fill in 'nodeAnnotations' (with 'Data')+ -> SrcSpanAnnA -- ^ return an empty list if this is unhelpful+ -> Type -- ^ type to associate with the node+ -> ReaderT NodeOrigin m [HieAST Type]+makeTypeNodeA x spn etyp = makeTypeNode x (locA spn) etyp {-# INLINEABLE makeTypeNode #-} makeTypeNode
compiler/GHC/Iface/Load.hs view
@@ -57,6 +57,7 @@ import GHC.Iface.Ext.Fields import GHC.Iface.Binary import GHC.Iface.Rename+import GHC.Iface.Env import GHC.Tc.Utils.Monad @@ -81,6 +82,7 @@ import GHC.Types.Id.Make ( seqId ) import GHC.Types.Annotations import GHC.Types.Name+import GHC.Types.Name.Cache import GHC.Types.Name.Env import GHC.Types.Avail import GHC.Types.Fixity@@ -166,7 +168,9 @@ -- It's not a wired-in thing -- the caller caught that importDecl name = ASSERT( not (isWiredInName name) )- do { traceIf nd_doc+ do { dflags <- getDynFlags+ ; logger <- getLogger+ ; liftIO $ trace_if logger dflags nd_doc -- Load the interface, which should populate the PTE ; mb_iface <- ASSERT2( isExternalName name, ppr name )@@ -240,7 +244,9 @@ = return () | otherwise = do { mod <- getModule- ; traceIf (text "checkWiredInTyCon" <+> ppr tc_name $$ ppr mod)+ ; dflags <- getDynFlags+ ; logger <- getLogger+ ; liftIO $ trace_if logger dflags (text "checkWiredInTyCon" <+> ppr tc_name $$ ppr mod) ; ASSERT( isExternalName tc_name ) when (mod /= nameModule tc_name) (initIfaceTcRn (loadWiredInHomeIface tc_name))@@ -311,12 +317,16 @@ -- and create a ModLocation. If successful, loadIface will read the -- interface; it will call the Finder again, but the ModLocation will be -- cached from the first search.- = do { hsc_env <- getTopEnv- ; res <- liftIO $ findImportedModule hsc_env mod maybe_pkg- ; case res of+ = do hsc_env <- getTopEnv+ let fc = hsc_FC hsc_env+ let dflags = hsc_dflags hsc_env+ let units = hsc_units hsc_env+ let home_unit = hsc_home_unit hsc_env+ res <- liftIO $ findImportedModule fc units home_unit dflags mod maybe_pkg+ case res of Found _ mod -> initIfaceTcRn $ loadInterface doc mod (ImportByUser want_boot) -- TODO: Make sure this error message is good- err -> return (Failed (cannotFindModule hsc_env mod err)) }+ err -> return (Failed (cannotFindModule hsc_env mod err)) -- | Load interface directly for a fully qualified 'Module'. (This is a fairly -- rare operation, but in particular it is used to load orphan modules@@ -405,7 +415,9 @@ -- | A wrapper for 'loadInterface' that throws an exception if it fails loadInterfaceWithException :: SDoc -> Module -> WhereFrom -> IfM lcl ModIface loadInterfaceWithException doc mod_name where_from- = withException (loadInterface doc mod_name where_from)+ = do+ dflags <- getDynFlags+ withException dflags (loadInterface doc mod_name where_from) ------------------ loadInterface :: SDoc -> Module -> WhereFrom@@ -438,8 +450,10 @@ { -- Read the state (eps,hpt) <- getEpsAndHpt ; gbl_env <- getGblEnv+ ; dflags <- getDynFlags+ ; logger <- getLogger - ; traceIf (text "Considering whether to load" <+> ppr mod <+> ppr from)+ ; liftIO $ trace_if logger dflags (text "Considering whether to load" <+> ppr mod <+> ppr from) -- Check whether we have the interface already ; hsc_env <- getTopEnv@@ -455,7 +469,9 @@ -- READ THE MODULE IN ; read_result <- case (wantHiBootFile home_unit eps mod from) of Failed err -> return (Failed err)- Succeeded hi_boot_file -> computeInterface doc_str hi_boot_file mod+ Succeeded hi_boot_file -> do+ hsc_env <- getTopEnv+ liftIO $ computeInterface hsc_env doc_str hi_boot_file mod ; case read_result of { Failed err -> do { let fake_iface = emptyFullModIface mod@@ -665,28 +681,32 @@ -- apply to the requirement itself; e.g., @p[A=<A>]:A@ does not require -- A.hi to be up-to-date (and indeed, we MUST NOT attempt to read A.hi, unless -- we are actually typechecking p.)-computeInterface ::- SDoc -> IsBootInterface -> Module- -> TcRnIf gbl lcl (MaybeErr SDoc (ModIface, FilePath))-computeInterface doc_str hi_boot_file mod0 = do- MASSERT( not (isHoleModule mod0) )- hsc_env <- getTopEnv- let home_unit = hsc_home_unit hsc_env- case getModuleInstantiation mod0 of- (imod, Just indef) | isHomeUnitIndefinite home_unit -> do- r <- findAndReadIface doc_str imod mod0 hi_boot_file- case r of- Succeeded (iface0, path) -> do- hsc_env <- getTopEnv- r <- liftIO $- rnModIface hsc_env (instUnitInsts (moduleUnit indef))- Nothing iface0- case r of- Right x -> return (Succeeded (x, path))- Left errs -> liftIO . throwIO . mkSrcErr $ errs- Failed err -> return (Failed err)- (mod, _) ->- findAndReadIface doc_str mod mod0 hi_boot_file+computeInterface+ :: HscEnv+ -> SDoc+ -> IsBootInterface+ -> Module+ -> IO (MaybeErr SDoc (ModIface, FilePath))+computeInterface hsc_env doc_str hi_boot_file mod0 = do+ MASSERT( not (isHoleModule mod0) )+ let name_cache = hsc_NC hsc_env+ let fc = hsc_FC hsc_env+ let home_unit = hsc_home_unit hsc_env+ let units = hsc_units hsc_env+ let dflags = hsc_dflags hsc_env+ let logger = hsc_logger hsc_env+ let hooks = hsc_hooks hsc_env+ let find_iface m = findAndReadIface logger name_cache fc hooks units home_unit dflags doc_str+ m mod0 hi_boot_file+ case getModuleInstantiation mod0 of+ (imod, Just indef) | isHomeUnitIndefinite home_unit ->+ find_iface imod >>= \case+ Succeeded (iface0, path) ->+ rnModIface hsc_env (instUnitInsts (moduleUnit indef)) Nothing iface0 >>= \case+ Right x -> return (Succeeded (x, path))+ Left errs -> throwIO . mkSrcErr $ errs+ Failed err -> return (Failed err)+ (mod, _) -> find_iface mod -- | Compute the signatures which must be compiled in order to -- load the interface for a 'Module'. The output of this function@@ -705,8 +725,10 @@ | otherwise = case getModuleInstantiation mod of (imod, Just indef) -> do+ dflags <- getDynFlags+ logger <- getLogger let insts = instUnitInsts (moduleUnit indef)- traceIf (text "Considering whether to load" <+> ppr mod <+>+ liftIO $ trace_if logger dflags (text "Considering whether to load" <+> ppr mod <+> text "to compute precise free module holes") (eps, hpt) <- getEpsAndHpt case tryEpsAndHpt eps hpt `firstJust` tryDepsCache eps imod insts of@@ -721,7 +743,17 @@ Just ifhs -> Just (renameFreeHoles ifhs insts) _otherwise -> Nothing readAndCache imod insts = do- mb_iface <- findAndReadIface (text "moduleFreeHolesPrecise" <+> doc_str) imod mod NotBoot+ hsc_env <- getTopEnv+ let nc = hsc_NC hsc_env+ let fc = hsc_FC hsc_env+ let home_unit = hsc_home_unit hsc_env+ let units = hsc_units hsc_env+ let dflags = hsc_dflags hsc_env+ let logger = hsc_logger hsc_env+ let hooks = hsc_hooks hsc_env+ mb_iface <- liftIO $ findAndReadIface logger nc fc hooks units home_unit dflags+ (text "moduleFreeHolesPrecise" <+> doc_str)+ imod mod NotBoot case mb_iface of Succeeded (iface, _) -> do let ifhs = mi_free_holes iface@@ -810,24 +842,25 @@ See #8320. -} -findAndReadIface :: SDoc- -- The unique identifier of the on-disk module we're- -- looking for- -> InstalledModule- -- The *actual* module we're looking for. We use- -- this to check the consistency of the requirements- -- of the module we read out.- -> Module- -> IsBootInterface -- True <=> Look for a .hi-boot file- -- False <=> Look for .hi file- -> TcRnIf gbl lcl (MaybeErr SDoc (ModIface, FilePath))- -- Nothing <=> file not found, or unreadable, or illegible- -- Just x <=> successfully found and parsed+findAndReadIface+ :: Logger+ -> NameCache+ -> FinderCache+ -> Hooks+ -> UnitState+ -> HomeUnit+ -> DynFlags+ -> SDoc -- ^ Reason for loading the iface (used for tracing)+ -> InstalledModule -- ^ The unique identifier of the on-disk module we're looking for+ -> Module -- ^ The *actual* module we're looking for. We use+ -- this to check the consistency of the requirements of the+ -- module we read out.+ -> IsBootInterface -- ^ Looking for .hi-boot or .hi file+ -> IO (MaybeErr SDoc (ModIface, FilePath))+findAndReadIface logger name_cache fc hooks unit_state home_unit dflags doc_str mod wanted_mod hi_boot_file = do+ let profile = targetProfile dflags - -- It *doesn't* add an error to the monad, because- -- sometimes it's ok to fail... see notes with loadInterface-findAndReadIface doc_str mod wanted_mod_with_insts hi_boot_file- = do traceIf (sep [hsep [text "Reading",+ trace_if logger dflags (sep [hsep [text "Reading", if hi_boot_file == IsBoot then text "[boot]" else Outputable.empty,@@ -835,92 +868,91 @@ ppr mod <> semi], nest 4 (text "reason:" <+> doc_str)]) - -- Check for GHC.Prim, and return its static interface- -- See Note [GHC.Prim] in primops.txt.pp.- -- TODO: make this check a function- if mod `installedModuleEq` gHC_PRIM- then do- hooks <- getHooks- let iface = case ghcPrimIfaceHook hooks of- Nothing -> ghcPrimIface- Just h -> h- return (Succeeded (iface, "<built in interface for GHC.Prim>"))- else do- dflags <- getDynFlags- -- Look for the file- hsc_env <- getTopEnv- mb_found <- liftIO (findExactModule hsc_env mod)- let home_unit = hsc_home_unit hsc_env- case mb_found of- InstalledFound loc mod -> do- -- Found file, so read it- let file_path = addBootSuffix_maybe hi_boot_file- (ml_hi_file loc)+ -- Check for GHC.Prim, and return its static interface+ -- See Note [GHC.Prim] in primops.txt.pp.+ -- TODO: make this check a function+ if mod `installedModuleEq` gHC_PRIM+ then do+ let iface = case ghcPrimIfaceHook hooks of+ Nothing -> ghcPrimIface+ Just h -> h+ return (Succeeded (iface, "<built in interface for GHC.Prim>"))+ else do+ -- Look for the file+ mb_found <- liftIO (findExactModule fc dflags unit_state home_unit mod)+ case mb_found of+ InstalledFound loc mod -> do+ -- Found file, so read it+ let file_path = addBootSuffix_maybe hi_boot_file (ml_hi_file loc)+ -- See Note [Home module load error]+ if isHomeInstalledModule home_unit mod &&+ not (isOneShot (ghcMode dflags))+ then return (Failed (homeModError mod loc))+ else do+ r <- read_file logger name_cache unit_state dflags wanted_mod file_path+ case r of+ Failed _+ -> return ()+ Succeeded (iface,fp)+ -> load_dynamic_too_maybe logger name_cache unit_state+ dflags wanted_mod+ hi_boot_file iface fp+ return r+ err -> do+ trace_if logger dflags (text "...not found")+ return $ Failed $ cannotFindInterface+ unit_state+ home_unit+ profile+ (may_show_locations dflags)+ (moduleName mod)+ err - -- See Note [Home module load error]- if isHomeInstalledModule home_unit mod &&- not (isOneShot (ghcMode dflags))- then return (Failed (homeModError mod loc))- else do r <- read_file file_path- checkBuildDynamicToo r- return r- err -> do- traceIf (text "...not found")- hsc_env <- getTopEnv- let profile = Profile (targetPlatform dflags) (ways dflags)- return $ Failed $ cannotFindInterface- (hsc_unit_env hsc_env)- profile- (may_show_locations (hsc_dflags hsc_env))- (moduleName mod)- err- where read_file file_path = do- traceIf (text "readIFace" <+> text file_path)- -- Figure out what is recorded in mi_module. If this is- -- a fully definite interface, it'll match exactly, but- -- if it's indefinite, the inside will be uninstantiated!- unit_state <- hsc_units <$> getTopEnv- let wanted_mod =- case getModuleInstantiation wanted_mod_with_insts of- (_, Nothing) -> wanted_mod_with_insts- (_, Just indef_mod) ->- instModuleToModule unit_state- (uninstantiateInstantiatedModule indef_mod)- read_result <- readIface wanted_mod file_path- case read_result of- Failed err -> return (Failed (badIfaceFile file_path err))- Succeeded iface -> return (Succeeded (iface, file_path))- -- Don't forget to fill in the package name...+-- | Check if we need to try the dynamic interface for -dynamic-too+load_dynamic_too_maybe :: Logger -> NameCache -> UnitState -> DynFlags -> Module -> IsBootInterface -> ModIface -> FilePath -> IO ()+load_dynamic_too_maybe logger name_cache unit_state dflags wanted_mod is_boot iface file_path+ -- Indefinite interfaces are ALWAYS non-dynamic.+ | not (moduleIsDefinite (mi_module iface)) = return ()+ | otherwise = dynamicTooState dflags >>= \case+ DT_Dont -> return ()+ DT_Failed -> return ()+ DT_Dyn -> load_dynamic_too logger name_cache unit_state dflags wanted_mod is_boot iface file_path+ DT_OK -> load_dynamic_too logger name_cache unit_state (setDynamicNow dflags) wanted_mod is_boot iface file_path - -- Indefinite interfaces are ALWAYS non-dynamic.- checkBuildDynamicToo (Succeeded (iface, _filePath))- | not (moduleIsDefinite (mi_module iface)) = return ()+load_dynamic_too :: Logger -> NameCache -> UnitState -> DynFlags -> Module -> IsBootInterface -> ModIface -> FilePath -> IO ()+load_dynamic_too logger name_cache unit_state dflags wanted_mod is_boot iface file_path = do+ let dynFilePath = addBootSuffix_maybe is_boot+ $ replaceExtension file_path (hiSuf dflags)+ read_file logger name_cache unit_state dflags wanted_mod dynFilePath >>= \case+ Succeeded (dynIface, _)+ | mi_mod_hash (mi_final_exts iface) == mi_mod_hash (mi_final_exts dynIface)+ -> return ()+ | otherwise ->+ do trace_if logger dflags (text "Dynamic hash doesn't match")+ setDynamicTooFailed dflags+ Failed err ->+ do trace_if logger dflags (text "Failed to load dynamic interface file:" $$ err)+ setDynamicTooFailed dflags - checkBuildDynamicToo (Succeeded (iface, filePath)) = do- let load_dynamic = do- dflags <- getDynFlags- let dynFilePath = addBootSuffix_maybe hi_boot_file- $ replaceExtension filePath (hiSuf dflags)- r <- read_file dynFilePath- case r of- Succeeded (dynIface, _)- | mi_mod_hash (mi_final_exts iface) == mi_mod_hash (mi_final_exts dynIface) ->- return ()- | otherwise ->- do traceIf (text "Dynamic hash doesn't match")- setDynamicTooFailed dflags- Failed err ->- do traceIf (text "Failed to load dynamic interface file:" $$ err)- setDynamicTooFailed dflags+read_file :: Logger -> NameCache -> UnitState -> DynFlags -> Module -> FilePath -> IO (MaybeErr SDoc (ModIface, FilePath))+read_file logger name_cache unit_state dflags wanted_mod file_path = do+ trace_if logger dflags (text "readIFace" <+> text file_path) - dflags <- getDynFlags- dynamicTooState dflags >>= \case- DT_Dont -> return ()- DT_Failed -> return ()- DT_Dyn -> load_dynamic- DT_OK -> withDynamicNow load_dynamic+ -- Figure out what is recorded in mi_module. If this is+ -- a fully definite interface, it'll match exactly, but+ -- if it's indefinite, the inside will be uninstantiated!+ let wanted_mod' =+ case getModuleInstantiation wanted_mod of+ (_, Nothing) -> wanted_mod+ (_, Just indef_mod) ->+ instModuleToModule unit_state+ (uninstantiateInstantiatedModule indef_mod)+ read_result <- readIface dflags name_cache wanted_mod' file_path+ case read_result of+ Failed err -> return (Failed (badIfaceFile file_path err))+ Succeeded iface -> return (Succeeded (iface, file_path))+ -- Don't forget to fill in the package name... - checkBuildDynamicToo _ = return () -- | Write interface file writeIface :: Logger -> DynFlags -> FilePath -> ModIface -> IO ()@@ -930,29 +962,32 @@ profile = targetProfile dflags writeBinIface profile printer hi_file_path new_iface --- @readIface@ tries just the one file.-readIface :: Module -> FilePath- -> TcRnIf gbl lcl (MaybeErr SDoc ModIface)- -- Failed err <=> file not found, or unreadable, or illegible- -- Succeeded iface <=> successfully found and parsed--readIface wanted_mod file_path- = do { res <- tryMostM $- readBinIface CheckHiWay QuietBinIFace file_path- ; case res of- Right iface- -- NB: This check is NOT just a sanity check, it is- -- critical for correctness of recompilation checking- -- (it lets us tell when -this-unit-id has changed.)- | wanted_mod == actual_mod- -> return (Succeeded iface)- | otherwise -> return (Failed err)- where- actual_mod = mi_module iface- err = hiModuleNameMismatchWarn wanted_mod actual_mod+-- | @readIface@ tries just the one file.+--+-- Failed err <=> file not found, or unreadable, or illegible+-- Succeeded iface <=> successfully found and parsed+readIface+ :: DynFlags+ -> NameCache+ -> Module+ -> FilePath+ -> IO (MaybeErr SDoc ModIface)+readIface dflags name_cache wanted_mod file_path = do+ let profile = targetProfile dflags+ res <- tryMost $ readBinIface profile name_cache CheckHiWay QuietBinIFace file_path+ case res of+ Right iface+ -- NB: This check is NOT just a sanity check, it is+ -- critical for correctness of recompilation checking+ -- (it lets us tell when -this-unit-id has changed.)+ | wanted_mod == actual_mod+ -> return (Succeeded iface)+ | otherwise -> return (Failed err)+ where+ actual_mod = mi_module iface+ err = hiModuleNameMismatchWarn wanted_mod actual_mod - Left exn -> return (Failed (text (showException exn)))- }+ Left exn -> return (Failed (text (showException exn))) {- *********************************************************@@ -1049,17 +1084,14 @@ -} -- | Read binary interface, and print it out-showIface :: HscEnv -> FilePath -> IO ()-showIface hsc_env filename = do- let dflags = hsc_dflags hsc_env- let logger = hsc_logger hsc_env- unit_state = hsc_units hsc_env- printer = putLogMsg logger dflags NoReason SevOutput noSrcSpan . withPprStyle defaultDumpStyle+showIface :: Logger -> DynFlags -> UnitState -> NameCache -> FilePath -> IO ()+showIface logger dflags unit_state name_cache filename = do+ let profile = targetProfile dflags+ printer = putLogMsg logger dflags MCOutput noSrcSpan . withPprStyle defaultDumpStyle -- skip the hi way check; we don't want to worry about profiled vs. -- non-profiled interfaces, for example.- iface <- initTcRnIf 's' hsc_env () () $- readBinIface IgnoreHiWay (TraceBinIFace printer) filename+ iface <- readBinIface profile name_cache IgnoreHiWay (TraceBinIFace printer) filename let -- See Note [Name qualification with --show-iface] qualifyImportedNames mod _@@ -1068,7 +1100,7 @@ print_unqual = QueryQualify qualifyImportedNames neverQualifyModules neverQualifyPackages- putLogMsg logger dflags NoReason SevDump noSrcSpan+ putLogMsg logger dflags MCDump noSrcSpan $ withPprStyle (mkDumpStyle print_unqual) $ pprModIface unit_state iface @@ -1265,25 +1297,24 @@ -- ----------------------------------------------------------------------------- -- Error messages -cannotFindInterface :: UnitEnv -> Profile -> ([FilePath] -> SDoc) -> ModuleName -> InstalledFindResult -> SDoc+cannotFindInterface :: UnitState -> HomeUnit -> Profile -> ([FilePath] -> SDoc) -> ModuleName -> InstalledFindResult -> SDoc cannotFindInterface = cantFindInstalledErr (sLit "Failed to load interface for") (sLit "Ambiguous interface for") cantFindInstalledErr :: PtrString -> PtrString- -> UnitEnv+ -> UnitState+ -> HomeUnit -> Profile -> ([FilePath] -> SDoc) -> ModuleName -> InstalledFindResult -> SDoc-cantFindInstalledErr cannot_find _ unit_env profile tried_these mod_name find_result+cantFindInstalledErr cannot_find _ unit_state home_unit profile tried_these mod_name find_result = ptext cannot_find <+> quotes (ppr mod_name) $$ more_info where- home_unit = ue_home_unit unit_env- unit_state = ue_units unit_env build_tag = waysBuildTag (profileWays profile) more_info
compiler/GHC/Iface/Make.hs view
@@ -73,6 +73,7 @@ import GHC.Types.SourceFile import GHC.Types.TyThing import GHC.Types.HpcInfo+import GHC.Types.CompleteMatch import GHC.Utils.Outputable import GHC.Utils.Panic@@ -211,7 +212,7 @@ usages <- mkUsageInfo hsc_env this_mod (imp_mods imports) used_names dep_files merged pluginModules - let (doc_hdr', doc_map, arg_map) = extractDocs tc_result+ (doc_hdr', doc_map, arg_map) <- extractDocs tc_result let partial_iface = mkIface_ hsc_env this_mod hsc_src@@ -347,8 +348,8 @@ -} mkIfaceCompleteMatch :: CompleteMatch -> IfaceCompleteMatch-mkIfaceCompleteMatch cls =- IfaceCompleteMatch (map conLikeName (uniqDSetToList cls))+mkIfaceCompleteMatch (CompleteMatch cls mtc) =+ IfaceCompleteMatch (map conLikeName (uniqDSetToList cls)) (toIfaceTyCon <$> mtc) {-
compiler/GHC/Iface/Recomp.hs view
@@ -24,6 +24,7 @@ import GHC.Iface.Recomp.Binary import GHC.Iface.Load import GHC.Iface.Recomp.Flags+import GHC.Iface.Env import GHC.Core import GHC.Tc.Utils.Monad@@ -40,6 +41,7 @@ import GHC.Utils.Binary import GHC.Utils.Fingerprint import GHC.Utils.Exception+import GHC.Utils.Logger import GHC.Types.Annotations import GHC.Types.Name@@ -156,33 +158,35 @@ check_old_iface hsc_env mod_summary src_modified maybe_iface = let dflags = hsc_dflags hsc_env+ logger = hsc_logger hsc_env getIface = case maybe_iface of Just _ -> do- traceIf (text "We already have the old interface for" <+>+ trace_if logger dflags (text "We already have the old interface for" <+> ppr (ms_mod mod_summary)) return maybe_iface Nothing -> loadIface loadIface = do let iface_path = msHiFilePath mod_summary- read_result <- readIface (ms_mod mod_summary) iface_path+ let ncu = hsc_NC hsc_env+ read_result <- readIface dflags ncu (ms_mod mod_summary) iface_path case read_result of Failed err -> do- traceIf (text "FYI: cannot read old interface file:" $$ nest 4 err)- traceHiDiffs (text "Old interface file was invalid:" $$ nest 4 err)+ trace_if logger dflags (text "FYI: cannot read old interface file:" $$ nest 4 err)+ trace_hi_diffs logger dflags (text "Old interface file was invalid:" $$ nest 4 err) return Nothing Succeeded iface -> do- traceIf (text "Read the interface file" <+> text iface_path)+ trace_if logger dflags (text "Read the interface file" <+> text iface_path) return $ Just iface src_changed- | gopt Opt_ForceRecomp (hsc_dflags hsc_env) = True+ | gopt Opt_ForceRecomp dflags = True | SourceModified <- src_modified = True | otherwise = False in do when src_changed $- traceHiDiffs (nest 4 $ text "Source file changed or recompilation check turned off")+ liftIO $ trace_hi_diffs logger dflags (nest 4 $ text "Source file changed or recompilation check turned off") case src_changed of -- If the source has changed and we're in interactive mode,@@ -194,11 +198,11 @@ -- Try and read the old interface for the current module -- from the .hi file left from the last time we compiled it True -> do- maybe_iface' <- getIface+ maybe_iface' <- liftIO $ getIface return (MustCompile, maybe_iface') False -> do- maybe_iface' <- getIface+ maybe_iface' <- liftIO $ getIface case maybe_iface' of -- We can't retrieve the iface Nothing -> return (MustCompile, Nothing)@@ -225,25 +229,27 @@ -> ModIface -- Old interface -> IfG (RecompileRequired, Maybe ModIface) checkVersions hsc_env mod_summary iface- = do { traceHiDiffs (text "Considering whether compilation is required for" <+>+ = do { liftIO $ trace_hi_diffs logger dflags+ (text "Considering whether compilation is required for" <+> ppr (mi_module iface) <> colon) -- readIface will have verified that the UnitId matches, -- but we ALSO must make sure the instantiation matches up. See -- test case bkpcabal04!+ ; hsc_env <- getTopEnv ; if not (isHomeModule home_unit (mi_module iface)) then return (RecompBecause "-this-unit-id changed", Nothing) else do {- ; recomp <- checkFlagHash hsc_env iface+ ; recomp <- liftIO $ checkFlagHash hsc_env iface ; if recompileRequired recomp then return (recomp, Nothing) else do {- ; recomp <- checkOptimHash hsc_env iface+ ; recomp <- liftIO $ checkOptimHash hsc_env iface ; if recompileRequired recomp then return (recomp, Nothing) else do {- ; recomp <- checkHpcHash hsc_env iface+ ; recomp <- liftIO $ checkHpcHash hsc_env iface ; if recompileRequired recomp then return (recomp, Nothing) else do {- ; recomp <- checkMergedSignatures mod_summary iface+ ; recomp <- liftIO $ checkMergedSignatures hsc_env mod_summary iface ; if recompileRequired recomp then return (recomp, Nothing) else do {- ; recomp <- checkHsig mod_summary iface+ ; recomp <- liftIO $ checkHsig logger home_unit dflags mod_summary iface ; if recompileRequired recomp then return (recomp, Nothing) else do {- ; recomp <- checkHie mod_summary+ ; recomp <- pure (checkHie dflags mod_summary) ; if recompileRequired recomp then return (recomp, Nothing) else do { ; recomp <- checkDependencies hsc_env mod_summary iface ; if recompileRequired recomp then return (recomp, Just iface) else do {@@ -270,6 +276,8 @@ ; return (recomp, Just iface) }}}}}}}}}} where+ logger = hsc_logger hsc_env+ dflags = hsc_dflags hsc_env home_unit = hsc_home_unit hsc_env -- This is a bit of a hack really mod_deps :: ModuleNameEnv ModuleNameWithIsBoot@@ -347,88 +355,91 @@ -- | Check if an hsig file needs recompilation because its -- implementing module has changed.-checkHsig :: ModSummary -> ModIface -> IfG RecompileRequired-checkHsig mod_summary iface = do- hsc_env <- getTopEnv- let home_unit = hsc_home_unit hsc_env- outer_mod = ms_mod mod_summary+checkHsig :: Logger -> HomeUnit -> DynFlags -> ModSummary -> ModIface -> IO RecompileRequired+checkHsig logger home_unit dflags mod_summary iface = do+ let outer_mod = ms_mod mod_summary inner_mod = homeModuleNameInstantiation home_unit (moduleName outer_mod) MASSERT( isHomeModule home_unit outer_mod ) case inner_mod == mi_semantic_module iface of- True -> up_to_date (text "implementing module unchanged")+ True -> up_to_date logger dflags (text "implementing module unchanged") False -> return (RecompBecause "implementing module changed") -- | Check if @.hie@ file is out of date or missing.-checkHie :: ModSummary -> IfG RecompileRequired-checkHie mod_summary = do- dflags <- getDynFlags+checkHie :: DynFlags -> ModSummary -> RecompileRequired+checkHie dflags mod_summary = let hie_date_opt = ms_hie_date mod_summary hs_date = ms_hs_date mod_summary- pure $ case gopt Opt_WriteHie dflags of- False -> UpToDate- True -> case hie_date_opt of- Nothing -> RecompBecause "HIE file is missing"- Just hie_date- | hie_date < hs_date- -> RecompBecause "HIE file is out of date"- | otherwise- -> UpToDate+ in if not (gopt Opt_WriteHie dflags)+ then UpToDate+ else case hie_date_opt of+ Nothing -> RecompBecause "HIE file is missing"+ Just hie_date+ | hie_date < hs_date+ -> RecompBecause "HIE file is out of date"+ | otherwise+ -> UpToDate -- | Check the flags haven't changed-checkFlagHash :: HscEnv -> ModIface -> IfG RecompileRequired+checkFlagHash :: HscEnv -> ModIface -> IO RecompileRequired checkFlagHash hsc_env iface = do+ let dflags = hsc_dflags hsc_env+ let logger = hsc_logger hsc_env let old_hash = mi_flag_hash (mi_final_exts iface)- new_hash <- liftIO $ fingerprintDynFlags hsc_env- (mi_module iface)- putNameLiterally+ new_hash <- fingerprintDynFlags hsc_env (mi_module iface) putNameLiterally case old_hash == new_hash of- True -> up_to_date (text "Module flags unchanged")- False -> out_of_date_hash "flags changed"+ True -> up_to_date logger dflags (text "Module flags unchanged")+ False -> out_of_date_hash logger dflags "flags changed" (text " Module flags have changed") old_hash new_hash -- | Check the optimisation flags haven't changed-checkOptimHash :: HscEnv -> ModIface -> IfG RecompileRequired+checkOptimHash :: HscEnv -> ModIface -> IO RecompileRequired checkOptimHash hsc_env iface = do+ let dflags = hsc_dflags hsc_env+ let logger = hsc_logger hsc_env let old_hash = mi_opt_hash (mi_final_exts iface)- new_hash <- liftIO $ fingerprintOptFlags (hsc_dflags hsc_env)+ new_hash <- fingerprintOptFlags (hsc_dflags hsc_env) putNameLiterally if | old_hash == new_hash- -> up_to_date (text "Optimisation flags unchanged")+ -> up_to_date logger dflags (text "Optimisation flags unchanged") | gopt Opt_IgnoreOptimChanges (hsc_dflags hsc_env)- -> up_to_date (text "Optimisation flags changed; ignoring")+ -> up_to_date logger dflags (text "Optimisation flags changed; ignoring") | otherwise- -> out_of_date_hash "Optimisation flags changed"+ -> out_of_date_hash logger dflags "Optimisation flags changed" (text " Optimisation flags have changed") old_hash new_hash -- | Check the HPC flags haven't changed-checkHpcHash :: HscEnv -> ModIface -> IfG RecompileRequired+checkHpcHash :: HscEnv -> ModIface -> IO RecompileRequired checkHpcHash hsc_env iface = do+ let dflags = hsc_dflags hsc_env+ let logger = hsc_logger hsc_env let old_hash = mi_hpc_hash (mi_final_exts iface)- new_hash <- liftIO $ fingerprintHpcFlags (hsc_dflags hsc_env)+ new_hash <- fingerprintHpcFlags (hsc_dflags hsc_env) putNameLiterally if | old_hash == new_hash- -> up_to_date (text "HPC flags unchanged")+ -> up_to_date logger dflags (text "HPC flags unchanged") | gopt Opt_IgnoreHpcChanges (hsc_dflags hsc_env)- -> up_to_date (text "HPC flags changed; ignoring")+ -> up_to_date logger dflags (text "HPC flags changed; ignoring") | otherwise- -> out_of_date_hash "HPC flags changed"+ -> out_of_date_hash logger dflags "HPC flags changed" (text " HPC flags have changed") old_hash new_hash -- Check that the set of signatures we are merging in match. -- If the -unit-id flags change, this can change too.-checkMergedSignatures :: ModSummary -> ModIface -> IfG RecompileRequired-checkMergedSignatures mod_summary iface = do- unit_state <- hsc_units <$> getTopEnv+checkMergedSignatures :: HscEnv -> ModSummary -> ModIface -> IO RecompileRequired+checkMergedSignatures hsc_env mod_summary iface = do+ let dflags = hsc_dflags hsc_env+ let logger = hsc_logger hsc_env+ let unit_state = hsc_units hsc_env let old_merged = sort [ mod | UsageMergedRequirement{ usg_mod = mod } <- mi_usages iface ] new_merged = case Map.lookup (ms_mod_name mod_summary) (requirementContext unit_state) of Nothing -> [] Just r -> sort $ map (instModuleToModule unit_state) r if old_merged == new_merged- then up_to_date (text "signatures to merge in unchanged" $$ ppr new_merged)+ then up_to_date logger dflags (text "signatures to merge in unchanged" $$ ppr new_merged) else return (RecompBecause "signatures to merge in changed") -- If the direct imports of this module are resolved to targets that@@ -452,31 +463,35 @@ checkDependencies hsc_env summary iface = checkList $- [ checkList (map dep_missing (ms_imps summary ++ ms_srcimps summary))+ [ liftIO $ checkList (map dep_missing (ms_imps summary ++ ms_srcimps summary)) , do (recomp, mnames_seen) <- runUntilRecompRequired $ map checkForNewHomeDependency (ms_home_imps summary)- case recomp of+ liftIO $ case recomp of UpToDate -> do let seen_home_deps = Set.unions $ map Set.fromList mnames_seen checkIfAllOldHomeDependenciesAreSeen seen_home_deps _ -> return recomp] where+ dflags = hsc_dflags hsc_env+ logger = hsc_logger hsc_env+ fc = hsc_FC hsc_env+ home_unit = hsc_home_unit hsc_env+ units = hsc_units hsc_env prev_dep_mods = dep_mods (mi_deps iface) prev_dep_plgn = dep_plgins (mi_deps iface) prev_dep_pkgs = dep_pkgs (mi_deps iface)- home_unit = hsc_home_unit hsc_env dep_missing (mb_pkg, L _ mod) = do- find_res <- liftIO $ findImportedModule hsc_env mod (mb_pkg)+ find_res <- findImportedModule fc units home_unit dflags mod (mb_pkg) let reason = moduleNameString mod ++ " changed" case find_res of Found _ mod | isHomeUnit home_unit pkg -> if moduleName mod `notElem` map gwib_mod prev_dep_mods ++ prev_dep_plgn- then do traceHiDiffs $+ then do trace_hi_diffs logger dflags $ text "imported module " <> quotes (ppr mod) <> text " not among previous dependencies" return (RecompBecause reason)@@ -484,7 +499,7 @@ return UpToDate | otherwise -> if toUnitId pkg `notElem` (map fst prev_dep_pkgs)- then do traceHiDiffs $+ then do trace_hi_diffs logger dflags $ text "imported module " <> quotes (ppr mod) <> text " is from package " <> quotes (ppr pkg) <> text ", which is not among previous dependencies"@@ -516,7 +531,7 @@ case find (not . isOldHomeDeps) mnames of Nothing -> return (UpToDate, mnames) Just new_dep_mname -> do- traceHiDiffs $+ trace_hi_diffs logger dflags $ text "imported home module " <> quotes (ppr mod) <> text " has a new dependency " <> quotes (ppr new_dep_mname) return (RecompBecause reason, [])@@ -541,12 +556,12 @@ if not (null unseen_old_deps) then do let missing_dep = Set.elemAt 0 unseen_old_deps- traceHiDiffs $+ trace_hi_diffs logger dflags $ text "missing old home dependency " <> quotes (ppr missing_dep) return $ RecompBecause "missing old dependency" else return UpToDate -needInterface :: Module -> (ModIface -> IfG RecompileRequired)+needInterface :: Module -> (ModIface -> IO RecompileRequired) -> IfG RecompileRequired needInterface mod continue = do@@ -558,12 +573,14 @@ Nothing -> return MustCompile Just recomp -> return recomp -getFromModIface :: String -> Module -> (ModIface -> IfG a)+getFromModIface :: String -> Module -> (ModIface -> IO a) -> IfG (Maybe a) getFromModIface doc_msg mod getter = do -- Load the imported interface if possible+ dflags <- getDynFlags+ logger <- getLogger let doc_str = sep [text doc_msg, ppr mod]- traceHiDiffs (text "Checking innterface for module" <+> ppr mod)+ liftIO $ trace_hi_diffs logger dflags (text "Checking interface for module" <+> ppr mod) mb_iface <- loadInterface doc_str mod ImportBySystem -- Load the interface, but don't complain on failure;@@ -571,14 +588,13 @@ case mb_iface of Failed _ -> do- traceHiDiffs (sep [text "Couldn't load interface for module",- ppr mod])+ liftIO $ trace_hi_diffs logger dflags (sep [text "Couldn't load interface for module", ppr mod]) return Nothing -- Couldn't find or parse a module mentioned in the -- old interface file. Don't complain: it might -- just be that the current module doesn't need that -- import and it's been deleted- Succeeded iface -> Just <$> getter iface+ Succeeded iface -> Just <$> liftIO (getter iface) -- | Given the usage information extracted from the old -- M.hi file for the module being compiled, figure out@@ -586,19 +602,23 @@ checkModUsage :: Unit -> Usage -> IfG RecompileRequired checkModUsage _this_pkg UsagePackageModule{ usg_mod = mod,- usg_mod_hash = old_mod_hash }- = needInterface mod $ \iface -> do+ usg_mod_hash = old_mod_hash } = do+ dflags <- getDynFlags+ logger <- getLogger+ needInterface mod $ \iface -> do let reason = moduleNameString (moduleName mod) ++ " changed"- checkModuleFingerprint reason old_mod_hash (mi_mod_hash (mi_final_exts iface))+ checkModuleFingerprint logger dflags reason old_mod_hash (mi_mod_hash (mi_final_exts iface)) -- We only track the ABI hash of package modules, rather than -- individual entity usages, so if the ABI hash changes we must -- recompile. This is safe but may entail more recompilation when -- a dependent package has changed. -checkModUsage _ UsageMergedRequirement{ usg_mod = mod, usg_mod_hash = old_mod_hash }- = needInterface mod $ \iface -> do+checkModUsage _ UsageMergedRequirement{ usg_mod = mod, usg_mod_hash = old_mod_hash } = do+ dflags <- getDynFlags+ logger <- getLogger+ needInterface mod $ \iface -> do let reason = moduleNameString (moduleName mod) ++ " changed (raw)"- checkModuleFingerprint reason old_mod_hash (mi_mod_hash (mi_final_exts iface))+ checkModuleFingerprint logger dflags reason old_mod_hash (mi_mod_hash (mi_final_exts iface)) checkModUsage this_pkg UsageHomeModule{ usg_mod_name = mod_name,@@ -607,30 +627,32 @@ usg_entities = old_decl_hash } = do let mod = mkModule this_pkg mod_name+ dflags <- getDynFlags+ logger <- getLogger needInterface mod $ \iface -> do-- let- new_mod_hash = mi_mod_hash (mi_final_exts iface)- new_decl_hash = mi_hash_fn (mi_final_exts iface)- new_export_hash = mi_exp_hash (mi_final_exts iface)+ let+ new_mod_hash = mi_mod_hash (mi_final_exts iface)+ new_decl_hash = mi_hash_fn (mi_final_exts iface)+ new_export_hash = mi_exp_hash (mi_final_exts iface) - reason = moduleNameString mod_name ++ " changed"+ reason = moduleNameString mod_name ++ " changed" + liftIO $ do -- CHECK MODULE- recompile <- checkModuleFingerprint reason old_mod_hash new_mod_hash+ recompile <- checkModuleFingerprint logger dflags reason old_mod_hash new_mod_hash if not (recompileRequired recompile) then return UpToDate else -- CHECK EXPORT LIST- checkMaybeHash reason maybe_old_export_hash new_export_hash+ checkMaybeHash logger dflags reason maybe_old_export_hash new_export_hash (text " Export list changed") $ do -- CHECK ITEMS ONE BY ONE- recompile <- checkList [ checkEntityUsage reason new_decl_hash u+ recompile <- checkList [ checkEntityUsage logger dflags reason new_decl_hash u | u <- old_decl_hash] if recompileRequired recompile then return recompile -- This one failed, so just bail out now- else up_to_date (text " Great! The bits I use are up to date")+ else up_to_date logger dflags (text " Great! The bits I use are up to date") checkModUsage _this_pkg UsageFile{ usg_file_path = file,@@ -651,54 +673,68 @@ #endif -------------------------checkModuleFingerprint :: String -> Fingerprint -> Fingerprint- -> IfG RecompileRequired-checkModuleFingerprint reason old_mod_hash new_mod_hash+checkModuleFingerprint+ :: Logger+ -> DynFlags+ -> String+ -> Fingerprint+ -> Fingerprint+ -> IO RecompileRequired+checkModuleFingerprint logger dflags reason old_mod_hash new_mod_hash | new_mod_hash == old_mod_hash- = up_to_date (text "Module fingerprint unchanged")+ = up_to_date logger dflags (text "Module fingerprint unchanged") | otherwise- = out_of_date_hash reason (text " Module fingerprint has changed")+ = out_of_date_hash logger dflags reason (text " Module fingerprint has changed") old_mod_hash new_mod_hash -------------------------checkMaybeHash :: String -> Maybe Fingerprint -> Fingerprint -> SDoc- -> IfG RecompileRequired -> IfG RecompileRequired-checkMaybeHash reason maybe_old_hash new_hash doc continue+checkMaybeHash+ :: Logger+ -> DynFlags+ -> String+ -> Maybe Fingerprint+ -> Fingerprint+ -> SDoc+ -> IO RecompileRequired+ -> IO RecompileRequired+checkMaybeHash logger dflags reason maybe_old_hash new_hash doc continue | Just hash <- maybe_old_hash, hash /= new_hash- = out_of_date_hash reason doc hash new_hash+ = out_of_date_hash logger dflags reason doc hash new_hash | otherwise = continue -------------------------checkEntityUsage :: String+checkEntityUsage :: Logger+ -> DynFlags+ -> String -> (OccName -> Maybe (OccName, Fingerprint)) -> (OccName, Fingerprint)- -> IfG RecompileRequired-checkEntityUsage reason new_hash (name,old_hash)- = case new_hash name of-- Nothing -> -- We used it before, but it ain't there now- out_of_date reason (sep [text "No longer exported:", ppr name])-- Just (_, new_hash) -- It's there, but is it up to date?- | new_hash == old_hash -> do traceHiDiffs (text " Up to date" <+> ppr name <+> parens (ppr new_hash))- return UpToDate- | otherwise -> out_of_date_hash reason (text " Out of date:" <+> ppr name)- old_hash new_hash+ -> IO RecompileRequired+checkEntityUsage logger dflags reason new_hash (name,old_hash) = do+ case new_hash name of+ -- We used it before, but it ain't there now+ Nothing -> out_of_date logger dflags reason (sep [text "No longer exported:", ppr name])+ -- It's there, but is it up to date?+ Just (_, new_hash)+ | new_hash == old_hash+ -> do trace_hi_diffs logger dflags (text " Up to date" <+> ppr name <+> parens (ppr new_hash))+ return UpToDate+ | otherwise+ -> out_of_date_hash logger dflags reason (text " Out of date:" <+> ppr name) old_hash new_hash -up_to_date :: SDoc -> IfG RecompileRequired-up_to_date msg = traceHiDiffs msg >> return UpToDate+up_to_date :: Logger -> DynFlags -> SDoc -> IO RecompileRequired+up_to_date logger dflags msg = trace_hi_diffs logger dflags msg >> return UpToDate -out_of_date :: String -> SDoc -> IfG RecompileRequired-out_of_date reason msg = traceHiDiffs msg >> return (RecompBecause reason)+out_of_date :: Logger -> DynFlags -> String -> SDoc -> IO RecompileRequired+out_of_date logger dflags reason msg = trace_hi_diffs logger dflags msg >> return (RecompBecause reason) -out_of_date_hash :: String -> SDoc -> Fingerprint -> Fingerprint -> IfG RecompileRequired-out_of_date_hash reason msg old_hash new_hash- = out_of_date reason (hsep [msg, ppr old_hash, text "->", ppr new_hash])+out_of_date_hash :: Logger -> DynFlags -> String -> SDoc -> Fingerprint -> Fingerprint -> IO RecompileRequired+out_of_date_hash logger dflags reason msg old_hash new_hash+ = out_of_date logger dflags reason (hsep [msg, ppr old_hash, text "->", ppr new_hash]) -----------------------checkList :: [IfG RecompileRequired] -> IfG RecompileRequired+checkList :: Monad m => [m RecompileRequired] -> m RecompileRequired -- This helper is used in two places checkList [] = return UpToDate checkList (check:checks) = do recompile <- check@@ -1161,12 +1197,13 @@ eps <- hscEPS hsc_env let hpt = hsc_HPT hsc_env+ dflags = hsc_dflags hsc_env pit = eps_PIT eps get_orph_hash mod = case lookupIfaceByModule hpt pit mod of Just iface -> return (mi_orphan_hash (mi_final_exts iface)) Nothing -> do -- similar to 'mkHashFun'- iface <- initIfaceLoad hsc_env . withException+ iface <- initIfaceLoad hsc_env . withException dflags $ loadInterface (text "getOrphanHashes") mod ImportBySystem return (mi_orphan_hash (mi_final_exts iface)) @@ -1454,6 +1491,7 @@ = lookup orig_mod where home_unit = hsc_home_unit hsc_env+ dflags = hsc_dflags hsc_env hpt = hsc_HPT hsc_env pit = eps_PIT eps occ = nameOccName name@@ -1467,7 +1505,7 @@ -- requirements; we didn't do any /real/ typechecking -- so there's no guarantee everything is loaded. -- Kind of a heinous hack.- initIfaceLoad hsc_env . withException+ initIfaceLoad hsc_env . withException dflags $ withoutDynamicNow -- For some unknown reason, we need to reset the -- dynamicNow bit, otherwise only dynamic
compiler/GHC/Iface/Rename.hs view
@@ -76,7 +76,7 @@ errs_var <- fmap sh_if_errs getGblEnv errs <- readTcRef errs_var -- TODO: maybe associate this with a source location?- writeTcRef errs_var (errs `snocBag` mkPlainMsgEnvelope noSrcSpan doc)+ writeTcRef errs_var (errs `snocBag` mkPlainMsgEnvelope ErrorWithoutFlag noSrcSpan doc) failM -- | What we have is a generalized ModIface, which corresponds to
compiler/GHC/Iface/Tidy.hs view
@@ -23,6 +23,7 @@ import GHC.Driver.Env import GHC.Tc.Types+import GHC.Tc.Utils.Env import GHC.Core import GHC.Core.Unfold@@ -44,9 +45,6 @@ import GHC.Iface.Tidy.StaticPtrTable import GHC.Iface.Env -import GHC.Tc.Utils.Env-import GHC.Tc.Utils.Monad- import GHC.Utils.Outputable import GHC.Utils.Misc( filterOut ) import GHC.Utils.Panic@@ -68,7 +66,7 @@ import GHC.Types.Name.Cache import GHC.Types.Name.Ppr import GHC.Types.Avail-import GHC.Types.Unique.Supply+import GHC.Types.Tickish import GHC.Types.TypeEnv import GHC.Unit.Module@@ -81,7 +79,6 @@ import Control.Monad import Data.Function import Data.List ( sortBy, mapAccumL )-import Data.IORef ( atomicModifyIORef' ) {- Constructing the TypeEnv, Instances, Rules from which the@@ -634,7 +631,7 @@ ; let internal_ids = filter (not . (`elemVarEnv` unfold_env1)) binders ; tidy_internal internal_ids unfold_env1 occ_env1 } where- nc_var = hsc_NC hsc_env+ name_cache = hsc_NC hsc_env -- init_ext_ids is the initial list of Ids that should be -- externalised. It serves as the starting point for finding a@@ -696,7 +693,7 @@ search ((idocc,referrer) : rest) unfold_env occ_env | idocc `elemVarEnv` unfold_env = search rest unfold_env occ_env | otherwise = do- (occ_env', name') <- tidyTopName mod nc_var (Just referrer) occ_env idocc+ (occ_env', name') <- tidyTopName mod name_cache (Just referrer) occ_env idocc let (new_ids, show_unfold) = addExternal omit_prags expose_all refined_id @@ -716,7 +713,7 @@ -> IO (UnfoldEnv, TidyOccEnv) tidy_internal [] unfold_env occ_env = return (unfold_env,occ_env) tidy_internal (id:ids) unfold_env occ_env = do- (occ_env', name') <- tidyTopName mod nc_var Nothing occ_env id+ (occ_env', name') <- tidyTopName mod name_cache Nothing occ_env id let unfold_env' = extendVarEnv unfold_env id (name',False) tidy_internal ids unfold_env' occ_env' @@ -737,7 +734,7 @@ show_unfold = show_unfolding unfolding never_active = isNeverActive (inlinePragmaActivation (inlinePragInfo idinfo)) loop_breaker = isStrongLoopBreaker (occInfo idinfo)- bottoming_fn = isDeadEndSig (strictnessInfo idinfo)+ bottoming_fn = isDeadEndSig (dmdSigInfo idinfo) -- Stuff to do with the Id's unfolding -- We leave the unfolding there even if there is a worker@@ -817,7 +814,7 @@ dffvExpr (Var v) = insert v dffvExpr (App e1 e2) = dffvExpr e1 >> dffvExpr e2 dffvExpr (Lam v e) = extendScope v (dffvExpr e)-dffvExpr (Tick (Breakpoint _ ids) e) = mapM_ insert ids >> dffvExpr e+dffvExpr (Tick (Breakpoint _ _ ids) e) = mapM_ insert ids >> dffvExpr e dffvExpr (Tick _other e) = dffvExpr e dffvExpr (Cast e _) = dffvExpr e dffvExpr (Let (NonRec x r) e) = dffvBind (x,r) >> extendScope x (dffvExpr e)@@ -1023,9 +1020,9 @@ we intend to externalise it. -} -tidyTopName :: Module -> IORef NameCache -> Maybe Id -> TidyOccEnv+tidyTopName :: Module -> NameCache -> Maybe Id -> TidyOccEnv -> Id -> IO (TidyOccEnv, Name)-tidyTopName mod nc_var maybe_ref occ_env id+tidyTopName mod name_cache maybe_ref occ_env id | global && internal = return (occ_env, localiseName name) | global && external = return (occ_env, name)@@ -1036,16 +1033,23 @@ -- Now we get to the real reason that all this is in the IO Monad: -- we have to update the name cache in a nice atomic fashion - | local && internal = do { new_local_name <- atomicModifyIORef' nc_var mk_new_local- ; return (occ_env', new_local_name) }+ | local && internal = do uniq <- takeUniqFromNameCache name_cache+ let new_local_name = mkInternalName uniq occ' loc+ return (occ_env', new_local_name) -- Even local, internal names must get a unique occurrence, because -- if we do -split-objs we externalise the name later, in the code generator -- -- Similarly, we must make sure it has a system-wide Unique, because -- the byte-code generator builds a system-wide Name->BCO symbol table - | local && external = do { new_external_name <- atomicModifyIORef' nc_var mk_new_external- ; return (occ_env', new_external_name) }+ | local && external = do new_external_name <- allocateGlobalBinder name_cache mod occ' loc+ return (occ_env', new_external_name)+ -- If we want to externalise a currently-local name, check+ -- whether we have already assigned a unique for it.+ -- If so, use it; if not, extend the table.+ -- All this is done by allocateGlobalBinder.+ -- This is needed when *re*-compiling a module in GHCi; we must+ -- use the same name for externally-visible things as we did before. | otherwise = panic "tidyTopName" where@@ -1079,18 +1083,7 @@ (occ_env', occ') = tidyOccName occ_env new_occ - mk_new_local nc = (nc { nsUniqs = us }, mkInternalName uniq occ' loc)- where- (uniq, us) = takeUniqFromSupply (nsUniqs nc) - mk_new_external nc = allocateGlobalBinder nc mod occ' loc- -- If we want to externalise a currently-local name, check- -- whether we have already assigned a unique for it.- -- If so, use it; if not, extend the table.- -- All this is done by allcoateGlobalBinder.- -- This is needed when *re*-compiling a module in GHCi; we must- -- use the same name for externally-visible things as we did before.- {- ************************************************************************ * *@@ -1100,7 +1093,7 @@ -} -- TopTidyEnv: when tidying we need to know--- * nc_var: The NameCache, containing a unique supply and any pre-ordained Names.+-- * name_cache: The NameCache, containing a unique supply and any pre-ordained Names. -- These may have arisen because the -- renamer read in an interface file mentioning M.$wf, say, -- and assigned it unique r77. If, on this compilation, we've@@ -1197,16 +1190,16 @@ -- Arity and strictness info are enough; -- c.f. GHC.Core.Tidy.tidyLetBndr `setArityInfo` arity- `setStrictnessInfo` final_sig- `setCprInfo` final_cpr+ `setDmdSigInfo` final_sig+ `setCprSigInfo` final_cpr `setUnfoldingInfo` minimal_unfold_info -- See note [Preserve evaluatedness] -- in GHC.Core.Tidy | otherwise -- Externally-visible Ids get the whole lot = vanillaIdInfo `setArityInfo` arity- `setStrictnessInfo` final_sig- `setCprInfo` final_cpr+ `setDmdSigInfo` final_sig+ `setCprSigInfo` final_cpr `setOccInfo` robust_occ_info `setInlinePragInfo` (inlinePragInfo idinfo) `setUnfoldingInfo` unfold_info@@ -1223,14 +1216,14 @@ --------- Strictness ------------ mb_bot_str = exprBotStrictness_maybe orig_rhs - sig = strictnessInfo idinfo+ sig = dmdSigInfo idinfo final_sig | not $ isTopSig sig = WARN( _bottom_hidden sig , ppr name ) sig -- try a cheap-and-cheerful bottom analyser | Just (_, nsig) <- mb_bot_str = nsig | otherwise = sig - cpr = cprInfo idinfo+ cpr = cprSigInfo idinfo final_cpr | Just _ <- mb_bot_str = mkCprSig arity botCpr | otherwise
compiler/GHC/Iface/Tidy/StaticPtrTable.hs view
@@ -148,6 +148,7 @@ import GHC.Types.Name import GHC.Types.Id import GHC.Types.TyThing+import GHC.Types.ForeignStubs import Control.Monad.Trans.Class (lift) import Control.Monad.Trans.State@@ -264,9 +265,9 @@ -- -- @fps@ is a list associating each binding corresponding to a static entry with -- its fingerprint.-sptModuleInitCode :: Platform -> Module -> [SptEntry] -> SDoc-sptModuleInitCode _ _ [] = Outputable.empty-sptModuleInitCode platform this_mod entries = vcat+sptModuleInitCode :: Platform -> Module -> [SptEntry] -> CStub+sptModuleInitCode _ _ [] = mempty+sptModuleInitCode platform this_mod entries = CStub $ vcat [ text "static void hs_spt_init_" <> ppr this_mod <> text "(void) __attribute__((constructor));" , text "static void hs_spt_init_" <> ppr this_mod <> text "(void)"
compiler/GHC/IfaceToCore.hs view
@@ -85,6 +85,7 @@ import GHC.Types.SourceFile import GHC.Types.SourceText import GHC.Types.Basic hiding ( SuccessFlag(..) )+import GHC.Types.CompleteMatch import GHC.Types.SrcLoc import GHC.Types.TypeEnv import GHC.Types.Unique.FM@@ -99,12 +100,14 @@ import GHC.Types.Id import GHC.Types.Id.Make import GHC.Types.Id.Info+import GHC.Types.Tickish import GHC.Types.TyThing import GHC.Fingerprint import qualified GHC.Data.BooleanFormula as BF import Control.Monad+import GHC.Parser.Annotation {- This module takes@@ -257,7 +260,7 @@ (mkNameEnv [ (n, op) | op@(IfaceClassOp n _ _) <- ops2 ]) in d1 { ifBody = (ifBody d1) { ifSigs = ops,- ifMinDef = BF.mkOr [noLoc bf1, noLoc bf2]+ ifMinDef = BF.mkOr [noLocA bf1, noLocA bf2] } } `withRolesFrom` d2 -- It doesn't matter; we'll check for consistency later when@@ -540,7 +543,15 @@ -- Re #9245, we always check if there is an hi-boot interface -- to check consistency against, rather than just when we notice -- that an hi-boot is necessary due to a circular import.- { read_result <- findAndReadIface+ { hsc_env <- getTopEnv+ ; let nc = hsc_NC hsc_env+ ; let fc = hsc_FC hsc_env+ ; let home_unit = hsc_home_unit hsc_env+ ; let units = hsc_units hsc_env+ ; let dflags = hsc_dflags hsc_env+ ; let logger = hsc_logger hsc_env+ ; let hooks = hsc_hooks hsc_env+ ; read_result <- liftIO $ findAndReadIface logger nc fc hooks units home_unit dflags need (fst (getModuleInstantiation mod)) mod IsBoot -- Hi-boot file @@ -1280,8 +1291,10 @@ tcIfaceCompleteMatches = mapM tcIfaceCompleteMatch tcIfaceCompleteMatch :: IfaceCompleteMatch -> IfL CompleteMatch-tcIfaceCompleteMatch (IfaceCompleteMatch ms) =- mkUniqDSet <$> mapM (forkM doc . tcIfaceConLike) ms+tcIfaceCompleteMatch (IfaceCompleteMatch ms mtc) = do+ conlikes <- mkUniqDSet <$> mapM (forkM doc . tcIfaceConLike) ms+ mtc' <- traverse tcIfaceTyCon mtc+ return (CompleteMatch conlikes mtc') where doc = text "COMPLETE sig" <+> ppr ms @@ -1529,7 +1542,7 @@ return (Tick tickish' expr') --------------------------tcIfaceTickish :: IfaceTickish -> IfM lcl (Tickish Id)+tcIfaceTickish :: IfaceTickish -> IfM lcl CoreTickish tcIfaceTickish (IfaceHpcTick modl ix) = return (HpcTick modl ix) tcIfaceTickish (IfaceSCC cc tick push) = return (ProfNote cc tick push) tcIfaceTickish (IfaceSource src name) = return (SourceNote src name)@@ -1624,8 +1637,8 @@ tcPrag :: IdInfo -> IfaceInfoItem -> IfL IdInfo tcPrag info HsNoCafRefs = return (info `setCafInfo` NoCafRefs) tcPrag info (HsArity arity) = return (info `setArityInfo` arity)- tcPrag info (HsStrictness str) = return (info `setStrictnessInfo` str)- tcPrag info (HsCpr cpr) = return (info `setCprInfo` cpr)+ tcPrag info (HsDmdSig str) = return (info `setDmdSigInfo` str)+ tcPrag info (HsCprSig cpr) = return (info `setCprSigInfo` cpr) tcPrag info (HsInline prag) = return (info `setInlinePragInfo` prag) tcPrag info HsLevity = return (info `setNeverLevPoly` ty) tcPrag info (HsLFInfo lf_info) = do@@ -1687,7 +1700,7 @@ } where -- Strictness should occur before unfolding!- strict_sig = strictnessInfo info+ strict_sig = dmdSigInfo info tcUnfolding toplvl name _ _ (IfCompulsory if_expr) = do { mb_expr <- tcPragExpr True toplvl name if_expr
compiler/GHC/IfaceToCore.hs-boot view
@@ -8,7 +8,7 @@ import GHC.Core.InstEnv ( ClsInst ) import GHC.Core.FamInstEnv ( FamInst ) import GHC.Core ( CoreRule )-import GHC.Types.CompleteMatch ( CompleteMatch )+import GHC.Types.CompleteMatch import GHC.Types.Annotations ( Annotation ) import GHC.Types.Name import GHC.Fingerprint.Type
compiler/GHC/Linker/Dynamic.hs view
@@ -23,12 +23,13 @@ import GHC.Linker.Unit import GHC.SysTools.Tasks import GHC.Utils.Logger+import GHC.Utils.TmpFs import qualified Data.Set as Set import System.FilePath -linkDynLib :: Logger -> DynFlags -> UnitEnv -> [String] -> [UnitId] -> IO ()-linkDynLib logger dflags0 unit_env o_files dep_packages+linkDynLib :: Logger -> TmpFs -> DynFlags -> UnitEnv -> [String] -> [UnitId] -> IO ()+linkDynLib logger tmpfs dflags0 unit_env o_files dep_packages = do let platform = ue_platform unit_env os = platformOS platform@@ -104,7 +105,7 @@ Just s -> s Nothing -> "HSdll.dll" - runLink logger dflags (+ runLink logger tmpfs dflags ( map Option verbFlags ++ [ Option "-o" , FileOption "" output_fn@@ -164,7 +165,7 @@ instName <- case dylibInstallName dflags of Just n -> return n Nothing -> return $ "@rpath" `combine` (takeFileName output_fn)- runLink logger dflags (+ runLink logger tmpfs dflags ( map Option verbFlags ++ [ Option "-dynamiclib" , Option "-o"@@ -206,7 +207,7 @@ -- See Note [-Bsymbolic assumptions by GHC] ["-Wl,-Bsymbolic" | not unregisterised] - runLink logger dflags (+ runLink logger tmpfs dflags ( map Option verbFlags ++ libmLinkOpts ++ [ Option "-o"
compiler/GHC/Linker/ExtraObj.hs view
@@ -32,6 +32,7 @@ import GHC.Utils.Misc import GHC.Utils.Outputable as Outputable import GHC.Utils.Logger+import GHC.Utils.TmpFs import GHC.Driver.Session import GHC.Driver.Ppr@@ -39,7 +40,6 @@ import qualified GHC.Data.ShortText as ST import GHC.SysTools.Elf-import GHC.SysTools.FileCleanup import GHC.SysTools.Tasks import GHC.SysTools.Info import GHC.Linker.Unit@@ -48,13 +48,13 @@ import Control.Monad import Data.Maybe -mkExtraObj :: Logger -> DynFlags -> UnitState -> Suffix -> String -> IO FilePath-mkExtraObj logger dflags unit_state extn xs- = do cFile <- newTempName logger dflags TFL_CurrentModule extn- oFile <- newTempName logger dflags TFL_GhcSession "o"+mkExtraObj :: Logger -> TmpFs -> DynFlags -> UnitState -> Suffix -> String -> IO FilePath+mkExtraObj logger tmpfs dflags unit_state extn xs+ = do cFile <- newTempName logger tmpfs dflags TFL_CurrentModule extn+ oFile <- newTempName logger tmpfs dflags TFL_GhcSession "o" writeFile cFile xs ccInfo <- liftIO $ getCompilerInfo logger dflags- runCc Nothing logger dflags+ runCc Nothing logger tmpfs dflags ([Option "-c", FileOption "" cFile, Option "-o",@@ -87,8 +87,8 @@ -- -- On Windows, when making a shared library we also may need a DllMain. ---mkExtraObjToLinkIntoBinary :: Logger -> DynFlags -> UnitState -> IO (Maybe FilePath)-mkExtraObjToLinkIntoBinary logger dflags unit_state = do+mkExtraObjToLinkIntoBinary :: Logger -> TmpFs -> DynFlags -> UnitState -> IO (Maybe FilePath)+mkExtraObjToLinkIntoBinary logger tmpfs dflags unit_state = do when (gopt Opt_NoHsMain dflags && haveRtsOptsFlags dflags) $ logInfo logger dflags $ withPprStyle defaultUserStyle (text "Warning: -rtsopts and -with-rtsopts have no effect with -no-hs-main." $$@@ -114,7 +114,7 @@ _ -> mk_extra_obj exeMain where- mk_extra_obj = fmap Just . mkExtraObj logger dflags unit_state "c" . showSDoc dflags+ mk_extra_obj = fmap Just . mkExtraObj logger tmpfs dflags unit_state "c" . showSDoc dflags exeMain = vcat [ text "#include <Rts.h>",@@ -163,12 +163,12 @@ -- this was included as inline assembly in the main.c file but this -- is pretty fragile. gas gets upset trying to calculate relative offsets -- that span the .note section (notably .text) when debug info is present-mkNoteObjsToLinkIntoBinary :: Logger -> DynFlags -> UnitEnv -> [UnitId] -> IO [FilePath]-mkNoteObjsToLinkIntoBinary logger dflags unit_env dep_packages = do+mkNoteObjsToLinkIntoBinary :: Logger -> TmpFs -> DynFlags -> UnitEnv -> [UnitId] -> IO [FilePath]+mkNoteObjsToLinkIntoBinary logger tmpfs dflags unit_env dep_packages = do link_info <- getLinkInfo dflags unit_env dep_packages if (platformSupportsSavingLinkOpts (platformOS platform ))- then fmap (:[]) $ mkExtraObj logger dflags unit_state "s" (showSDoc dflags (link_opts link_info))+ then fmap (:[]) $ mkExtraObj logger tmpfs dflags unit_state "s" (showSDoc dflags (link_opts link_info)) else return [] where
compiler/GHC/Linker/Loader.hs view
@@ -48,7 +48,6 @@ import GHC.Tc.Utils.Monad import GHC.Runtime.Interpreter-import GHC.Runtime.Interpreter.Types import GHCi.RemoteTypes import GHC.Iface.Load@@ -58,7 +57,6 @@ import GHC.ByteCode.Types import GHC.SysTools-import GHC.SysTools.FileCleanup import GHC.Types.Basic import GHC.Types.Name@@ -71,6 +69,7 @@ import GHC.Utils.Misc import GHC.Utils.Error import GHC.Utils.Logger+import GHC.Utils.TmpFs import GHC.Unit.Env import GHC.Unit.Finder@@ -116,25 +115,19 @@ uninitialised :: a uninitialised = panic "Loader not initialised" -modifyLS_ :: Loader -> (LoaderState -> IO LoaderState) -> IO ()-modifyLS_ dl f =- modifyMVar_ (loader_state dl) (fmap pure . f . fromMaybe uninitialised)+modifyLoaderState_ :: Interp -> (LoaderState -> IO LoaderState) -> IO ()+modifyLoaderState_ interp f =+ modifyMVar_ (loader_state (interpLoader interp))+ (fmap pure . f . fromMaybe uninitialised) -modifyLS :: Loader -> (LoaderState -> IO (LoaderState, a)) -> IO a-modifyLS dl f =- modifyMVar (loader_state dl) (fmapFst pure . f . fromMaybe uninitialised)+modifyLoaderState :: Interp -> (LoaderState -> IO (LoaderState, a)) -> IO a+modifyLoaderState interp f =+ modifyMVar (loader_state (interpLoader interp))+ (fmapFst pure . f . fromMaybe uninitialised) where fmapFst f = fmap (\(x, y) -> (f x, y)) -readLS :: Loader -> IO LoaderState-readLS dl =- (fmap (fromMaybe uninitialised) . readMVar) (loader_state dl)--modifyMbLS_- :: Loader -> (Maybe LoaderState -> IO (Maybe LoaderState)) -> IO ()-modifyMbLS_ dl f = modifyMVar_ (loader_state dl) f--emptyLS :: LoaderState-emptyLS = LoaderState+emptyLoaderState :: LoaderState+emptyLoaderState = LoaderState { closure_env = emptyNameEnv , itbl_env = emptyNameEnv , pkgs_loaded = init_pkgs@@ -149,21 +142,21 @@ -- explicit list. See rts/Linker.c for details. where init_pkgs = [rtsUnitId] -extendLoadedPkgs :: Loader -> [UnitId] -> IO ()-extendLoadedPkgs dl pkgs =- modifyLS_ dl $ \s ->+extendLoadedPkgs :: Interp -> [UnitId] -> IO ()+extendLoadedPkgs interp pkgs =+ modifyLoaderState_ interp $ \s -> return s{ pkgs_loaded = pkgs ++ pkgs_loaded s } -extendLoadedEnv :: Loader -> [(Name,ForeignHValue)] -> IO ()-extendLoadedEnv dl new_bindings =- modifyLS_ dl $ \pls@LoaderState{..} -> do+extendLoadedEnv :: Interp -> [(Name,ForeignHValue)] -> IO ()+extendLoadedEnv interp new_bindings =+ modifyLoaderState_ interp $ \pls@LoaderState{..} -> do let new_ce = extendClosureEnv closure_env new_bindings return $! pls{ closure_env = new_ce } -- strictness is important for not retaining old copies of the pls -deleteFromLoadedEnv :: Loader -> [Name] -> IO ()-deleteFromLoadedEnv dl to_remove =- modifyLS_ dl $ \pls -> do+deleteFromLoadedEnv :: Interp -> [Name] -> IO ()+deleteFromLoadedEnv interp to_remove =+ modifyLoaderState_ interp $ \pls -> do let ce = closure_env pls let new_ce = delListFromNameEnv ce to_remove return pls{ closure_env = new_ce }@@ -171,15 +164,14 @@ -- | Load the module containing the given Name and get its associated 'HValue'. -- -- Throws a 'ProgramError' if loading fails or the name cannot be found.-loadName :: HscEnv -> Name -> IO ForeignHValue-loadName hsc_env name = do- let dl = hsc_loader hsc_env- initLoaderState hsc_env- modifyLS dl $ \pls0 -> do+loadName :: Interp -> HscEnv -> Name -> IO ForeignHValue+loadName interp hsc_env name = do+ initLoaderState interp hsc_env+ modifyLoaderState interp $ \pls0 -> do pls <- if not (isExternalName name) then return pls0 else do- (pls', ok) <- loadDependencies hsc_env pls0 noSrcSpan+ (pls', ok) <- loadDependencies interp hsc_env pls0 noSrcSpan [nameModule name] if failed ok then throwGhcExceptionIO (ProgramError "")@@ -189,40 +181,47 @@ Just (_,aa) -> return (pls,aa) Nothing -> ASSERT2(isExternalName name, ppr name) do let sym_to_find = nameToCLabel name "closure"- m <- lookupClosure hsc_env (unpackFS sym_to_find)+ m <- lookupClosure interp (unpackFS sym_to_find) r <- case m of- Just hvref -> mkFinalizedHValue hsc_env hvref+ Just hvref -> mkFinalizedHValue interp hvref Nothing -> linkFail "GHC.Linker.Loader.loadName" (unpackFS sym_to_find) return (pls,r) -loadDependencies :: HscEnv -> LoaderState- -> SrcSpan -> [Module]- -> IO (LoaderState, SuccessFlag)-loadDependencies hsc_env pls span needed_mods = do+loadDependencies+ :: Interp+ -> HscEnv+ -> LoaderState+ -> SrcSpan -> [Module]+ -> IO (LoaderState, SuccessFlag)+loadDependencies interp hsc_env pls span needed_mods = do -- initLoaderState (hsc_dflags hsc_env) dl let hpt = hsc_HPT hsc_env+ let dflags = hsc_dflags hsc_env -- The interpreter and dynamic linker can only handle object code built -- the "normal" way, i.e. no non-std ways like profiling or ticky-ticky. -- So here we check the build tag: if we're building a non-standard way -- then we need to find & link object files built the "normal" way.- maybe_normal_osuf <- checkNonStdWay hsc_env span+ maybe_normal_osuf <- checkNonStdWay dflags interp span -- Find what packages and linkables are required (lnks, pkgs) <- getLinkDeps hsc_env hpt pls maybe_normal_osuf span needed_mods -- Link the packages and modules required- pls1 <- loadPackages' hsc_env pkgs pls- loadModules hsc_env pls1 lnks+ pls1 <- loadPackages' interp hsc_env pkgs pls+ loadModules interp hsc_env pls1 lnks -- | Temporarily extend the loaded env.--withExtendedLoadedEnv :: (ExceptionMonad m) =>- Loader -> [(Name,ForeignHValue)] -> m a -> m a-withExtendedLoadedEnv dl new_env action- = MC.bracket (liftIO $ extendLoadedEnv dl new_env)+withExtendedLoadedEnv+ :: (ExceptionMonad m)+ => Interp+ -> [(Name,ForeignHValue)]+ -> m a+ -> m a+withExtendedLoadedEnv interp new_env action+ = MC.bracket (liftIO $ extendLoadedEnv interp new_env) (\_ -> reset_old_env) (\_ -> action) where@@ -232,23 +231,27 @@ -- package), so the reset action only removes the names we -- added earlier. reset_old_env = liftIO $- modifyLS_ dl $ \pls ->+ modifyLoaderState_ interp $ \pls -> let cur = closure_env pls new = delListFromNameEnv cur (map fst new_env) in return pls{ closure_env = new } --- | Display the persistent linker state.-showLoaderState :: Loader -> IO SDoc-showLoaderState dl- = do pls <- readLS dl- return $ withPprStyle defaultDumpStyle- (vcat [text "----- Loader state -----",- text "Pkgs:" <+> ppr (pkgs_loaded pls),- text "Objs:" <+> ppr (objs_loaded pls),- text "BCOs:" <+> ppr (bcos_loaded pls)])+-- | Display the loader state.+showLoaderState :: Interp -> IO SDoc+showLoaderState interp = do+ ls <- readMVar (loader_state (interpLoader interp))+ let docs = case ls of+ Nothing -> [ text "Loader not initialised"]+ Just pls -> [ text "Pkgs:" <+> ppr (pkgs_loaded pls)+ , text "Objs:" <+> ppr (objs_loaded pls)+ , text "BCOs:" <+> ppr (bcos_loaded pls)+ ] + return $ withPprStyle defaultDumpStyle+ $ vcat (text "----- Loader state -----":docs) + {- ********************************************************************** Initialisation@@ -273,38 +276,40 @@ -- nothing. This is useful in Template Haskell, where we call it before -- trying to link. ---initLoaderState :: HscEnv -> IO ()-initLoaderState hsc_env = do- let dl = hsc_loader hsc_env- modifyMbLS_ dl $ \pls -> do+initLoaderState :: Interp -> HscEnv -> IO ()+initLoaderState interp hsc_env = do+ modifyMVar_ (loader_state (interpLoader interp)) $ \pls -> do case pls of Just _ -> return pls- Nothing -> Just <$> reallyInitLoaderState hsc_env+ Nothing -> Just <$> reallyInitLoaderState interp hsc_env -reallyInitLoaderState :: HscEnv -> IO LoaderState-reallyInitLoaderState hsc_env = do+reallyInitLoaderState :: Interp -> HscEnv -> IO LoaderState+reallyInitLoaderState interp hsc_env = do -- Initialise the linker state- let pls0 = emptyLS+ let pls0 = emptyLoaderState -- (a) initialise the C dynamic linker- initObjLinker hsc_env+ initObjLinker interp -- (b) Load packages from the command-line (Note [preload packages])- pls <- loadPackages' hsc_env (preloadUnits (hsc_units hsc_env)) pls0+ pls <- loadPackages' interp hsc_env (preloadUnits (hsc_units hsc_env)) pls0 -- steps (c), (d) and (e)- loadCmdLineLibs' hsc_env pls+ loadCmdLineLibs' interp hsc_env pls -loadCmdLineLibs :: HscEnv -> IO ()-loadCmdLineLibs hsc_env = do- let dl = hsc_loader hsc_env- initLoaderState hsc_env- modifyLS_ dl $ \pls ->- loadCmdLineLibs' hsc_env pls+loadCmdLineLibs :: Interp -> HscEnv -> IO ()+loadCmdLineLibs interp hsc_env = do+ initLoaderState interp hsc_env+ modifyLoaderState_ interp $ \pls ->+ loadCmdLineLibs' interp hsc_env pls -loadCmdLineLibs' :: HscEnv -> LoaderState -> IO LoaderState-loadCmdLineLibs' hsc_env pls =+loadCmdLineLibs'+ :: Interp+ -> HscEnv+ -> LoaderState+ -> IO LoaderState+loadCmdLineLibs' interp hsc_env pls = do let dflags@(DynFlags { ldInputs = cmdline_ld_inputs , libraryPaths = lib_paths_base})@@ -335,7 +340,7 @@ maybePutStr logger dflags (unlines $ map (" "++) gcc_paths) libspecs- <- mapM (locateLib hsc_env False lib_paths_env gcc_paths) minus_ls+ <- mapM (locateLib interp hsc_env False lib_paths_env gcc_paths) minus_ls -- (d) Link .o files from the command-line classified_ld_inputs <- mapM (classifyLdInput logger dflags)@@ -364,17 +369,17 @@ in nub $ map normalise paths let lib_paths = nub $ lib_paths_base ++ gcc_paths all_paths_env <- addEnvPaths "LD_LIBRARY_PATH" all_paths- pathCache <- mapM (addLibrarySearchPath hsc_env) all_paths_env+ pathCache <- mapM (addLibrarySearchPath interp) all_paths_env let merged_specs = mergeStaticObjects cmdline_lib_specs- pls1 <- foldM (preloadLib hsc_env lib_paths framework_paths) pls+ pls1 <- foldM (preloadLib interp hsc_env lib_paths framework_paths) pls merged_specs maybePutStr logger dflags "final link ... "- ok <- resolveObjs hsc_env+ ok <- resolveObjs interp -- DLLs are loaded, reset the search paths- mapM_ (removeLibrarySearchPath hsc_env) $ reverse pathCache+ mapM_ (removeLibrarySearchPath interp) $ reverse pathCache if succeeded ok then maybePutStrLn logger dflags "done" else throwGhcExceptionIO (ProgramError "linking extra libraries/objects failed")@@ -424,16 +429,21 @@ | isObjectFilename platform f = return (Just (Objects [f])) | isDynLibFilename platform f = return (Just (DLLPath f)) | otherwise = do- putLogMsg logger dflags NoReason SevInfo noSrcSpan+ putLogMsg logger dflags MCInfo noSrcSpan $ withPprStyle defaultUserStyle (text ("Warning: ignoring unrecognised input `" ++ f ++ "'")) return Nothing where platform = targetPlatform dflags preloadLib- :: HscEnv -> [String] -> [String] -> LoaderState- -> LibrarySpec -> IO LoaderState-preloadLib hsc_env lib_paths framework_paths pls lib_spec = do+ :: Interp+ -> HscEnv+ -> [String]+ -> [String]+ -> LoaderState+ -> LibrarySpec+ -> IO LoaderState+preloadLib interp hsc_env lib_paths framework_paths pls lib_spec = do maybePutStr logger dflags ("Loading object " ++ showLS lib_spec ++ " ... ") case lib_spec of Objects static_ishs -> do@@ -447,7 +457,7 @@ return pls DLL dll_unadorned -> do- maybe_errstr <- loadDLL hsc_env (platformSOName platform dll_unadorned)+ maybe_errstr <- loadDLL interp (platformSOName platform dll_unadorned) case maybe_errstr of Nothing -> maybePutStrLn logger dflags "done" Just mm | platformOS platform /= OSDarwin ->@@ -457,14 +467,14 @@ -- since (apparently) some things install that way - see -- ticket #8770. let libfile = ("lib" ++ dll_unadorned) <.> "so"- err2 <- loadDLL hsc_env libfile+ err2 <- loadDLL interp libfile case err2 of Nothing -> maybePutStrLn logger dflags "done" Just _ -> preloadFailed mm lib_paths lib_spec return pls DLLPath dll_path -> do- do maybe_errstr <- loadDLL hsc_env dll_path+ do maybe_errstr <- loadDLL interp dll_path case maybe_errstr of Nothing -> maybePutStrLn logger dflags "done" Just mm -> preloadFailed mm lib_paths lib_spec@@ -472,7 +482,7 @@ Framework framework -> if platformUsesFrameworks (targetPlatform dflags)- then do maybe_errstr <- loadFramework hsc_env framework_paths framework+ then do maybe_errstr <- loadFramework interp framework_paths framework case maybe_errstr of Nothing -> maybePutStrLn logger dflags "done" Just mm -> preloadFailed mm framework_paths lib_spec@@ -501,9 +511,9 @@ = do b <- or <$> mapM doesFileExist names if not b then return (False, pls) else if hostIsDynamic- then do pls1 <- dynLoadObjs hsc_env pls names+ then do pls1 <- dynLoadObjs interp hsc_env pls names return (True, pls1)- else do mapM_ (loadObj hsc_env) names+ else do mapM_ (loadObj interp) names return (True, pls) preload_static_archive _paths name@@ -512,7 +522,7 @@ else do if hostIsDynamic then throwGhcExceptionIO $ CmdLineError dynamic_msg- else loadArchive hsc_env name+ else loadArchive interp name return True where dynamic_msg = unlines@@ -535,38 +545,31 @@ -- Raises an IO exception ('ProgramError') if it can't find a compiled -- version of the dependents to load. ---loadExpr :: HscEnv -> SrcSpan -> UnlinkedBCO -> IO ForeignHValue-loadExpr hsc_env span root_ul_bco- = do {- -- Initialise the linker (if it's not been done already)- ; initLoaderState hsc_env-- -- Extract the Loader value for passing into required places- ; let dl = hsc_loader hsc_env-- -- Take lock for the actual work.- ; modifyLS dl $ \pls0 -> do {-- -- Load the packages and modules required- ; (pls, ok) <- loadDependencies hsc_env pls0 span needed_mods- ; if failed ok then- throwGhcExceptionIO (ProgramError "")- else do {-- -- Load the expression itself- let ie = itbl_env pls- ce = closure_env pls+loadExpr :: Interp -> HscEnv -> SrcSpan -> UnlinkedBCO -> IO ForeignHValue+loadExpr interp hsc_env span root_ul_bco = do+ -- Initialise the linker (if it's not been done already)+ initLoaderState interp hsc_env - -- Load the necessary packages and linkables+ -- Take lock for the actual work.+ modifyLoaderState interp $ \pls0 -> do+ -- Load the packages and modules required+ (pls, ok) <- loadDependencies interp hsc_env pls0 span needed_mods+ if failed ok+ then throwGhcExceptionIO (ProgramError "")+ else do+ -- Load the expression itself+ let ie = itbl_env pls+ ce = closure_env pls - ; let nobreakarray = error "no break array"- bco_ix = mkNameEnv [(unlinkedBCOName root_ul_bco, 0)]- ; resolved <- linkBCO hsc_env ie ce bco_ix nobreakarray root_ul_bco- ; [root_hvref] <- createBCOs hsc_env [resolved]- ; fhv <- mkFinalizedHValue hsc_env root_hvref- ; return (pls, fhv)- }}}- where+ -- Load the necessary packages and linkables+ let nobreakarray = error "no break array"+ bco_ix = mkNameEnv [(unlinkedBCOName root_ul_bco, 0)]+ resolved <- linkBCO interp ie ce bco_ix nobreakarray root_ul_bco+ [root_hvref] <- createBCOs interp dflags [resolved]+ fhv <- mkFinalizedHValue interp root_hvref+ return (pls, fhv)+ where+ dflags = hsc_dflags hsc_env free_names = uniqDSetToList (bcoFreeNames root_ul_bco) needed_mods :: [Module]@@ -580,12 +583,12 @@ -- by default, so we can safely ignore them here. dieWith :: DynFlags -> SrcSpan -> SDoc -> IO a-dieWith dflags span msg = throwGhcExceptionIO (ProgramError (showSDoc dflags (mkLocMessage SevFatal span msg)))+dieWith dflags span msg = throwGhcExceptionIO (ProgramError (showSDoc dflags (mkLocMessage MCFatal span msg))) -checkNonStdWay :: HscEnv -> SrcSpan -> IO (Maybe FilePath)-checkNonStdWay hsc_env srcspan- | Just (ExternalInterp {}) <- hsc_interp hsc_env = return Nothing+checkNonStdWay :: DynFlags -> Interp -> SrcSpan -> IO (Maybe FilePath)+checkNonStdWay dflags interp srcspan+ | ExternalInterp {} <- interpInstance interp = return Nothing -- with -fexternal-interpreter we load the .o files, whatever way -- they were built. If they were built for a non-std way, then -- we will use the appropriate variant of the iserv binary to load them.@@ -594,12 +597,12 @@ -- Only if we are compiling with the same ways as GHC is built -- with, can we dynamically load those object files. (see #3604) - | objectSuf (hsc_dflags hsc_env) == normalObjectSuffix && not (null targetFullWays)- = failNonStd (hsc_dflags hsc_env) srcspan+ | objectSuf dflags == normalObjectSuffix && not (null targetFullWays)+ = failNonStd dflags srcspan | otherwise = return (Just (hostWayTag ++ "o")) where- targetFullWays = fullWays (ways (hsc_dflags hsc_env))+ targetFullWays = fullWays (ways dflags) hostWayTag = case waysTag hostFullWays of "" -> "" tag -> tag ++ "_"@@ -728,7 +731,10 @@ | otherwise = do -- It's not in the HPT because we are in one shot mode, -- so use the Finder to get a ModLocation...- mb_stuff <- findHomeModule hsc_env mod_name+ let fc = hsc_FC hsc_env+ let home_unit = hsc_home_unit hsc_env+ let dflags = hsc_dflags hsc_env+ mb_stuff <- findHomeModule fc home_unit dflags mod_name case mb_stuff of Found loc mod -> found loc mod _ -> no_obj mod_name@@ -771,18 +777,15 @@ ********************************************************************* -} -loadDecls :: HscEnv -> SrcSpan -> CompiledByteCode -> IO ()-loadDecls hsc_env span cbc@CompiledByteCode{..} = do+loadDecls :: Interp -> HscEnv -> SrcSpan -> CompiledByteCode -> IO ()+loadDecls interp hsc_env span cbc@CompiledByteCode{..} = do -- Initialise the linker (if it's not been done already)- initLoaderState hsc_env-- -- Extract the Loader for passing into required places- let dl = hsc_loader hsc_env+ initLoaderState interp hsc_env -- Take lock for the actual work.- modifyLS_ dl $ \pls0 -> do+ modifyLoaderState_ interp $ \pls0 -> do -- Link the packages and modules required- (pls, ok) <- loadDependencies hsc_env pls0 span needed_mods+ (pls, ok) <- loadDependencies interp hsc_env pls0 span needed_mods if failed ok then throwGhcExceptionIO (ProgramError "") else do@@ -791,12 +794,13 @@ ce = closure_env pls -- Link the necessary packages and linkables- new_bindings <- linkSomeBCOs hsc_env ie ce [cbc]- nms_fhvs <- makeForeignNamedHValueRefs hsc_env new_bindings+ new_bindings <- linkSomeBCOs dflags interp ie ce [cbc]+ nms_fhvs <- makeForeignNamedHValueRefs interp new_bindings let pls2 = pls { closure_env = extendClosureEnv ce nms_fhvs , itbl_env = ie } return pls2 where+ dflags = hsc_dflags hsc_env free_names = uniqDSetToList $ foldr (unionUniqDSets . bcoFreeNames) emptyUniqDSet bc_bcos @@ -816,12 +820,11 @@ ********************************************************************* -} -loadModule :: HscEnv -> Module -> IO ()-loadModule hsc_env mod = do- initLoaderState hsc_env- let dl = hsc_loader hsc_env- modifyLS_ dl $ \pls -> do- (pls', ok) <- loadDependencies hsc_env pls noSrcSpan [mod]+loadModule :: Interp -> HscEnv -> Module -> IO ()+loadModule interp hsc_env mod = do+ initLoaderState interp hsc_env+ modifyLoaderState_ interp $ \pls -> do+ (pls', ok) <- loadDependencies interp hsc_env pls noSrcSpan [mod] if failed ok then throwGhcExceptionIO (ProgramError "could not load module") else return pls'@@ -834,20 +837,21 @@ ********************************************************************* -} -loadModules :: HscEnv -> LoaderState -> [Linkable] -> IO (LoaderState, SuccessFlag)-loadModules hsc_env pls linkables+loadModules :: Interp -> HscEnv -> LoaderState -> [Linkable] -> IO (LoaderState, SuccessFlag)+loadModules interp hsc_env pls linkables = mask_ $ do -- don't want to be interrupted by ^C in here let (objs, bcos) = partition isObjectLinkable (concatMap partitionLinkable linkables)+ let dflags = hsc_dflags hsc_env -- Load objects first; they can't depend on BCOs- (pls1, ok_flag) <- loadObjects hsc_env pls objs+ (pls1, ok_flag) <- loadObjects interp hsc_env pls objs if failed ok_flag then return (pls1, Failed) else do- pls2 <- dynLinkBCOs hsc_env pls1 bcos+ pls2 <- dynLinkBCOs dflags interp pls1 bcos return (pls2, Succeeded) @@ -887,43 +891,48 @@ -- -- If the interpreter uses dynamic-linking, build a shared library and load it. -- Otherwise, use the RTS linker.-loadObjects :: HscEnv -> LoaderState -> [Linkable]- -> IO (LoaderState, SuccessFlag)-loadObjects hsc_env pls objs = do+loadObjects+ :: Interp+ -> HscEnv+ -> LoaderState+ -> [Linkable]+ -> IO (LoaderState, SuccessFlag)+loadObjects interp hsc_env pls objs = do let (objs_loaded', new_objs) = rmDupLinkables (objs_loaded pls) objs pls1 = pls { objs_loaded = objs_loaded' } unlinkeds = concatMap linkableUnlinked new_objs wanted_objs = map nameOfObject unlinkeds - if interpreterDynamic (hscInterp hsc_env)- then do pls2 <- dynLoadObjs hsc_env pls1 wanted_objs+ if interpreterDynamic interp+ then do pls2 <- dynLoadObjs interp hsc_env pls1 wanted_objs return (pls2, Succeeded)- else do mapM_ (loadObj hsc_env) wanted_objs+ else do mapM_ (loadObj interp) wanted_objs -- Link them all together- ok <- resolveObjs hsc_env+ ok <- resolveObjs interp -- If resolving failed, unload all our -- object modules and carry on if succeeded ok then return (pls1, Succeeded) else do- pls2 <- unload_wkr hsc_env [] pls1+ pls2 <- unload_wkr interp [] pls1 return (pls2, Failed) -- | Create a shared library containing the given object files and load it.-dynLoadObjs :: HscEnv -> LoaderState -> [FilePath] -> IO LoaderState-dynLoadObjs _ pls [] = return pls-dynLoadObjs hsc_env pls@LoaderState{..} objs = do+dynLoadObjs :: Interp -> HscEnv -> LoaderState -> [FilePath] -> IO LoaderState+dynLoadObjs _ _ pls [] = return pls+dynLoadObjs interp hsc_env pls@LoaderState{..} objs = do let unit_env = hsc_unit_env hsc_env let dflags = hsc_dflags hsc_env let logger = hsc_logger hsc_env+ let tmpfs = hsc_tmpfs hsc_env let platform = ue_platform unit_env let minus_ls = [ lib | Option ('-':'l':lib) <- ldInputs dflags ] let minus_big_ls = [ lib | Option ('-':'L':lib) <- ldInputs dflags ] (soFile, libPath , libName) <-- newTempLibName logger dflags TFL_CurrentModule (platformSOExt platform)+ newTempLibName logger tmpfs dflags TFL_CurrentModule (platformSOExt platform) let dflags2 = dflags { -- We don't want the original ldInputs in@@ -969,11 +978,11 @@ -- link all "loaded packages" so symbols in those can be resolved -- Note: We are loading packages with local scope, so to see the -- symbols in this link we must link all loaded packages again.- linkDynLib logger dflags2 unit_env objs pkgs_loaded+ linkDynLib logger tmpfs dflags2 unit_env objs pkgs_loaded -- if we got this far, extend the lifetime of the library file- changeTempFilesLifetime dflags TFL_GhcSession [soFile]- m <- loadDLL hsc_env soFile+ changeTempFilesLifetime tmpfs TFL_GhcSession [soFile]+ m <- loadDLL interp soFile case m of Nothing -> return $! pls { temp_sos = (libPath, libName) : temp_sos } Just err -> linkFail msg err@@ -999,8 +1008,8 @@ ********************************************************************* -} -dynLinkBCOs :: HscEnv -> LoaderState -> [Linkable] -> IO LoaderState-dynLinkBCOs hsc_env pls bcos = do+dynLinkBCOs :: DynFlags -> Interp -> LoaderState -> [Linkable] -> IO LoaderState+dynLinkBCOs dflags interp pls bcos = do let (bcos_loaded', new_bcos) = rmDupLinkables (bcos_loaded pls) bcos pls1 = pls { bcos_loaded = bcos_loaded' }@@ -1015,21 +1024,22 @@ gce = closure_env pls final_ie = foldr plusNameEnv (itbl_env pls) ies - names_and_refs <- linkSomeBCOs hsc_env final_ie gce cbcs+ names_and_refs <- linkSomeBCOs dflags interp final_ie gce cbcs -- We only want to add the external ones to the ClosureEnv let (to_add, to_drop) = partition (isExternalName.fst) names_and_refs -- Immediately release any HValueRefs we're not going to add- freeHValueRefs hsc_env (map snd to_drop)+ freeHValueRefs interp (map snd to_drop) -- Wrap finalizers on the ones we want to keep- new_binds <- makeForeignNamedHValueRefs hsc_env to_add+ new_binds <- makeForeignNamedHValueRefs interp to_add return pls1 { closure_env = extendClosureEnv gce new_binds, itbl_env = final_ie } -- Link a bunch of BCOs and return references to their values-linkSomeBCOs :: HscEnv+linkSomeBCOs :: DynFlags+ -> Interp -> ItblEnv -> ClosureEnv -> [CompiledByteCode]@@ -1038,7 +1048,7 @@ -- the incoming unlinked BCOs. Each gives the -- value of the corresponding unlinked BCO -linkSomeBCOs hsc_env ie ce mods = foldr fun do_link mods []+linkSomeBCOs dflags interp ie ce mods = foldr fun do_link mods [] where fun CompiledByteCode{..} inner accum = case bc_breaks of@@ -1051,16 +1061,16 @@ let flat = [ (breakarray, bco) | (breakarray, bcos) <- mods, bco <- bcos ] names = map (unlinkedBCOName . snd) flat bco_ix = mkNameEnv (zip names [0..])- resolved <- sequence [ linkBCO hsc_env ie ce bco_ix breakarray bco+ resolved <- sequence [ linkBCO interp ie ce bco_ix breakarray bco | (breakarray, bco) <- flat ]- hvrefs <- createBCOs hsc_env resolved+ hvrefs <- createBCOs interp dflags resolved return (zip names hvrefs) -- | Useful to apply to the result of 'linkSomeBCOs' makeForeignNamedHValueRefs- :: HscEnv -> [(Name,HValueRef)] -> IO [(Name,ForeignHValue)]-makeForeignNamedHValueRefs hsc_env bindings =- mapM (\(n, hvref) -> (n,) <$> mkFinalizedHValue hsc_env hvref) bindings+ :: Interp -> [(Name,HValueRef)] -> IO [(Name,ForeignHValue)]+makeForeignNamedHValueRefs interp bindings =+ mapM (\(n, hvref) -> (n,) <$> mkFinalizedHValue interp hvref) bindings {- ********************************************************************** @@ -1082,21 +1092,20 @@ -- -- * we also implicitly unload all temporary bindings at this point. ---unload :: HscEnv- -> [Linkable] -- ^ The linkables to *keep*.- -> IO ()-unload hsc_env linkables+unload+ :: Interp+ -> HscEnv+ -> [Linkable] -- ^ The linkables to *keep*.+ -> IO ()+unload interp hsc_env linkables = mask_ $ do -- mask, so we're safe from Ctrl-C in here -- Initialise the linker (if it's not been done already)- initLoaderState hsc_env-- -- Extract Loader for passing into required places- let dl = hsc_loader hsc_env+ initLoaderState interp hsc_env new_pls- <- modifyLS dl $ \pls -> do- pls1 <- unload_wkr hsc_env linkables pls+ <- modifyLoaderState interp $ \pls -> do+ pls1 <- unload_wkr interp linkables pls return (pls1, pls1) let dflags = hsc_dflags hsc_env@@ -1107,14 +1116,15 @@ text "unload: retaining bcos" <+> ppr (bcos_loaded new_pls) return () -unload_wkr :: HscEnv- -> [Linkable] -- stable linkables- -> LoaderState- -> IO LoaderState+unload_wkr+ :: Interp+ -> [Linkable] -- stable linkables+ -> LoaderState+ -> IO LoaderState -- Does the core unload business -- (the wrapper blocks exceptions and deals with the LS get and put) -unload_wkr hsc_env keep_linkables pls@LoaderState{..} = do+unload_wkr interp keep_linkables pls@LoaderState{..} = do -- NB. careful strictness here to avoid keeping the old LS when -- we're unloading some code. -fghci-leak-check with the tests in -- testsuite/ghci can detect space leaks here.@@ -1135,7 +1145,7 @@ -- of lookupSymbol results. when (not (null (objs_to_unload ++ filter (not . null . linkableObjs) bcos_to_unload))) $- purgeLookupSymbolCache hsc_env+ purgeLookupSymbolCache interp let !bcos_retained = mkModuleSet $ map linkableModule remaining_bcos_loaded @@ -1167,7 +1177,7 @@ -- not much benefit. | otherwise- = mapM_ (unloadObj hsc_env) [f | DotO f <- linkableUnlinked lnk]+ = mapM_ (unloadObj interp) [f | DotO f <- linkableUnlinked lnk] -- The components of a BCO linkable may contain -- dot-o files. Which is very confusing. --@@ -1236,7 +1246,7 @@ -- automatically, and it doesn't matter what order you specify the input -- packages. ---loadPackages :: HscEnv -> [UnitId] -> IO ()+loadPackages :: Interp -> HscEnv -> [UnitId] -> IO () -- NOTE: in fact, since each module tracks all the packages it depends on, -- we don't really need to use the package-config dependencies. --@@ -1245,16 +1255,15 @@ -- perhaps makes the error message a bit more localised if we get a link -- failure. So the dependency walking code is still here. -loadPackages hsc_env new_pkgs = do+loadPackages interp hsc_env new_pkgs = do -- It's probably not safe to try to load packages concurrently, so we take -- a lock.- initLoaderState hsc_env- let dl = hsc_loader hsc_env- modifyLS_ dl $ \pls ->- loadPackages' hsc_env new_pkgs pls+ initLoaderState interp hsc_env+ modifyLoaderState_ interp $ \pls ->+ loadPackages' interp hsc_env new_pkgs pls -loadPackages' :: HscEnv -> [UnitId] -> LoaderState -> IO LoaderState-loadPackages' hsc_env new_pks pls = do+loadPackages' :: Interp -> HscEnv -> [UnitId] -> LoaderState -> IO LoaderState+loadPackages' interp hsc_env new_pks pls = do pkgs' <- link (pkgs_loaded pls) new_pks return $! pls { pkgs_loaded = pkgs' } where@@ -1270,20 +1279,20 @@ = do { -- Link dependents first pkgs' <- link pkgs (unitDepends pkg_cfg) -- Now link the package itself- ; loadPackage hsc_env pkg_cfg+ ; loadPackage interp hsc_env pkg_cfg ; return (new_pkg : pkgs') } | otherwise = throwGhcExceptionIO (CmdLineError ("unknown package: " ++ unpackFS (unitIdFS new_pkg))) -loadPackage :: HscEnv -> UnitInfo -> IO ()-loadPackage hsc_env pkg+loadPackage :: Interp -> HscEnv -> UnitInfo -> IO ()+loadPackage interp hsc_env pkg = do let dflags = hsc_dflags hsc_env let logger = hsc_logger hsc_env platform = targetPlatform dflags- is_dyn = interpreterDynamic (hscInterp hsc_env)+ is_dyn = interpreterDynamic interp dirs | is_dyn = map ST.unpack $ Packages.unitLibraryDynDirs pkg | otherwise = map ST.unpack $ Packages.unitLibraryDirs pkg @@ -1313,9 +1322,9 @@ dirs_env <- addEnvPaths "LIBRARY_PATH" dirs hs_classifieds- <- mapM (locateLib hsc_env True dirs_env gcc_paths) hs_libs'+ <- mapM (locateLib interp hsc_env True dirs_env gcc_paths) hs_libs' extra_classifieds- <- mapM (locateLib hsc_env False dirs_env gcc_paths) extra_libs+ <- mapM (locateLib interp hsc_env False dirs_env gcc_paths) extra_libs let classifieds = hs_classifieds ++ extra_classifieds -- Complication: all the .so's must be loaded before any of the .o's.@@ -1329,7 +1338,7 @@ let dll_paths = map takeDirectory known_dlls all_paths = nub $ map normalise $ dll_paths ++ dirs all_paths_env <- addEnvPaths "LD_LIBRARY_PATH" all_paths- pathCache <- mapM (addLibrarySearchPath hsc_env) all_paths_env+ pathCache <- mapM (addLibrarySearchPath interp) all_paths_env maybePutSDoc logger dflags (text "Loading unit " <> pprUnitInfoForUser pkg <> text " ... ")@@ -1337,28 +1346,28 @@ -- See comments with partOfGHCi #if defined(CAN_LOAD_DLL) when (unitPackageName pkg `notElem` partOfGHCi) $ do- loadFrameworks hsc_env platform pkg+ loadFrameworks interp platform pkg -- See Note [Crash early load_dyn and locateLib] -- Crash early if can't load any of `known_dlls`- mapM_ (load_dyn hsc_env True) known_dlls+ mapM_ (load_dyn interp hsc_env True) known_dlls -- For remaining `dlls` crash early only when there is surely -- no package's DLL around ... (not is_dyn)- mapM_ (load_dyn hsc_env (not is_dyn) . platformSOName platform) dlls+ mapM_ (load_dyn interp hsc_env (not is_dyn) . platformSOName platform) dlls #endif -- After loading all the DLLs, we can load the static objects. -- Ordering isn't important here, because we do one final link -- step to resolve everything.- mapM_ (loadObj hsc_env) objs- mapM_ (loadArchive hsc_env) archs+ mapM_ (loadObj interp) objs+ mapM_ (loadArchive interp) archs maybePutStr logger dflags "linking ... "- ok <- resolveObjs hsc_env+ ok <- resolveObjs interp -- DLLs are loaded, reset the search paths -- Import libraries will be loaded via loadArchive so only -- reset the DLL search path after all archives are loaded -- as well.- mapM_ (removeLibrarySearchPath hsc_env) $ reverse pathCache+ mapM_ (removeLibrarySearchPath interp) $ reverse pathCache if succeeded ok then maybePutStrLn logger dflags "done."@@ -1413,9 +1422,9 @@ -- can be passed directly to loadDLL. They are either fully-qualified -- ("/usr/lib/libfoo.so"), or unqualified ("libfoo.so"). In the latter case, -- loadDLL is going to search the system paths to find the library.-load_dyn :: HscEnv -> Bool -> FilePath -> IO ()-load_dyn hsc_env crash_early dll = do- r <- loadDLL hsc_env dll+load_dyn :: Interp -> HscEnv -> Bool -> FilePath -> IO ()+load_dyn interp hsc_env crash_early dll = do+ r <- loadDLL interp dll case r of Nothing -> return () Just err ->@@ -1424,7 +1433,7 @@ else when (wopt Opt_WarnMissedExtraSharedLib dflags) $ putLogMsg logger dflags- (Reason Opt_WarnMissedExtraSharedLib) SevWarning+ (mkMCDiagnostic $ WarningWithFlag Opt_WarnMissedExtraSharedLib) noSrcSpan $ withPprStyle defaultUserStyle (note err) where dflags = hsc_dflags hsc_env@@ -1435,14 +1444,14 @@ , "(the package DLL is loaded by the system linker" , " which manages dependencies by itself)." ] -loadFrameworks :: HscEnv -> Platform -> UnitInfo -> IO ()-loadFrameworks hsc_env platform pkg+loadFrameworks :: Interp -> Platform -> UnitInfo -> IO ()+loadFrameworks interp platform pkg = when (platformUsesFrameworks platform) $ mapM_ load frameworks where fw_dirs = map ST.unpack $ Packages.unitExtDepFrameworkDirs pkg frameworks = map ST.unpack $ Packages.unitExtDepFrameworks pkg - load fw = do r <- loadFramework hsc_env fw_dirs fw+ load fw = do r <- loadFramework interp fw_dirs fw case r of Nothing -> return () Just err -> cmdLineErrorIO ("can't load framework: "@@ -1454,9 +1463,15 @@ -- standard system search path. -- For GHCi we tend to prefer dynamic libraries over static ones as -- they are easier to load and manage, have less overhead.-locateLib :: HscEnv -> Bool -> [FilePath] -> [FilePath] -> String- -> IO LibrarySpec-locateLib hsc_env is_hs lib_dirs gcc_dirs lib+locateLib+ :: Interp+ -> HscEnv+ -> Bool+ -> [FilePath]+ -> [FilePath]+ -> String+ -> IO LibrarySpec+locateLib interp hsc_env is_hs lib_dirs gcc_dirs lib | not is_hs -- For non-Haskell libraries (e.g. gmp, iconv): -- first look in library-dirs for a dynamic library (on User paths only)@@ -1509,7 +1524,6 @@ where dflags = hsc_dflags hsc_env logger = hsc_logger hsc_env- interp = hscInterp hsc_env dirs = lib_dirs ++ gcc_dirs gcc = False user = True@@ -1548,7 +1562,7 @@ findDll re = let dirs' = if re == user then lib_dirs else gcc_dirs in liftM (fmap DLLPath) $ findFile dirs' dyn_lib_file findSysDll = fmap (fmap $ DLL . dropExtension . takeFileName) $- findSystemLibrary hsc_env so_name+ findSystemLibrary interp so_name tryGcc = let search = searchForLibUsingGcc logger dflags dllpath = liftM (fmap DLLPath) short = dllpath $ search so_name lib_dirs@@ -1717,8 +1731,7 @@ maybePutSDoc logger dflags s = when (verbosity dflags > 1) $ putLogMsg logger dflags- NoReason- SevInteractive+ MCInteractive noSrcSpan $ withPprStyle defaultUserStyle s
compiler/GHC/Linker/MacOS.hs view
@@ -10,7 +10,6 @@ import GHC.Platform import GHC.Driver.Session-import GHC.Driver.Env import GHC.Unit.Types import GHC.Unit.State@@ -18,7 +17,7 @@ import GHC.SysTools.Tasks -import GHC.Runtime.Interpreter (loadDLL)+import GHC.Runtime.Interpreter import GHC.Utils.Exception import GHC.Utils.Logger@@ -123,8 +122,8 @@ -- Darwin / MacOS X only: load a framework -- a framework is a dynamic library packaged inside a directory of the same -- name. They are searched for in different paths than normal libraries.-loadFramework :: HscEnv -> [FilePath] -> FilePath -> IO (Maybe String)-loadFramework hsc_env extraPaths rootname+loadFramework :: Interp -> [FilePath] -> FilePath -> IO (Maybe String)+loadFramework interp extraPaths rootname = do { either_dir <- tryIO getHomeDirectory ; let homeFrameworkPath = case either_dir of Left _ -> []@@ -147,7 +146,7 @@ -- has no built-in paths for frameworks: give up return $ Just errs findLoadDLL (p:ps) errs =- do { dll <- loadDLL hsc_env (p </> fwk_file)+ do { dll <- loadDLL interp (p </> fwk_file) ; case dll of Nothing -> return Nothing Just err -> findLoadDLL ps ((p ++ ": " ++ err):errs)
compiler/GHC/Linker/Static.hs view
@@ -13,7 +13,6 @@ import GHC.SysTools import GHC.SysTools.Ar-import GHC.SysTools.FileCleanup import GHC.Unit.Env import GHC.Unit.Types@@ -23,6 +22,7 @@ import GHC.Utils.Logger import GHC.Utils.Monad import GHC.Utils.Misc+import GHC.Utils.TmpFs import GHC.Linker.MacOS import GHC.Linker.Unit@@ -64,11 +64,11 @@ -Xlinker, but not -Wl. -} -linkBinary :: Logger -> DynFlags -> UnitEnv -> [FilePath] -> [UnitId] -> IO ()+linkBinary :: Logger -> TmpFs -> DynFlags -> UnitEnv -> [FilePath] -> [UnitId] -> IO () linkBinary = linkBinary' False -linkBinary' :: Bool -> Logger -> DynFlags -> UnitEnv -> [FilePath] -> [UnitId] -> IO ()-linkBinary' staticLink logger dflags unit_env o_files dep_units = do+linkBinary' :: Bool -> Logger -> TmpFs -> DynFlags -> UnitEnv -> [FilePath] -> [UnitId] -> IO ()+linkBinary' staticLink logger tmpfs dflags unit_env o_files dep_units = do let platform = ue_platform unit_env unit_state = ue_units unit_env toolSettings' = toolSettings dflags@@ -123,7 +123,7 @@ if gopt Opt_SingleLibFolder dflags then do libs <- getLibs dflags unit_env dep_units- tmpDir <- newTempDir logger dflags+ tmpDir <- newTempDir logger tmpfs dflags sequence_ [ copyFile lib (tmpDir </> basename) | (lib, basename) <- libs] return [ "-L" ++ tmpDir ]@@ -138,8 +138,8 @@ let lib_paths = libraryPaths dflags let lib_path_opts = map ("-L"++) lib_paths - extraLinkObj <- maybeToList <$> mkExtraObjToLinkIntoBinary logger dflags unit_state- noteLinkObjs <- mkNoteObjsToLinkIntoBinary logger dflags unit_env dep_units+ extraLinkObj <- maybeToList <$> mkExtraObjToLinkIntoBinary logger tmpfs dflags unit_state+ noteLinkObjs <- mkNoteObjsToLinkIntoBinary logger tmpfs dflags unit_env dep_units let (pre_hs_libs, post_hs_libs)@@ -181,16 +181,16 @@ let extra_ld_inputs = ldInputs dflags rc_objs <- case platformOS platform of- OSMinGW32 | gopt Opt_GenManifest dflags -> maybeCreateManifest logger dflags output_fn+ OSMinGW32 | gopt Opt_GenManifest dflags -> maybeCreateManifest logger tmpfs dflags output_fn _ -> return [] let link dflags args | staticLink = GHC.SysTools.runLibtool logger dflags args | platformOS platform == OSDarwin = do- GHC.SysTools.runLink logger dflags args+ GHC.SysTools.runLink logger tmpfs dflags args GHC.Linker.MacOS.runInjectRPaths logger dflags pkg_lib_paths output_fn | otherwise- = GHC.SysTools.runLink logger dflags args+ = GHC.SysTools.runLink logger tmpfs dflags args link dflags ( map GHC.SysTools.Option verbFlags
compiler/GHC/Linker/Windows.hs view
@@ -6,7 +6,7 @@ import GHC.Prelude import GHC.SysTools import GHC.Driver.Session-import GHC.SysTools.FileCleanup+import GHC.Utils.TmpFs import GHC.Utils.Logger import System.FilePath@@ -14,10 +14,11 @@ maybeCreateManifest :: Logger+ -> TmpFs -> DynFlags -> FilePath -- ^ filename of executable -> IO [FilePath] -- ^ extra objects to embed, maybe-maybeCreateManifest logger dflags exe_filename = do+maybeCreateManifest logger tmpfs dflags exe_filename = do let manifest_filename = exe_filename <.> "manifest" manifest = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n\@@ -44,9 +45,9 @@ if not (gopt Opt_EmbedManifest dflags) then return [] else do- rc_filename <- newTempName logger dflags TFL_CurrentModule "rc"+ rc_filename <- newTempName logger tmpfs dflags TFL_CurrentModule "rc" rc_obj_filename <-- newTempName logger dflags TFL_GhcSession (objectSuf dflags)+ newTempName logger tmpfs dflags TFL_GhcSession (objectSuf dflags) writeFile rc_filename $ "1 24 MOVEABLE PURE " ++ show manifest_filename ++ "\n"
compiler/GHC/Rename/Bind.hs view
@@ -1,3 +1,4 @@+{-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE ScopedTypeVariables, BangPatterns #-} {-# LANGUAGE TypeFamilies #-} @@ -31,7 +32,7 @@ import GHC.Prelude -import {-# SOURCE #-} GHC.Rename.Expr( rnLExpr, rnStmts )+import {-# SOURCE #-} GHC.Rename.Expr( rnExpr, rnLExpr, rnStmts ) import GHC.Hs import GHC.Tc.Utils.Monad@@ -40,8 +41,8 @@ import GHC.Rename.Names import GHC.Rename.Env import GHC.Rename.Fixity-import GHC.Rename.Utils ( HsDocContext(..), mapFvRn, extendTyVarEnvFVRn- , checkDupRdrNames, warnUnusedLocalBinds+import GHC.Rename.Utils ( HsDocContext(..), mapFvRn+ , checkDupRdrNames, checkDupRdrNamesN, warnUnusedLocalBinds , checkUnusedRecordWildcard , checkDupAndShadowedNames, bindLocalNamesFV , addNoNestedForallsContextsErr, checkInferredVars )@@ -224,13 +225,13 @@ rnIPBinds :: HsIPBinds GhcPs -> RnM (HsIPBinds GhcRn, FreeVars) rnIPBinds (IPBinds _ ip_binds ) = do- (ip_binds', fvs_s) <- mapAndUnzipM (wrapLocFstM rnIPBind) ip_binds+ (ip_binds', fvs_s) <- mapAndUnzipM (wrapLocFstMA rnIPBind) ip_binds return (IPBinds noExtField ip_binds', plusFVs fvs_s) rnIPBind :: IPBind GhcPs -> RnM (IPBind GhcRn, FreeVars) rnIPBind (IPBind _ ~(Left n) expr) = do (expr',fvExpr) <- rnLExpr expr- return (IPBind noExtField (Left n) expr', fvExpr)+ return (IPBind noAnn (Left n) expr', fvExpr) {- ************************************************************************@@ -282,7 +283,7 @@ -> HsValBinds GhcPs -> RnM (HsValBindsLR GhcRn GhcPs) rnValBindsLHS topP (ValBinds x mbinds sigs)- = do { mbinds' <- mapBagM (wrapLocM (rnBindLHS topP doc)) mbinds+ = do { mbinds' <- mapBagM (wrapLocMA (rnBindLHS topP doc)) mbinds ; return $ ValBinds x mbinds' sigs } where bndrs = collectHsBindsBinders CollNoDictBinders mbinds@@ -429,15 +430,15 @@ rnBindLHS name_maker _ (PatSynBind x psb@PSB{ psb_id = rdrname }) | isTopRecNameMaker name_maker- = do { addLocM checkConName rdrname- ; name <- lookupLocatedTopBndrRn rdrname -- Should be in scope already- ; return (PatSynBind x psb{ psb_ext = noExtField, psb_id = name }) }+ = do { addLocMA checkConName rdrname+ ; name <- lookupLocatedTopBndrRnN rdrname -- Should be in scope already+ ; return (PatSynBind x psb{ psb_ext = noAnn, psb_id = name }) } | otherwise -- Pattern synonym, not at top level = do { addErr localPatternSynonymErr -- Complain, but make up a fake -- name so that we can carry on ; name <- applyNameMaker name_maker rdrname- ; return (PatSynBind x psb{ psb_ext = noExtField, psb_id = name }) }+ ; return (PatSynBind x psb{ psb_ext = noAnn, psb_id = name }) } where localPatternSynonymErr :: SDoc localPatternSynonymErr@@ -450,7 +451,7 @@ -> LHsBindLR GhcRn GhcPs -> RnM (LHsBind GhcRn, [Name], Uses) rnLBind sig_fn (L loc bind)- = setSrcSpan loc $+ = setSrcSpanA loc $ do { (bind', bndrs, dus) <- rnBind sig_fn bind ; return (L loc bind', bndrs, dus) } @@ -488,7 +489,7 @@ -- See Note [Pattern bindings that bind no variables] ; whenWOptM Opt_WarnUnusedPatternBinds $ when (null bndrs && not ok_nobind_pat) $- addWarn (Reason Opt_WarnUnusedPatternBinds) $+ addDiagnostic (WarningWithFlag Opt_WarnUnusedPatternBinds) $ unusedPatBindWarn bind' ; fvs' `seq` -- See Note [Free-variable space leak]@@ -608,7 +609,7 @@ where env = mkHsSigEnv get_scoped_tvs sigs - get_scoped_tvs :: LSig GhcRn -> Maybe ([Located Name], [Name])+ get_scoped_tvs :: LSig GhcRn -> Maybe ([LocatedN Name], [Name]) -- Returns (binders, scoped tvs for those binders) get_scoped_tvs (L _ (ClassOpSig _ _ names sig_ty)) = Just (names, hsScopedTvs sig_ty)@@ -631,7 +632,7 @@ where add_one_sig :: MiniFixityEnv -> LFixitySig GhcPs -> RnM MiniFixityEnv add_one_sig env (L loc (FixitySig _ names fixity)) =- foldlM add_one env [ (loc,name_loc,name,fixity)+ foldlM add_one env [ (locA loc,locA name_loc,name,fixity) | L name_loc name <- names ] add_one env (loc, name_loc, name,fixity) = do@@ -681,7 +682,7 @@ -- from the left-hand side case details of PrefixCon _ vars ->- do { checkDupRdrNames vars+ do { checkDupRdrNamesN vars ; names <- mapM lookupPatSynBndr vars ; return ( (pat', PrefixCon noTypeArgs names) , mkFVs (map unLoc names)) }@@ -738,7 +739,7 @@ } where -- See Note [Renaming pattern synonym variables]- lookupPatSynBndr = wrapLocM lookupLocalOccRn+ lookupPatSynBndr = wrapLocMA lookupLocalOccRn patternSynonymErr :: SDoc patternSynonymErr@@ -843,7 +844,7 @@ -- * the default method bindings in a class decl -- * the method bindings in an instance decl rnMethodBinds is_cls_decl cls ktv_names binds sigs- = do { checkDupRdrNames (collectMethodBinders binds)+ = do { checkDupRdrNamesN (collectMethodBinders binds) -- Check that the same method is not given twice in the -- same instance decl instance C T where -- f x = ...@@ -868,7 +869,7 @@ sig_ctxt | is_cls_decl = ClsDeclCtxt cls | otherwise = InstDeclCtxt bound_nms ; (spec_inst_prags', sip_fvs) <- renameSigs sig_ctxt spec_inst_prags- ; (other_sigs', sig_fvs) <- extendTyVarEnvFVRn ktv_names $+ ; (other_sigs', sig_fvs) <- bindLocalNamesFV ktv_names $ renameSigs sig_ctxt other_sigs -- Rename the bindings RHSs. Again there's an issue about whether the@@ -888,8 +889,8 @@ -> LHsBindsLR GhcRn GhcPs -> RnM (LHsBindsLR GhcRn GhcPs) rnMethodBindLHS _ cls (L loc bind@(FunBind { fun_id = name })) rest- = setSrcSpan loc $- do { sel_name <- wrapLocM (lookupInstDeclBndr cls (text "method")) name+ = setSrcSpanA loc $ do+ do { sel_name <- wrapLocMA (lookupInstDeclBndr cls (text "method")) name -- We use the selector name as the binder ; let bind' = bind { fun_id = sel_name, fun_ext = noExtField } ; return (L loc bind' `consBag` rest ) }@@ -897,7 +898,7 @@ -- Report error for all other forms of bindings -- This is why we use a fold rather than map rnMethodBindLHS is_cls_decl _ (L loc bind) rest- = do { addErrAt loc $+ = do { addErrAt (locA loc) $ vcat [ what <+> text "not allowed in" <+> decl_sort , nest 2 (ppr bind) ] ; return rest }@@ -936,7 +937,7 @@ ; checkDupMinimalSigs sigs - ; (sigs', sig_fvs) <- mapFvRn (wrapLocFstM (renameSig ctxt)) sigs+ ; (sigs', sig_fvs) <- mapFvRn (wrapLocFstMA (renameSig ctxt)) sigs ; let (good_sigs, bad_sigs) = partition (okHsSig ctxt) sigs' ; mapM_ misplacedSigErr bad_sigs -- Misplaced@@ -958,18 +959,18 @@ = return (IdSig noExtField x, emptyFVs) -- Actually this never occurs renameSig ctxt sig@(TypeSig _ vs ty)- = do { new_vs <- mapM (lookupSigOccRn ctxt sig) vs+ = do { new_vs <- mapM (lookupSigOccRnN ctxt sig) vs ; let doc = TypeSigCtx (ppr_sig_bndrs vs) ; (new_ty, fvs) <- rnHsSigWcType doc ty- ; return (TypeSig noExtField new_vs new_ty, fvs) }+ ; return (TypeSig noAnn new_vs new_ty, fvs) } renameSig ctxt sig@(ClassOpSig _ is_deflt vs ty) = do { defaultSigs_on <- xoptM LangExt.DefaultSignatures ; when (is_deflt && not defaultSigs_on) $ addErr (defaultSigErr sig)- ; new_v <- mapM (lookupSigOccRn ctxt sig) vs+ ; new_v <- mapM (lookupSigOccRnN ctxt sig) vs ; (new_ty, fvs) <- rnHsSigType ty_ctxt TypeLevel ty- ; return (ClassOpSig noExtField is_deflt new_v new_ty, fvs) }+ ; return (ClassOpSig noAnn is_deflt new_v new_ty, fvs) } where (v1:_) = vs ty_ctxt = GenericCtx (text "a class method signature for"@@ -984,7 +985,7 @@ -- GHC.Hs.Type). ; addNoNestedForallsContextsErr doc (text "SPECIALISE instance type") (getLHsInstDeclHead new_ty)- ; return (SpecInstSig noExtField src new_ty,fvs) }+ ; return (SpecInstSig noAnn src new_ty,fvs) } where doc = SpecInstSigCtx inf_msg = Just (text "Inferred type variables are not allowed")@@ -996,9 +997,9 @@ renameSig ctxt sig@(SpecSig _ v tys inl) = do { new_v <- case ctxt of TopSigCtxt {} -> lookupLocatedOccRn v- _ -> lookupSigOccRn ctxt sig v+ _ -> lookupSigOccRnN ctxt sig v ; (new_ty, fvs) <- foldM do_one ([],emptyFVs) tys- ; return (SpecSig noExtField new_v new_ty inl, fvs) }+ ; return (SpecSig noAnn new_v new_ty inl, fvs) } where ty_ctxt = GenericCtx (text "a SPECIALISE signature for" <+> quotes (ppr v))@@ -1007,28 +1008,28 @@ ; return ( new_ty:tys, fvs_ty `plusFV` fvs) } renameSig ctxt sig@(InlineSig _ v s)- = do { new_v <- lookupSigOccRn ctxt sig v- ; return (InlineSig noExtField new_v s, emptyFVs) }+ = do { new_v <- lookupSigOccRnN ctxt sig v+ ; return (InlineSig noAnn new_v s, emptyFVs) } renameSig ctxt (FixSig _ fsig) = do { new_fsig <- rnSrcFixityDecl ctxt fsig- ; return (FixSig noExtField new_fsig, emptyFVs) }+ ; return (FixSig noAnn new_fsig, emptyFVs) } renameSig ctxt sig@(MinimalSig _ s (L l bf))- = do new_bf <- traverse (lookupSigOccRn ctxt sig) bf- return (MinimalSig noExtField s (L l new_bf), emptyFVs)+ = do new_bf <- traverse (lookupSigOccRnN ctxt sig) bf+ return (MinimalSig noAnn s (L l new_bf), emptyFVs) renameSig ctxt sig@(PatSynSig _ vs ty)- = do { new_vs <- mapM (lookupSigOccRn ctxt sig) vs+ = do { new_vs <- mapM (lookupSigOccRnN ctxt sig) vs ; (ty', fvs) <- rnHsSigType ty_ctxt TypeLevel ty- ; return (PatSynSig noExtField new_vs ty', fvs) }+ ; return (PatSynSig noAnn new_vs ty', fvs) } where ty_ctxt = GenericCtx (text "a pattern synonym signature for" <+> ppr_sig_bndrs vs) renameSig ctxt sig@(SCCFunSig _ st v s)- = do { new_v <- lookupSigOccRn ctxt sig v- ; return (SCCFunSig noExtField st new_v s, emptyFVs) }+ = do { new_v <- lookupSigOccRnN ctxt sig v+ ; return (SCCFunSig noAnn st new_v s, emptyFVs) } -- COMPLETE Sigs can refer to imported IDs which is why we use -- lookupLocatedOccRn rather than lookupSigOccRn@@ -1041,7 +1042,7 @@ -- Why 'any'? See Note [Orphan COMPLETE pragmas] addErrCtxt (text "In" <+> ppr sig) $ failWithTc orphanError - return (CompleteMatchSig noExtField s (L l new_bf) new_mty, emptyFVs)+ return (CompleteMatchSig noAnn s (L l new_bf) new_mty, emptyFVs) where orphanError :: SDoc orphanError =@@ -1071,7 +1072,7 @@ complexity of supporting them properly doesn't seem worthwhile. -} -ppr_sig_bndrs :: [Located RdrName] -> SDoc+ppr_sig_bndrs :: [LocatedN RdrName] -> SDoc ppr_sig_bndrs bs = quotes (pprWithCommas ppr bs) okHsSig :: HsSigCtxt -> LSig (GhcPass a) -> Bool@@ -1116,7 +1117,7 @@ (CompleteMatchSig {}, _) -> False --------------------findDupSigs :: [LSig GhcPs] -> [NonEmpty (Located RdrName, Sig GhcPs)]+findDupSigs :: [LSig GhcPs] -> [NonEmpty (LocatedN RdrName, Sig GhcPs)] -- Check for duplicates on RdrName version, -- because renamed version has unboundName for -- not-in-scope binders, which gives bogus dup-sig errors@@ -1128,6 +1129,7 @@ findDupSigs sigs = findDupsEq matching_sig (concatMap (expand_sig . unLoc) sigs) where+ expand_sig :: Sig GhcPs -> [(LocatedN RdrName, Sig GhcPs)] -- AZ expand_sig sig@(FixSig _ (FixitySig _ ns _)) = zip ns (repeat sig) expand_sig sig@(InlineSig _ n _) = [(n,sig)] expand_sig sig@(TypeSig _ ns _) = [(n,sig) | n <- ns]@@ -1136,6 +1138,7 @@ expand_sig sig@(SCCFunSig _ _ n _) = [(n,sig)] expand_sig _ = [] + matching_sig :: (LocatedN RdrName, Sig GhcPs) -> (LocatedN RdrName, Sig GhcPs) -> Bool --AZ matching_sig (L _ n1,sig1) (L _ n2,sig2) = n1 == n2 && mtch sig1 sig2 mtch (FixSig {}) (FixSig {}) = True mtch (InlineSig {}) (InlineSig {}) = True@@ -1160,35 +1163,46 @@ ************************************************************************ -} -rnMatchGroup :: Outputable (body GhcPs) => HsMatchContext GhcRn- -> (Located (body GhcPs) -> RnM (Located (body GhcRn), FreeVars))- -> MatchGroup GhcPs (Located (body GhcPs))- -> RnM (MatchGroup GhcRn (Located (body GhcRn)), FreeVars)-rnMatchGroup ctxt rnBody (MG { mg_alts = L _ ms, mg_origin = origin })+type AnnoBody body+ = ( Anno [LocatedA (Match GhcRn (LocatedA (body GhcRn)))] ~ SrcSpanAnnL+ , Anno [LocatedA (Match GhcPs (LocatedA (body GhcPs)))] ~ SrcSpanAnnL+ , Anno (Match GhcRn (LocatedA (body GhcRn))) ~ SrcSpanAnnA+ , Anno (Match GhcPs (LocatedA (body GhcPs))) ~ SrcSpanAnnA+ , Anno (GRHS GhcRn (LocatedA (body GhcRn))) ~ SrcSpan+ , Anno (GRHS GhcPs (LocatedA (body GhcPs))) ~ SrcSpan+ , Outputable (body GhcPs)+ )++rnMatchGroup :: (Outputable (body GhcPs), AnnoBody body) => HsMatchContext GhcRn+ -> (LocatedA (body GhcPs) -> RnM (LocatedA (body GhcRn), FreeVars))+ -> MatchGroup GhcPs (LocatedA (body GhcPs))+ -> RnM (MatchGroup GhcRn (LocatedA (body GhcRn)), FreeVars)+rnMatchGroup ctxt rnBody (MG { mg_alts = L lm ms, mg_origin = origin }) = do { empty_case_ok <- xoptM LangExt.EmptyCase ; when (null ms && not empty_case_ok) (addErr (emptyCaseErr ctxt)) ; (new_ms, ms_fvs) <- mapFvRn (rnMatch ctxt rnBody) ms- ; return (mkMatchGroup origin new_ms, ms_fvs) }+ ; return (mkMatchGroup origin (L lm new_ms), ms_fvs) } -rnMatch :: Outputable (body GhcPs) => HsMatchContext GhcRn- -> (Located (body GhcPs) -> RnM (Located (body GhcRn), FreeVars))- -> LMatch GhcPs (Located (body GhcPs))- -> RnM (LMatch GhcRn (Located (body GhcRn)), FreeVars)-rnMatch ctxt rnBody = wrapLocFstM (rnMatch' ctxt rnBody)+rnMatch :: AnnoBody body+ => HsMatchContext GhcRn+ -> (LocatedA (body GhcPs) -> RnM (LocatedA (body GhcRn), FreeVars))+ -> LMatch GhcPs (LocatedA (body GhcPs))+ -> RnM (LMatch GhcRn (LocatedA (body GhcRn)), FreeVars)+rnMatch ctxt rnBody = wrapLocFstMA (rnMatch' ctxt rnBody) --- Note that there are no local fixity decls for matches-rnMatch' :: Outputable (body GhcPs) => HsMatchContext GhcRn- -> (Located (body GhcPs) -> RnM (Located (body GhcRn), FreeVars))- -> Match GhcPs (Located (body GhcPs))- -> RnM (Match GhcRn (Located (body GhcRn)), FreeVars)-rnMatch' ctxt rnBody (Match { m_ctxt = mf, m_pats = pats, m_grhss = grhss }) =- rnPats ctxt pats $ \ pats' -> do+rnMatch' :: (AnnoBody body)+ => HsMatchContext GhcRn+ -> (LocatedA (body GhcPs) -> RnM (LocatedA (body GhcRn), FreeVars))+ -> Match GhcPs (LocatedA (body GhcPs))+ -> RnM (Match GhcRn (LocatedA (body GhcRn)), FreeVars)+rnMatch' ctxt rnBody (Match { m_ctxt = mf, m_pats = pats, m_grhss = grhss })+ = rnPats ctxt pats $ \ pats' -> do { (grhss', grhss_fvs) <- rnGRHSs ctxt rnBody grhss ; let mf' = case (ctxt, mf) of- (FunRhs { mc_fun = L _ funid }, FunRhs { mc_fun = L lf _ }) ->- mf { mc_fun = L lf funid }- _ -> ctxt- ; return (Match { m_ext = noExtField, m_ctxt = mf', m_pats = pats'+ (FunRhs { mc_fun = L _ funid }, FunRhs { mc_fun = L lf _ })+ -> mf { mc_fun = L lf funid }+ _ -> ctxt+ ; return (Match { m_ext = noAnn, m_ctxt = mf', m_pats = pats' , m_grhss = grhss'}, grhss_fvs ) } emptyCaseErr :: HsMatchContext GhcRn -> SDoc@@ -1208,34 +1222,36 @@ ************************************************************************ -} -rnGRHSs :: HsMatchContext GhcRn- -> (Located (body GhcPs) -> RnM (Located (body GhcRn), FreeVars))- -> GRHSs GhcPs (Located (body GhcPs))- -> RnM (GRHSs GhcRn (Located (body GhcRn)), FreeVars)-rnGRHSs ctxt rnBody (GRHSs _ grhss (L l binds))+rnGRHSs :: AnnoBody body+ => HsMatchContext GhcRn+ -> (LocatedA (body GhcPs) -> RnM (LocatedA (body GhcRn), FreeVars))+ -> GRHSs GhcPs (LocatedA (body GhcPs))+ -> RnM (GRHSs GhcRn (LocatedA (body GhcRn)), FreeVars)+rnGRHSs ctxt rnBody (GRHSs _ grhss binds) = rnLocalBindsAndThen binds $ \ binds' _ -> do (grhss', fvGRHSs) <- mapFvRn (rnGRHS ctxt rnBody) grhss- return (GRHSs noExtField grhss' (L l binds'), fvGRHSs)+ return (GRHSs noExtField grhss' binds', fvGRHSs) -rnGRHS :: HsMatchContext GhcRn- -> (Located (body GhcPs) -> RnM (Located (body GhcRn), FreeVars))- -> LGRHS GhcPs (Located (body GhcPs))- -> RnM (LGRHS GhcRn (Located (body GhcRn)), FreeVars)+rnGRHS :: AnnoBody body+ => HsMatchContext GhcRn+ -> (LocatedA (body GhcPs) -> RnM (LocatedA (body GhcRn), FreeVars))+ -> LGRHS GhcPs (LocatedA (body GhcPs))+ -> RnM (LGRHS GhcRn (LocatedA (body GhcRn)), FreeVars) rnGRHS ctxt rnBody = wrapLocFstM (rnGRHS' ctxt rnBody) rnGRHS' :: HsMatchContext GhcRn- -> (Located (body GhcPs) -> RnM (Located (body GhcRn), FreeVars))- -> GRHS GhcPs (Located (body GhcPs))- -> RnM (GRHS GhcRn (Located (body GhcRn)), FreeVars)+ -> (LocatedA (body GhcPs) -> RnM (LocatedA (body GhcRn), FreeVars))+ -> GRHS GhcPs (LocatedA (body GhcPs))+ -> RnM (GRHS GhcRn (LocatedA (body GhcRn)), FreeVars) rnGRHS' ctxt rnBody (GRHS _ guards rhs) = do { pattern_guards_allowed <- xoptM LangExt.PatternGuards- ; ((guards', rhs'), fvs) <- rnStmts (PatGuard ctxt) rnLExpr guards $ \ _ ->+ ; ((guards', rhs'), fvs) <- rnStmts (PatGuard ctxt) rnExpr guards $ \ _ -> rnBody rhs ; unless (pattern_guards_allowed || is_standard_guard guards')- (addWarn NoReason (nonStdGuardErr guards'))+ (addDiagnostic WarningWithoutFlag (nonStdGuardErr guards')) - ; return (GRHS noExtField guards' rhs', fvs) }+ ; return (GRHS noAnn guards' rhs', fvs) } where -- Standard Haskell 1.4 guards are just a single boolean -- expression, rather than a list of qualifiers as in the@@ -1267,9 +1283,9 @@ = do names <- concatMapM lookup_one fnames return (FixitySig noExtField names fixity) - lookup_one :: Located RdrName -> RnM [Located Name]+ lookup_one :: LocatedN RdrName -> RnM [LocatedN Name] lookup_one (L name_loc rdr_name)- = setSrcSpan name_loc $+ = setSrcSpanA name_loc $ -- This lookup will fail if the name is not defined in the -- same binding group as this fixity declaration. do names <- lookupLocalTcNames sig_ctxt what rdr_name@@ -1284,13 +1300,13 @@ ************************************************************************ -} -dupSigDeclErr :: NonEmpty (Located RdrName, Sig GhcPs) -> RnM ()+dupSigDeclErr :: NonEmpty (LocatedN RdrName, Sig GhcPs) -> RnM () dupSigDeclErr pairs@((L loc name, sig) :| _)- = addErrAt loc $+ = addErrAt (locA loc) $ vcat [ text "Duplicate" <+> what_it_is <> text "s for" <+> quotes (ppr name) , text "at" <+> vcat (map ppr $ sortBy SrcLoc.leftmost_smallest- $ map (getLoc . fst)+ $ map (getLocA . fst) $ toList pairs) ] where@@ -1298,7 +1314,7 @@ misplacedSigErr :: LSig GhcRn -> RnM () misplacedSigErr (L loc sig)- = addErrAt loc $+ = addErrAt (locA loc) $ sep [text "Misplaced" <+> hsSigDoc sig <> colon, ppr sig] defaultSigErr :: Sig GhcPs -> SDoc@@ -1311,7 +1327,9 @@ = hang (text "Bindings in hs-boot files are not allowed") 2 (ppr mbinds) -nonStdGuardErr :: Outputable body => [LStmtLR GhcRn GhcRn body] -> SDoc+nonStdGuardErr :: (Outputable body,+ Anno (Stmt GhcRn body) ~ SrcSpanAnnA)+ => [LStmtLR GhcRn GhcRn body] -> SDoc nonStdGuardErr guards = hang (text "accepting non-standard pattern guards (use PatternGuards to suppress this message)") 4 (interpp'SP guards)@@ -1323,8 +1341,8 @@ dupMinimalSigErr :: [LSig GhcPs] -> RnM () dupMinimalSigErr sigs@(L loc _ : _)- = addErrAt loc $+ = addErrAt (locA loc) $ vcat [ text "Multiple minimal complete definitions"- , text "at" <+> vcat (map ppr $ sortBy SrcLoc.leftmost_smallest $ map getLoc sigs)+ , text "at" <+> vcat (map ppr $ sortBy SrcLoc.leftmost_smallest $ map getLocA sigs) , text "Combine alternative minimal complete definitions with `|'" ] dupMinimalSigErr [] = panic "dupMinimalSigErr"
compiler/GHC/Rename/Env.hs view
@@ -1,6 +1,4 @@-{-# LANGUAGE CPP #-}-{-# LANGUAGE DeriveFunctor #-}-{-# LANGUAGE MultiWayIf #-}+{-# LANGUAGE CPP #-} {-# LANGUAGE NamedFieldPuns #-} {-# LANGUAGE TypeApplications #-} @@ -14,7 +12,7 @@ module GHC.Rename.Env ( newTopSrcBinder, - lookupLocatedTopBndrRn, lookupTopBndrRn,+ lookupLocatedTopBndrRn, lookupLocatedTopBndrRnN, lookupTopBndrRn, lookupLocatedOccRn, lookupOccRn, lookupOccRn_maybe, lookupLocalOccRn_maybe, lookupInfoOccRn,@@ -31,8 +29,8 @@ lookupSubBndrOcc_helper, combineChildLookupResult, -- Called by lookupChildrenExport - HsSigCtxt(..), lookupLocalTcNames, lookupSigOccRn,- lookupSigCtxtOccRn,+ HsSigCtxt(..), lookupLocalTcNames, lookupSigOccRn, lookupSigOccRnN,+ lookupSigCtxtOccRn, lookupSigCtxtOccRnN, lookupInstDeclBndr, lookupFamInstName, lookupConstructorFields,@@ -168,7 +166,7 @@ Note [Handling of deprecations] -} -newTopSrcBinder :: Located RdrName -> RnM Name+newTopSrcBinder :: LocatedN RdrName -> RnM Name newTopSrcBinder (L loc rdr_name) | Just name <- isExact_maybe rdr_name = -- This is here to catch@@ -183,7 +181,7 @@ if isExternalName name then do { this_mod <- getModule ; unless (this_mod == nameModule name)- (addErrAt loc (badOrigBinding rdr_name))+ (addErrAt (locA loc) (badOrigBinding rdr_name)) ; return name } else -- See Note [Binders in Template Haskell] in "GHC.ThToHs" do { this_mod <- getModule@@ -192,7 +190,7 @@ | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name = do { this_mod <- getModule ; unless (rdr_mod == this_mod || rdr_mod == rOOT_MAIN)- (addErrAt loc (badOrigBinding rdr_name))+ (addErrAt (locA loc) (badOrigBinding rdr_name)) -- When reading External Core we get Orig names as binders, -- but they should agree with the module gotten from the monad --@@ -210,11 +208,11 @@ -- the RdrName, not from the environment. In principle, it'd be fine to -- have an arbitrary mixture of external core definitions in a single module, -- (apart from module-initialisation issues, perhaps).- ; newGlobalBinder rdr_mod rdr_occ loc }+ ; newGlobalBinder rdr_mod rdr_occ (locA loc) } | otherwise = do { when (isQual rdr_name)- (addErrAt loc (badQualBndrErr rdr_name))+ (addErrAt (locA loc) (badQualBndrErr rdr_name)) -- Binders should not be qualified; if they are, and with a different -- module name, we get a confusing "M.T is not in scope" error later @@ -223,11 +221,11 @@ -- We are inside a TH bracket, so make an *Internal* name -- See Note [Top-level Names in Template Haskell decl quotes] in GHC.Rename.Names do { uniq <- newUnique- ; return (mkInternalName uniq (rdrNameOcc rdr_name) loc) }+ ; return (mkInternalName uniq (rdrNameOcc rdr_name) (locA loc)) } else do { this_mod <- getModule- ; traceRn "newTopSrcBinder" (ppr this_mod $$ ppr rdr_name $$ ppr loc)- ; newGlobalBinder this_mod (rdrNameOcc rdr_name) loc }+ ; traceRn "newTopSrcBinder" (ppr this_mod $$ ppr rdr_name $$ ppr (locA loc))+ ; newGlobalBinder this_mod (rdrNameOcc rdr_name) (locA loc) } } {-@@ -285,6 +283,9 @@ lookupLocatedTopBndrRn :: Located RdrName -> RnM (Located Name) lookupLocatedTopBndrRn = wrapLocM lookupTopBndrRn +lookupLocatedTopBndrRnN :: LocatedN RdrName -> RnM (LocatedN Name)+lookupLocatedTopBndrRnN = wrapLocMA lookupTopBndrRn+ -- | Lookup an @Exact@ @RdrName@. See Note [Looking up Exact RdrNames]. -- This never adds an error, but it may return one, see -- Note [Errors in lookup functions]@@ -387,12 +388,12 @@ doc = what <+> text "of class" <+> quotes (ppr cls) ------------------------------------------------lookupFamInstName :: Maybe Name -> Located RdrName- -> RnM (Located Name)+lookupFamInstName :: Maybe Name -> LocatedN RdrName+ -> RnM (LocatedN Name) -- Used for TyData and TySynonym family instances only, -- See Note [Family instance binders] lookupFamInstName (Just cls) tc_rdr -- Associated type; c.f GHC.Rename.Bind.rnMethodBind- = wrapLocM (lookupInstDeclBndr cls (text "associated type")) tc_rdr+ = wrapLocMA (lookupInstDeclBndr cls (text "associated type")) tc_rdr lookupFamInstName Nothing tc_rdr -- Family instance; tc_rdr is an *occurrence* = lookupLocatedOccRn tc_rdr @@ -690,7 +691,7 @@ -- `checkPatSynParent`. traceRn "parent" (ppr parent) traceRn "lookupExportChild original_gres:" (ppr original_gres)- traceRn "lookupExportChild picked_gres:" (ppr $ picked_gres original_gres)+ traceRn "lookupExportChild picked_gres:" (ppr (picked_gres original_gres) $$ ppr must_have_parent) case picked_gres original_gres of NoOccurrence -> noMatchingParentErr original_gres@@ -720,6 +721,7 @@ -- constructors, neither of which is the parent. noMatchingParentErr :: [GlobalRdrElt] -> RnM ChildLookupResult noMatchingParentErr original_gres = do+ traceRn "npe" (ppr original_gres) dup_fields_ok <- xoptM LangExt.DuplicateRecordFields case original_gres of [] -> return NameNotFound@@ -987,8 +989,9 @@ -} -lookupLocatedOccRn :: Located RdrName -> RnM (Located Name)-lookupLocatedOccRn = wrapLocM lookupOccRn+lookupLocatedOccRn :: GenLocated (SrcSpanAnn' ann) RdrName+ -> TcRn (GenLocated (SrcSpanAnn' ann) Name)+lookupLocatedOccRn = wrapLocMA lookupOccRn lookupLocalOccRn_maybe :: RdrName -> RnM (Maybe Name) -- Just look in the local environment@@ -1045,8 +1048,8 @@ Nothing -> unboundNameX WL_Any rdr_name star_info Just demoted_name -> do { whenWOptM Opt_WarnUntickedPromotedConstructors $- addWarn- (Reason Opt_WarnUntickedPromotedConstructors)+ addDiagnostic+ (WarningWithFlag Opt_WarnUntickedPromotedConstructors) (untickedPromConstrWarn demoted_name) ; return demoted_name } } else do { -- We need to check if a data constructor of this name is@@ -1520,8 +1523,8 @@ -- See Note [Handling of deprecations] do { iface <- loadInterfaceForName doc name ; case lookupImpDeprec iface gre of- Just txt -> addWarn (Reason Opt_WarnWarningsDeprecations)- (mk_msg imp_spec txt)+ Just txt -> addDiagnostic (WarningWithFlag Opt_WarnWarningsDeprecations)+ (mk_msg imp_spec txt) Nothing -> return () } } | otherwise = return ()@@ -1741,16 +1744,34 @@ lookupSigOccRn :: HsSigCtxt -> Sig GhcPs- -> Located RdrName -> RnM (Located Name)+ -> LocatedA RdrName -> RnM (LocatedA Name) lookupSigOccRn ctxt sig = lookupSigCtxtOccRn ctxt (hsSigDoc sig) +lookupSigOccRnN :: HsSigCtxt+ -> Sig GhcPs+ -> LocatedN RdrName -> RnM (LocatedN Name)+lookupSigOccRnN ctxt sig = lookupSigCtxtOccRnN ctxt (hsSigDoc sig)++ -- | Lookup a name in relation to the names in a 'HsSigCtxt'+lookupSigCtxtOccRnN :: HsSigCtxt+ -> SDoc -- ^ description of thing we're looking up,+ -- like "type family"+ -> LocatedN RdrName -> RnM (LocatedN Name)+lookupSigCtxtOccRnN ctxt what+ = wrapLocMA $ \ rdr_name ->+ do { mb_name <- lookupBindGroupOcc ctxt what rdr_name+ ; case mb_name of+ Left err -> do { addErr err; return (mkUnboundNameRdr rdr_name) }+ Right name -> return name }++-- | Lookup a name in relation to the names in a 'HsSigCtxt' lookupSigCtxtOccRn :: HsSigCtxt -> SDoc -- ^ description of thing we're looking up, -- like "type family"- -> Located RdrName -> RnM (Located Name)+ -> LocatedA RdrName -> RnM (LocatedA Name) lookupSigCtxtOccRn ctxt what- = wrapLocM $ \ rdr_name ->+ = wrapLocMA $ \ rdr_name -> do { mb_name <- lookupBindGroupOcc ctxt what rdr_name ; case mb_name of Left err -> do { addErr err; return (mkUnboundNameRdr rdr_name) }@@ -1993,10 +2014,10 @@ lookupSyntaxNames std_names = do { rebindable_on <- xoptM LangExt.RebindableSyntax ; if not rebindable_on then- return (map (HsVar noExtField . noLoc) std_names, emptyFVs)+ return (map (HsVar noExtField . noLocA) std_names, emptyFVs) else do { usr_names <- mapM (lookupOccRn . mkRdrUnqual . nameOccName) std_names- ; return (map (HsVar noExtField . noLoc) usr_names, mkFVs usr_names) } }+ ; return (map (HsVar noExtField . noLocA) usr_names, mkFVs usr_names) } } {-
compiler/GHC/Rename/Expr.hs view
@@ -1,4 +1,5 @@ {-# LANGUAGE CPP #-}+{-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE MultiWayIf #-} {-# LANGUAGE ScopedTypeVariables #-}@@ -20,7 +21,8 @@ -} module GHC.Rename.Expr (- rnLExpr, rnExpr, rnStmts+ rnLExpr, rnExpr, rnStmts,+ AnnoBody ) where #include "GhclibHsVersions.h"@@ -183,18 +185,18 @@ -- Variables. We look up the variable and return the resulting name. rnLExpr :: LHsExpr GhcPs -> RnM (LHsExpr GhcRn, FreeVars)-rnLExpr = wrapLocFstM rnExpr+rnLExpr = wrapLocFstMA rnExpr rnExpr :: HsExpr GhcPs -> RnM (HsExpr GhcRn, FreeVars) -finishHsVar :: Located Name -> RnM (HsExpr GhcRn, FreeVars)+finishHsVar :: LocatedA Name -> RnM (HsExpr GhcRn, FreeVars) -- Separated from rnExpr because it's also used -- when renaming infix expressions finishHsVar (L l name) = do { this_mod <- getModule ; when (nameIsLocalOrFrom this_mod name) $ checkThLocalName name- ; return (HsVar noExtField (L l name), unitFV name) }+ ; return (HsVar noExtField (L (la2na l) name), unitFV name) } rnUnboundVar :: RdrName -> RnM (HsExpr GhcRn, FreeVars) rnUnboundVar v =@@ -204,9 +206,9 @@ -- and let the type checker report the error return (HsUnboundVar noExtField (rdrNameOcc v), emptyFVs) - else -- Fail immediately (qualified name)- do { n <- reportUnboundName v- ; return (HsVar noExtField (noLoc n), emptyFVs) }+ else -- Fail immediately (qualified name)+ do { n <- reportUnboundName v+ ; return (HsVar noExtField (noLocA n), emptyFVs) } rnExpr (HsVar _ (L l v)) = do { dflags <- getDynFlags@@ -220,10 +222,10 @@ -- OverloadedLists works correctly -- Note [Empty lists] in GHC.Hs.Expr , xopt LangExt.OverloadedLists dflags- -> rnExpr (ExplicitList noExtField [])+ -> rnExpr (ExplicitList noAnn []) | otherwise- -> finishHsVar (L l name) ;+ -> finishHsVar (L (na2la l) name) ; Just (UnambiguousGre (FieldGreName fl)) -> let sel_name = flSelector fl in return ( HsRecFld noExtField (Unambiguous sel_name (L l v) ), unitFV sel_name) ;@@ -234,13 +236,13 @@ rnExpr (HsIPVar x v) = return (HsIPVar x v, emptyFVs) -rnExpr (HsUnboundVar x v)- = return (HsUnboundVar x v, emptyFVs)+rnExpr (HsUnboundVar _ v)+ = return (HsUnboundVar noExtField v, emptyFVs) -- HsOverLabel: see Note [Handling overloaded and rebindable constructs] rnExpr (HsOverLabel _ v) = do { (from_label, fvs) <- lookupSyntaxName fromLabelClassOpName- ; return ( mkExpandedExpr (HsOverLabel noExtField v) $+ ; return ( mkExpandedExpr (HsOverLabel noAnn v) $ HsAppType noExtField (genLHsVar from_label) hs_ty_arg , fvs ) } where@@ -263,20 +265,21 @@ = do { ((lit', mb_neg), fvs) <- rnOverLit lit -- See Note [Negative zero] ; case mb_neg of Nothing -> return (HsOverLit x lit', fvs)- Just neg -> return (HsApp x (noLoc neg) (noLoc (HsOverLit x lit'))- , fvs ) }+ Just neg ->+ return (HsApp noComments (noLocA neg) (noLocA (HsOverLit x lit'))+ , fvs ) } rnExpr (HsApp x fun arg) = do { (fun',fvFun) <- rnLExpr fun ; (arg',fvArg) <- rnLExpr arg ; return (HsApp x fun' arg', fvFun `plusFV` fvArg) } -rnExpr (HsAppType x fun arg)+rnExpr (HsAppType _ fun arg) = do { type_app <- xoptM LangExt.TypeApplications ; unless type_app $ addErr $ typeAppErr "type" $ hswc_body arg ; (fun',fvFun) <- rnLExpr fun ; (arg',fvArg) <- rnHsWcType HsTypeCtx arg- ; return (HsAppType x fun' arg', fvFun `plusFV` fvArg) }+ ; return (HsAppType NoExtField fun' arg', fvFun `plusFV` fvArg) } rnExpr (OpApp _ e1 op e2) = do { (e1', fv_e1) <- rnLExpr e1@@ -304,6 +307,27 @@ ; return (final_e, fv_e `plusFV` fv_neg) } ------------------------------------------+-- Record dot syntax++rnExpr (HsGetField _ e f)+ = do { (getField, fv_getField) <- lookupSyntaxName getFieldName+ ; (e, fv_e) <- rnLExpr e+ ; let f' = rnHsFieldLabel f+ ; return ( mkExpandedExpr+ (HsGetField noExtField e f')+ (mkGetField getField e (fmap (unLoc . hflLabel) f'))+ , fv_e `plusFV` fv_getField ) }++rnExpr (HsProjection _ fs)+ = do { (getField, fv_getField) <- lookupSyntaxName getFieldName+ ; circ <- lookupOccRn compose_RDR+ ; let fs' = fmap rnHsFieldLabel fs+ ; return ( mkExpandedExpr+ (HsProjection noExtField fs')+ (mkProjection getField circ (map (fmap (unLoc . hflLabel)) fs'))+ , unitFV circ `plusFV` fv_getField) }++------------------------------------------ -- Template Haskell extensions rnExpr e@(HsBracket _ br_body) = rnBracket e br_body @@ -345,51 +369,50 @@ = do { (matches', fvs_ms) <- rnMatchGroup CaseAlt rnLExpr matches ; return (HsLamCase x matches', fvs_ms) } -rnExpr (HsCase x expr matches)+rnExpr (HsCase _ expr matches) = do { (new_expr, e_fvs) <- rnLExpr expr ; (new_matches, ms_fvs) <- rnMatchGroup CaseAlt rnLExpr matches- ; return (HsCase x new_expr new_matches, e_fvs `plusFV` ms_fvs) }+ ; return (HsCase noExtField new_expr new_matches, e_fvs `plusFV` ms_fvs) } -rnExpr (HsLet x (L l binds) expr)+rnExpr (HsLet _ binds expr) = rnLocalBindsAndThen binds $ \binds' _ -> do { (expr',fvExpr) <- rnLExpr expr- ; return (HsLet x (L l binds') expr', fvExpr) }+ ; return (HsLet noExtField binds' expr', fvExpr) } -rnExpr (HsDo x do_or_lc (L l stmts))+rnExpr (HsDo _ do_or_lc (L l stmts)) = do { ((stmts', _), fvs) <-- rnStmtsWithPostProcessing do_or_lc rnLExpr+ rnStmtsWithPostProcessing do_or_lc rnExpr postProcessStmtsForApplicativeDo stmts (\ _ -> return ((), emptyFVs))- ; return ( HsDo x do_or_lc (L l stmts'), fvs ) }+ ; return ( HsDo noExtField do_or_lc (L l stmts'), fvs ) } -- ExplicitList: see Note [Handling overloaded and rebindable constructs]-rnExpr (ExplicitList x exps)+rnExpr (ExplicitList _ exps) = do { (exps', fvs) <- rnExprs exps ; opt_OverloadedLists <- xoptM LangExt.OverloadedLists ; if not opt_OverloadedLists- then return (ExplicitList x exps', fvs)+ then return (ExplicitList noExtField exps', fvs) else do { (from_list_n_name, fvs') <- lookupSyntaxName fromListNName- ; let rn_list = ExplicitList x exps'+ ; let rn_list = ExplicitList noExtField exps' lit_n = mkIntegralLit (length exps)- hs_lit = wrapGenSpan (HsLit noExtField (HsInt noExtField lit_n))+ hs_lit = wrapGenSpan (HsLit noAnn (HsInt noExtField lit_n)) exp_list = genHsApps from_list_n_name [hs_lit, wrapGenSpan rn_list] ; return ( mkExpandedExpr rn_list exp_list , fvs `plusFV` fvs') } } -rnExpr (ExplicitTuple x tup_args boxity)+rnExpr (ExplicitTuple _ tup_args boxity) = do { checkTupleSection tup_args ; (tup_args', fvs) <- mapAndUnzipM rnTupArg tup_args- ; return (ExplicitTuple x tup_args' boxity, plusFVs fvs) }+ ; return (ExplicitTuple noExtField tup_args' boxity, plusFVs fvs) } where- rnTupArg (L l (Present x e)) = do { (e',fvs) <- rnLExpr e- ; return (L l (Present x e'), fvs) }- rnTupArg (L l (Missing _)) = return (L l (Missing noExtField)- , emptyFVs)+ rnTupArg (Present x e) = do { (e',fvs) <- rnLExpr e+ ; return (Present x e', fvs) }+ rnTupArg (Missing _) = return (Missing noExtField, emptyFVs) -rnExpr (ExplicitSum x alt arity expr)+rnExpr (ExplicitSum _ alt arity expr) = do { (expr', fvs) <- rnLExpr expr- ; return (ExplicitSum x alt arity expr', fvs) }+ ; return (ExplicitSum noExtField alt arity expr', fvs) } rnExpr (RecordCon { rcon_con = con_id , rcon_flds = rec_binds@(HsRecFields { rec_dotdot = dd }) })@@ -401,16 +424,33 @@ , rcon_con = con_lname, rcon_flds = rec_binds' } , fvs `plusFV` plusFVs fvss `addOneFV` con_name) } where- mk_hs_var l n = HsVar noExtField (L l n)+ mk_hs_var l n = HsVar noExtField (L (noAnnSrcSpan l) n) rn_field (L l fld) = do { (arg', fvs) <- rnLExpr (hsRecFieldArg fld) ; return (L l (fld { hsRecFieldArg = arg' }), fvs) } rnExpr (RecordUpd { rupd_expr = expr, rupd_flds = rbinds })- = do { (expr', fvExpr) <- rnLExpr expr- ; (rbinds', fvRbinds) <- rnHsRecUpdFields rbinds- ; return (RecordUpd { rupd_ext = noExtField, rupd_expr = expr'- , rupd_flds = rbinds' }- , fvExpr `plusFV` fvRbinds) }+ = case rbinds of+ Left flds -> -- 'OverloadedRecordUpdate' is not in effect. Regular record update.+ do { ; (e, fv_e) <- rnLExpr expr+ ; (rs, fv_rs) <- rnHsRecUpdFields flds+ ; return ( RecordUpd noExtField e (Left rs), fv_e `plusFV` fv_rs )+ }+ Right flds -> -- 'OverloadedRecordUpdate' is in effect. Record dot update desugaring.+ do { ; unlessXOptM LangExt.RebindableSyntax $+ addErr $ text "RebindableSyntax is required if OverloadedRecordUpdate is enabled."+ ; let punnedFields = [fld | (L _ fld) <- flds, hsRecPun fld]+ ; punsEnabled <-xoptM LangExt.RecordPuns+ ; unless (null punnedFields || punsEnabled) $+ addErr $ text "For this to work enable NamedFieldPuns."+ ; (getField, fv_getField) <- lookupSyntaxName getFieldName+ ; (setField, fv_setField) <- lookupSyntaxName setFieldName+ ; (e, fv_e) <- rnLExpr expr+ ; (us, fv_us) <- rnHsUpdProjs flds+ ; return ( mkExpandedExpr+ (RecordUpd noExtField e (Right us))+ (mkRecordDotUpd getField setField e us)+ , plusFVs [fv_getField, fv_setField, fv_e, fv_us] )+ } rnExpr (ExprWithTySig _ expr pty) = do { (pty', fvTy) <- rnHsSigWcType ExprWithTySigCtx pty@@ -440,20 +480,20 @@ fvs = plusFVs [fvs_if, unitFV ite_name] ; return (mkExpandedExpr rn_if ds_if, fvs) } } -rnExpr (HsMultiIf x alts)+rnExpr (HsMultiIf _ alts) = do { (alts', fvs) <- mapFvRn (rnGRHS IfAlt rnLExpr) alts- ; return (HsMultiIf x alts', fvs) }+ ; return (HsMultiIf noExtField alts', fvs) } -rnExpr (ArithSeq x _ seq)+rnExpr (ArithSeq _ _ seq) = do { opt_OverloadedLists <- xoptM LangExt.OverloadedLists ; (new_seq, fvs) <- rnArithSeq seq ; if opt_OverloadedLists then do { ; (from_list_name, fvs') <- lookupSyntax fromListName- ; return (ArithSeq x (Just from_list_name) new_seq+ ; return (ArithSeq noExtField (Just from_list_name) new_seq , fvs `plusFV` fvs') } else- return (ArithSeq x Nothing new_seq, fvs) }+ return (ArithSeq noExtField Nothing new_seq, fvs) } {- ************************************************************************@@ -505,7 +545,6 @@ rnExpr other = pprPanic "rnExpr: unexpected expression" (ppr other) -- HsWrap - {- ********************************************************************* * * Operator sections@@ -536,9 +575,9 @@ -- Note [Left and right sections] ; let rn_section = SectionL x expr' op' ds_section- | postfix_ops = HsApp noExtField op' expr'+ | postfix_ops = HsApp noAnn op' expr' | otherwise = genHsApps leftSectionName- [wrapGenSpan $ HsApp noExtField op' expr']+ [wrapGenSpan $ HsApp noAnn op' expr'] ; return ( mkExpandedExpr rn_section ds_section , fvs_op `plusFV` fvs_expr) } @@ -658,7 +697,20 @@ See #18151. -} +{-+************************************************************************+* *+ Field Labels+* *+************************************************************************+-} +rnHsFieldLabel :: Located (HsFieldLabel GhcPs) -> Located (HsFieldLabel GhcRn)+rnHsFieldLabel (L l (HsFieldLabel x label)) = L l (HsFieldLabel x label)++rnFieldLabelStrings :: FieldLabelStrings GhcPs -> FieldLabelStrings GhcRn+rnFieldLabelStrings (FieldLabelStrings fls) = FieldLabelStrings (map rnHsFieldLabel fls)+ {- ************************************************************************ * *@@ -689,14 +741,14 @@ fvCmd `plusFV` cmd_fvs) } rnLCmd :: LHsCmd GhcPs -> RnM (LHsCmd GhcRn, FreeVars)-rnLCmd = wrapLocFstM rnCmd+rnLCmd = wrapLocFstMA rnCmd rnCmd :: HsCmd GhcPs -> RnM (HsCmd GhcRn, FreeVars) -rnCmd (HsCmdArrApp x arrow arg ho rtl)+rnCmd (HsCmdArrApp _ arrow arg ho rtl) = do { (arrow',fvArrow) <- select_arrow_scope (rnLExpr arrow) ; (arg',fvArg) <- rnLExpr arg- ; return (HsCmdArrApp x arrow' arg' ho rtl,+ ; return (HsCmdArrApp noExtField arrow' arg' ho rtl, fvArrow `plusFV` fvArg) } where select_arrow_scope tc = case ho of@@ -719,34 +771,36 @@ ; final_e <- mkOpFormRn arg1' op' fixity arg2' ; return (final_e, fv_arg1 `plusFV` fv_op `plusFV` fv_arg2) } -rnCmd (HsCmdArrForm x op f fixity cmds)+rnCmd (HsCmdArrForm _ op f fixity cmds) = do { (op',fvOp) <- escapeArrowScope (rnLExpr op) ; (cmds',fvCmds) <- rnCmdArgs cmds- ; return (HsCmdArrForm x op' f fixity cmds', fvOp `plusFV` fvCmds) }+ ; return ( HsCmdArrForm noExtField op' f fixity cmds'+ , fvOp `plusFV` fvCmds) } rnCmd (HsCmdApp x fun arg) = do { (fun',fvFun) <- rnLCmd fun ; (arg',fvArg) <- rnLExpr arg ; return (HsCmdApp x fun' arg', fvFun `plusFV` fvArg) } -rnCmd (HsCmdLam x matches)+rnCmd (HsCmdLam _ matches) = do { (matches', fvMatch) <- rnMatchGroup LambdaExpr rnLCmd matches- ; return (HsCmdLam x matches', fvMatch) }+ ; return (HsCmdLam noExtField matches', fvMatch) } rnCmd (HsCmdPar x e) = do { (e', fvs_e) <- rnLCmd e ; return (HsCmdPar x e', fvs_e) } -rnCmd (HsCmdCase x expr matches)+rnCmd (HsCmdCase _ expr matches) = do { (new_expr, e_fvs) <- rnLExpr expr ; (new_matches, ms_fvs) <- rnMatchGroup CaseAlt rnLCmd matches- ; return (HsCmdCase x new_expr new_matches, e_fvs `plusFV` ms_fvs) }+ ; return (HsCmdCase noExtField new_expr new_matches+ , e_fvs `plusFV` ms_fvs) } rnCmd (HsCmdLamCase x matches) = do { (new_matches, ms_fvs) <- rnMatchGroup CaseAlt rnLCmd matches ; return (HsCmdLamCase x new_matches, ms_fvs) } -rnCmd (HsCmdIf x _ p b1 b2)+rnCmd (HsCmdIf _ _ p b1 b2) = do { (p', fvP) <- rnLExpr p ; (b1', fvB1) <- rnLCmd b1 ; (b2', fvB2) <- rnLCmd b2@@ -756,17 +810,17 @@ Just ite_name -> (mkRnSyntaxExpr ite_name, unitFV ite_name) Nothing -> (NoSyntaxExprRn, emptyFVs) - ; return (HsCmdIf x ite p' b1' b2', plusFVs [fvITE, fvP, fvB1, fvB2])}+ ; return (HsCmdIf noExtField ite p' b1' b2', plusFVs [fvITE, fvP, fvB1, fvB2])} -rnCmd (HsCmdLet x (L l binds) cmd)+rnCmd (HsCmdLet _ binds cmd) = rnLocalBindsAndThen binds $ \ binds' _ -> do { (cmd',fvExpr) <- rnLCmd cmd- ; return (HsCmdLet x (L l binds') cmd', fvExpr) }+ ; return (HsCmdLet noExtField binds' cmd', fvExpr) } -rnCmd (HsCmdDo x (L l stmts))+rnCmd (HsCmdDo _ (L l stmts)) = do { ((stmts', _), fvs) <-- rnStmts ArrowExpr rnLCmd stmts (\ _ -> return ((), emptyFVs))- ; return ( HsCmdDo x (L l stmts'), fvs ) }+ rnStmts ArrowExpr rnCmd stmts (\ _ -> return ((), emptyFVs))+ ; return ( HsCmdDo noExtField (L l stmts'), fvs ) } --------------------------------------------------- type CmdNeeds = FreeVars -- Only inhabitants are@@ -822,18 +876,18 @@ methodNamesGRHS (L _ (GRHS _ _ rhs)) = methodNamesLCmd rhs ----------------------------------------------------methodNamesStmts :: [Located (StmtLR GhcRn GhcRn (LHsCmd GhcRn))] -> FreeVars+methodNamesStmts :: [LStmtLR GhcRn GhcRn (LHsCmd GhcRn)] -> FreeVars methodNamesStmts stmts = plusFVs (map methodNamesLStmt stmts) ----------------------------------------------------methodNamesLStmt :: Located (StmtLR GhcRn GhcRn (LHsCmd GhcRn)) -> FreeVars+methodNamesLStmt :: LStmtLR GhcRn GhcRn (LHsCmd GhcRn) -> FreeVars methodNamesLStmt = methodNamesStmt . unLoc methodNamesStmt :: StmtLR GhcRn GhcRn (LHsCmd GhcRn) -> FreeVars methodNamesStmt (LastStmt _ cmd _ _) = methodNamesLCmd cmd methodNamesStmt (BodyStmt _ cmd _ _) = methodNamesLCmd cmd methodNamesStmt (BindStmt _ _ cmd) = methodNamesLCmd cmd-methodNamesStmt (RecStmt { recS_stmts = stmts }) =+methodNamesStmt (RecStmt { recS_stmts = L _ stmts }) = methodNamesStmts stmts `addOneFV` loopAName methodNamesStmt (LetStmt {}) = emptyFVs methodNamesStmt (ParStmt {}) = emptyFVs@@ -901,35 +955,42 @@ See Note [Deterministic UniqFM] to learn more about nondeterminism. -} +type AnnoBody body+ = ( Outputable (body GhcPs)+ , Anno (StmtLR GhcPs GhcPs (LocatedA (body GhcPs))) ~ SrcSpanAnnA+ , Anno (StmtLR GhcRn GhcPs (LocatedA (body GhcPs))) ~ SrcSpanAnnA+ , Anno (StmtLR GhcRn GhcRn (LocatedA (body GhcRn))) ~ SrcSpanAnnA+ )+ -- | Rename some Stmts-rnStmts :: Outputable (body GhcPs)+rnStmts :: AnnoBody body => HsStmtContext GhcRn- -> (Located (body GhcPs) -> RnM (Located (body GhcRn), FreeVars))+ -> (body GhcPs -> RnM (body GhcRn, FreeVars)) -- ^ How to rename the body of each statement (e.g. rnLExpr)- -> [LStmt GhcPs (Located (body GhcPs))]+ -> [LStmt GhcPs (LocatedA (body GhcPs))] -- ^ Statements -> ([Name] -> RnM (thing, FreeVars)) -- ^ if these statements scope over something, this renames it -- and returns the result.- -> RnM (([LStmt GhcRn (Located (body GhcRn))], thing), FreeVars)+ -> RnM (([LStmt GhcRn (LocatedA (body GhcRn))], thing), FreeVars) rnStmts ctxt rnBody = rnStmtsWithPostProcessing ctxt rnBody noPostProcessStmts -- | like 'rnStmts' but applies a post-processing step to the renamed Stmts rnStmtsWithPostProcessing- :: Outputable (body GhcPs)+ :: AnnoBody body => HsStmtContext GhcRn- -> (Located (body GhcPs) -> RnM (Located (body GhcRn), FreeVars))+ -> (body GhcPs -> RnM (body GhcRn, FreeVars)) -- ^ How to rename the body of each statement (e.g. rnLExpr) -> (HsStmtContext GhcRn- -> [(LStmt GhcRn (Located (body GhcRn)), FreeVars)]- -> RnM ([LStmt GhcRn (Located (body GhcRn))], FreeVars))+ -> [(LStmt GhcRn (LocatedA (body GhcRn)), FreeVars)]+ -> RnM ([LStmt GhcRn (LocatedA (body GhcRn))], FreeVars)) -- ^ postprocess the statements- -> [LStmt GhcPs (Located (body GhcPs))]+ -> [LStmt GhcPs (LocatedA (body GhcPs))] -- ^ Statements -> ([Name] -> RnM (thing, FreeVars)) -- ^ if these statements scope over something, this renames it -- and returns the result.- -> RnM (([LStmt GhcRn (Located (body GhcRn))], thing), FreeVars)+ -> RnM (([LStmt GhcRn (LocatedA (body GhcRn))], thing), FreeVars) rnStmtsWithPostProcessing ctxt rnBody ppStmts stmts thing_inside = do { ((stmts', thing), fvs) <- rnStmtsWithFreeVars ctxt rnBody stmts thing_inside@@ -961,17 +1022,17 @@ -- | strip the FreeVars annotations from statements noPostProcessStmts :: HsStmtContext GhcRn- -> [(LStmt GhcRn (Located (body GhcRn)), FreeVars)]- -> RnM ([LStmt GhcRn (Located (body GhcRn))], FreeVars)+ -> [(LStmt GhcRn (LocatedA (body GhcRn)), FreeVars)]+ -> RnM ([LStmt GhcRn (LocatedA (body GhcRn))], FreeVars) noPostProcessStmts _ stmts = return (map fst stmts, emptyNameSet) -rnStmtsWithFreeVars :: Outputable (body GhcPs)+rnStmtsWithFreeVars :: AnnoBody body => HsStmtContext GhcRn- -> (Located (body GhcPs) -> RnM (Located (body GhcRn), FreeVars))- -> [LStmt GhcPs (Located (body GhcPs))]+ -> ((body GhcPs) -> RnM ((body GhcRn), FreeVars))+ -> [LStmt GhcPs (LocatedA (body GhcPs))] -> ([Name] -> RnM (thing, FreeVars))- -> RnM ( ([(LStmt GhcRn (Located (body GhcRn)), FreeVars)], thing)+ -> RnM ( ([(LStmt GhcRn (LocatedA (body GhcRn)), FreeVars)], thing) , FreeVars) -- Each Stmt body is annotated with its FreeVars, so that -- we can rearrange statements for ApplicativeDo.@@ -987,7 +1048,7 @@ rnStmtsWithFreeVars mDoExpr@MDoExpr{} rnBody stmts thing_inside -- Deal with mdo = -- Behave like do { rec { ...all but last... }; last } do { ((stmts1, (stmts2, thing)), fvs)- <- rnStmt mDoExpr rnBody (noLoc $ mkRecStmt all_but_last) $ \ _ ->+ <- rnStmt mDoExpr rnBody (noLocA $ mkRecStmt noAnn (noLocA all_but_last)) $ \ _ -> do { last_stmt' <- checkLastStmt mDoExpr last_stmt ; rnStmt mDoExpr rnBody last_stmt' thing_inside } ; return (((stmts1 ++ stmts2), thing), fvs) }@@ -996,13 +1057,13 @@ rnStmtsWithFreeVars ctxt rnBody (lstmt@(L loc _) : lstmts) thing_inside | null lstmts- = setSrcSpan loc $+ = setSrcSpanA loc $ do { lstmt' <- checkLastStmt ctxt lstmt ; rnStmt ctxt rnBody lstmt' thing_inside } | otherwise = do { ((stmts1, (stmts2, thing)), fvs)- <- setSrcSpan loc $+ <- setSrcSpanA loc $ do { checkStmt ctxt lstmt ; rnStmt ctxt rnBody lstmt $ \ bndrs1 -> rnStmtsWithFreeVars ctxt rnBody lstmts $ \ bndrs2 ->@@ -1031,20 +1092,20 @@ At one point we failed to make this distinction, leading to #11216. -} -rnStmt :: Outputable (body GhcPs)+rnStmt :: AnnoBody body => HsStmtContext GhcRn- -> (Located (body GhcPs) -> RnM (Located (body GhcRn), FreeVars))+ -> (body GhcPs -> RnM (body GhcRn, FreeVars)) -- ^ How to rename the body of the statement- -> LStmt GhcPs (Located (body GhcPs))+ -> LStmt GhcPs (LocatedA (body GhcPs)) -- ^ The statement -> ([Name] -> RnM (thing, FreeVars)) -- ^ Rename the stuff that this statement scopes over- -> RnM ( ([(LStmt GhcRn (Located (body GhcRn)), FreeVars)], thing)+ -> RnM ( ([(LStmt GhcRn (LocatedA (body GhcRn)), FreeVars)], thing) , FreeVars) -- Variables bound by the Stmt, and mentioned in thing_inside, -- do not appear in the result FreeVars -rnStmt ctxt rnBody (L loc (LastStmt _ body noret _)) thing_inside+rnStmt ctxt rnBody (L loc (LastStmt _ (L lb body) noret _)) thing_inside = do { (body', fv_expr) <- rnBody body ; (ret_op, fvs1) <- if isMonadCompContext ctxt then lookupStmtName ctxt returnMName@@ -1055,10 +1116,10 @@ -- #15607 ; (thing, fvs3) <- thing_inside []- ; return (([(L loc (LastStmt noExtField body' noret ret_op), fv_expr)]+ ; return (([(L loc (LastStmt noExtField (L lb body') noret ret_op), fv_expr)] , thing), fv_expr `plusFV` fvs1 `plusFV` fvs3) } -rnStmt ctxt rnBody (L loc (BodyStmt _ body _ _)) thing_inside+rnStmt ctxt rnBody (L loc (BodyStmt _ (L lb body) _ _)) thing_inside = do { (body', fv_expr) <- rnBody body ; (then_op, fvs1) <- lookupQualifiedDoStmtName ctxt thenMName @@ -1070,10 +1131,10 @@ -- Here "gd" is a guard ; (thing, fvs3) <- thing_inside []- ; return ( ([(L loc (BodyStmt noExtField body' then_op guard_op), fv_expr)]+ ; return ( ([(L loc (BodyStmt noExtField (L lb body') then_op guard_op), fv_expr)] , thing), fv_expr `plusFV` fvs1 `plusFV` fvs2 `plusFV` fvs3) } -rnStmt ctxt rnBody (L loc (BindStmt _ pat body)) thing_inside+rnStmt ctxt rnBody (L loc (BindStmt _ pat (L lb body))) thing_inside = do { (body', fv_expr) <- rnBody body -- The binders do not scope over the expression ; (bind_op, fvs1) <- lookupQualifiedDoStmtName ctxt bindMName@@ -1083,19 +1144,19 @@ ; rnPat (StmtCtxt ctxt) pat $ \ pat' -> do { (thing, fvs3) <- thing_inside (collectPatBinders CollNoDictBinders pat') ; let xbsrn = XBindStmtRn { xbsrn_bindOp = bind_op, xbsrn_failOp = fail_op }- ; return (( [( L loc (BindStmt xbsrn pat' body'), fv_expr )]+ ; return (( [( L loc (BindStmt xbsrn pat' (L lb body')), fv_expr )] , thing), fv_expr `plusFV` fvs1 `plusFV` fvs2 `plusFV` fvs3) }} -- fv_expr shouldn't really be filtered by the rnPatsAndThen -- but it does not matter because the names are unique -rnStmt _ _ (L loc (LetStmt _ (L l binds))) thing_inside+rnStmt _ _ (L loc (LetStmt _ binds)) thing_inside = rnLocalBindsAndThen binds $ \binds' bind_fvs -> do { (thing, fvs) <- thing_inside (collectLocalBinders CollNoDictBinders binds')- ; return ( ([(L loc (LetStmt noExtField (L l binds')), bind_fvs)], thing)+ ; return ( ([(L loc (LetStmt noAnn binds'), bind_fvs)], thing) , fvs) } -rnStmt ctxt rnBody (L loc (RecStmt { recS_stmts = rec_stmts })) thing_inside+rnStmt ctxt rnBody (L loc (RecStmt { recS_stmts = L _ rec_stmts })) thing_inside = do { (return_op, fvs1) <- lookupQualifiedDoStmtName ctxt returnMName ; (mfix_op, fvs2) <- lookupQualifiedDoStmtName ctxt mfixName ; (bind_op, fvs3) <- lookupQualifiedDoStmtName ctxt bindMName@@ -1119,7 +1180,7 @@ segs -- See Note [Deterministic ApplicativeDo and RecursiveDo desugaring] ; (thing, fvs_later) <- thing_inside bndrs- ; let (rec_stmts', fvs) = segmentRecStmts loc ctxt empty_rec_stmt segs fvs_later+ ; let (rec_stmts', fvs) = segmentRecStmts (locA loc) ctxt empty_rec_stmt segs fvs_later -- We aren't going to try to group RecStmts with -- ApplicativeDo, so attaching empty FVs is fine. ; return ( ((zip rec_stmts' (repeat emptyNameSet)), thing)@@ -1141,7 +1202,7 @@ -- Rename the stmts and the 'by' expression -- Keep track of the variables mentioned in the 'by' expression ; ((stmts', (by', used_bndrs, thing)), fvs2)- <- rnStmts (TransStmtCtxt ctxt) rnLExpr stmts $ \ bndrs ->+ <- rnStmts (TransStmtCtxt ctxt) rnExpr stmts $ \ bndrs -> do { (by', fvs_by) <- mapMaybeFvRn rnLExpr by ; (thing, fvs_thing) <- thing_inside bndrs ; let fvs = fvs_by `plusFV` fvs_thing@@ -1193,7 +1254,7 @@ rn_segs env bndrs_so_far (ParStmtBlock x stmts _ _ : segs) = do { ((stmts', (used_bndrs, segs', thing)), fvs)- <- rnStmts ctxt rnLExpr stmts $ \ bndrs ->+ <- rnStmts ctxt rnExpr stmts $ \ bndrs -> setLocalRdrEnv env $ do { ((segs', thing), fvs) <- rn_segs env (bndrs ++ bndrs_so_far) segs ; let used_bndrs = filter (`elemNameSet` fvs) bndrs@@ -1228,12 +1289,12 @@ = do { rebindable_on <- xoptM LangExt.RebindableSyntax ; if rebindable_on then do { fm <- lookupOccRn (nameRdrName name)- ; return (HsVar noExtField (noLoc fm), unitFV fm) }+ ; return (HsVar noExtField (noLocA fm), unitFV fm) } else not_rebindable } | otherwise = not_rebindable where- not_rebindable = return (HsVar noExtField (noLoc name), emptyFVs)+ not_rebindable = return (HsVar noExtField (noLocA name), emptyFVs) -- | Is this a context where we respect RebindableSyntax? -- but ListComp are never rebindable@@ -1289,14 +1350,13 @@ -- wrapper that does both the left- and right-hand sides-rnRecStmtsAndThen :: Outputable (body GhcPs) =>+rnRecStmtsAndThen :: AnnoBody body => HsStmtContext GhcRn- -> (Located (body GhcPs)- -> RnM (Located (body GhcRn), FreeVars))- -> [LStmt GhcPs (Located (body GhcPs))]+ -> (body GhcPs -> RnM (body GhcRn, FreeVars))+ -> [LStmt GhcPs (LocatedA (body GhcPs))] -- assumes that the FreeVars returned includes -- the FreeVars of the Segments- -> ([Segment (LStmt GhcRn (Located (body GhcRn)))]+ -> ([Segment (LStmt GhcRn (LocatedA (body GhcRn)))] -> RnM (a, FreeVars)) -> RnM (a, FreeVars) rnRecStmtsAndThen ctxt rnBody s cont@@ -1326,7 +1386,7 @@ collectRecStmtsFixities :: [LStmtLR GhcPs GhcPs body] -> [LFixitySig GhcPs] collectRecStmtsFixities l = foldr (\ s -> \acc -> case s of- (L _ (LetStmt _ (L _ (HsValBinds _ (ValBinds _ _ sigs))))) ->+ (L _ (LetStmt _ (HsValBinds _ (ValBinds _ _ sigs)))) -> foldr (\ sig -> \ acc -> case sig of (L loc (FixSig _ s)) -> (L loc s) : acc _ -> acc) acc sigs@@ -1334,12 +1394,12 @@ -- left-hand sides -rn_rec_stmt_lhs :: Outputable body => MiniFixityEnv- -> LStmt GhcPs body+rn_rec_stmt_lhs :: AnnoBody body => MiniFixityEnv+ -> LStmt GhcPs (LocatedA (body GhcPs)) -- rename LHS, and return its FVs -- Warning: we will only need the FreeVars below in the case of a BindStmt, -- so we don't bother to compute it accurately in the other cases- -> RnM [(LStmtLR GhcRn GhcPs body, FreeVars)]+ -> RnM [(LStmtLR GhcRn GhcPs (LocatedA (body GhcPs)), FreeVars)] rn_rec_stmt_lhs _ (L loc (BodyStmt _ body a b)) = return [(L loc (BodyStmt noExtField body a b), emptyFVs)]@@ -1351,20 +1411,20 @@ = do -- should the ctxt be MDo instead? (pat', fv_pat) <- rnBindPat (localRecNameMaker fix_env) pat- return [(L loc (BindStmt noExtField pat' body), fv_pat)]+ return [(L loc (BindStmt noAnn pat' body), fv_pat)] -rn_rec_stmt_lhs _ (L _ (LetStmt _ (L _ binds@(HsIPBinds {}))))+rn_rec_stmt_lhs _ (L _ (LetStmt _ binds@(HsIPBinds {}))) = failWith (badIpBinds (text "an mdo expression") binds) -rn_rec_stmt_lhs fix_env (L loc (LetStmt _ (L l (HsValBinds x binds))))+rn_rec_stmt_lhs fix_env (L loc (LetStmt _ (HsValBinds x binds))) = do (_bound_names, binds') <- rnLocalValBindsLHS fix_env binds- return [(L loc (LetStmt noExtField (L l (HsValBinds x binds'))),+ return [(L loc (LetStmt noAnn (HsValBinds x binds')), -- Warning: this is bogus; see function invariant emptyFVs )] -- XXX Do we need to do something with the return and mfix names?-rn_rec_stmt_lhs fix_env (L _ (RecStmt { recS_stmts = stmts })) -- Flatten Rec inside Rec+rn_rec_stmt_lhs fix_env (L _ (RecStmt { recS_stmts = L _ stmts })) -- Flatten Rec inside Rec = rn_rec_stmts_lhs fix_env stmts rn_rec_stmt_lhs _ stmt@(L _ (ParStmt {})) -- Syntactically illegal in mdo@@ -1376,12 +1436,12 @@ rn_rec_stmt_lhs _ stmt@(L _ (ApplicativeStmt {})) -- Shouldn't appear yet = pprPanic "rn_rec_stmt" (ppr stmt) -rn_rec_stmt_lhs _ (L _ (LetStmt _ (L _ (EmptyLocalBinds _))))+rn_rec_stmt_lhs _ (L _ (LetStmt _ (EmptyLocalBinds _))) = panic "rn_rec_stmt LetStmt EmptyLocalBinds" -rn_rec_stmts_lhs :: Outputable body => MiniFixityEnv- -> [LStmt GhcPs body]- -> RnM [(LStmtLR GhcRn GhcPs body, FreeVars)]+rn_rec_stmts_lhs :: AnnoBody body => MiniFixityEnv+ -> [LStmt GhcPs (LocatedA (body GhcPs))]+ -> RnM [(LStmtLR GhcRn GhcPs (LocatedA (body GhcPs)), FreeVars)] rn_rec_stmts_lhs fix_env stmts = do { ls <- concatMapM (rn_rec_stmt_lhs fix_env) stmts ; let boundNames = collectLStmtsBinders CollNoDictBinders (map fst ls)@@ -1394,28 +1454,28 @@ -- right-hand-sides -rn_rec_stmt :: (Outputable (body GhcPs)) =>+rn_rec_stmt :: AnnoBody body => HsStmtContext GhcRn- -> (Located (body GhcPs) -> RnM (Located (body GhcRn), FreeVars))+ -> (body GhcPs -> RnM (body GhcRn, FreeVars)) -> [Name]- -> (LStmtLR GhcRn GhcPs (Located (body GhcPs)), FreeVars)- -> RnM [Segment (LStmt GhcRn (Located (body GhcRn)))]+ -> (LStmtLR GhcRn GhcPs (LocatedA (body GhcPs)), FreeVars)+ -> RnM [Segment (LStmt GhcRn (LocatedA (body GhcRn)))] -- Rename a Stmt that is inside a RecStmt (or mdo) -- Assumes all binders are already in scope -- Turns each stmt into a singleton Stmt-rn_rec_stmt ctxt rnBody _ (L loc (LastStmt _ body noret _), _)+rn_rec_stmt ctxt rnBody _ (L loc (LastStmt _ (L lb body) noret _), _) = do { (body', fv_expr) <- rnBody body ; (ret_op, fvs1) <- lookupQualifiedDo ctxt returnMName ; return [(emptyNameSet, fv_expr `plusFV` fvs1, emptyNameSet,- L loc (LastStmt noExtField body' noret ret_op))] }+ L loc (LastStmt noExtField (L lb body') noret ret_op))] } -rn_rec_stmt ctxt rnBody _ (L loc (BodyStmt _ body _ _), _)+rn_rec_stmt ctxt rnBody _ (L loc (BodyStmt _ (L lb body) _ _), _) = do { (body', fvs) <- rnBody body ; (then_op, fvs1) <- lookupQualifiedDo ctxt thenMName ; return [(emptyNameSet, fvs `plusFV` fvs1, emptyNameSet,- L loc (BodyStmt noExtField body' then_op noSyntaxExpr))] }+ L loc (BodyStmt noExtField (L lb body') then_op noSyntaxExpr))] } -rn_rec_stmt ctxt rnBody _ (L loc (BindStmt _ pat' body), fv_pat)+rn_rec_stmt ctxt rnBody _ (L loc (BindStmt _ pat' (L lb body)), fv_pat) = do { (body', fv_expr) <- rnBody body ; (bind_op, fvs1) <- lookupQualifiedDo ctxt bindMName @@ -1425,17 +1485,17 @@ fvs = fv_expr `plusFV` fv_pat `plusFV` fvs1 `plusFV` fvs2 ; let xbsrn = XBindStmtRn { xbsrn_bindOp = bind_op, xbsrn_failOp = fail_op } ; return [(bndrs, fvs, bndrs `intersectNameSet` fvs,- L loc (BindStmt xbsrn pat' body'))] }+ L loc (BindStmt xbsrn pat' (L lb body')))] } -rn_rec_stmt _ _ _ (L _ (LetStmt _ (L _ binds@(HsIPBinds {}))), _)+rn_rec_stmt _ _ _ (L _ (LetStmt _ binds@(HsIPBinds {})), _) = failWith (badIpBinds (text "an mdo expression") binds) -rn_rec_stmt _ _ all_bndrs (L loc (LetStmt _ (L l (HsValBinds x binds'))), _)+rn_rec_stmt _ _ all_bndrs (L loc (LetStmt _ (HsValBinds x binds')), _) = do { (binds', du_binds) <- rnLocalValBindsRHS (mkNameSet all_bndrs) binds' -- fixities and unused are handled above in rnRecStmtsAndThen ; let fvs = allUses du_binds ; return [(duDefs du_binds, fvs, emptyNameSet,- L loc (LetStmt noExtField (L l (HsValBinds x binds'))))] }+ L loc (LetStmt noAnn (HsValBinds x binds')))] } -- no RecStmt case because they get flattened above when doing the LHSes rn_rec_stmt _ _ _ stmt@(L _ (RecStmt {}), _)@@ -1447,27 +1507,28 @@ rn_rec_stmt _ _ _ stmt@(L _ (TransStmt {}), _) -- Syntactically illegal in mdo = pprPanic "rn_rec_stmt: TransStmt" (ppr stmt) -rn_rec_stmt _ _ _ (L _ (LetStmt _ (L _ (EmptyLocalBinds _))), _)+rn_rec_stmt _ _ _ (L _ (LetStmt _ (EmptyLocalBinds _)), _) = panic "rn_rec_stmt: LetStmt EmptyLocalBinds" rn_rec_stmt _ _ _ stmt@(L _ (ApplicativeStmt {}), _) = pprPanic "rn_rec_stmt: ApplicativeStmt" (ppr stmt) -rn_rec_stmts :: Outputable (body GhcPs) =>+rn_rec_stmts :: AnnoBody body => HsStmtContext GhcRn- -> (Located (body GhcPs) -> RnM (Located (body GhcRn), FreeVars))+ -> (body GhcPs -> RnM (body GhcRn, FreeVars)) -> [Name]- -> [(LStmtLR GhcRn GhcPs (Located (body GhcPs)), FreeVars)]- -> RnM [Segment (LStmt GhcRn (Located (body GhcRn)))]+ -> [(LStmtLR GhcRn GhcPs (LocatedA (body GhcPs)), FreeVars)]+ -> RnM [Segment (LStmt GhcRn (LocatedA (body GhcRn)))] rn_rec_stmts ctxt rnBody bndrs stmts = do { segs_s <- mapM (rn_rec_stmt ctxt rnBody bndrs) stmts ; return (concat segs_s) } ----------------------------------------------segmentRecStmts :: SrcSpan -> HsStmtContext GhcRn- -> Stmt GhcRn body- -> [Segment (LStmt GhcRn body)] -> FreeVars- -> ([LStmt GhcRn body], FreeVars)+segmentRecStmts :: AnnoBody body+ => SrcSpan -> HsStmtContext GhcRn+ -> Stmt GhcRn (LocatedA (body GhcRn))+ -> [Segment (LStmt GhcRn (LocatedA (body GhcRn)))] -> FreeVars+ -> ([LStmt GhcRn (LocatedA (body GhcRn))], FreeVars) segmentRecStmts loc ctxt empty_rec_stmt segs fvs_later | null segs@@ -1482,8 +1543,8 @@ -- used 'after' the RecStmt | otherwise- = ([ L loc $- empty_rec_stmt { recS_stmts = ss+ = ([ L (noAnnSrcSpan loc) $+ empty_rec_stmt { recS_stmts = noLocA ss , recS_later_ids = nameSetElemsStable (defs `intersectNameSet` fvs_later) , recS_rec_ids = nameSetElemsStable@@ -1600,12 +1661,12 @@ not_needed (defs,_,_,_) = disjointNameSet defs uses -----------------------------------------------------segsToStmts :: Stmt GhcRn body+segsToStmts :: Stmt GhcRn (LocatedA (body GhcRn)) -- A RecStmt with the SyntaxOps filled in- -> [Segment [LStmt GhcRn body]]+ -> [Segment [LStmt GhcRn (LocatedA (body GhcRn))]] -- Each Segment has a non-empty list of Stmts -> FreeVars -- Free vars used 'later'- -> ([LStmt GhcRn body], FreeVars)+ -> ([LStmt GhcRn (LocatedA (body GhcRn))], FreeVars) segsToStmts _ [] fvs_later = ([], fvs_later) segsToStmts empty_rec_stmt ((defs, uses, fwds, ss) : segs) fvs_later@@ -1615,7 +1676,7 @@ (later_stmts, later_uses) = segsToStmts empty_rec_stmt segs fvs_later new_stmt | non_rec = head ss | otherwise = L (getLoc (head ss)) rec_stmt- rec_stmt = empty_rec_stmt { recS_stmts = ss+ rec_stmt = empty_rec_stmt { recS_stmts = noLocA ss , recS_later_ids = nameSetElemsStable used_later , recS_rec_ids = nameSetElemsStable fwds } -- See Note [Deterministic ApplicativeDo and RecursiveDo desugaring]@@ -1983,14 +2044,14 @@ pvars = nameSetElemsStable pvarset -- See Note [Deterministic ApplicativeDo and RecursiveDo desugaring] pat = mkBigLHsVarPatTup pvars- tup = mkBigLHsVarTup pvars+ tup = mkBigLHsVarTup pvars noExtField (stmts',fvs2) <- stmtTreeToStmts monad_names ctxt tree [] pvarset (mb_ret, fvs1) <- if | L _ ApplicativeStmt{} <- last stmts' -> return (unLoc tup, emptyNameSet) | otherwise -> do (ret, _) <- lookupQualifiedDoExpr ctxt returnMName- let expr = HsApp noExtField (noLoc ret) tup+ let expr = HsApp noComments (noLocA ret) tup return (expr, emptyFVs) return ( ApplicativeArgMany { xarg_app_arg_many = noExtField@@ -2142,10 +2203,10 @@ _other -> (stmts,[]) slurpIndependentStmts- :: [(LStmt GhcRn (Located (body GhcRn)), FreeVars)]- -> Maybe ( [(LStmt GhcRn (Located (body GhcRn)), FreeVars)] -- LetStmts- , [(LStmt GhcRn (Located (body GhcRn)), FreeVars)] -- BindStmts- , [(LStmt GhcRn (Located (body GhcRn)), FreeVars)] )+ :: [(LStmt GhcRn (LocatedA (body GhcRn)), FreeVars)]+ -> Maybe ( [(LStmt GhcRn (LocatedA (body GhcRn)), FreeVars)] -- LetStmts+ , [(LStmt GhcRn (LocatedA (body GhcRn)), FreeVars)] -- BindStmts+ , [(LStmt GhcRn (LocatedA (body GhcRn)), FreeVars)] ) slurpIndependentStmts stmts = go [] [] emptyNameSet stmts where -- If we encounter a BindStmt that doesn't depend on a previous BindStmt@@ -2198,7 +2259,7 @@ ; return (Just join_op, fvs) } else return (Nothing, emptyNameSet)- ; let applicative_stmt = noLoc $ ApplicativeStmt noExtField+ ; let applicative_stmt = noLocA $ ApplicativeStmt noExtField (zip (fmap_op : repeat ap_op) args) mb_join ; return ( applicative_stmt : body_stmts@@ -2260,9 +2321,9 @@ emptyErr ctxt = text "Empty" <+> pprStmtContext ctxt -----------------------checkLastStmt :: Outputable (body GhcPs) => HsStmtContext GhcRn- -> LStmt GhcPs (Located (body GhcPs))- -> RnM (LStmt GhcPs (Located (body GhcPs)))+checkLastStmt :: AnnoBody body => HsStmtContext GhcRn+ -> LStmt GhcPs (LocatedA (body GhcPs))+ -> RnM (LStmt GhcPs (LocatedA (body GhcPs))) checkLastStmt ctxt lstmt@(L loc stmt) = case ctxt of ListComp -> check_comp@@ -2291,7 +2352,7 @@ -- Checking when a particular Stmt is ok checkStmt :: HsStmtContext GhcRn- -> LStmt GhcPs (Located (body GhcPs))+ -> LStmt GhcPs (LocatedA (body GhcPs)) -> RnM () checkStmt ctxt (L _ stmt) = do { dflags <- getDynFlags@@ -2318,7 +2379,7 @@ okStmt, okDoStmt, okCompStmt, okParStmt :: DynFlags -> HsStmtContext GhcRn- -> Stmt GhcPs (Located (body GhcPs)) -> Validity+ -> Stmt GhcPs (LocatedA (body GhcPs)) -> Validity -- Return Nothing if OK, (Just extra) if not ok -- The "extra" is an SDoc that is appended to a generic error message @@ -2335,7 +2396,7 @@ TransStmtCtxt ctxt -> okStmt dflags ctxt stmt --------------okPatGuardStmt :: Stmt GhcPs (Located (body GhcPs)) -> Validity+okPatGuardStmt :: Stmt GhcPs (LocatedA (body GhcPs)) -> Validity okPatGuardStmt stmt = case stmt of BodyStmt {} -> IsValid@@ -2346,8 +2407,8 @@ ------------- okParStmt dflags ctxt stmt = case stmt of- LetStmt _ (L _ (HsIPBinds {})) -> emptyInvalid- _ -> okStmt dflags ctxt stmt+ LetStmt _ (HsIPBinds {}) -> emptyInvalid+ _ -> okStmt dflags ctxt stmt ---------------- okDoStmt dflags ctxt stmt@@ -2378,7 +2439,7 @@ ApplicativeStmt {} -> emptyInvalid ----------checkTupleSection :: [LHsTupArg GhcPs] -> RnM ()+checkTupleSection :: [HsTupArg GhcPs] -> RnM () checkTupleSection args = do { tuple_section <- xoptM LangExt.TupleSections ; checkErr (all tupArgPresent args || tuple_section) msg }@@ -2468,10 +2529,10 @@ arg_name <- newSysName arg_lit let arg_syn_expr = nlHsVar arg_name body :: LHsExpr GhcRn =- nlHsApp (noLoc failExpr)- (nlHsApp (noLoc $ fromStringExpr) arg_syn_expr)+ nlHsApp (noLocA failExpr)+ (nlHsApp (noLocA $ fromStringExpr) arg_syn_expr) let failAfterFromStringExpr :: HsExpr GhcRn =- unLoc $ mkHsLam [noLoc $ VarPat noExtField $ noLoc arg_name] body+ unLoc $ mkHsLam [noLocA $ VarPat noExtField $ noLocA arg_name] body let failAfterFromStringSynExpr :: SyntaxExpr GhcRn = mkSyntaxExpr failAfterFromStringExpr return (failAfterFromStringSynExpr, failFvs `plusFV` fromStringFvs)@@ -2489,7 +2550,7 @@ genHsApps fun args = foldl genHsApp (genHsVar fun) args genHsApp :: HsExpr GhcRn -> LHsExpr GhcRn -> HsExpr GhcRn-genHsApp fun arg = HsApp noExtField (wrapGenSpan fun) arg+genHsApp fun arg = HsApp noAnn (wrapGenSpan fun) arg genLHsVar :: Name -> LHsExpr GhcRn genLHsVar nm = wrapGenSpan $ genHsVar nm@@ -2497,10 +2558,16 @@ genHsVar :: Name -> HsExpr GhcRn genHsVar nm = HsVar noExtField $ wrapGenSpan nm -wrapGenSpan :: a -> Located a+genAppType :: HsExpr GhcRn -> HsType (NoGhcTc GhcRn) -> HsExpr GhcRn+genAppType expr = HsAppType noExtField (wrapGenSpan expr) . mkEmptyWildCardBndrs . wrapGenSpan++genHsTyLit :: FastString -> HsType GhcRn+genHsTyLit = HsTyLit noExtField . HsStrTy NoSourceText++wrapGenSpan :: a -> LocatedAn an a -- Wrap something in a "generatedSrcSpan" -- See Note [Rebindable syntax and HsExpansion]-wrapGenSpan x = L generatedSrcSpan x+wrapGenSpan x = L (noAnnSrcSpan generatedSrcSpan) x -- | Build a 'HsExpansion' out of an extension constructor, -- and the two components of the expansion: original and@@ -2510,3 +2577,76 @@ -> HsExpr GhcRn -- ^ expanded expression -> HsExpr GhcRn -- ^ suitably wrapped 'HsExpansion' mkExpandedExpr a b = XExpr (HsExpanded a b)++-----------------------------------------+-- Bits and pieces for RecordDotSyntax.+--+-- See Note [Overview of record dot syntax] in GHC.Hs.Expr.++-- mkGetField arg field calcuates a get_field @field arg expression.+-- e.g. z.x = mkGetField z x = get_field @x z+mkGetField :: Name -> LHsExpr GhcRn -> Located FieldLabelString -> HsExpr GhcRn+mkGetField get_field arg field = unLoc (head $ mkGet get_field [arg] field)++-- mkSetField a field b calculates a set_field @field expression.+-- e.g mkSetSetField a field b = set_field @"field" a b (read as "set field 'field' on a to b").+mkSetField :: Name -> LHsExpr GhcRn -> Located FieldLabelString -> LHsExpr GhcRn -> HsExpr GhcRn+mkSetField set_field a (L _ field) b =+ genHsApp (genHsApp (genHsVar set_field `genAppType` genHsTyLit field) a) b++mkGet :: Name -> [LHsExpr GhcRn] -> Located FieldLabelString -> [LHsExpr GhcRn]+mkGet get_field l@(r : _) (L _ field) =+ wrapGenSpan (genHsApp (genHsVar get_field `genAppType` genHsTyLit field) r) : l+mkGet _ [] _ = panic "mkGet : The impossible has happened!"++mkSet :: Name -> LHsExpr GhcRn -> (Located FieldLabelString, LHsExpr GhcRn) -> LHsExpr GhcRn+mkSet set_field acc (field, g) = wrapGenSpan (mkSetField set_field g field acc)++-- mkProjection fields calculates a projection.+-- e.g. .x = mkProjection [x] = getField @"x"+-- .x.y = mkProjection [.x, .y] = (.y) . (.x) = getField @"y" . getField @"x"+mkProjection :: Name -> Name -> [Located FieldLabelString] -> HsExpr GhcRn+mkProjection getFieldName circName (field : fields) = foldl' f (proj field) fields+ where+ f :: HsExpr GhcRn -> Located FieldLabelString -> HsExpr GhcRn+ f acc field = genHsApps circName $ map wrapGenSpan [proj field, acc]++ proj :: Located FieldLabelString -> HsExpr GhcRn+ proj (L _ f) = genHsVar getFieldName `genAppType` genHsTyLit f+mkProjection _ _ [] = panic "mkProjection: The impossible happened"++-- mkProjUpdateSetField calculates functions representing dot notation record updates.+-- e.g. Suppose an update like foo.bar = 1.+-- We calculate the function \a -> setField @"foo" a (setField @"bar" (getField @"foo" a) 1).+mkProjUpdateSetField :: Name -> Name -> LHsRecProj GhcRn (LHsExpr GhcRn) -> (LHsExpr GhcRn -> LHsExpr GhcRn)+mkProjUpdateSetField get_field set_field (L _ (HsRecField { hsRecFieldLbl = (L _ (FieldLabelStrings flds')), hsRecFieldArg = arg } ))+ = let {+ ; flds = map (fmap (unLoc . hflLabel)) flds'+ ; final = last flds -- quux+ ; fields = init flds -- [foo, bar, baz]+ ; getters = \a -> foldl' (mkGet get_field) [a] fields -- Ordered from deep to shallow.+ -- [getField@"baz"(getField@"bar"(getField@"foo" a), getField@"bar"(getField@"foo" a), getField@"foo" a, a]+ ; zips = \a -> (final, head (getters a)) : zip (reverse fields) (tail (getters a)) -- Ordered from deep to shallow.+ -- [("quux", getField@"baz"(getField@"bar"(getField@"foo" a)), ("baz", getField@"bar"(getField@"foo" a)), ("bar", getField@"foo" a), ("foo", a)]+ }+ in (\a -> foldl' (mkSet set_field) arg (zips a))+ -- setField@"foo" (a) (setField@"bar" (getField @"foo" (a))(setField@"baz" (getField @"bar" (getField @"foo" (a)))(setField@"quux" (getField @"baz" (getField @"bar" (getField @"foo" (a))))(quux))))++mkRecordDotUpd :: Name -> Name -> LHsExpr GhcRn -> [LHsRecUpdProj GhcRn] -> HsExpr GhcRn+mkRecordDotUpd get_field set_field exp updates = foldl' fieldUpdate (unLoc exp) updates+ where+ fieldUpdate :: HsExpr GhcRn -> LHsRecUpdProj GhcRn -> HsExpr GhcRn+ fieldUpdate acc lpu = unLoc $ (mkProjUpdateSetField get_field set_field lpu) (wrapGenSpan acc)++rnHsUpdProjs :: [LHsRecUpdProj GhcPs] -> RnM ([LHsRecUpdProj GhcRn], FreeVars)+rnHsUpdProjs us = do+ (u, fvs) <- unzip <$> mapM rnRecUpdProj us+ pure (u, plusFVs fvs)+ where+ rnRecUpdProj :: LHsRecUpdProj GhcPs -> RnM (LHsRecUpdProj GhcRn, FreeVars)+ rnRecUpdProj (L l (HsRecField _ fs arg pun))+ = do { (arg, fv) <- rnLExpr arg+ ; return $ (L l (HsRecField { hsRecFieldAnn = noAnn+ , hsRecFieldLbl = fmap rnFieldLabelStrings fs+ , hsRecFieldArg = arg+ , hsRecPun = pun}), fv) }
compiler/GHC/Rename/Expr.hs-boot view
@@ -1,17 +1,27 @@+{-# LANGUAGE TypeFamilies #-}+{-# LANGUAGE ConstraintKinds #-} module GHC.Rename.Expr where import GHC.Types.Name import GHC.Hs import GHC.Types.Name.Set ( FreeVars ) import GHC.Tc.Types-import GHC.Types.SrcLoc ( Located ) import GHC.Utils.Outputable ( Outputable ) +rnExpr :: HsExpr GhcPs+ -> RnM (HsExpr GhcRn, FreeVars)+ rnLExpr :: LHsExpr GhcPs -> RnM (LHsExpr GhcRn, FreeVars) +type AnnoBody body+ = ( Outputable (body GhcPs)+ , Anno (StmtLR GhcPs GhcPs (LocatedA (body GhcPs))) ~ SrcSpanAnnA+ , Anno (StmtLR GhcRn GhcPs (LocatedA (body GhcPs))) ~ SrcSpanAnnA+ , Anno (StmtLR GhcRn GhcRn (LocatedA (body GhcRn))) ~ SrcSpanAnnA+ ) rnStmts :: --forall thing body.- Outputable (body GhcPs) => HsStmtContext GhcRn- -> (Located (body GhcPs) -> RnM (Located (body GhcRn), FreeVars))- -> [LStmt GhcPs (Located (body GhcPs))]+ AnnoBody body => HsStmtContext GhcRn+ -> (body GhcPs -> RnM (body GhcRn, FreeVars))+ -> [LStmt GhcPs (LocatedA (body GhcPs))] -> ([Name] -> RnM (thing, FreeVars))- -> RnM (([LStmt GhcRn (Located (body GhcRn))], thing), FreeVars)+ -> RnM (([LStmt GhcRn (LocatedA (body GhcRn))], thing), FreeVars)
compiler/GHC/Rename/Fixity.hs view
@@ -181,7 +181,7 @@ doc = text "Checking fixity for" <+> ppr name ----------------lookupTyFixityRn :: Located Name -> RnM Fixity+lookupTyFixityRn :: LocatedN Name -> RnM Fixity lookupTyFixityRn = lookupFixityRn . unLoc -- | Look up the fixity of a (possibly ambiguous) occurrence of a record field
compiler/GHC/Rename/HsType.hs view
@@ -1,4 +1,6 @@ {-# LANGUAGE CPP #-}+{-# LANGUAGE DataKinds #-}+{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeFamilies #-}@@ -34,7 +36,7 @@ extractHsTysRdrTyVars, extractRdrKindSigVars, extractConDeclGADTDetailsTyVars, extractDataDefnKindVars, extractHsOuterTvBndrs, extractHsTyArgRdrKiTyVars,- nubL+ nubL, nubN ) where import GHC.Prelude@@ -47,7 +49,7 @@ import GHC.Rename.Env import GHC.Rename.Utils ( HsDocContext(..), inHsDocContext, withHsDocContext , mapFvRn, pprHsDocContext, bindLocalNamesFV- , typeAppErr, newLocalBndrRn, checkDupRdrNames+ , typeAppErr, newLocalBndrRn, checkDupRdrNamesN , checkShadowedRdrNames ) import GHC.Rename.Fixity ( lookupFieldFixityRn, lookupFixityRn , lookupTyFixityRn )@@ -155,7 +157,7 @@ ; checkErr ty_sig_okay (unexpectedPatSigTypeErr sig_ty) ; free_vars <- filterInScopeM (extractHsTyRdrTyVars pat_sig_ty) ; (nwc_rdrs', tv_rdrs) <- partition_nwcs free_vars- ; let nwc_rdrs = nubL nwc_rdrs'+ ; let nwc_rdrs = nubN nwc_rdrs' implicit_bndrs = case scoping of AlwaysBind -> tv_rdrs NeverBind -> []@@ -228,7 +230,7 @@ (res, fvs') <- thing_inside sig_ty return (res, fvs `plusFV` fvs') -rnWcBody :: HsDocContext -> [Located RdrName] -> LHsType GhcPs+rnWcBody :: HsDocContext -> [LocatedN RdrName] -> LHsType GhcPs -> RnM ([Name], LHsType GhcRn, FreeVars) rnWcBody ctxt nwc_rdrs hs_ty = do { nwcs <- mapM newLocalBndrRn nwc_rdrs@@ -241,7 +243,7 @@ ; return (nwcs, hs_ty', fvs) } where rn_lty env (L loc hs_ty)- = setSrcSpan loc $+ = setSrcSpanA loc $ do { (hs_ty', fvs) <- rn_ty env hs_ty ; return (L loc hs_ty', fvs) } @@ -254,26 +256,35 @@ , hst_tele = tele', hst_body = hs_body' } , fvs) } - rn_ty env (HsQualTy { hst_ctxt = L cx hs_ctxt+ rn_ty env (HsQualTy { hst_ctxt = m_ctxt , hst_body = hs_ty })- | Just (hs_ctxt1, hs_ctxt_last) <- snocView hs_ctxt+ | Just (L cx hs_ctxt) <- m_ctxt+ , Just (hs_ctxt1, hs_ctxt_last) <- snocView hs_ctxt , L lx (HsWildCardTy _) <- ignoreParens hs_ctxt_last = do { (hs_ctxt1', fvs1) <- mapFvRn (rn_top_constraint env) hs_ctxt1- ; setSrcSpan lx $ checkExtraConstraintWildCard env hs_ctxt1+ ; setSrcSpanA lx $ checkExtraConstraintWildCard env hs_ctxt1 ; let hs_ctxt' = hs_ctxt1' ++ [L lx (HsWildCardTy noExtField)] ; (hs_ty', fvs2) <- rnLHsTyKi env hs_ty ; return (HsQualTy { hst_xqual = noExtField- , hst_ctxt = L cx hs_ctxt', hst_body = hs_ty' }+ , hst_ctxt = Just (L cx hs_ctxt')+ , hst_body = hs_ty' } , fvs1 `plusFV` fvs2) } - | otherwise+ | Just (L cx hs_ctxt) <- m_ctxt = do { (hs_ctxt', fvs1) <- mapFvRn (rn_top_constraint env) hs_ctxt ; (hs_ty', fvs2) <- rnLHsTyKi env hs_ty ; return (HsQualTy { hst_xqual = noExtField- , hst_ctxt = L cx hs_ctxt'+ , hst_ctxt = Just (L cx hs_ctxt') , hst_body = hs_ty' } , fvs1 `plusFV` fvs2) } + | Nothing <- m_ctxt+ = do { (hs_ty', fvs2) <- rnLHsTyKi env hs_ty+ ; return (HsQualTy { hst_xqual = noExtField+ , hst_ctxt = Nothing+ , hst_body = hs_ty' }+ , fvs2) }+ rn_ty env hs_ty = rnHsTyKi env hs_ty rn_top_constraint env = rnLHsTyKi (env { rtke_what = RnTopConstraint })@@ -326,7 +337,7 @@ -- FreeKiTyVars in the argument and returns them in a separate list. -- When the extension is disabled, the function returns the argument -- and empty list. See Note [Renaming named wild cards]-partition_nwcs :: FreeKiTyVars -> RnM ([Located RdrName], FreeKiTyVars)+partition_nwcs :: FreeKiTyVars -> RnM ([LocatedN RdrName], FreeKiTyVars) partition_nwcs free_vars = do { wildcards_enabled <- xoptM LangExt.NamedWildCards ; return $@@ -334,7 +345,7 @@ then partition is_wildcard free_vars else ([], free_vars) } where- is_wildcard :: Located RdrName -> Bool+ is_wildcard :: LocatedN RdrName -> Bool is_wildcard rdr = startsWithUnderscore (rdrNameOcc (unLoc rdr)) {- Note [Renaming named wild cards]@@ -364,7 +375,7 @@ -- that cannot have wildcards rnHsSigType ctx level (L loc sig_ty@(HsSig { sig_bndrs = outer_bndrs, sig_body = body }))- = setSrcSpan loc $+ = setSrcSpanA loc $ do { traceRn "rnHsSigType" (ppr sig_ty) ; case outer_bndrs of HsOuterExplicit{} -> checkPolyKinds env sig_ty@@ -390,7 +401,7 @@ -> ([Name] -> RnM (a, FreeVars)) -> RnM (a, FreeVars) rnImplicitTvOccs mb_assoc implicit_vs_with_dups thing_inside- = do { let implicit_vs = nubL implicit_vs_with_dups+ = do { let implicit_vs = nubN implicit_vs_with_dups ; traceRn "rnImplicitTvOccs" $ vcat [ ppr implicit_vs_with_dups, ppr implicit_vs ]@@ -398,7 +409,8 @@ -- Use the currently set SrcSpan as the new source location for each Name. -- See Note [Source locations for implicitly bound type variables]. ; loc <- getSrcSpanM- ; vars <- mapM (newTyVarNameRn mb_assoc . L loc . unLoc) implicit_vs+ ; let loc' = noAnnSrcSpan loc+ ; vars <- mapM (newTyVarNameRn mb_assoc . L loc' . unLoc) implicit_vs ; bindLocalNamesFV vars $ thing_inside vars }@@ -564,22 +576,23 @@ rnLHsTypeArgs doc args = mapFvRn (rnLHsTypeArg doc) args ---------------rnTyKiContext :: RnTyKiEnv -> LHsContext GhcPs- -> RnM (LHsContext GhcRn, FreeVars)-rnTyKiContext env (L loc cxt)+rnTyKiContext :: RnTyKiEnv -> Maybe (LHsContext GhcPs)+ -> RnM (Maybe (LHsContext GhcRn), FreeVars)+rnTyKiContext _ Nothing = return (Nothing, emptyFVs)+rnTyKiContext env (Just (L loc cxt)) = do { traceRn "rncontext" (ppr cxt) ; let env' = env { rtke_what = RnConstraint } ; (cxt', fvs) <- mapFvRn (rnLHsTyKi env') cxt- ; return (L loc cxt', fvs) }+ ; return (Just $ L loc cxt', fvs) } -rnContext :: HsDocContext -> LHsContext GhcPs- -> RnM (LHsContext GhcRn, FreeVars)+rnContext :: HsDocContext -> Maybe (LHsContext GhcPs)+ -> RnM (Maybe (LHsContext GhcRn), FreeVars) rnContext doc theta = rnTyKiContext (mkTyKiEnv doc TypeLevel RnConstraint) theta -------------- rnLHsTyKi :: RnTyKiEnv -> LHsType GhcPs -> RnM (LHsType GhcRn, FreeVars) rnLHsTyKi env (L loc ty)- = setSrcSpan loc $+ = setSrcSpanA loc $ do { (ty', fvs) <- rnHsTyKi env ty ; return (L loc ty', fvs) } @@ -612,10 +625,10 @@ -- Any type variable at the kind level is illegal without the use -- of PolyKinds (see #14710) ; name <- rnTyVar env rdr_name- ; return (HsTyVar noExtField ip (L loc name), unitFV name) }+ ; return (HsTyVar noAnn ip (L loc name), unitFV name) } rnHsTyKi env ty@(HsOpTy _ ty1 l_op ty2)- = setSrcSpan (getLoc l_op) $+ = setSrcSpan (getLocA l_op) $ do { (l_op', fvs1) <- rnHsTyOp env ty l_op ; fix <- lookupTyFixityRn l_op' ; (ty1', fvs2) <- rnLHsTyKi env ty1@@ -625,11 +638,11 @@ rnHsTyKi env (HsParTy _ ty) = do { (ty', fvs) <- rnLHsTyKi env ty- ; return (HsParTy noExtField ty', fvs) }+ ; return (HsParTy noAnn ty', fvs) } -rnHsTyKi env (HsBangTy _ b ty)+rnHsTyKi env (HsBangTy x b ty) = do { (ty', fvs) <- rnLHsTyKi env ty- ; return (HsBangTy noExtField b ty', fvs) }+ ; return (HsBangTy x b ty', fvs) } rnHsTyKi env ty@(HsRecTy _ flds) = do { let ctxt = rtke_ctxt env@@ -651,35 +664,35 @@ ; return (HsFunTy u mult' ty1' ty2' , plusFVs [fvs1, fvs2, w_fvs]) } -rnHsTyKi env listTy@(HsListTy _ ty)+rnHsTyKi env listTy@(HsListTy x ty) = do { data_kinds <- xoptM LangExt.DataKinds ; when (not data_kinds && isRnKindLevel env) (addErr (dataKindsErr env listTy)) ; (ty', fvs) <- rnLHsTyKi env ty- ; return (HsListTy noExtField ty', fvs) }+ ; return (HsListTy x ty', fvs) } -rnHsTyKi env (HsKindSig _ ty k)+rnHsTyKi env (HsKindSig x ty k) = do { kind_sigs_ok <- xoptM LangExt.KindSignatures ; unless kind_sigs_ok (badKindSigErr (rtke_ctxt env) ty) ; (ty', lhs_fvs) <- rnLHsTyKi env ty ; (k', sig_fvs) <- rnLHsTyKi (env { rtke_level = KindLevel }) k- ; return (HsKindSig noExtField ty' k', lhs_fvs `plusFV` sig_fvs) }+ ; return (HsKindSig x ty' k', lhs_fvs `plusFV` sig_fvs) } -- Unboxed tuples are allowed to have poly-typed arguments. These -- sometimes crop up as a result of CPR worker-wrappering dictionaries.-rnHsTyKi env tupleTy@(HsTupleTy _ tup_con tys)+rnHsTyKi env tupleTy@(HsTupleTy x tup_con tys) = do { data_kinds <- xoptM LangExt.DataKinds ; when (not data_kinds && isRnKindLevel env) (addErr (dataKindsErr env tupleTy)) ; (tys', fvs) <- mapFvRn (rnLHsTyKi env) tys- ; return (HsTupleTy noExtField tup_con tys', fvs) }+ ; return (HsTupleTy x tup_con tys', fvs) } -rnHsTyKi env sumTy@(HsSumTy _ tys)+rnHsTyKi env sumTy@(HsSumTy x tys) = do { data_kinds <- xoptM LangExt.DataKinds ; when (not data_kinds && isRnKindLevel env) (addErr (dataKindsErr env sumTy)) ; (tys', fvs) <- mapFvRn (rnLHsTyKi env) tys- ; return (HsSumTy noExtField tys', fvs) }+ ; return (HsSumTy x tys', fvs) } -- Ensure that a type-level integer is nonnegative (#8306, #8412) rnHsTyKi env tyLit@(HsTyLit _ t)@@ -705,10 +718,10 @@ ; (k', fvs2) <- rnLHsTyKi (env {rtke_level = KindLevel }) k ; return (HsAppKindTy l ty' k', fvs1 `plusFV` fvs2) } -rnHsTyKi env t@(HsIParamTy _ n ty)+rnHsTyKi env t@(HsIParamTy x n ty) = do { notInKinds env t ; (ty', fvs) <- rnLHsTyKi env ty- ; return (HsIParamTy noExtField n ty', fvs) }+ ; return (HsIParamTy x n ty', fvs) } rnHsTyKi _ (HsStarTy _ isUni) = return (HsStarTy noExtField isUni, emptyFVs)@@ -716,9 +729,9 @@ rnHsTyKi _ (HsSpliceTy _ sp) = rnSpliceType sp -rnHsTyKi env (HsDocTy _ ty haddock_doc)+rnHsTyKi env (HsDocTy x ty haddock_doc) = do { (ty', fvs) <- rnLHsTyKi env ty- ; return (HsDocTy noExtField ty' haddock_doc, fvs) }+ ; return (HsDocTy x ty' haddock_doc, fvs) } -- See Note [Renaming HsCoreTys] rnHsTyKi env (XHsType ty)@@ -753,9 +766,9 @@ rnHsArrow :: RnTyKiEnv -> HsArrow GhcPs -> RnM (HsArrow GhcRn, FreeVars) rnHsArrow _env (HsUnrestrictedArrow u) = return (HsUnrestrictedArrow u, emptyFVs)-rnHsArrow _env (HsLinearArrow u) = return (HsLinearArrow u, emptyFVs)-rnHsArrow env (HsExplicitMult u p)- = (\(mult, fvs) -> (HsExplicitMult u mult, fvs)) <$> rnLHsTyKi env p+rnHsArrow _env (HsLinearArrow u a) = return (HsLinearArrow u a, emptyFVs)+rnHsArrow env (HsExplicitMult u a p)+ = (\(mult, fvs) -> (HsExplicitMult u a mult, fvs)) <$> rnLHsTyKi env p {- Note [Renaming HsCoreTys]@@ -797,7 +810,7 @@ ; checkNamedWildCard env name ; return name } -rnLTyVar :: Located RdrName -> RnM (Located Name)+rnLTyVar :: LocatedN RdrName -> RnM (LocatedN Name) -- Called externally; does not deal with wildcards rnLTyVar (L loc rdr_name) = do { tyvar <- lookupTypeOccRn rdr_name@@ -805,8 +818,8 @@ -------------- rnHsTyOp :: Outputable a- => RnTyKiEnv -> a -> Located RdrName- -> RnM (Located Name, FreeVars)+ => RnTyKiEnv -> a -> LocatedN RdrName+ -> RnM (LocatedN Name, FreeVars) rnHsTyOp env overall_ty (L loc op) = do { ops_ok <- xoptM LangExt.TypeOperators ; op' <- rnTyVar env op@@ -949,7 +962,7 @@ ; let -- See Note [bindHsQTyVars examples] for what -- all these various things are doing- bndrs, implicit_kvs :: [Located RdrName]+ bndrs, implicit_kvs :: [LocatedN RdrName] bndrs = map hsLTyVarLocName hs_tv_bndrs implicit_kvs = filterFreeVarsToBind bndrs $ bndr_kv_occs ++ body_kv_occs@@ -990,11 +1003,19 @@ -- -- class C (a :: j) (b :: k) where -- ^^^^^^^^^^^^^^^- bndrs_loc = case map getLoc hs_tv_bndrs ++ map getLoc body_kv_occs of+ bndrs_loc = case map get_bndr_loc hs_tv_bndrs ++ map getLocA body_kv_occs of [] -> panic "bindHsQTyVars.bndrs_loc" [loc] -> loc (loc:locs) -> loc `combineSrcSpans` last locs + -- The in-tree API annotations extend the LHsTyVarBndr location to+ -- include surrounding parens. for error messages to be+ -- compatible, we recreate the location from the contents+ get_bndr_loc :: LHsTyVarBndr () GhcPs -> SrcSpan+ get_bndr_loc (L _ (UserTyVar _ _ ln)) = getLocA ln+ get_bndr_loc (L _ (KindedTyVar _ _ ln lk))+ = combineSrcSpans (getLocA ln) (getLocA lk)+ {- Note [bindHsQTyVars examples] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Suppose we have@@ -1117,7 +1138,7 @@ -Wunused-foralls warnings in exactly one place: in bindHsQTyVars. -} -bindHsOuterTyVarBndrs :: OutputableBndrFlag flag+bindHsOuterTyVarBndrs :: OutputableBndrFlag flag 'Renamed => HsDocContext -> Maybe assoc -- ^ @'Just' _@ => an associated type decl@@ -1147,10 +1168,10 @@ case tele of HsForAllVis { hsf_vis_bndrs = bndrs } -> bindLHsTyVarBndrs doc WarnUnusedForalls Nothing bndrs $ \bndrs' ->- thing_inside $ mkHsForAllVisTele bndrs'+ thing_inside $ mkHsForAllVisTele noAnn bndrs' HsForAllInvis { hsf_invis_bndrs = bndrs } -> bindLHsTyVarBndrs doc WarnUnusedForalls Nothing bndrs $ \bndrs' ->- thing_inside $ mkHsForAllInvisTele bndrs'+ thing_inside $ mkHsForAllInvisTele noAnn bndrs' -- | Should GHC warn if a quantified type variable goes unused? Usually, the -- answer is \"yes\", but in the particular case of binding 'LHsQTyVars', we@@ -1165,7 +1186,7 @@ WarnUnusedForalls -> "WarnUnusedForalls" NoWarnUnusedForalls -> "NoWarnUnusedForalls" -bindLHsTyVarBndrs :: (OutputableBndrFlag flag)+bindLHsTyVarBndrs :: (OutputableBndrFlag flag 'Renamed) => HsDocContext -> WarnUnusedForalls -> Maybe a -- Just _ => an associated type decl@@ -1174,7 +1195,7 @@ -> RnM (b, FreeVars) bindLHsTyVarBndrs doc wuf mb_assoc tv_bndrs thing_inside = do { when (isNothing mb_assoc) (checkShadowedRdrNames tv_names_w_loc)- ; checkDupRdrNames tv_names_w_loc+ ; checkDupRdrNamesN tv_names_w_loc ; go tv_bndrs thing_inside } where tv_names_w_loc = map hsLTyVarLocName tv_bndrs@@ -1213,7 +1234,7 @@ ; return (b, fvs1 `plusFV` fvs2) } newTyVarNameRn :: Maybe a -- associated class- -> Located RdrName -> RnM Name+ -> LocatedN RdrName -> RnM Name newTyVarNameRn mb_assoc lrdr@(L _ rdr) = do { rdr_env <- getLocalRdrEnv ; case (mb_assoc, lookupLocalRdrEnv rdr_env rdr) of@@ -1250,7 +1271,7 @@ rnField fl_env env (L l (ConDeclField _ names ty haddock_doc)) = do { let new_names = map (fmap (lookupField fl_env)) names ; (new_ty, fvs) <- rnLHsTyKi env ty- ; return (L l (ConDeclField noExtField new_names new_ty haddock_doc)+ ; return (L l (ConDeclField noAnn new_names new_ty haddock_doc) , fvs) } lookupField :: FastStringEnv FieldLabel -> FieldOcc GhcPs -> FieldOcc GhcRn@@ -1291,7 +1312,7 @@ --------------- -- Building (ty1 `op1` (ty21 `op2` ty22))-mkHsOpTyRn :: Located Name -> Fixity -> LHsType GhcRn -> LHsType GhcRn+mkHsOpTyRn :: LocatedN Name -> Fixity -> LHsType GhcRn -> LHsType GhcRn -> RnM (HsType GhcRn) mkHsOpTyRn op1 fix1 ty1 (L loc2 (HsOpTy _ ty21 op2 ty22))@@ -1302,9 +1323,9 @@ = return (HsOpTy noExtField ty1 op1 ty2) ----------------mk_hs_op_ty :: Located Name -> Fixity -> LHsType GhcRn- -> Located Name -> Fixity -> LHsType GhcRn- -> LHsType GhcRn -> SrcSpan+mk_hs_op_ty :: LocatedN Name -> Fixity -> LHsType GhcRn+ -> LocatedN Name -> Fixity -> LHsType GhcRn+ -> LHsType GhcRn -> SrcSpanAnnA -> RnM (HsType GhcRn) mk_hs_op_ty op1 fix1 ty1 op2 fix2 ty21 ty22 loc2 | nofix_error = do { precParseErr (NormalOp (unLoc op1),fix1)@@ -1313,7 +1334,7 @@ | associate_right = return (ty1 `op1ty` (L loc2 (ty21 `op2ty` ty22))) | otherwise = do { -- Rearrange to ((ty1 `op1` ty21) `op2` ty22) new_ty <- mkHsOpTyRn op1 fix1 ty1 ty21- ; return (noLoc new_ty `op2ty` ty22) }+ ; return (noLocA new_ty `op2ty` ty22) } where lhs `op1ty` rhs = HsOpTy noExtField lhs op1 rhs lhs `op2ty` rhs = HsOpTy noExtField lhs op2 rhs@@ -1337,7 +1358,7 @@ new_e <- mkOpAppRn e12 op2 fix2 e2 return (OpApp fix1 e11 op1 (L loc' new_e)) where- loc'= combineLocs e12 e2+ loc'= combineLocsA e12 e2 (nofix_error, associate_right) = compareFixity fix1 fix2 ---------------------------@@ -1351,7 +1372,7 @@ = do new_e <- mkOpAppRn neg_arg op2 fix2 e2 return (NegApp noExtField (L loc' new_e) neg_name) where- loc' = combineLocs neg_arg e2+ loc' = combineLocsA neg_arg e2 (nofix_error, associate_right) = compareFixity negateFixity fix2 ---------------------------@@ -1407,8 +1428,7 @@ -- Parser initially makes negation bind more tightly than any other operator -- And "deriving" code should respect this (use HsPar if not)-mkNegAppRn :: LHsExpr (GhcPass id) -> SyntaxExpr (GhcPass id)- -> RnM (HsExpr (GhcPass id))+mkNegAppRn :: LHsExpr GhcRn -> SyntaxExpr GhcRn -> RnM (HsExpr GhcRn) mkNegAppRn neg_arg neg_name = ASSERT( not_op_app (unLoc neg_arg) ) return (NegApp noExtField neg_arg neg_name)@@ -1436,7 +1456,7 @@ | associate_right = do new_c <- mkOpFormRn a12 op2 fix2 a2 return (HsCmdArrForm noExtField op1 f (Just fix1)- [a11, L loc (HsCmdTop [] (L loc new_c))])+ [a11, L loc (HsCmdTop [] (L (noAnnSrcSpan loc) new_c))]) -- TODO: locs are wrong where (nofix_error, associate_right) = compareFixity fix1 fix2@@ -1447,7 +1467,7 @@ ---------------------------------------mkConOpPatRn :: Located Name -> Fixity -> LPat GhcRn -> LPat GhcRn+mkConOpPatRn :: LocatedN Name -> Fixity -> LPat GhcRn -> LPat GhcRn -> RnM (Pat GhcRn) mkConOpPatRn op2 fix2 p1@(L loc (ConPat NoExtField op1 (InfixCon p11 p12))) p2@@ -1504,7 +1524,7 @@ check (L _ (Match { m_pats = (L l1 p1) : (L l2 p2) : _ }))- = setSrcSpan (combineSrcSpans l1 l2) $+ = setSrcSpan (locA $ combineSrcSpansA l1 l2) $ do checkPrec op p1 False checkPrec op p2 True @@ -1612,7 +1632,7 @@ badKindSigErr :: HsDocContext -> LHsType GhcPs -> TcM () badKindSigErr doc (L loc ty)- = setSrcSpan loc $ addErr $+ = setSrcSpanA loc $ addErr $ withHsDocContext doc $ hang (text "Illegal kind signature:" <+> quotes (ppr ty)) 2 (text "Perhaps you intended to use KindSignatures")@@ -1625,12 +1645,12 @@ pp_what | isRnKindLevel env = text "kind" | otherwise = text "type" -warnUnusedForAll :: OutputableBndrFlag flag+warnUnusedForAll :: OutputableBndrFlag flag 'Renamed => HsDocContext -> LHsTyVarBndr flag GhcRn -> FreeVars -> TcM () warnUnusedForAll doc (L loc tv) used_names = whenWOptM Opt_WarnUnusedForalls $ unless (hsTyVarName tv `elemNameSet` used_names) $- addWarnAt (Reason Opt_WarnUnusedForalls) loc $+ addDiagnosticAt (WarningWithFlag Opt_WarnUnusedForalls) (locA loc) $ vcat [ text "Unused quantified type variable" <+> quotes (ppr tv) , inHsDocContext doc ] @@ -1795,7 +1815,7 @@ -- These lists are guaranteed to preserve left-to-right ordering of -- the types the variables were extracted from. See also -- Note [Ordering of implicit variables].-type FreeKiTyVars = [Located RdrName]+type FreeKiTyVars = [LocatedN RdrName] -- | Filter out any type and kind variables that are already in scope in the -- the supplied LocalRdrEnv. Note that this includes named wildcards, which@@ -1890,8 +1910,9 @@ extractDataDefnKindVars (HsDataDefn { dd_kindSig = ksig }) = maybe [] extractHsTyRdrTyVars ksig -extract_lctxt :: LHsContext GhcPs -> FreeKiTyVars -> FreeKiTyVars-extract_lctxt ctxt = extract_ltys (unLoc ctxt)+extract_lctxt :: Maybe (LHsContext GhcPs) -> FreeKiTyVars -> FreeKiTyVars+extract_lctxt Nothing = const []+extract_lctxt (Just ctxt) = extract_ltys (unLoc ctxt) extract_scaled_ltys :: [HsScaled GhcPs (LHsType GhcPs)] -> FreeKiTyVars -> FreeKiTyVars@@ -1951,7 +1972,7 @@ extract_hs_arrow :: HsArrow GhcPs -> FreeKiTyVars -> FreeKiTyVars-extract_hs_arrow (HsExplicitMult _ p) acc = extract_lty p acc+extract_hs_arrow (HsExplicitMult _ _ p) acc = extract_lty p acc extract_hs_arrow _ acc = acc extract_hs_for_all_telescope :: HsForAllTelescope GhcPs@@ -2002,7 +2023,7 @@ foldr extract_lty [] [k | L _ (KindedTyVar _ _ _ k) <- tv_bndrs] -extract_tv :: Located RdrName -> FreeKiTyVars -> FreeKiTyVars+extract_tv :: LocatedN RdrName -> FreeKiTyVars -> FreeKiTyVars extract_tv tv acc = if isRdrTyVar (unLoc tv) then tv:acc else acc @@ -2019,8 +2040,11 @@ -- relies on to maintain the left-to-right ordering of implicitly quantified -- type variables. -- See Note [Ordering of implicit variables].-nubL :: Eq a => [Located a] -> [Located a]+nubL :: Eq a => [GenLocated l a] -> [GenLocated l a] nubL = nubBy eqLocated++nubN :: Eq a => [LocatedN a] -> [LocatedN a]+nubN = nubBy eqLocated -- | Filter out any potential implicit binders that are either -- already in scope, or are explicitly bound in the binder.
compiler/GHC/Rename/Module.hs view
@@ -30,9 +30,9 @@ import GHC.Rename.Bind import GHC.Rename.Env import GHC.Rename.Utils ( HsDocContext(..), mapFvRn, bindLocalNames- , checkDupRdrNames, bindLocalNamesFV+ , checkDupRdrNamesN, bindLocalNamesFV , checkShadowedRdrNames, warnUnusedTypePatterns- , extendTyVarEnvFVRn, newLocalBndrsRn+ , newLocalBndrsRn , withHsDocContext, noNestedForallsContextsErr , addNoNestedForallsContextsErr, checkInferredVars ) import GHC.Rename.Unbound ( mkUnboundName, notInScopeErr )@@ -241,8 +241,8 @@ -- but there doesn't seem anywhere very logical to put it. addTcgDUs tcg_env dus = tcg_env { tcg_dus = tcg_dus tcg_env `plusDU` dus } -rnList :: (a -> RnM (b, FreeVars)) -> [Located a] -> RnM ([Located b], FreeVars)-rnList f xs = mapFvRn (wrapLocFstM f) xs+rnList :: (a -> RnM (b, FreeVars)) -> [LocatedA a] -> RnM ([LocatedA b], FreeVars)+rnList f xs = mapFvRn (wrapLocFstMA f) xs {- *********************************************************@@ -266,9 +266,9 @@ rnSrcWarnDecls bndr_set decls' = do { -- check for duplicates ; mapM_ (\ dups -> let ((L loc rdr) :| (lrdr':_)) = dups- in addErrAt loc (dupWarnDecl lrdr' rdr))+ in addErrAt (locA loc) (dupWarnDecl lrdr' rdr)) warn_rdr_dups- ; pairs_s <- mapM (addLocM rn_deprec) decls+ ; pairs_s <- mapM (addLocMA rn_deprec) decls ; return (WarnSome ((concat pairs_s))) } where decls = concatMap (wd_warnings . unLoc) decls'@@ -286,18 +286,18 @@ warn_rdr_dups = findDupRdrNames $ concatMap (\(L _ (Warning _ ns _)) -> ns) decls -findDupRdrNames :: [Located RdrName] -> [NonEmpty (Located RdrName)]+findDupRdrNames :: [LocatedN RdrName] -> [NonEmpty (LocatedN RdrName)] findDupRdrNames = findDupsEq (\ x -> \ y -> rdrNameOcc (unLoc x) == rdrNameOcc (unLoc y)) -- look for duplicates among the OccNames; -- we check that the names are defined above -- invt: the lists returned by findDupsEq always have at least two elements -dupWarnDecl :: Located RdrName -> RdrName -> SDoc+dupWarnDecl :: LocatedN RdrName -> RdrName -> SDoc -- Located RdrName -> DeprecDecl RdrName -> SDoc dupWarnDecl d rdr_name = vcat [text "Multiple warning declarations for" <+> quotes (ppr rdr_name),- text "also at " <+> ppr (getLoc d)]+ text "also at " <+> ppr (getLocA d)] {- *********************************************************@@ -313,13 +313,16 @@ do { (provenance', provenance_fvs) <- rnAnnProvenance provenance ; (expr', expr_fvs) <- setStage (Splice Untyped) $ rnLExpr expr- ; return (HsAnnotation noExtField s provenance' expr',+ ; return (HsAnnotation noAnn s provenance' expr', provenance_fvs `plusFV` expr_fvs) } -rnAnnProvenance :: AnnProvenance RdrName- -> RnM (AnnProvenance Name, FreeVars)+rnAnnProvenance :: AnnProvenance GhcPs+ -> RnM (AnnProvenance GhcRn, FreeVars) rnAnnProvenance provenance = do- provenance' <- traverse lookupTopBndrRn provenance+ provenance' <- case provenance of+ ValueAnnProvenance n -> ValueAnnProvenance <$> lookupLocatedTopBndrRnN n+ TypeAnnProvenance n -> TypeAnnProvenance <$> lookupLocatedTopBndrRnN n+ ModuleAnnProvenance -> return ModuleAnnProvenance return (provenance', maybe emptyFVs unitFV (annProvenanceName_maybe provenance')) {-@@ -348,7 +351,7 @@ rnHsForeignDecl :: ForeignDecl GhcPs -> RnM (ForeignDecl GhcRn, FreeVars) rnHsForeignDecl (ForeignImport { fd_name = name, fd_sig_ty = ty, fd_fi = spec }) = do { topEnv :: HscEnv <- getTopEnv- ; name' <- lookupLocatedTopBndrRn name+ ; name' <- lookupLocatedTopBndrRnN name ; (ty', fvs) <- rnHsSigType (ForeignDeclCtx name) TypeLevel ty -- Mark any PackageTarget style imports as coming from the current package@@ -453,7 +456,7 @@ -- checkCanonicalMonadInstances refURL | cls == applicativeClassName =- forM_ (bagToList mbinds) $ \(L loc mbind) -> setSrcSpan loc $+ forM_ (bagToList mbinds) $ \(L loc mbind) -> setSrcSpanA loc $ case mbind of FunBind { fun_id = L _ name , fun_matches = mg }@@ -468,7 +471,7 @@ _ -> return () | cls == monadClassName =- forM_ (bagToList mbinds) $ \(L loc mbind) -> setSrcSpan loc $+ forM_ (bagToList mbinds) $ \(L loc mbind) -> setSrcSpanA loc $ case mbind of FunBind { fun_id = L _ name , fun_matches = mg }@@ -499,7 +502,7 @@ -- checkCanonicalMonoidInstances refURL | cls == semigroupClassName =- forM_ (bagToList mbinds) $ \(L loc mbind) -> setSrcSpan loc $+ forM_ (bagToList mbinds) $ \(L loc mbind) -> setSrcSpanA loc $ case mbind of FunBind { fun_id = L _ name , fun_matches = mg }@@ -510,7 +513,7 @@ _ -> return () | cls == monoidClassName =- forM_ (bagToList mbinds) $ \(L loc mbind) -> setSrcSpan loc $+ forM_ (bagToList mbinds) $ \(L loc mbind) -> setSrcSpanA loc $ case mbind of FunBind { fun_id = L _ name , fun_matches = mg }@@ -529,13 +532,13 @@ isAliasMG MG {mg_alts = (L _ [L _ (Match { m_pats = [] , m_grhss = grhss })])} | GRHSs _ [L _ (GRHS _ [] body)] lbinds <- grhss- , EmptyLocalBinds _ <- unLoc lbinds+ , EmptyLocalBinds _ <- lbinds , HsVar _ lrhsName <- unLoc body = Just (unLoc lrhsName) isAliasMG _ = Nothing -- got "lhs = rhs" but expected something different addWarnNonCanonicalMethod1 refURL flag lhs rhs =- addWarn (Reason flag) $ vcat+ addDiagnostic (WarningWithFlag flag) $ vcat [ text "Noncanonical" <+> quotes (text (lhs ++ " = " ++ rhs)) <+> text "definition detected"@@ -549,7 +552,7 @@ -- expected "lhs = rhs" but got something else addWarnNonCanonicalMethod2 refURL flag lhs rhs =- addWarn (Reason flag) $ vcat+ addDiagnostic (WarningWithFlag flag) $ vcat [ text "Noncanonical" <+> quotes (text lhs) <+> text "definition detected"@@ -594,7 +597,7 @@ eith_cls = case hsTyGetAppHead_maybe head_ty' of Just (L _ cls) -> Right cls Nothing -> Left- ( getLoc head_ty'+ ( getLocA head_ty' , hang (text "Illegal head of an instance declaration:" <+> quotes (ppr head_ty')) 2 (vcat [ text "Instance heads must be of the form"@@ -625,7 +628,7 @@ -- Both need to have the instance type variables in scope ; traceRn "rnSrcInstDecl" (ppr inst_ty' $$ ppr ktv_names) ; ((ats', adts'), more_fvs)- <- extendTyVarEnvFVRn ktv_names $+ <- bindLocalNamesFV ktv_names $ do { (ats', at_fvs) <- rnATInstDecls rnTyFamInstDecl cls ktv_names ats ; (adts', adt_fvs) <- rnATInstDecls rnDataFamInstDecl cls ktv_names adts ; return ( (ats', adts'), at_fvs `plusFV` adt_fvs) }@@ -733,7 +736,7 @@ rn_outer_bndrs' = mapHsOuterImplicit (map (`setNameLoc` lhs_loc)) rn_outer_bndrs - groups :: [NonEmpty (Located RdrName)]+ groups :: [NonEmpty (LocatedN RdrName)] groups = equivClasses cmpLocated pat_kity_vars ; nms_dups <- mapM (lookupOccRn . unLoc) $ [ tv | (tv :| (_:_)) <- groups ]@@ -769,7 +772,7 @@ -> eqn_fvs _ -> eqn_fvs `addOneFV` unLoc tycon' - ; return (FamEqn { feqn_ext = noExtField+ ; return (FamEqn { feqn_ext = noAnn , feqn_tycon = tycon' -- Note [Wildcards in family instances] , feqn_bndrs = rn_outer_bndrs'@@ -802,7 +805,7 @@ -- -- type instance F a b c = Either a b -- ^^^^^- lhs_loc = case map lhsTypeArgSrcSpan pats ++ map getLoc extra_kvars of+ lhs_loc = case map lhsTypeArgSrcSpan pats ++ map getLocA extra_kvars of [] -> panic "rnFamEqn.lhs_loc" [loc] -> loc (loc:locs) -> loc `combineSrcSpans` last locs@@ -817,9 +820,9 @@ rnTyFamInstDecl :: AssocTyFamInfo -> TyFamInstDecl GhcPs -> RnM (TyFamInstDecl GhcRn, FreeVars)-rnTyFamInstDecl atfi (TyFamInstDecl { tfid_eqn = eqn })+rnTyFamInstDecl atfi (TyFamInstDecl { tfid_xtn = x, tfid_eqn = eqn }) = do { (eqn', fvs) <- rnTyFamInstEqn atfi eqn- ; return (TyFamInstDecl { tfid_eqn = eqn' }, fvs) }+ ; return (TyFamInstDecl { tfid_xtn = x, tfid_eqn = eqn' }, fvs) } -- | Tracks whether we are renaming: --@@ -903,8 +906,8 @@ RnM (decl GhcRn, FreeVars)) -- or rnDataFamInstDecl -> Name -- Class -> [Name]- -> [Located (decl GhcPs)]- -> RnM ([Located (decl GhcRn)], FreeVars)+ -> [LocatedA (decl GhcPs)]+ -> RnM ([LocatedA (decl GhcRn)], FreeVars) -- Used for data and type family defaults in a class decl -- and the family instance declarations in an instance --@@ -1162,11 +1165,11 @@ (text "Standalone-derived instance head") (getLHsInstDeclHead $ dropWildCards ty') ; warnNoDerivStrat mds' loc- ; return (DerivDecl noExtField ty' mds' overlap, fvs) }+ ; return (DerivDecl noAnn ty' mds' overlap, fvs) } where ctxt = DerivDeclCtx inf_err = Just (text "Inferred type variables are not allowed")- loc = getLoc nowc_ty+ loc = getLocA nowc_ty nowc_ty = dropWildCards ty standaloneDerivErr :: SDoc@@ -1198,7 +1201,7 @@ , rd_lhs = lhs , rd_rhs = rhs }) = do { let rdr_names_w_loc = map (get_var . unLoc) tmvs- ; checkDupRdrNames rdr_names_w_loc+ ; checkDupRdrNamesN rdr_names_w_loc ; checkShadowedRdrNames rdr_names_w_loc ; names <- newLocalBndrsRn rdr_names_w_loc ; let doc = RuleCtx (snd $ unLoc rule_name)@@ -1215,7 +1218,7 @@ , rd_lhs = lhs' , rd_rhs = rhs' }, fv_lhs' `plusFV` fv_rhs') } } where- get_var :: RuleBndr GhcPs -> Located RdrName+ get_var :: RuleBndr GhcPs -> LocatedN RdrName get_var (RuleBndrSig _ v _) = v get_var (RuleBndr _ v) = v @@ -1229,13 +1232,13 @@ where go ((L l (RuleBndr _ (L loc _))) : vars) (n : ns) thing_inside = go vars ns $ \ vars' ->- thing_inside (L l (RuleBndr noExtField (L loc n)) : vars')+ thing_inside (L l (RuleBndr noAnn (L loc n)) : vars') go ((L l (RuleBndrSig _ (L loc _) bsig)) : vars) (n : ns) thing_inside = rnHsPatSigType bind_free_tvs doc bsig $ \ bsig' -> go vars ns $ \ vars' ->- thing_inside (L l (RuleBndrSig noExtField (L loc n) bsig') : vars')+ thing_inside (L l (RuleBndrSig noAnn (L loc n) bsig') : vars') go [] [] thing_inside = thing_inside [] go vars names _ = pprPanic "bindRuleVars" (ppr vars $$ ppr names)@@ -1475,10 +1478,10 @@ -- Rename the declarations and do dependency analysis on them rnTyClDecls tycl_ds = do { -- Rename the type/class, instance, and role declaraations- ; tycls_w_fvs <- mapM (wrapLocFstM rnTyClDecl) (tyClGroupTyClDecls tycl_ds)+ ; tycls_w_fvs <- mapM (wrapLocFstMA rnTyClDecl) (tyClGroupTyClDecls tycl_ds) ; let tc_names = mkNameSet (map (tcdName . unLoc . fst) tycls_w_fvs) ; kisigs_w_fvs <- rnStandaloneKindSignatures tc_names (tyClGroupKindSigs tycl_ds)- ; instds_w_fvs <- mapM (wrapLocFstM rnSrcInstDecl) (tyClGroupInstDecls tycl_ds)+ ; instds_w_fvs <- mapM (wrapLocFstMA rnSrcInstDecl) (tyClGroupInstDecls tycl_ds) ; role_annots <- rnRoleAnnots tc_names (tyClGroupRoleDecls tycl_ds) -- Do SCC analysis on the type/class decls@@ -1561,7 +1564,7 @@ = do { let (no_dups, dup_kisigs) = removeDups (compare `on` get_name) kisigs get_name = standaloneKindSigName . unLoc ; mapM_ dupKindSig_Err dup_kisigs- ; mapM (wrapLocFstM (rnStandaloneKindSignature tc_names)) no_dups+ ; mapM (wrapLocFstMA (rnStandaloneKindSignature tc_names)) no_dups } rnStandaloneKindSignature@@ -1571,7 +1574,7 @@ rnStandaloneKindSignature tc_names (StandaloneKindSig _ v ki) = do { standalone_ki_sig_ok <- xoptM LangExt.StandaloneKindSignatures ; unless standalone_ki_sig_ok $ addErr standaloneKiSigErr- ; new_v <- lookupSigCtxtOccRn (TopSigCtxt tc_names) (text "standalone kind signature") v+ ; new_v <- lookupSigCtxtOccRnN (TopSigCtxt tc_names) (text "standalone kind signature") v ; let doc = StandaloneKindSigCtx (ppr v) ; (new_ki, fvs) <- rnHsSigType doc KindLevel ki ; return (StandaloneKindSig noExtField new_v new_ki, fvs)@@ -1639,19 +1642,19 @@ let (no_dups, dup_annots) = removeDups (compare `on` get_name) role_annots get_name = roleAnnotDeclName . unLoc ; mapM_ dupRoleAnnotErr dup_annots- ; mapM (wrapLocM rn_role_annot1) no_dups }+ ; mapM (wrapLocMA rn_role_annot1) no_dups } where rn_role_annot1 (RoleAnnotDecl _ tycon roles) = do { -- the name is an *occurrence*, but look it up only in the -- decls defined in this group (see #10263)- tycon' <- lookupSigCtxtOccRn (RoleAnnotCtxt tc_names)- (text "role annotation")- tycon+ tycon' <- lookupSigCtxtOccRnN (RoleAnnotCtxt tc_names)+ (text "role annotation")+ tycon ; return $ RoleAnnotDecl noExtField tycon' roles } dupRoleAnnotErr :: NonEmpty (LRoleAnnotDecl GhcPs) -> RnM () dupRoleAnnotErr list- = addErrAt loc $+ = addErrAt (locA loc) $ hang (text "Duplicate role annotations for" <+> quotes (ppr $ roleAnnotDeclName first_decl) <> colon) 2 (vcat $ map pp_role_annot $ NE.toList sorted_list)@@ -1660,13 +1663,13 @@ ((L loc first_decl) :| _) = sorted_list pp_role_annot (L loc decl) = hang (ppr decl)- 4 (text "-- written at" <+> ppr loc)+ 4 (text "-- written at" <+> ppr (locA loc)) - cmp_loc = SrcLoc.leftmost_smallest `on` getLoc+ cmp_loc = SrcLoc.leftmost_smallest `on` getLocA dupKindSig_Err :: NonEmpty (LStandaloneKindSig GhcPs) -> RnM () dupKindSig_Err list- = addErrAt loc $+ = addErrAt (locA loc) $ hang (text "Duplicate standalone kind signatures for" <+> quotes (ppr $ standaloneKindSigName first_decl) <> colon) 2 (vcat $ map pp_kisig $ NE.toList sorted_list)@@ -1675,9 +1678,9 @@ ((L loc first_decl) :| _) = sorted_list pp_kisig (L loc decl) =- hang (ppr decl) 4 (text "-- written at" <+> ppr loc)+ hang (ppr decl) 4 (text "-- written at" <+> ppr (locA loc)) - cmp_loc = SrcLoc.leftmost_smallest `on` getLoc+ cmp_loc = SrcLoc.leftmost_smallest `on` getLocA {- Note [Role annotations in the renamer] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~@@ -1760,7 +1763,7 @@ rnTyClDecl (SynDecl { tcdLName = tycon, tcdTyVars = tyvars, tcdFixity = fixity, tcdRhs = rhs })- = do { tycon' <- lookupLocatedTopBndrRn tycon+ = do { tycon' <- lookupLocatedTopBndrRnN tycon ; let kvs = extractHsTyRdrTyVarsKindVars rhs doc = TySynCtx tycon ; traceRn "rntycl-ty" (ppr tycon <+> ppr kvs)@@ -1776,7 +1779,7 @@ tcdFixity = fixity, tcdDataDefn = defn@HsDataDefn{ dd_ND = new_or_data , dd_kindSig = kind_sig} })- = do { tycon' <- lookupLocatedTopBndrRn tycon+ = do { tycon' <- lookupLocatedTopBndrRnN tycon ; let kvs = extractDataDefnKindVars defn doc = TyDataCtx tycon ; traceRn "rntycl-data" (ppr tycon <+> ppr kvs)@@ -1797,7 +1800,7 @@ tcdFDs = fds, tcdSigs = sigs, tcdMeths = mbinds, tcdATs = ats, tcdATDefs = at_defs, tcdDocs = docs})- = do { lcls' <- lookupLocatedTopBndrRn lcls+ = do { lcls' <- lookupLocatedTopBndrRnN lcls ; let cls' = unLoc lcls' kvs = [] -- No scoped kind vars except those in -- kind signatures on the tyvars@@ -1824,7 +1827,7 @@ ; let sig_rdr_names_w_locs = [op | L _ (ClassOpSig _ False ops _) <- sigs , op <- ops]- ; checkDupRdrNames sig_rdr_names_w_locs+ ; checkDupRdrNamesN sig_rdr_names_w_locs -- Typechecker is responsible for checking that we only -- give default-method bindings for things in this class. -- The renamer *could* check this for class decls, but can't@@ -1897,7 +1900,7 @@ rnDataDefn doc (HsDataDefn { dd_ND = new_or_data, dd_cType = cType , dd_ctxt = context, dd_cons = condecls , dd_kindSig = m_sig, dd_derivs = derivs })- = do { checkTc (h98_style || null (unLoc context))+ = do { checkTc (h98_style || null (fromMaybeContext context)) (badGadtStupidTheta doc) ; (m_sig', sig_fvs) <- case m_sig of@@ -1918,7 +1921,7 @@ ; let all_fvs = fvs1 `plusFV` fvs3 `plusFV` con_fvs `plusFV` sig_fvs- ; return ( HsDataDefn { dd_ext = noExtField+ ; return ( HsDataDefn { dd_ext = noAnn , dd_ND = new_or_data, dd_cType = cType , dd_ctxt = context', dd_kindSig = m_sig' , dd_cons = condecls'@@ -1930,12 +1933,12 @@ (L _ (ConDeclGADT {})) : _ -> False _ -> True - rn_derivs (L loc ds)+ rn_derivs ds = do { deriv_strats_ok <- xoptM LangExt.DerivingStrategies ; failIfTc (lengthExceeds ds 1 && not deriv_strats_ok) multipleDerivClausesErr ; (ds', fvs) <- mapFvRn (rnLHsDerivingClause doc) ds- ; return (L loc ds', fvs) }+ ; return (ds', fvs) } warnNoDerivStrat :: Maybe (LDerivStrategy GhcRn) -> SrcSpan@@ -1944,8 +1947,8 @@ = do { dyn_flags <- getDynFlags ; when (wopt Opt_WarnMissingDerivingStrategies dyn_flags) $ case mds of- Nothing -> addWarnAt- (Reason Opt_WarnMissingDerivingStrategies)+ Nothing -> addDiagnosticAt+ (WarningWithFlag Opt_WarnMissingDerivingStrategies) loc (if xopt LangExt.DerivingStrategies dyn_flags then no_strat_warning@@ -2025,10 +2028,10 @@ failWith $ illegalDerivStrategyErr ds case ds of- StockStrategy -> boring_case StockStrategy- AnyclassStrategy -> boring_case AnyclassStrategy- NewtypeStrategy -> boring_case NewtypeStrategy- ViaStrategy via_ty ->+ StockStrategy _ -> boring_case (StockStrategy noExtField)+ AnyclassStrategy _ -> boring_case (AnyclassStrategy noExtField)+ NewtypeStrategy _ -> boring_case (NewtypeStrategy noExtField)+ ViaStrategy (XViaStrategyPs _ via_ty) -> do checkInferredVars doc inf_err via_ty (via_ty', fvs1) <- rnHsSigType doc TypeLevel via_ty let HsSig { sig_bndrs = via_outer_bndrs@@ -2040,7 +2043,7 @@ -- (Wrinkle: Derived instances) in GHC.Hs.Type. addNoNestedForallsContextsErr doc (quotes (text "via") <+> text "type") via_body- (thing, fvs2) <- extendTyVarEnvFVRn via_tvs thing_inside+ (thing, fvs2) <- bindLocalNamesFV via_tvs thing_inside pure (ViaStrategy via_ty', thing, fvs1 `plusFV` fvs2) inf_err = Just (text "Inferred type variables are not allowed")@@ -2079,10 +2082,11 @@ -> FamilyDecl GhcPs -> RnM (FamilyDecl GhcRn, FreeVars) rnFamDecl mb_cls (FamilyDecl { fdLName = tycon, fdTyVars = tyvars+ , fdTopLevel = toplevel , fdFixity = fixity , fdInfo = info, fdResultSig = res_sig , fdInjectivityAnn = injectivity })- = do { tycon' <- lookupLocatedTopBndrRn tycon+ = do { tycon' <- lookupLocatedTopBndrRnN tycon ; ((tyvars', res_sig', injectivity'), fv1) <- bindHsQTyVars doc mb_cls kvs tyvars $ \ tyvars' _ -> do { let rn_sig = rnFamResultSig doc@@ -2091,8 +2095,9 @@ injectivity ; return ( (tyvars', res_sig', injectivity') , fv_kind ) } ; (info', fv2) <- rn_info info- ; return (FamilyDecl { fdExt = noExtField+ ; return (FamilyDecl { fdExt = noAnn , fdLName = tycon', fdTyVars = tyvars'+ , fdTopLevel = toplevel , fdFixity = fixity , fdInfo = info', fdResultSig = res_sig' , fdInjectivityAnn = injectivity' }@@ -2133,7 +2138,7 @@ rdr_env <- getLocalRdrEnv ; let resName = hsLTyVarName tvbndr ; when (resName `elemLocalRdrEnv` rdr_env) $- addErrAt (getLoc tvbndr) $+ addErrAt (getLocA tvbndr) $ (hsep [ text "Type variable", quotes (ppr resName) <> comma , text "naming a type family result," ] $$@@ -2184,16 +2189,16 @@ -> LInjectivityAnn GhcPs -- ^ Injectivity annotation -> RnM (LInjectivityAnn GhcRn) rnInjectivityAnn tvBndrs (L _ (TyVarSig _ resTv))- (L srcSpan (InjectivityAnn injFrom injTo))+ (L srcSpan (InjectivityAnn x injFrom injTo)) = do- { (injDecl'@(L _ (InjectivityAnn injFrom' injTo')), noRnErrors)+ { (injDecl'@(L _ (InjectivityAnn _ injFrom' injTo')), noRnErrors) <- askNoErrs $ bindLocalNames [hsLTyVarName resTv] $ -- The return type variable scopes over the injectivity annotation -- e.g. type family F a = (r::*) | r -> a do { injFrom' <- rnLTyVar injFrom ; injTo' <- mapM rnLTyVar injTo- ; return $ L srcSpan (InjectivityAnn injFrom' injTo') }+ ; return $ L srcSpan (InjectivityAnn x injFrom' injTo') } ; let tvNames = Set.fromList $ hsAllLTyVarNames tvBndrs resName = hsLTyVarName resTv@@ -2205,7 +2210,7 @@ -- not-in-scope variables) don't check the validity of injectivity -- annotation. This gives better error messages. ; when (noRnErrors && not lhsValid) $- addErrAt (getLoc injFrom)+ addErrAt (getLocA injFrom) ( vcat [ text $ "Incorrect type variable on the LHS of " ++ "injectivity condition" , nest 5@@ -2229,12 +2234,12 @@ -- -- So we rename injectivity annotation like we normally would except that -- this time we expect "result" to be reported not in scope by rnLTyVar.-rnInjectivityAnn _ _ (L srcSpan (InjectivityAnn injFrom injTo)) =+rnInjectivityAnn _ _ (L srcSpan (InjectivityAnn x injFrom injTo)) = setSrcSpan srcSpan $ do (injDecl', _) <- askNoErrs $ do injFrom' <- rnLTyVar injFrom injTo' <- mapM rnLTyVar injTo- return $ L srcSpan (InjectivityAnn injFrom' injTo')+ return $ L srcSpan (InjectivityAnn x injFrom' injTo') return $ injDecl' {-@@ -2257,14 +2262,14 @@ ----------------- rnConDecls :: [LConDecl GhcPs] -> RnM ([LConDecl GhcRn], FreeVars)-rnConDecls = mapFvRn (wrapLocFstM rnConDecl)+rnConDecls = mapFvRn (wrapLocFstMA rnConDecl) rnConDecl :: ConDecl GhcPs -> RnM (ConDecl GhcRn, FreeVars) rnConDecl decl@(ConDeclH98 { con_name = name, con_ex_tvs = ex_tvs , con_mb_cxt = mcxt, con_args = args , con_doc = mb_doc, con_forall = forall })- = do { _ <- addLocM checkConName name- ; new_name <- lookupLocatedTopBndrRn name+ = do { _ <- addLocMA checkConName name+ ; new_name <- lookupLocatedTopBndrRnN name -- We bind no implicit binders here; this is just like -- a nested HsForAllTy. E.g. consider@@ -2285,7 +2290,7 @@ [ text "ex_tvs:" <+> ppr ex_tvs , text "new_ex_dqtvs':" <+> ppr new_ex_tvs ]) - ; return (decl { con_ext = noExtField+ ; return (decl { con_ext = noAnn , con_name = new_name, con_ex_tvs = new_ex_tvs , con_mb_cxt = new_context, con_args = new_args , con_doc = mb_doc@@ -2298,8 +2303,8 @@ , con_g_args = args , con_res_ty = res_ty , con_doc = mb_doc })- = do { mapM_ (addLocM checkConName) names- ; new_names <- mapM lookupLocatedTopBndrRn names+ = do { mapM_ (addLocMA checkConName) names+ ; new_names <- mapM lookupLocatedTopBndrRnN names ; let -- We must ensure that we extract the free tkvs in left-to-right -- order of their appearance in the constructor type.@@ -2329,7 +2334,7 @@ ; traceRn "rnConDecl (ConDeclGADT)" (ppr names $$ ppr outer_bndrs')- ; return (ConDeclGADT { con_g_ext = noExtField, con_names = new_names+ ; return (ConDeclGADT { con_g_ext = noAnn, con_names = new_names , con_bndrs = L l outer_bndrs', con_mb_cxt = new_cxt , con_g_args = new_args, con_res_ty = new_res_ty , con_doc = mb_doc },@@ -2338,8 +2343,8 @@ rnMbContext :: HsDocContext -> Maybe (LHsContext GhcPs) -> RnM (Maybe (LHsContext GhcRn), FreeVars) rnMbContext _ Nothing = return (Nothing, emptyFVs)-rnMbContext doc (Just cxt) = do { (ctx',fvs) <- rnContext doc cxt- ; return (Just ctx',fvs) }+rnMbContext doc cxt = do { (ctx',fvs) <- rnContext doc cxt+ ; return (ctx',fvs) } rnConDeclH98Details :: Name@@ -2372,8 +2377,8 @@ rnRecConDeclFields :: Name -> HsDocContext- -> Located [LConDeclField GhcPs]- -> RnM (Located [LConDeclField GhcRn], FreeVars)+ -> LocatedL [LConDeclField GhcPs]+ -> RnM (LocatedL [LConDeclField GhcRn], FreeVars) rnRecConDeclFields con doc (L l fields) = do { fls <- lookupConstructorFields con ; (new_fields, fvs) <- rnConDeclFields doc fls fields@@ -2410,13 +2415,13 @@ | (L bind_loc (PatSynBind _ (PSB { psb_id = L _ n , psb_args = RecCon as }))) <- bind = do- bnd_name <- newTopSrcBinder (L bind_loc n)- let field_occs = map ((\ f -> L (getLoc (rdrNameFieldOcc f)) f) . recordPatSynField) as+ bnd_name <- newTopSrcBinder (L (l2l bind_loc) n)+ let field_occs = map ((\ f -> L (getLocA (rdrNameFieldOcc f)) f) . recordPatSynField) as flds <- mapM (newRecordSelector dup_fields_ok has_sel [bnd_name]) field_occs return ((bnd_name, flds): names) | L bind_loc (PatSynBind _ (PSB { psb_id = L _ n})) <- bind = do- bnd_name <- newTopSrcBinder (L bind_loc n)+ bnd_name <- newTopSrcBinder (L (la2na bind_loc) n) return ((bnd_name, []): names) | otherwise = return names@@ -2431,17 +2436,18 @@ rnFds :: [LHsFunDep GhcPs] -> RnM [LHsFunDep GhcRn] rnFds fds- = mapM (wrapLocM rn_fds) fds+ = mapM (wrapLocMA rn_fds) fds where- rn_fds (tys1, tys2)+ rn_fds :: FunDep GhcPs -> RnM (FunDep GhcRn)+ rn_fds (FunDep x tys1 tys2) = do { tys1' <- rnHsTyVars tys1 ; tys2' <- rnHsTyVars tys2- ; return (tys1', tys2') }+ ; return (FunDep x tys1' tys2') } -rnHsTyVars :: [Located RdrName] -> RnM [Located Name]+rnHsTyVars :: [LocatedN RdrName] -> RnM [LocatedN Name] rnHsTyVars tvs = mapM rnHsTyVar tvs -rnHsTyVar :: Located RdrName -> RnM (Located Name)+rnHsTyVar :: LocatedN RdrName -> RnM (LocatedN Name) rnHsTyVar (L l tyvar) = do tyvar' <- lookupOccRn tyvar return (L l tyvar')@@ -2470,7 +2476,7 @@ addl gp (L l d : ds) = add gp l d ds -add :: HsGroup GhcPs -> SrcSpan -> HsDecl GhcPs -> [LHsDecl GhcPs]+add :: HsGroup GhcPs -> SrcSpanAnnA -> HsDecl GhcPs -> [LHsDecl GhcPs] -> RnM (HsGroup GhcPs, Maybe (SpliceDecl GhcPs, [LHsDecl GhcPs])) -- #10047: Declaration QuasiQuoters are expanded immediately, without@@ -2486,7 +2492,7 @@ case flag of ExplicitSplice -> return () ImplicitSplice -> do { th_on <- xoptM LangExt.TemplateHaskell- ; unless th_on $ setSrcSpan loc $+ ; unless th_on $ setSrcSpan (locA loc) $ failWith badImplicitSplice } ; return (gp, Just (splice, ds)) }
compiler/GHC/Rename/Names.hs view
@@ -52,6 +52,7 @@ import GHC.Core.Type import GHC.Core.PatSyn import GHC.Core.TyCo.Ppr+import GHC.Core.TyCon ( TyCon, tyConName, tyConKind ) import qualified GHC.LanguageExtensions as LangExt import GHC.Utils.Outputable as Outputable@@ -286,13 +287,12 @@ rnImportDecl :: Module -> LImportDecl GhcPs -> RnM (LImportDecl GhcRn, GlobalRdrEnv, ImportAvails, AnyHpcUsage) rnImportDecl this_mod- (L loc decl@(ImportDecl { ideclExt = noExtField- , ideclName = loc_imp_mod_name+ (L loc decl@(ImportDecl { ideclName = loc_imp_mod_name , ideclPkgQual = mb_pkg , ideclSource = want_boot, ideclSafe = mod_safe , ideclQualified = qual_style, ideclImplicit = implicit , ideclAs = as_mod, ideclHiding = imp_details }))- = setSrcSpan loc $ do+ = setSrcSpanA loc $ do when (isJust mb_pkg) $ do pkg_imports <- xoptM LangExt.PackageImports@@ -323,7 +323,7 @@ -- or the name of this_mod's package. Yurgh! -- c.f. GHC.findModule, and #9997 Nothing -> True- Just (StringLiteral _ pkg_fs) -> pkg_fs == fsLit "this" ||+ Just (StringLiteral _ pkg_fs _) -> pkg_fs == fsLit "this" || fsToUnit pkg_fs == moduleUnit this_mod)) (addErr (text "A module cannot import itself:" <+> ppr imp_mod_name)) @@ -334,8 +334,8 @@ _ | implicit -> return () -- Do not bleat for implicit imports | qual_only -> return () | otherwise -> whenWOptM Opt_WarnMissingImportList $- addWarn (Reason Opt_WarnMissingImportList)- (missingImportListWarn imp_mod_name)+ addDiagnostic (WarningWithFlag Opt_WarnMissingImportList)+ (missingImportListWarn imp_mod_name) iface <- loadSrcInterface doc imp_mod_name want_boot (fmap sl_fs mb_pkg) @@ -362,7 +362,7 @@ let qual_mod_name = fmap unLoc as_mod `orElse` imp_mod_name imp_spec = ImpDeclSpec { is_mod = imp_mod_name, is_qual = qual_only,- is_dloc = loc, is_as = qual_mod_name }+ is_dloc = locA loc, is_as = qual_mod_name } -- filter the imports according to the import declaration (new_imp_details, gres) <- filterImports iface imp_spec imp_details@@ -385,7 +385,7 @@ let home_unit = hsc_home_unit hsc_env imv = ImportedModsVal { imv_name = qual_mod_name- , imv_span = loc+ , imv_span = locA loc , imv_is_safe = mod_safe' , imv_is_hiding = is_hiding , imv_all_exports = potential_gres@@ -396,8 +396,8 @@ -- Complain if we import a deprecated module whenWOptM Opt_WarnWarningsDeprecations ( case (mi_warns iface) of- WarnAll txt -> addWarn (Reason Opt_WarnWarningsDeprecations)- (moduleWarn imp_mod_name txt)+ WarnAll txt -> addDiagnostic (WarningWithFlag Opt_WarnWarningsDeprecations)+ (moduleWarn imp_mod_name txt) _ -> return () ) @@ -522,7 +522,7 @@ warnUnqualifiedImport decl iface = whenWOptM Opt_WarnCompatUnqualifiedImports $ when bad_import- $ addWarnAt (Reason Opt_WarnCompatUnqualifiedImports) loc warning+ $ addDiagnosticAt (WarningWithFlag Opt_WarnCompatUnqualifiedImports) loc warning where mod = mi_module iface loc = getLoc $ ideclName decl@@ -624,7 +624,8 @@ | otherwise = rdr_env lcl_env3 = lcl_env2 { tcl_th_bndrs = extendNameEnvList th_bndrs- [ (n, (TopLevel, th_lvl))+ [ ( greNameMangledName n+ , (TopLevel, th_lvl) ) | n <- new_names ] } ; rdr_env2 <- foldlM add_gre rdr_env1 new_gres@@ -635,8 +636,8 @@ ; traceRn "extendGlobalRdrEnvRn 2" (pprGlobalRdrEnv True rdr_env2) ; return (gbl_env', lcl_env3) } where- new_names = concatMap availNames avails- new_occs = map nameOccName new_names+ new_names = concatMap availGreNames avails+ new_occs = map occName new_names -- If there is a fixity decl for the gre, add it to the fixity env extend_fix_env fix_env gre@@ -832,17 +833,17 @@ where ValBinds _ _val_binds val_sigs = binds - for_hs_bndrs :: [Located RdrName]+ for_hs_bndrs :: [LocatedN RdrName] for_hs_bndrs = hsForeignDeclsBinders foreign_decls -- In a hs-boot file, the value binders come from the -- *signatures*, and there should be no foreign binders- hs_boot_sig_bndrs = [ L decl_loc (unLoc n)+ hs_boot_sig_bndrs = [ L (l2l decl_loc) (unLoc n) | L decl_loc (TypeSig _ ns _) <- val_sigs, n <- ns] -- the SrcSpan attached to the input should be the span of the -- declaration, not just the name- new_simple :: Located RdrName -> RnM AvailInfo+ new_simple :: LocatedN RdrName -> RnM AvailInfo new_simple rdr_name = do{ nm <- newTopSrcBinder rdr_name ; return (avail nm) } @@ -850,7 +851,7 @@ -> RnM (AvailInfo, [(Name, [FieldLabel])]) new_tc dup_fields_ok has_sel tc_decl -- NOT for type/data instances = do { let (bndrs, flds) = hsLTyClDeclBinders tc_decl- ; names@(main_name : sub_names) <- mapM newTopSrcBinder bndrs+ ; names@(main_name : sub_names) <- mapM (newTopSrcBinder . l2n) bndrs ; flds' <- mapM (newRecordSelector dup_fields_ok has_sel sub_names) flds ; let fld_env = case unLoc tc_decl of DataDecl { tcdDataDefn = d } -> mk_fld_env d names flds'@@ -913,7 +914,7 @@ -- See (1) above L loc cls_rdr <- MaybeT $ pure $ getLHsInstDeclClass_maybe inst_ty -- See (2) above- MaybeT $ setSrcSpan loc $ lookupGlobalOccRn_maybe cls_rdr+ MaybeT $ setSrcSpan (locA loc) $ lookupGlobalOccRn_maybe cls_rdr -- Assuming the previous step succeeded, process any associated data -- family instances. If the previous step failed, bail out. case mb_cls_nm of@@ -928,7 +929,7 @@ new_di dup_fields_ok has_sel mb_cls dfid@(DataFamInstDecl { dfid_eqn = ti_decl }) = do { main_name <- lookupFamInstName mb_cls (feqn_tycon ti_decl) ; let (bndrs, flds) = hsDataFamInstBinders dfid- ; sub_names <- mapM newTopSrcBinder bndrs+ ; sub_names <- mapM (newTopSrcBinder .l2n) bndrs ; flds' <- mapM (newRecordSelector dup_fields_ok has_sel sub_names) flds ; let avail = availTC (unLoc main_name) sub_names flds' -- main_name is not bound here!@@ -942,7 +943,7 @@ newRecordSelector :: DuplicateRecordFields -> FieldSelectors -> [Name] -> LFieldOcc GhcPs -> RnM FieldLabel newRecordSelector _ _ [] _ = error "newRecordSelector: datatype has no constructors!" newRecordSelector dup_fields_ok has_sel (dc:_) (L loc (FieldOcc _ (L _ fld)))- = do { selName <- newTopSrcBinder $ L loc $ field+ = do { selName <- newTopSrcBinder $ L (noAnnSrcSpan loc) $ field ; return $ FieldLabel { flLabel = fieldLabelString , flHasDuplicateRecordFields = dup_fields_ok , flHasFieldSelector = has_sel@@ -1079,8 +1080,8 @@ filterImports :: ModIface -> ImpDeclSpec -- The span for the entire import decl- -> Maybe (Bool, Located [LIE GhcPs]) -- Import spec; True => hiding- -> RnM (Maybe (Bool, Located [LIE GhcRn]), -- Import spec w/ Names+ -> Maybe (Bool, LocatedL [LIE GhcPs]) -- Import spec; True => hiding+ -> RnM (Maybe (Bool, LocatedL [LIE GhcRn]), -- Import spec w/ Names [GlobalRdrElt]) -- Same again, but in GRE form filterImports iface decl_spec Nothing = return (Nothing, gresFromAvails (Just imp_spec) (mi_exports iface))@@ -1156,7 +1157,7 @@ lookup_lie :: LIE GhcPs -> TcRn [(LIE GhcRn, AvailInfo)] lookup_lie (L loc ieRdr)- = do (stuff, warns) <- setSrcSpan loc $+ = do (stuff, warns) <- setSrcSpanA loc $ liftM (fromMaybe ([],[])) $ run_lookup (lookup_ie ieRdr) mapM_ emit_warning warns@@ -1164,11 +1165,11 @@ where -- Warn when importing T(..) if T was exported abstractly emit_warning (DodgyImport n) = whenWOptM Opt_WarnDodgyImports $- addWarn (Reason Opt_WarnDodgyImports) (dodgyImportWarn n)+ addDiagnostic (WarningWithFlag Opt_WarnDodgyImports) (dodgyImportWarn n) emit_warning MissingImportList = whenWOptM Opt_WarnMissingImportList $- addWarn (Reason Opt_WarnMissingImportList) (missingImportListItem ieRdr)+ addDiagnostic (WarningWithFlag Opt_WarnMissingImportList) (missingImportListItem ieRdr) emit_warning (BadImportW ie) = whenWOptM Opt_WarnDodgyImports $- addWarn (Reason Opt_WarnDodgyImports) (lookup_err_msg (BadImport ie))+ addDiagnostic (WarningWithFlag Opt_WarnDodgyImports) (lookup_err_msg (BadImport ie)) run_lookup :: IELookupM a -> TcRn (Maybe a) run_lookup m = case m of@@ -1216,7 +1217,7 @@ | otherwise -> [] - renamed_ie = IEThingAll noExtField (L l (replaceWrappedName tc name))+ renamed_ie = IEThingAll noAnn (L l (replaceWrappedName tc name)) sub_avails = case avail of Avail {} -> [] AvailTC name2 subs -> [(renamed_ie, AvailTC name2 (subs \\ [NormalGreName name]))]@@ -1244,7 +1245,7 @@ IEThingWith xt ltc@(L l rdr_tc) wc rdr_ns -> do (name, avail, mb_parent)- <- lookup_name (IEThingAbs noExtField ltc) (ieWrappedName rdr_tc)+ <- lookup_name (IEThingAbs noAnn ltc) (ieWrappedName rdr_tc) -- Look up the children in the sub-names of the parent -- See Note [Importing DuplicateRecordFields]@@ -1283,9 +1284,9 @@ where mkIEThingAbs tc l (n, av, Nothing )- = (IEThingAbs noExtField (L l (replaceWrappedName tc n)), trimAvail av n)+ = (IEThingAbs noAnn (L l (replaceWrappedName tc n)), trimAvail av n) mkIEThingAbs tc l (n, _, Just parent)- = (IEThingAbs noExtField (L l (replaceWrappedName tc n))+ = (IEThingAbs noAnn (L l (replaceWrappedName tc n)) , availTC parent [n] []) handle_bad_import m = catchIELookup m $ \err -> case err of@@ -1336,7 +1337,8 @@ prov_fn name = Just (ImpSpec { is_decl = decl_spec, is_item = item_spec }) where- item_spec = ImpSome { is_explicit = is_explicit name, is_iloc = loc }+ item_spec = ImpSome { is_explicit = is_explicit name+ , is_iloc = locA loc } {-@@ -1367,7 +1369,7 @@ lookupChildren :: [GreName] -> [LIEWrappedName RdrName] -> MaybeErr [LIEWrappedName RdrName] -- The ones for which the lookup failed- ([Located Name], [Located FieldLabel])+ ([LocatedA Name], [Located FieldLabel]) -- (lookupChildren all_kids rdr_items) maps each rdr_item to its -- corresponding Name all_kids, if the former exists -- The matching is done by FastString, not OccName, so that@@ -1379,19 +1381,19 @@ | null fails = Succeeded (fmap concat (partitionEithers oks)) -- This 'fmap concat' trickily applies concat to the /second/ component- -- of the pair, whose type is ([Located Name], [[Located FieldLabel]])+ -- of the pair, whose type is ([LocatedA Name], [[Located FieldLabel]]) | otherwise = Failed fails where mb_xs = map doOne rdr_items fails = [ bad_rdr | Failed bad_rdr <- mb_xs ] oks = [ ok | Succeeded ok <- mb_xs ]- oks :: [Either (Located Name) [Located FieldLabel]]+ oks :: [Either (LocatedA Name) [Located FieldLabel]] doOne item@(L l r) = case (lookupFsEnv kid_env . occNameFS . rdrNameOcc . ieWrappedName) r of Just [NormalGreName n] -> Succeeded (Left (L l n))- Just rs | Just fs <- traverse greNameFieldLabel rs -> Succeeded (Right (map (L l) fs))+ Just rs | Just fs <- traverse greNameFieldLabel rs -> Succeeded (Right (map (L (locA l)) fs)) _ -> Failed item -- See Note [Children for duplicate record fields]@@ -1416,7 +1418,8 @@ ; traceRn "RUN" (ppr (tcg_dus gbl_env)) ; warnUnusedImportDecls gbl_env hsc_src ; warnUnusedTopBinds $ unused_locals keep- ; warnMissingSignatures gbl_env }+ ; warnMissingSignatures gbl_env+ ; warnMissingKindSignatures gbl_env } where used_names :: NameSet -> NameSet used_names keep = findUses (tcg_dus gbl_env) emptyNameSet `unionNameSet` keep@@ -1511,14 +1514,38 @@ add_warn name msg = when (name `elemNameSet` sig_ns && export_check name)- (addWarnAt (Reason flag) (getSrcSpan name) msg)+ (addDiagnosticAt (WarningWithFlag flag) (getSrcSpan name) msg) export_check name = warn_missing_sigs || not warn_only_exported || name `elemNameSet` exports ; add_sig_warns } +-- | Warn the user about tycons that lack kind signatures.+-- Called /after/ type (and kind) inference, so that we can report the+-- inferred kinds.+warnMissingKindSignatures :: TcGblEnv -> RnM ()+warnMissingKindSignatures gbl_env+ = do { warn_missing_kind_sigs <- woptM Opt_WarnMissingKindSignatures+ ; cusks_enabled <- xoptM LangExt.CUSKs+ ; when (warn_missing_kind_sigs) (mapM_ (add_ty_warn cusks_enabled) tcs)+ }+ where+ tcs = tcg_tcs gbl_env+ ksig_ns = tcg_ksigs gbl_env + add_ty_warn :: Bool -> TyCon -> IOEnv (Env TcGblEnv TcLclEnv) ()+ add_ty_warn cusks_enabled tyCon = when (name `elemNameSet` ksig_ns) $+ addDiagnosticAt (WarningWithFlag Opt_WarnMissingKindSignatures) (getSrcSpan name) $+ hang msg 2 (text "type" <+> pprPrefixName name <+> dcolon <+> ki_msg)+ where+ msg | cusks_enabled = text "Top-level type constructor with no standalone kind signature or CUSK:"+ | otherwise = text "Top-level type constructor with no standalone kind signature:"+ name = tyConName tyCon+ ki = tyConKind tyCon+ ki_msg :: SDoc+ ki_msg = pprKind ki+ {- ********************************************************* * *@@ -1577,7 +1604,7 @@ unused_decl decl@(L loc (ImportDecl { ideclHiding = imps })) = (decl, used_gres, nameSetElemsStable unused_imps) where- used_gres = lookupSrcLoc (srcSpanEnd loc) import_usage+ used_gres = lookupSrcLoc (srcSpanEnd $ locA loc) import_usage -- srcSpanEnd: see Note [The ImportMap] `orElse` [] @@ -1676,7 +1703,7 @@ -- Nothing used; drop entire declaration | null used- = addWarnAt (Reason flag) loc msg1+ = addDiagnosticAt (WarningWithFlag flag) (locA loc) msg1 -- Everything imported is used; nop | null unused@@ -1687,11 +1714,11 @@ | Just (_, L _ imports) <- ideclHiding decl , length unused == 1 , Just (L loc _) <- find (\(L _ ie) -> ((ieName ie) :: Name) `elem` unused) imports- = addWarnAt (Reason flag) loc msg2+ = addDiagnosticAt (WarningWithFlag flag) (locA loc) msg2 -- Some imports are unused | otherwise- = addWarnAt (Reason flag) loc msg2+ = addDiagnosticAt (WarningWithFlag flag) (locA loc) msg2 where msg1 = vcat [ pp_herald <+> quotes pp_mod <+> is_redundant@@ -1758,7 +1785,7 @@ ; iface <- loadSrcInterface doc mod_name is_boot (fmap sl_fs mb_pkg) ; let used_avails = gresToAvailInfo used_gres lies = map (L l) (concatMap (to_ie iface) used_avails)- ; return (L l (decl { ideclHiding = Just (False, L l lies) })) }+ ; return (L l (decl { ideclHiding = Just (False, L (l2l l) lies) })) } where doc = text "Compute minimal imports for" <+> ppr decl @@ -1767,25 +1794,26 @@ -- we want to say "T(..)", but if we're importing only a subset we want -- to say "T(A,B,C)". So we have to find out what the module exports. to_ie _ (Avail c) -- Note [Overloaded field import]- = [IEVar noExtField (to_ie_post_rn $ noLoc (greNamePrintableName c))]+ = [IEVar noExtField (to_ie_post_rn $ noLocA (greNamePrintableName c))] to_ie _ avail@(AvailTC n [_]) -- Exporting the main decl and nothing else- | availExportsDecl avail = [IEThingAbs noExtField (to_ie_post_rn $ noLoc n)]+ | availExportsDecl avail = [IEThingAbs noAnn (to_ie_post_rn $ noLocA n)] to_ie iface (AvailTC n cs) = case [xs | avail@(AvailTC x xs) <- mi_exports iface , x == n , availExportsDecl avail -- Note [Partial export] ] of- [xs] | all_used xs -> [IEThingAll noExtField (to_ie_post_rn $ noLoc n)]+ [xs] | all_used xs ->+ [IEThingAll noAnn (to_ie_post_rn $ noLocA n)] | otherwise ->- [IEThingWith (map noLoc fs) (to_ie_post_rn $ noLoc n) NoIEWildcard- (map (to_ie_post_rn . noLoc) (filter (/= n) ns))]+ [IEThingWith (map noLoc fs) (to_ie_post_rn $ noLocA n) NoIEWildcard+ (map (to_ie_post_rn . noLocA) (filter (/= n) ns))] -- Note [Overloaded field import] _other | all_non_overloaded fs- -> map (IEVar noExtField . to_ie_post_rn_var . noLoc) $ ns+ -> map (IEVar noExtField . to_ie_post_rn_var . noLocA) $ ns ++ map flSelector fs | otherwise ->- [IEThingWith (map noLoc fs) (to_ie_post_rn $ noLoc n) NoIEWildcard- (map (to_ie_post_rn . noLoc) (filter (/= n) ns))]+ [IEThingWith (map noLoc fs) (to_ie_post_rn $ noLocA n) NoIEWildcard+ (map (to_ie_post_rn . noLocA) (filter (/= n) ns))] where (ns, fs) = partitionGreNames cs @@ -1808,7 +1836,7 @@ merge :: [LImportDecl GhcRn] -> LImportDecl GhcRn merge [] = error "getMinimalImports: unexpected empty list"- merge decls@((L l decl) : _) = L l (decl { ideclHiding = Just (False, L l lies) })+ merge decls@((L l decl) : _) = L l (decl { ideclHiding = Just (False, L (noAnnSrcSpan (locA l)) lies) }) where lies = concatMap (unLoc . snd) $ mapMaybe (ideclHiding . unLoc) decls @@ -1838,16 +1866,16 @@ basefn = moduleNameString (moduleName this_mod) ++ suffix -to_ie_post_rn_var :: (HasOccName name) => Located name -> LIEWrappedName name+to_ie_post_rn_var :: (HasOccName name) => LocatedA name -> LIEWrappedName name to_ie_post_rn_var (L l n)- | isDataOcc $ occName n = L l (IEPattern (L l n))- | otherwise = L l (IEName (L l n))+ | isDataOcc $ occName n = L l (IEPattern (AR $ la2r l) (L (la2na l) n))+ | otherwise = L l (IEName (L (la2na l) n)) -to_ie_post_rn :: (HasOccName name) => Located name -> LIEWrappedName name+to_ie_post_rn :: (HasOccName name) => LocatedA name -> LIEWrappedName name to_ie_post_rn (L l n)- | isTcOcc occ && isSymOcc occ = L l (IEType (L l n))- | otherwise = L l (IEName (L l n))+ | isTcOcc occ && isSymOcc occ = L l (IEType (AR $ la2r l) (L (la2na l) n))+ | otherwise = L l (IEName (L (la2na l) n)) where occ = occName n {-@@ -1992,10 +2020,10 @@ text "but it has none" ] dodgyMsgInsert :: forall p . IdP (GhcPass p) -> IE (GhcPass p)-dodgyMsgInsert tc = IEThingAll noExtField ii+dodgyMsgInsert tc = IEThingAll noAnn ii where ii :: LIEWrappedName (IdP (GhcPass p))- ii = noLoc (IEName $ noLoc tc)+ ii = noLocA (IEName $ noLocA tc) addDupDeclErr :: [GlobalRdrElt] -> TcRn ()
compiler/GHC/Rename/Pat.hs view
@@ -1,3 +1,4 @@+{-# LANGUAGE TypeApplications #-} {-# LANGUAGE CPP #-} {-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE FlexibleContexts #-}@@ -139,14 +140,14 @@ liftCpsWithCont :: (forall r. (b -> RnM (r, FreeVars)) -> RnM (r, FreeVars)) -> CpsRn b liftCpsWithCont = CpsRn -wrapSrcSpanCps :: (a -> CpsRn b) -> Located a -> CpsRn (Located b)+wrapSrcSpanCps :: (a -> CpsRn b) -> LocatedA a -> CpsRn (LocatedA b) -- Set the location, and also wrap it around the value returned wrapSrcSpanCps fn (L loc a)- = CpsRn (\k -> setSrcSpan loc $+ = CpsRn (\k -> setSrcSpanA loc $ unCpsRn (fn a) $ \v -> k (L loc v)) -lookupConCps :: Located RdrName -> CpsRn (Located Name)+lookupConCps :: LocatedN RdrName -> CpsRn (LocatedN Name) lookupConCps con_rdr = CpsRn (\k -> do { con_name <- lookupLocatedOccRn con_rdr ; (r, fvs) <- k con_name@@ -225,12 +226,12 @@ ThPatQuote -> False _ -> True -newPatLName :: NameMaker -> Located RdrName -> CpsRn (Located Name)+newPatLName :: NameMaker -> LocatedN RdrName -> CpsRn (LocatedN Name) newPatLName name_maker rdr_name@(L loc _) = do { name <- newPatName name_maker rdr_name ; return (L loc name) } -newPatName :: NameMaker -> Located RdrName -> CpsRn Name+newPatName :: NameMaker -> LocatedN RdrName -> CpsRn Name newPatName (LamMk report_unused) rdr_name = CpsRn (\ thing_inside -> do { name <- newLocalBndrRn rdr_name@@ -360,7 +361,7 @@ rnPat ctxt pat thing_inside = rnPats ctxt [pat] (\pats' -> let [pat'] = pats' in thing_inside pat') -applyNameMaker :: NameMaker -> Located RdrName -> RnM (Located Name)+applyNameMaker :: NameMaker -> LocatedN RdrName -> RnM (LocatedN Name) applyNameMaker mk rdr = do { (n, _fvs) <- runCps (newPatLName mk rdr) ; return n } @@ -404,18 +405,18 @@ rnPatAndThen _ (WildPat _) = return (WildPat noExtField) rnPatAndThen mk (ParPat x pat) = do { pat' <- rnLPatAndThen mk pat ; return (ParPat x pat') }-rnPatAndThen mk (LazyPat x pat) = do { pat' <- rnLPatAndThen mk pat- ; return (LazyPat x pat') }-rnPatAndThen mk (BangPat x pat) = do { pat' <- rnLPatAndThen mk pat- ; return (BangPat x pat') }+rnPatAndThen mk (LazyPat _ pat) = do { pat' <- rnLPatAndThen mk pat+ ; return (LazyPat noExtField pat') }+rnPatAndThen mk (BangPat _ pat) = do { pat' <- rnLPatAndThen mk pat+ ; return (BangPat noExtField pat') } rnPatAndThen mk (VarPat x (L l rdr)) = do { loc <- liftCps getSrcSpanM- ; name <- newPatName mk (L loc rdr)+ ; name <- newPatName mk (L (noAnnSrcSpan loc) rdr) ; return (VarPat x (L l name)) } -- we need to bind pattern variables for view pattern expressions -- (e.g. in the pattern (x, x -> y) x needs to be bound in the rhs of the tuple) -rnPatAndThen mk (SigPat x pat sig)+rnPatAndThen mk (SigPat _ pat sig) -- When renaming a pattern type signature (e.g. f (a :: T) = ...), it is -- important to rename its type signature _before_ renaming the rest of the -- pattern, so that type variables are first bound by the _outermost_ pattern@@ -427,7 +428,7 @@ -- ~~~~~~~~~~~~~~~^ the same `a' then used here = do { sig' <- rnHsPatSigTypeAndThen sig ; pat' <- rnLPatAndThen mk pat- ; return (SigPat x pat' sig' ) }+ ; return (SigPat noExtField pat' sig' ) } where rnHsPatSigTypeAndThen :: HsPatSigType GhcPs -> CpsRn (HsPatSigType GhcRn) rnHsPatSigTypeAndThen sig = liftCpsWithCont (rnHsPatSigType AlwaysBind PatCtx sig)@@ -438,7 +439,7 @@ ; if ovlStr then rnPatAndThen mk (mkNPat (noLoc (mkHsIsString src s))- Nothing)+ Nothing noAnn) else normal_lit } | otherwise = normal_lit where@@ -458,24 +459,24 @@ ; eq' <- liftCpsFV $ lookupSyntax eqName ; return (NPat x (L l lit') mb_neg' eq') } -rnPatAndThen mk (NPlusKPat x rdr (L l lit) _ _ _ )- = do { new_name <- newPatName mk rdr+rnPatAndThen mk (NPlusKPat _ rdr (L l lit) _ _ _ )+ = do { new_name <- newPatName mk (l2n rdr) ; (lit', _) <- liftCpsFV $ rnOverLit lit -- See Note [Negative zero] -- We skip negateName as -- negative zero doesn't make -- sense in n + k patterns ; minus <- liftCpsFV $ lookupSyntax minusName ; ge <- liftCpsFV $ lookupSyntax geName- ; return (NPlusKPat x (L (nameSrcSpan new_name) new_name)- (L l lit') lit' ge minus) }+ ; return (NPlusKPat noExtField (L (noAnnSrcSpan $ nameSrcSpan new_name) new_name)+ (L l lit') lit' ge minus) } -- The Report says that n+k patterns must be in Integral -rnPatAndThen mk (AsPat x rdr pat)+rnPatAndThen mk (AsPat _ rdr pat) = do { new_name <- newPatLName mk rdr ; pat' <- rnLPatAndThen mk pat- ; return (AsPat x new_name pat') }+ ; return (AsPat noExtField new_name pat') } -rnPatAndThen mk p@(ViewPat x expr pat)+rnPatAndThen mk p@(ViewPat _ expr pat) = do { liftCps $ do { vp_flag <- xoptM LangExt.ViewPatterns ; checkErr vp_flag (badViewPat p) } -- Because of the way we're arranging the recursive calls,@@ -484,14 +485,14 @@ ; pat' <- rnLPatAndThen mk pat -- Note: at this point the PreTcType in ty can only be a placeHolder -- ; return (ViewPat expr' pat' ty) }- ; return (ViewPat x expr' pat') }+ ; return (ViewPat noExtField expr' pat') } -rnPatAndThen mk (ConPat NoExtField con args)+rnPatAndThen mk (ConPat _ con args) -- rnConPatAndThen takes care of reconstructing the pattern -- The pattern for the empty list needs to be replaced by an empty explicit list pattern when overloaded lists is turned on. = case unLoc con == nameRdrName (dataConName nilDataCon) of True -> do { ol_flag <- liftCps $ xoptM LangExt.OverloadedLists- ; if ol_flag then rnPatAndThen mk (ListPat noExtField [])+ ; if ol_flag then rnPatAndThen mk (ListPat noAnn []) else rnConPatAndThen mk con args} False -> rnConPatAndThen mk con args @@ -503,13 +504,13 @@ ; return (ListPat (Just to_list_name) pats')} False -> return (ListPat Nothing pats') } -rnPatAndThen mk (TuplePat x pats boxed)+rnPatAndThen mk (TuplePat _ pats boxed) = do { pats' <- rnLPatsAndThen mk pats- ; return (TuplePat x pats' boxed) }+ ; return (TuplePat noExtField pats' boxed) } -rnPatAndThen mk (SumPat x pat alt arity)+rnPatAndThen mk (SumPat _ pat alt arity) = do { pat <- rnLPatAndThen mk pat- ; return (SumPat x pat alt arity)+ ; return (SumPat noExtField pat alt arity) } -- If a splice has been run already, just rename the result.@@ -524,7 +525,7 @@ -------------------- rnConPatAndThen :: NameMaker- -> Located RdrName -- the constructor+ -> LocatedN RdrName -- the constructor -> HsConPatDetails GhcPs -> CpsRn (Pat GhcRn) @@ -579,7 +580,7 @@ return (r, fvs) ) -------------------- rnHsRecPatsAndThen :: NameMaker- -> Located Name -- Constructor+ -> LocatedN Name -- Constructor -> HsRecFields GhcPs (LPat GhcPs) -> CpsRn (HsRecFields GhcRn (LPat GhcRn)) rnHsRecPatsAndThen mk (L _ con)@@ -590,7 +591,7 @@ ; check_unused_wildcard (implicit_binders flds' <$> dd) ; return (HsRecFields { rec_flds = flds', rec_dotdot = dd }) } where- mkVarPat l n = VarPat noExtField (L l n)+ mkVarPat l n = VarPat noExtField (L (noAnnSrcSpan l) n) rn_field (L l fld, n') = do { arg' <- rnLPatAndThen (nested_mk dd mk n') (hsRecFieldArg fld) ; return (L l (fld { hsRecFieldArg = arg' })) }@@ -631,8 +632,8 @@ HsRecFieldContext -> (SrcSpan -> RdrName -> arg) -- When punning, use this to build a new field- -> HsRecFields GhcPs (Located arg)- -> RnM ([LHsRecField GhcRn (Located arg)], FreeVars)+ -> HsRecFields GhcPs (LocatedA arg)+ -> RnM ([LHsRecField GhcRn (LocatedA arg)], FreeVars) -- This surprisingly complicated pass -- a) looks up the field name (possibly using disambiguation)@@ -658,8 +659,8 @@ HsRecFieldPat con -> Just con _ {- update -} -> Nothing - rn_fld :: Bool -> Maybe Name -> LHsRecField GhcPs (Located arg)- -> RnM (LHsRecField GhcRn (Located arg))+ rn_fld :: Bool -> Maybe Name -> LHsRecField GhcPs (LocatedA arg)+ -> RnM (LHsRecField GhcRn (LocatedA arg)) rn_fld pun_ok parent (L l (HsRecField { hsRecFieldLbl =@@ -671,11 +672,11 @@ then do { checkErr pun_ok (badPun (L loc lbl)) -- Discard any module qualifier (#11662) ; let arg_rdr = mkRdrUnqual (rdrNameOcc lbl)- ; return (L loc (mk_arg loc arg_rdr)) }+ ; return (L (noAnnSrcSpan loc) (mk_arg loc arg_rdr)) } else return arg ; return (L l (HsRecField- { hsRecFieldLbl = (L loc (FieldOcc- sel (L ll lbl)))+ { hsRecFieldAnn = noAnn+ , hsRecFieldLbl = (L loc (FieldOcc sel (L ll lbl))) , hsRecFieldArg = arg' , hsRecPun = pun })) } @@ -683,8 +684,8 @@ rn_dotdot :: Maybe (Located Int) -- See Note [DotDot fields] in GHC.Hs.Pat -> Maybe Name -- The constructor (Nothing for an -- out of scope constructor)- -> [LHsRecField GhcRn (Located arg)] -- Explicit fields- -> RnM ([LHsRecField GhcRn (Located arg)]) -- Field Labels we need to fill in+ -> [LHsRecField GhcRn (LocatedA arg)] -- Explicit fields+ -> RnM ([LHsRecField GhcRn (LocatedA arg)]) -- Field Labels we need to fill in rn_dotdot (Just (L loc n)) (Just con) flds -- ".." on record construction / pat match | not (isUnboundName con) -- This test is because if the constructor -- isn't in scope the constructor lookup will add@@ -717,9 +718,12 @@ _other -> True ] ; addUsedGREs dot_dot_gres- ; return [ L loc (HsRecField- { hsRecFieldLbl = L loc (FieldOcc sel (L loc arg_rdr))- , hsRecFieldArg = L loc (mk_arg loc arg_rdr)+ ; let locn = noAnnSrcSpan loc+ ; return [ L (noAnnSrcSpan loc) (HsRecField+ { hsRecFieldAnn = noAnn+ , hsRecFieldLbl+ = L loc (FieldOcc sel (L (noAnnSrcSpan loc) arg_rdr))+ , hsRecFieldArg = L locn (mk_arg loc arg_rdr) , hsRecPun = False }) | fl <- dot_dot_fields , let sel = flSelector fl@@ -774,16 +778,18 @@ then do { checkErr pun_ok (badPun (L loc lbl)) -- Discard any module qualifier (#11662) ; let arg_rdr = mkRdrUnqual (rdrNameOcc lbl)- ; return (L loc (HsVar noExtField (L loc arg_rdr))) }+ ; return (L (noAnnSrcSpan loc) (HsVar noExtField+ (L (noAnnSrcSpan loc) arg_rdr))) } else return arg ; (arg'', fvs) <- rnLExpr arg' ; let (lbl', fvs') = case mb_sel of UnambiguousGre gname -> let sel_name = greNameMangledName gname- in (Unambiguous sel_name (L loc lbl), fvs `addOneFV` sel_name)- AmbiguousFields -> (Ambiguous noExtField (L loc lbl), fvs)+ in (Unambiguous sel_name (L (noAnnSrcSpan loc) lbl), fvs `addOneFV` sel_name)+ AmbiguousFields -> (Ambiguous noExtField (L (noAnnSrcSpan loc) lbl), fvs) - ; return (L l (HsRecField { hsRecFieldLbl = L loc lbl'+ ; return (L l (HsRecField { hsRecFieldAnn = noAnn+ , hsRecFieldLbl = L loc lbl' , hsRecFieldArg = arg'' , hsRecPun = pun }), fvs') } @@ -798,9 +804,9 @@ getFieldIds :: [LHsRecField GhcRn arg] -> [Name] getFieldIds flds = map (unLoc . hsRecFieldSel . unLoc) flds -getFieldLbls :: [LHsRecField id arg] -> [RdrName]+getFieldLbls :: forall p arg . UnXRec p => [LHsRecField p arg] -> [RdrName] getFieldLbls flds- = map (unLoc . rdrNameFieldOcc . unLoc . hsRecFieldLbl . unLoc) flds+ = map (unLoc . rdrNameFieldOcc . unLoc . hsRecFieldLbl . unXRec @p) flds getFieldUpdLbls :: [LHsRecUpdField GhcPs] -> [RdrName] getFieldUpdLbls flds = map (rdrNameAmbiguousFieldOcc . unLoc . hsRecFieldLbl . unLoc) flds
compiler/GHC/Rename/Splice.hs view
@@ -107,7 +107,7 @@ ; (body', fvs_e) <- setStage (Brack cur_stage RnPendingTyped) $ rn_bracket cur_stage br_body- ; return (HsBracket noExtField body', fvs_e) }+ ; return (HsBracket noAnn body', fvs_e) } False -> do { traceRn "Renaming untyped TH bracket" empty ; ps_var <- newMutVar []@@ -122,7 +122,7 @@ rn_bracket :: ThStage -> HsBracket GhcPs -> RnM (HsBracket GhcRn, FreeVars) rn_bracket outer_stage br@(VarBr x flg rdr_name)- = do { name <- lookupOccRn rdr_name+ = do { name <- lookupOccRn (unLoc rdr_name) ; this_mod <- getModule ; when (flg && nameIsLocalOrFrom this_mod name) $@@ -143,7 +143,7 @@ (quotedNameStageErr br) } } }- ; return (VarBr x flg name, unitFV name) }+ ; return (VarBr x flg (noLocA name), unitFV name) } rn_bracket _ (ExpBr x e) = do { (e', fvs) <- rnLExpr e ; return (ExpBr x e', fvs) }@@ -176,7 +176,7 @@ ; Just (splice, rest) -> do { group' <- groupDecls rest ; let group'' = appendGroups group group'- ; return group'' { hs_splcds = noLoc splice : hs_splcds group' }+ ; return group'' { hs_splcds = noLocA splice : hs_splcds group' } } }} @@ -377,14 +377,16 @@ -> LHsExpr GhcRn -- Return the expression (quoter "...quote...") -- which is what we must run in a quasi-quote-mkQuasiQuoteExpr flavour quoter q_span quote- = L q_span $ HsApp noExtField (L q_span- $ HsApp noExtField (L q_span (HsVar noExtField (L q_span quote_selector)))+mkQuasiQuoteExpr flavour quoter q_span' quote+ = L q_span $ HsApp noComments (L q_span+ $ HsApp noComments (L q_span+ (HsVar noExtField (L (la2na q_span) quote_selector))) quoterExpr) quoteExpr where- quoterExpr = L q_span $! HsVar noExtField $! (L q_span quoter)- quoteExpr = L q_span $! HsLit noExtField $! HsString NoSourceText quote+ q_span = noAnnSrcSpan q_span'+ quoterExpr = L q_span $! HsVar noExtField $! (L (la2na q_span) quoter)+ quoteExpr = L q_span $! HsLit noComments $! HsString NoSourceText quote quote_selector = case flavour of UntypedExpSplice -> quoteExpName UntypedPatSplice -> quotePatName@@ -396,19 +398,19 @@ -- Not exported...used for all rnSplice (HsTypedSplice x hasParen splice_name expr) = do { loc <- getSrcSpanM- ; n' <- newLocalBndrRn (L loc splice_name)+ ; n' <- newLocalBndrRn (L (noAnnSrcSpan loc) splice_name) ; (expr', fvs) <- rnLExpr expr ; return (HsTypedSplice x hasParen n' expr', fvs) } rnSplice (HsUntypedSplice x hasParen splice_name expr) = do { loc <- getSrcSpanM- ; n' <- newLocalBndrRn (L loc splice_name)+ ; n' <- newLocalBndrRn (L (noAnnSrcSpan loc) splice_name) ; (expr', fvs) <- rnLExpr expr ; return (HsUntypedSplice x hasParen n' expr', fvs) } rnSplice (HsQuasiQuote x splice_name quoter q_loc quote) = do { loc <- getSrcSpanM- ; splice_name' <- newLocalBndrRn (L loc splice_name)+ ; splice_name' <- newLocalBndrRn (L (noAnnSrcSpan loc) splice_name) -- Rename the quoter; akin to the HsVar case of rnExpr ; quoter' <- lookupOccRn quoter@@ -428,7 +430,7 @@ where pend_expr_splice :: HsSplice GhcRn -> (PendingRnSplice, HsExpr GhcRn) pend_expr_splice rn_splice- = (makePending UntypedExpSplice rn_splice, HsSpliceE noExtField rn_splice)+ = (makePending UntypedExpSplice rn_splice, HsSpliceE noAnn rn_splice) run_expr_splice :: HsSplice GhcRn -> RnM (HsExpr GhcRn, FreeVars) run_expr_splice rn_splice@@ -441,7 +443,7 @@ , isLocalGRE gre] lcl_names = mkNameSet (localRdrEnvElts lcl_rdr) - ; return (HsSpliceE noExtField rn_splice, lcl_names `plusFV` gbl_names) }+ ; return (HsSpliceE noAnn rn_splice, lcl_names `plusFV` gbl_names) } | otherwise -- Run it here, see Note [Running splices in the Renamer] = do { traceRn "rnSpliceExpr: untyped expression splice" empty@@ -449,7 +451,7 @@ runRnSplice UntypedExpSplice runMetaE ppr rn_splice ; (lexpr3, fvs) <- checkNoErrs (rnLExpr rn_expr) -- See Note [Delaying modFinalizers in untyped splices].- ; return ( HsPar noExtField $ HsSpliceE noExtField+ ; return ( HsPar noAnn $ HsSpliceE noAnn . HsSpliced noExtField (ThModFinalizers mod_finalizers) . HsSplicedExpr <$> lexpr3@@ -623,7 +625,7 @@ ; checkNoErrs $ rnLHsType doc hs_ty2 } -- checkNoErrs: see Note [Renamer errors] -- See Note [Delaying modFinalizers in untyped splices].- ; return ( HsParTy noExtField+ ; return ( HsParTy noAnn $ HsSpliceTy noExtField . HsSpliced noExtField (ThModFinalizers mod_finalizers) . HsSplicedTy <$>@@ -693,7 +695,7 @@ ; (pat, mod_finalizers) <- runRnSplice UntypedPatSplice runMetaP ppr rn_splice -- See Note [Delaying modFinalizers in untyped splices].- ; return ( Left $ ParPat noExtField $ ((SplicePat noExtField)+ ; return ( Left $ ParPat noAnn $ ((SplicePat noExtField) . HsSpliced noExtField (ThModFinalizers mod_finalizers) . HsSplicedPat) `mapLoc` pat@@ -813,7 +815,7 @@ , spliceGenerated = gen, spliceIsDecl = is_decl }) = do loc <- case mb_src of Nothing -> getSrcSpanM- Just (L loc _) -> return loc+ Just (L loc _) -> return (locA loc) traceOptTcRn Opt_D_dump_splices (spliceDebugDoc loc) when is_decl $ do -- Raw material for -dth-dec-file@@ -908,6 +910,12 @@ -- Construct the (lift x) expression ; let lift_expr = nlHsApp (nlHsVar liftName) (nlHsVar name) pend_splice = PendingRnSplice UntypedExpSplice name lift_expr++ -- Warning for implicit lift (#17804)+ ; whenWOptM Opt_WarnImplicitLift $+ addDiagnosticTc (WarningWithFlag Opt_WarnImplicitLift)+ (text "The variable" <+> quotes (ppr name) <+>+ text "is implicitly lifted in the TH quotation") -- Update the pending splices ; ps <- readMutVar ps_var
compiler/GHC/Rename/Utils.hs view
@@ -9,7 +9,7 @@ -} module GHC.Rename.Utils (- checkDupRdrNames, checkShadowedRdrNames,+ checkDupRdrNames, checkDupRdrNamesN, checkShadowedRdrNames, checkDupNames, checkDupAndShadowedNames, dupNamesErr, checkTupSize, checkCTupSize, addFvRn, mapFvRn, mapMaybeFvRn,@@ -25,7 +25,7 @@ bindLocalNames, bindLocalNamesFV, - addNameClashErrRn, extendTyVarEnvFVRn,+ addNameClashErrRn, checkInferredVars, noNestedForallsContextsErr, addNoNestedForallsContextsErr@@ -69,7 +69,7 @@ ********************************************************* -} -newLocalBndrRn :: Located RdrName -> RnM Name+newLocalBndrRn :: LocatedN RdrName -> RnM Name -- Used for non-top-level binders. These should -- never be qualified. newLocalBndrRn (L loc rdr_name)@@ -78,11 +78,11 @@ -- See Note [Binders in Template Haskell] in "GHC.ThToHs" | otherwise = do { unless (isUnqual rdr_name)- (addErrAt loc (badQualBndrErr rdr_name))+ (addErrAt (locA loc) (badQualBndrErr rdr_name)) ; uniq <- newUnique- ; return (mkInternalName uniq (rdrNameOcc rdr_name) loc) }+ ; return (mkInternalName uniq (rdrNameOcc rdr_name) (locA loc)) } -newLocalBndrsRn :: [Located RdrName] -> RnM [Name]+newLocalBndrsRn :: [LocatedN RdrName] -> RnM [Name] newLocalBndrsRn = mapM newLocalBndrRn bindLocalNames :: [Name] -> RnM a -> RnM a@@ -102,18 +102,20 @@ ; return (result, delFVs names fvs) } ---------------------------------------extendTyVarEnvFVRn :: [Name] -> RnM (a, FreeVars) -> RnM (a, FreeVars)-extendTyVarEnvFVRn tyvars thing_inside = bindLocalNamesFV tyvars thing_inside----------------------------------------checkDupRdrNames :: [Located RdrName] -> RnM ()+checkDupRdrNames :: [LocatedN RdrName] -> RnM () -- Check for duplicated names in a binding group checkDupRdrNames rdr_names_w_loc- = mapM_ (dupNamesErr getLoc) dups+ = mapM_ (dupNamesErr getLocA) dups where (_, dups) = removeDups (\n1 n2 -> unLoc n1 `compare` unLoc n2) rdr_names_w_loc +checkDupRdrNamesN :: [LocatedN RdrName] -> RnM ()+-- Check for duplicated names in a binding group+checkDupRdrNamesN rdr_names_w_loc+ = mapM_ (dupNamesErr getLocA) dups+ where+ (_, dups) = removeDups (\n1 n2 -> unLoc n1 `compare` unLoc n2) rdr_names_w_loc+ checkDupNames :: [Name] -> RnM () -- Check for duplicated names in a binding group checkDupNames names = check_dup_names (filterOut isSystemName names)@@ -126,14 +128,14 @@ (_, dups) = removeDups (\n1 n2 -> nameOccName n1 `compare` nameOccName n2) names ----------------------checkShadowedRdrNames :: [Located RdrName] -> RnM ()+checkShadowedRdrNames :: [LocatedN RdrName] -> RnM () checkShadowedRdrNames loc_rdr_names = do { envs <- getRdrEnvs ; checkShadowedOccs envs get_loc_occ filtered_rdrs } where filtered_rdrs = filterOut (isExact . unLoc) loc_rdr_names -- See Note [Binders in Template Haskell] in "GHC.ThToHs"- get_loc_occ (L loc rdr) = (loc,rdrNameOcc rdr)+ get_loc_occ (L loc rdr) = (locA loc,rdrNameOcc rdr) checkDupAndShadowedNames :: (GlobalRdrEnv, LocalRdrEnv) -> [Name] -> RnM () checkDupAndShadowedNames envs names@@ -167,9 +169,9 @@ -- we don't find any GREs that are in scope qualified-only complain [] = return ()- complain pp_locs = addWarnAt (Reason Opt_WarnNameShadowing)- loc- (shadowedNameWarn occ pp_locs)+ complain pp_locs = addDiagnosticAt (WarningWithFlag Opt_WarnNameShadowing)+ loc+ (shadowedNameWarn occ pp_locs) is_shadowed_gre :: GlobalRdrElt -> RnM Bool -- Returns False for record selectors that are shadowed, when@@ -289,13 +291,13 @@ -- types of terms, so we give a slightly more descriptive error -- message in the event that they contain visible dependent -- quantification (currently only allowed in kinds).- -> Just (l, vcat [ text "Illegal visible, dependent quantification" <+>- text "in the type of a term"- , text "(GHC does not yet support this)" ])+ -> Just (locA l, vcat [ text "Illegal visible, dependent quantification" <+>+ text "in the type of a term"+ , text "(GHC does not yet support this)" ]) | HsForAllInvis{} <- tele- -> Just (l, nested_foralls_contexts_err)+ -> Just (locA l, nested_foralls_contexts_err) L l (HsQualTy {})- -> Just (l, nested_foralls_contexts_err)+ -> Just (locA l, nested_foralls_contexts_err) _ -> Nothing where nested_foralls_contexts_err =@@ -384,8 +386,8 @@ warnRedundantRecordWildcard :: RnM () warnRedundantRecordWildcard = whenWOptM Opt_WarnRedundantRecordWildcards- (addWarn (Reason Opt_WarnRedundantRecordWildcards)- redundantWildcardWarning)+ (addDiagnostic (WarningWithFlag Opt_WarnRedundantRecordWildcards)+ redundantWildcardWarning) -- | Produce a warning when no variables bound by a `..` pattern are used.@@ -473,7 +475,7 @@ addUnusedWarning :: WarningFlag -> OccName -> SrcSpan -> SDoc -> RnM () addUnusedWarning flag occ span msg- = addWarnAt (Reason flag) span $+ = addDiagnosticAt (WarningWithFlag flag) span $ sep [msg <> colon, nest 2 $ pprNonVarNameSpace (occNameSpace occ) <+> quotes (ppr occ)]@@ -647,15 +649,15 @@ | PatCtx | SpecInstSigCtx | DefaultDeclCtx- | ForeignDeclCtx (Located RdrName)+ | ForeignDeclCtx (LocatedN RdrName) | DerivDeclCtx | RuleCtx FastString- | TyDataCtx (Located RdrName)- | TySynCtx (Located RdrName)- | TyFamilyCtx (Located RdrName)- | FamPatCtx (Located RdrName) -- The patterns of a type/data family instance- | ConDeclCtx [Located Name]- | ClassDeclCtx (Located RdrName)+ | TyDataCtx (LocatedN RdrName)+ | TySynCtx (LocatedN RdrName)+ | TyFamilyCtx (LocatedN RdrName)+ | FamPatCtx (LocatedN RdrName) -- The patterns of a type/data family instance+ | ConDeclCtx [LocatedN Name]+ | ClassDeclCtx (LocatedN RdrName) | ExprWithTySigCtx | TypBrCtx | HsTypeCtx
compiler/GHC/Runtime/Debugger.hs view
@@ -135,8 +135,8 @@ let ids = [ mkVanillaGlobal name ty | (name,ty) <- zip names tys] new_ic = extendInteractiveContextWithIds ictxt ids- dl = hsc_loader hsc_env- liftIO $ extendLoadedEnv dl (zip names fhvs)+ interp = hscInterp hsc_env+ liftIO $ extendLoadedEnv interp (zip names fhvs) setSession hsc_env {hsc_IC = new_ic } return t' where@@ -184,7 +184,7 @@ setSession new_env -- this disables logging of errors- let noop_log _ _ _ _ _ = return ()+ let noop_log _ _ _ _ = return () pushLogHookM (const noop_log) return (hsc_env, bname)@@ -197,12 +197,12 @@ let expr = "Prelude.return (Prelude.show " ++ showPpr dflags bname ++ ") :: Prelude.IO Prelude.String"- dl = hsc_loader hsc_env- txt_ <- withExtendedLoadedEnv dl+ interp = hscInterp hsc_env+ txt_ <- withExtendedLoadedEnv interp [(bname, fhv)] (GHC.compileExprRemote expr) let myprec = 10 -- application precedence. TODO Infix constructors- txt <- liftIO $ evalString hsc_env txt_+ txt <- liftIO $ evalString interp txt_ if not (null txt) then return $ Just $ cparen (prec >= myprec && needsParens txt) (text txt)
compiler/GHC/Runtime/Eval.hs view
@@ -1,6 +1,5 @@ {-# LANGUAGE BangPatterns #-} {-# LANGUAGE CPP #-}-{-# LANGUAGE LambdaCase #-} {-# LANGUAGE RecordWildCards #-} {-# OPTIONS_GHC -Wno-incomplete-uni-patterns #-}@@ -23,6 +22,7 @@ getHistorySpan, getModBreaks, getHistoryModule,+ setupBreakpoint, back, forward, setContext, getContext, getNamesInScope,@@ -56,7 +56,6 @@ import GHC.Runtime.Eval.Types import GHC.Runtime.Interpreter as GHCi-import GHC.Runtime.Interpreter.Types import GHC.Runtime.Heap.Inspect import GHC.Runtime.Context import GHCi.Message@@ -117,9 +116,9 @@ import System.Directory import Data.Dynamic import Data.Either+import Data.IntMap (IntMap) import qualified Data.IntMap as IntMap import Data.List (find,intercalate)-import Data.Map (Map) import qualified Data.Map as Map import Control.Monad import Control.Monad.Catch as MC@@ -209,6 +208,7 @@ execStmt' :: GhcMonad m => GhciLStmt GhcPs -> String -> ExecOptions -> m ExecResult execStmt' stmt stmt_text ExecOptions{..} = do hsc_env <- getSession+ let interp = hscInterp hsc_env -- Turn off -fwarn-unused-local-binds when running a statement, to hide -- warnings about the implicit bindings we introduce.@@ -228,7 +228,7 @@ status <- withVirtualCWD $ liftIO $- evalStmt hsc_env' (isStep execSingleStep) (execWrap hval)+ evalStmt interp idflags' (isStep execSingleStep) (execWrap hval) let ic = hsc_IC hsc_env bindings = (ic_tythings ic, ic_rn_gbl_env ic)@@ -281,7 +281,7 @@ -- a virtual CWD is only necessary when we're running interpreted code in -- the same process as the compiler.- case hsc_interp hsc_env of+ case interpInstance <$> hsc_interp hsc_env of Just (ExternalInterp {}) -> m _ -> do let ic = hsc_IC hsc_env@@ -322,6 +322,8 @@ , not is_exception = do hsc_env <- getSession+ let interp = hscInterp hsc_env+ let dflags = hsc_dflags hsc_env let hmi = expectJust "handleRunStatus" $ lookupHptDirectly (hsc_HPT hsc_env) (mkUniqueGrimily mod_uniq)@@ -329,18 +331,18 @@ breaks = getModBreaks hmi b <- liftIO $- breakpointStatus hsc_env (modBreaks_flags breaks) ix+ breakpointStatus interp (modBreaks_flags breaks) ix if b then not_tracing -- This breakpoint is explicitly enabled; we want to stop -- instead of just logging it. else do- apStack_fhv <- liftIO $ mkFinalizedHValue hsc_env apStack_ref+ apStack_fhv <- liftIO $ mkFinalizedHValue interp apStack_ref let bi = BreakInfo modl ix !history' = mkHistory hsc_env apStack_fhv bi `consBL` history -- history is strict, otherwise our BoundedList is pointless.- fhv <- liftIO $ mkFinalizedHValue hsc_env resume_ctxt- status <- liftIO $ GHCi.resumeStmt hsc_env True fhv+ fhv <- liftIO $ mkFinalizedHValue interp resume_ctxt+ status <- liftIO $ GHCi.resumeStmt interp dflags True fhv handleRunStatus RunAndLogSteps expr bindings final_ids status history' | otherwise@@ -351,8 +353,9 @@ | EvalBreak is_exception apStack_ref ix mod_uniq resume_ctxt ccs <- status = do hsc_env <- getSession- resume_ctxt_fhv <- liftIO $ mkFinalizedHValue hsc_env resume_ctxt- apStack_fhv <- liftIO $ mkFinalizedHValue hsc_env apStack_ref+ let interp = hscInterp hsc_env+ resume_ctxt_fhv <- liftIO $ mkFinalizedHValue interp resume_ctxt+ apStack_fhv <- liftIO $ mkFinalizedHValue interp apStack_ref let hmi = expectJust "handleRunStatus" $ lookupHptDirectly (hsc_HPT hsc_env) (mkUniqueGrimily mod_uniq)@@ -381,8 +384,8 @@ = do hsc_env <- getSession let final_ic = extendInteractiveContextWithIds (hsc_IC hsc_env) final_ids final_names = map getName final_ids- dl = hsc_loader hsc_env- liftIO $ Loader.extendLoadedEnv dl (zip final_names hvals)+ interp = hscInterp hsc_env+ liftIO $ Loader.extendLoadedEnv interp (zip final_names hvals) hsc_env' <- liftIO $ rttiEnvironment hsc_env{hsc_IC=final_ic} setSession hsc_env' return (ExecComplete (Right final_names) allocs)@@ -397,8 +400,9 @@ #endif -resumeExec :: GhcMonad m => (SrcSpan->Bool) -> SingleStep -> m ExecResult-resumeExec canLogSpan step+resumeExec :: GhcMonad m => (SrcSpan->Bool) -> SingleStep -> Maybe Int+ -> m ExecResult+resumeExec canLogSpan step mbCnt = do hsc_env <- getSession let ic = hsc_IC hsc_env@@ -423,8 +427,9 @@ new_names = [ n | thing <- ic_tythings ic , let n = getName thing , not (n `elem` old_names) ]- dl = hsc_loader hsc_env- liftIO $ Loader.deleteFromLoadedEnv dl new_names+ interp = hscInterp hsc_env+ dflags = hsc_dflags hsc_env+ liftIO $ Loader.deleteFromLoadedEnv interp new_names case r of Resume { resumeStmt = expr, resumeContext = fhv@@ -433,7 +438,11 @@ , resumeSpan = span , resumeHistory = hist } -> withVirtualCWD $ do- status <- liftIO $ GHCi.resumeStmt hsc_env (isStep step) fhv+ when (isJust mb_brkpt && isJust mbCnt) $ do+ setupBreakpoint hsc_env (fromJust mb_brkpt) (fromJust mbCnt)+ -- When the user specified a break ignore count, set it+ -- in the interpreter+ status <- liftIO $ GHCi.resumeStmt interp dflags (isStep step) fhv let prevHistoryLst = fromListBL 50 hist hist' = case mb_brkpt of Nothing -> prevHistoryLst@@ -443,6 +452,18 @@ fromListBL 50 hist handleRunStatus step expr bindings final_ids status hist' +setupBreakpoint :: GhcMonad m => HscEnv -> BreakInfo -> Int -> m () -- #19157+setupBreakpoint hsc_env brkInfo cnt = do+ let modl :: Module = breakInfo_module brkInfo+ breaks hsc_env modl = getModBreaks $ expectJust "setupBreakpoint" $+ lookupHpt (hsc_HPT hsc_env) (moduleName modl)+ ix = breakInfo_number brkInfo+ modBreaks = breaks hsc_env modl+ breakarray = modBreaks_flags modBreaks+ interp = hscInterp hsc_env+ _ <- liftIO $ GHCi.storeBreakpoint interp breakarray ix cnt+ pure ()+ back :: GhcMonad m => Int -> m ([Name], Int, SrcSpan, String) back n = moveHist (+n) @@ -518,9 +539,9 @@ ictxt0 = hsc_IC hsc_env ictxt1 = extendInteractiveContextWithIds ictxt0 [exn_id]- dl = hsc_loader hsc_env+ interp = hscInterp hsc_env --- Loader.extendLoadedEnv dl [(exn_name, apStack)]+ Loader.extendLoadedEnv interp [(exn_name, apStack)] return (hsc_env{ hsc_IC = ictxt1 }, [exn_name], span, "<exception thrown>") -- Just case: we stopped at a breakpoint, we have information about the location@@ -529,6 +550,7 @@ let hmi = expectJust "bindLocalsAtBreakpoint" $ lookupHpt (hsc_HPT hsc_env) (moduleName breakInfo_module)+ interp = hscInterp hsc_env breaks = getModBreaks hmi info = expectJust "bindLocalsAtBreakpoint2" $ IntMap.lookup breakInfo_number (modBreaks_breakInfo breaks)@@ -551,7 +573,7 @@ -- So that we don't fall over in a heap when this happens, just don't -- bind any free variables instead, and we emit a warning. mb_hValues <-- mapM (getBreakpointVar hsc_env apStack_fhv . fromIntegral) offsets+ mapM (getBreakpointVar interp apStack_fhv . fromIntegral) offsets when (any isNothing mb_hValues) $ debugTraceMsg (hsc_logger hsc_env) (hsc_dflags hsc_env) 1 $ text "Warning: _result has been evaluated, some bindings have been lost"@@ -575,11 +597,10 @@ ictxt0 = hsc_IC hsc_env ictxt1 = extendInteractiveContextWithIds ictxt0 final_ids names = map idName new_ids- dl = hsc_loader hsc_env let fhvs = catMaybes mb_hValues- Loader.extendLoadedEnv dl (zip names fhvs)- when result_ok $ Loader.extendLoadedEnv dl [(result_name, apStack_fhv)]+ Loader.extendLoadedEnv interp (zip names fhvs)+ when result_ok $ Loader.extendLoadedEnv interp [(result_name, apStack_fhv)] hsc_env1 <- rttiEnvironment hsc_env{ hsc_IC = ictxt1 } return (hsc_env1, if result_ok then result_name:names else names, span, decl) where@@ -675,7 +696,7 @@ There are 3 situations where items are removed from the Id list (or replaced with `Nothing`):- 1.) If function `GHC.CoreToByteCode.schemeER_wrk` (which creates+ 1.) If function `GHC.StgToByteCode.schemeER_wrk` (which creates the Id list) doesn't find an Id in the ByteCode environement. 2.) If function `GHC.Runtime.Eval.bindLocalsAtBreakpoint` filters out unboxed elements from the Id list, because GHCi cannot@@ -697,11 +718,12 @@ hsc_env <- getSession let ic = hsc_IC hsc_env resume = ic_resume ic+ interp = hscInterp hsc_env case resume of [] -> return False r:rs -> do setSession hsc_env{ hsc_IC = ic { ic_resume = rs } }- liftIO $ abandonStmt hsc_env (resumeContext r)+ liftIO $ abandonStmt interp (resumeContext r) return True abandonAll :: GhcMonad m => m Bool@@ -709,11 +731,12 @@ hsc_env <- getSession let ic = hsc_IC hsc_env resume = ic_resume ic+ interp = hscInterp hsc_env case resume of [] -> return False rs -> do setSession hsc_env{ hsc_IC = ic { ic_resume = [] } }- liftIO $ mapM_ (abandonStmt hsc_env. resumeContext) rs+ liftIO $ mapM_ (abandonStmt interp. resumeContext) rs return True -- -----------------------------------------------------------------------------@@ -782,7 +805,7 @@ (err : _, _) -> Left err } where idecls :: [LImportDecl GhcPs]- idecls = [noLoc d | IIDecl d <- imports]+ idecls = [noLocA d | IIDecl d <- imports] imods :: [ModuleName] imods = [m | IIModule m <- imports]@@ -879,7 +902,7 @@ getDocs :: GhcMonad m => Name- -> m (Either GetDocsFailure (Maybe HsDocString, Map Int HsDocString))+ -> m (Either GetDocsFailure (Maybe HsDocString, IntMap HsDocString)) -- TODO: What about docs for constructors etc.? getDocs name = withSession $ \hsc_env -> do@@ -896,7 +919,7 @@ if isNothing mb_doc_hdr && Map.null dmap && Map.null amap then pure (Left (NoDocsInIface mod compiled)) else pure (Right ( Map.lookup name dmap- , Map.findWithDefault Map.empty name amap))+ , Map.findWithDefault mempty name amap)) where compiled = -- TODO: Find a more direct indicator.@@ -1168,15 +1191,19 @@ -- the resulting HValue. compileParsedExprRemote :: GhcMonad m => LHsExpr GhcPs -> m ForeignHValue compileParsedExprRemote expr@(L loc _) = withSession $ \hsc_env -> do+ let dflags = hsc_dflags hsc_env+ let interp = hscInterp hsc_env+ -- > let _compileParsedExpr = expr -- Create let stmt from expr to make hscParsedStmt happy. -- We will ignore the returned [Id], namely [expr_id], and not really -- create a new binding. let expr_fs = fsLit "_compileParsedExpr"- expr_name = mkInternalName (getUnique expr_fs) (mkTyVarOccFS expr_fs) loc- let_stmt = L loc . LetStmt noExtField . L loc . (HsValBinds noExtField) $- ValBinds noExtField- (unitBag $ mkHsVarBind loc (getRdrName expr_name) expr) []+ loc' = locA loc+ expr_name = mkInternalName (getUnique expr_fs) (mkTyVarOccFS expr_fs) loc'+ let_stmt = L loc . LetStmt noAnn . (HsValBinds noAnn) $+ ValBinds NoAnnSortKey+ (unitBag $ mkHsVarBind loc' (getRdrName expr_name) expr) [] pstmt <- liftIO $ hscParsedStmt hsc_env let_stmt let (hvals_io, fix_env) = case pstmt of@@ -1184,7 +1211,7 @@ _ -> panic "compileParsedExprRemote" updateFixityEnv fix_env- status <- liftIO $ evalStmt hsc_env False (EvalThis hvals_io)+ status <- liftIO $ evalStmt interp dflags False (EvalThis hvals_io) case status of EvalComplete _ (EvalSuccess [hval]) -> return hval EvalComplete _ (EvalException e) ->@@ -1194,9 +1221,8 @@ compileParsedExpr :: GhcMonad m => LHsExpr GhcPs -> m HValue compileParsedExpr expr = do fhv <- compileParsedExprRemote expr- hsc_env <- getSession- liftIO $ withInterp hsc_env $ \interp ->- wormhole interp fhv+ interp <- hscInterp <$> getSession+ liftIO $ wormhole interp fhv -- | Compile an expression, run it and return the result as a Dynamic. dynCompileExpr :: GhcMonad m => String -> m Dynamic@@ -1204,7 +1230,7 @@ parsed_expr <- parseExpr expr -- > Data.Dynamic.toDyn expr let loc = getLoc parsed_expr- to_dyn_expr = mkHsApp (L loc . HsVar noExtField . L loc $ getRdrName toDynName)+ to_dyn_expr = mkHsApp (L loc . HsVar noExtField . L (la2na loc) $ getRdrName toDynName) parsed_expr hval <- compileParsedExpr to_dyn_expr return (unsafeCoerce hval :: Dynamic)@@ -1233,23 +1259,25 @@ obtainTermFromVal :: HscEnv -> Int -> Bool -> Type -> a -> IO Term #if defined(HAVE_INTERNAL_INTERPRETER)-obtainTermFromVal hsc_env bound force ty x = withInterp hsc_env $ \case+obtainTermFromVal hsc_env bound force ty x = case interpInstance interp of InternalInterp -> cvObtainTerm hsc_env bound force ty (unsafeCoerce x) #else-obtainTermFromVal hsc_env _bound _force _ty _x = withInterp hsc_env $ \case+obtainTermFromVal hsc_env _bound _force _ty _x = case interpInstance interp of #endif ExternalInterp {} -> throwIO (InstallationError "this operation requires -fno-external-interpreter")+ where+ interp = hscInterp hsc_env obtainTermFromId :: HscEnv -> Int -> Bool -> Id -> IO Term obtainTermFromId hsc_env bound force id = do- hv <- Loader.loadName hsc_env (varName id)+ hv <- Loader.loadName (hscInterp hsc_env) hsc_env (varName id) cvObtainTerm hsc_env bound force (idType id) hv -- Uses RTTI to reconstruct the type of an Id, making it less polymorphic reconstructType :: HscEnv -> Int -> Id -> IO (Maybe Type) reconstructType hsc_env bound id = do- hv <- Loader.loadName hsc_env (varName id)+ hv <- Loader.loadName (hscInterp hsc_env) hsc_env (varName id) cvReconstructType hsc_env bound (idType id) hv mkRuntimeUnkTyVar :: Name -> Kind -> TyVar
compiler/GHC/Runtime/Heap/Inspect.hs view
@@ -730,6 +730,8 @@ text "Type obtained: " <> ppr (termType term)) return term where+ interp = hscInterp hsc_env+ go :: Int -> Type -> Type -> ForeignHValue -> TcM Term -- I believe that my_ty should not have any enclosing -- foralls, nor any free RuntimeUnk skolems;@@ -740,18 +742,18 @@ go 0 my_ty _old_ty a = do traceTR (text "Gave up reconstructing a term after" <> int max_depth <> text " steps")- clos <- trIO $ GHCi.getClosure hsc_env a+ clos <- trIO $ GHCi.getClosure interp a return (Suspension (tipe (info clos)) my_ty a Nothing) go !max_depth my_ty old_ty a = do let monomorphic = not(isTyVarTy my_ty) -- This ^^^ is a convention. The ancestor tests for -- monomorphism and passes a type instead of a tv- clos <- trIO $ GHCi.getClosure hsc_env a+ clos <- trIO $ GHCi.getClosure interp a case clos of -- Thunks we may want to force t | isThunk t && force -> do traceTR (text "Forcing a " <> text (show (fmap (const ()) t)))- evalRslt <- liftIO $ GHCi.seqHValue hsc_env a+ evalRslt <- liftIO $ GHCi.seqHValue interp hsc_env a case evalRslt of -- #2950 EvalSuccess _ -> go (pred max_depth) my_ty old_ty a EvalException ex -> do@@ -764,7 +766,7 @@ -- of entering the TSO or BLOCKING_QUEUE (which leads to runtime panic). BlackholeClosure{indirectee=ind} -> do traceTR (text "Following a BLACKHOLE")- ind_clos <- trIO (GHCi.getClosure hsc_env ind)+ ind_clos <- trIO (GHCi.getClosure interp ind) let return_bh_value = return (Suspension BLACKHOLE my_ty a Nothing) case ind_clos of -- TSO and BLOCKING_QUEUE cases@@ -995,6 +997,8 @@ traceTR (text "RTTI completed. Type obtained:" <+> ppr new_ty) return new_ty where+ interp = hscInterp hsc_env+ -- search :: m Bool -> ([a] -> [a] -> [a]) -> [a] -> m () search _ _ _ 0 = traceTR (text "Failed to reconstruct a type after " <> int max_depth <> text " steps")@@ -1009,7 +1013,7 @@ go :: Type -> ForeignHValue -> TR [(Type, ForeignHValue)] go my_ty a = do traceTR (text "go" <+> ppr my_ty)- clos <- trIO $ GHCi.getClosure hsc_env a+ clos <- trIO $ GHCi.getClosure interp a case clos of BlackholeClosure{indirectee=ind} -> go my_ty ind IndClosure{indirectee=ind} -> go my_ty ind
compiler/GHC/Runtime/Interpreter.hs view
@@ -1,13 +1,17 @@-{-# LANGUAGE RecordWildCards, ScopedTypeVariables, BangPatterns, CPP #-}-{-# LANGUAGE LambdaCase #-}+{-# LANGUAGE BangPatterns #-}+{-# LANGUAGE CPP #-}+{-# LANGUAGE RecordWildCards #-}+{-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TupleSections #-} -- | Interacting with the iserv interpreter, whether it is running on an -- external process or in the current process. -- module GHC.Runtime.Interpreter- ( -- * High-level interface to the interpreter- evalStmt, EvalStatus_(..), EvalStatus, EvalResult(..), EvalExpr(..)+ ( module GHC.Runtime.Interpreter.Types++ -- * High-level interface to the interpreter+ , evalStmt, EvalStatus_(..), EvalStatus, EvalResult(..), EvalExpr(..) , resumeStmt , abandonStmt , evalIO@@ -19,7 +23,7 @@ , mkCostCentres , costCentreStackInfo , newBreakArray- , enableBreakpoint+ , storeBreakpoint , breakpointStatus , getBreakpointVar , getClosure@@ -42,8 +46,8 @@ , findSystemLibrary -- * Lower-level API using messages- , iservCmd, Message(..), withIServ, withIServ_- , withInterp, hscInterp, stopInterp+ , interpCmd, Message(..), withIServ, withIServ_+ , hscInterp, stopInterp , iservCall, readIServ, writeIServ , purgeLookupSymbolCache , freeHValueRefs@@ -186,23 +190,17 @@ -- external iserv process, and the response is deserialized (hence the -- @Binary@ constraint). With @-fno-external-interpreter@ we execute -- the command directly here.-iservCmd :: Binary a => HscEnv -> Message a -> IO a-iservCmd hsc_env msg = withInterp hsc_env $ \case+interpCmd :: Binary a => Interp -> Message a -> IO a+interpCmd interp msg = case interpInstance interp of #if defined(HAVE_INTERNAL_INTERPRETER) InternalInterp -> run msg -- Just run it directly #endif- (ExternalInterp c i) -> withIServ_ c i $ \iserv ->+ ExternalInterp c i -> withIServ_ c i $ \iserv -> uninterruptibleMask_ $ -- Note [uninterruptibleMask_] iservCall iserv msg --- | Execute an action with the interpreter------ Fails if no target code interpreter is available-withInterp :: HscEnv -> (Interp -> IO a) -> IO a-withInterp hsc_env action = action (hscInterp hsc_env)---- | Retrieve the targe code interpreter+-- | Retrieve the target code interpreter -- -- Fails if no target code interpreter is available hscInterp :: HscEnv -> Interp@@ -210,7 +208,7 @@ Nothing -> throw (InstallationError "Couldn't find a target code interpreter. Try with -fexternal-interpreter") Just i -> i --- Note [uninterruptibleMask_ and iservCmd]+-- Note [uninterruptibleMask_ and interpCmd] -- -- If we receive an async exception, such as ^C, while communicating -- with the iserv process then we will be out-of-sync and not be able@@ -261,13 +259,15 @@ -- | Execute an action of type @IO [a]@, returning 'ForeignHValue's for -- each of the results. evalStmt- :: HscEnv -> Bool -> EvalExpr ForeignHValue+ :: Interp+ -> DynFlags -- used by mkEvalOpts+ -> Bool -- "step" for mkEvalOpts+ -> EvalExpr ForeignHValue -> IO (EvalStatus_ [ForeignHValue] [HValueRef])-evalStmt hsc_env step foreign_expr = do- let dflags = hsc_dflags hsc_env+evalStmt interp dflags step foreign_expr = do status <- withExpr foreign_expr $ \expr ->- iservCmd hsc_env (EvalStmt (mkEvalOpts dflags step) expr)- handleEvalStatus hsc_env status+ interpCmd interp (EvalStmt (mkEvalOpts dflags step) expr)+ handleEvalStatus interp status where withExpr :: EvalExpr ForeignHValue -> (EvalExpr HValueRef -> IO a) -> IO a withExpr (EvalThis fhv) cont =@@ -278,23 +278,26 @@ cont (EvalApp fl' fr') resumeStmt- :: HscEnv -> Bool -> ForeignRef (ResumeContext [HValueRef])+ :: Interp+ -> DynFlags -- used by mkEvalOpts+ -> Bool -- "step" for mkEvalOpts+ -> ForeignRef (ResumeContext [HValueRef]) -> IO (EvalStatus_ [ForeignHValue] [HValueRef])-resumeStmt hsc_env step resume_ctxt = do- let dflags = hsc_dflags hsc_env+resumeStmt interp dflags step resume_ctxt = do status <- withForeignRef resume_ctxt $ \rhv ->- iservCmd hsc_env (ResumeStmt (mkEvalOpts dflags step) rhv)- handleEvalStatus hsc_env status+ interpCmd interp (ResumeStmt (mkEvalOpts dflags step) rhv)+ handleEvalStatus interp status -abandonStmt :: HscEnv -> ForeignRef (ResumeContext [HValueRef]) -> IO ()-abandonStmt hsc_env resume_ctxt =+abandonStmt :: Interp -> ForeignRef (ResumeContext [HValueRef]) -> IO ()+abandonStmt interp resume_ctxt = withForeignRef resume_ctxt $ \rhv ->- iservCmd hsc_env (AbandonStmt rhv)+ interpCmd interp (AbandonStmt rhv) handleEvalStatus- :: HscEnv -> EvalStatus [HValueRef]+ :: Interp+ -> EvalStatus [HValueRef] -> IO (EvalStatus_ [ForeignHValue] [HValueRef])-handleEvalStatus hsc_env status =+handleEvalStatus interp status = case status of EvalBreak a b c d e f -> return (EvalBreak a b c d e f) EvalComplete alloc res ->@@ -302,48 +305,47 @@ where addFinalizer (EvalException e) = return (EvalException e) addFinalizer (EvalSuccess rs) =- EvalSuccess <$> mapM (mkFinalizedHValue hsc_env) rs+ EvalSuccess <$> mapM (mkFinalizedHValue interp) rs -- | Execute an action of type @IO ()@-evalIO :: HscEnv -> ForeignHValue -> IO ()-evalIO hsc_env fhv =+evalIO :: Interp -> ForeignHValue -> IO ()+evalIO interp fhv = liftIO $ withForeignRef fhv $ \fhv ->- iservCmd hsc_env (EvalIO fhv) >>= fromEvalResult+ interpCmd interp (EvalIO fhv) >>= fromEvalResult -- | Execute an action of type @IO String@-evalString :: HscEnv -> ForeignHValue -> IO String-evalString hsc_env fhv =+evalString :: Interp -> ForeignHValue -> IO String+evalString interp fhv = liftIO $ withForeignRef fhv $ \fhv ->- iservCmd hsc_env (EvalString fhv) >>= fromEvalResult+ interpCmd interp (EvalString fhv) >>= fromEvalResult -- | Execute an action of type @String -> IO String@-evalStringToIOString :: HscEnv -> ForeignHValue -> String -> IO String-evalStringToIOString hsc_env fhv str =+evalStringToIOString :: Interp -> ForeignHValue -> String -> IO String+evalStringToIOString interp fhv str = liftIO $ withForeignRef fhv $ \fhv ->- iservCmd hsc_env (EvalStringToString fhv str) >>= fromEvalResult+ interpCmd interp (EvalStringToString fhv str) >>= fromEvalResult -- | Allocate and store the given bytes in memory, returning a pointer -- to the memory in the remote process.-mallocData :: HscEnv -> ByteString -> IO (RemotePtr ())-mallocData hsc_env bs = iservCmd hsc_env (MallocData bs)+mallocData :: Interp -> ByteString -> IO (RemotePtr ())+mallocData interp bs = interpCmd interp (MallocData bs) -mkCostCentres- :: HscEnv -> String -> [(String,String)] -> IO [RemotePtr CostCentre]-mkCostCentres hsc_env mod ccs =- iservCmd hsc_env (MkCostCentres mod ccs)+mkCostCentres :: Interp -> String -> [(String,String)] -> IO [RemotePtr CostCentre]+mkCostCentres interp mod ccs =+ interpCmd interp (MkCostCentres mod ccs) -- | Create a set of BCOs that may be mutually recursive.-createBCOs :: HscEnv -> [ResolvedBCO] -> IO [HValueRef]-createBCOs hsc_env rbcos = do- n_jobs <- case parMakeCount (hsc_dflags hsc_env) of+createBCOs :: Interp -> DynFlags -> [ResolvedBCO] -> IO [HValueRef]+createBCOs interp dflags rbcos = do+ n_jobs <- case parMakeCount dflags of Nothing -> liftIO getNumProcessors Just n -> return n -- Serializing ResolvedBCO is expensive, so if we're in parallel mode -- (-j<n>) parallelise the serialization. if (n_jobs == 1) then- iservCmd hsc_env (CreateBCOs [runPut (put rbcos)])+ interpCmd interp (CreateBCOs [runPut (put rbcos)]) else do old_caps <- getNumCapabilities@@ -352,7 +354,7 @@ else bracket_ (setNumCapabilities n_jobs) (setNumCapabilities old_caps) (void $ evaluate puts)- iservCmd hsc_env (CreateBCOs puts)+ interpCmd interp (CreateBCOs puts) where puts = parMap doChunk (chunkList 100 rbcos) @@ -365,56 +367,57 @@ parMap f (x:xs) = fx `par` (fxs `pseq` (fx : fxs)) where fx = f x; fxs = parMap f xs -addSptEntry :: HscEnv -> Fingerprint -> ForeignHValue -> IO ()-addSptEntry hsc_env fpr ref =+addSptEntry :: Interp -> Fingerprint -> ForeignHValue -> IO ()+addSptEntry interp fpr ref = withForeignRef ref $ \val ->- iservCmd hsc_env (AddSptEntry fpr val)+ interpCmd interp (AddSptEntry fpr val) -costCentreStackInfo :: HscEnv -> RemotePtr CostCentreStack -> IO [String]-costCentreStackInfo hsc_env ccs =- iservCmd hsc_env (CostCentreStackInfo ccs)+costCentreStackInfo :: Interp -> RemotePtr CostCentreStack -> IO [String]+costCentreStackInfo interp ccs =+ interpCmd interp (CostCentreStackInfo ccs) -newBreakArray :: HscEnv -> Int -> IO (ForeignRef BreakArray)-newBreakArray hsc_env size = do- breakArray <- iservCmd hsc_env (NewBreakArray size)- mkFinalizedHValue hsc_env breakArray+newBreakArray :: Interp -> Int -> IO (ForeignRef BreakArray)+newBreakArray interp size = do+ breakArray <- interpCmd interp (NewBreakArray size)+ mkFinalizedHValue interp breakArray -enableBreakpoint :: HscEnv -> ForeignRef BreakArray -> Int -> Bool -> IO ()-enableBreakpoint hsc_env ref ix b =+storeBreakpoint :: Interp -> ForeignRef BreakArray -> Int -> Int -> IO ()+storeBreakpoint interp ref ix cnt = do -- #19157 withForeignRef ref $ \breakarray ->- iservCmd hsc_env (EnableBreakpoint breakarray ix b)+ interpCmd interp (SetupBreakpoint breakarray ix cnt) -breakpointStatus :: HscEnv -> ForeignRef BreakArray -> Int -> IO Bool-breakpointStatus hsc_env ref ix =+breakpointStatus :: Interp -> ForeignRef BreakArray -> Int -> IO Bool+breakpointStatus interp ref ix = withForeignRef ref $ \breakarray ->- iservCmd hsc_env (BreakpointStatus breakarray ix)+ interpCmd interp (BreakpointStatus breakarray ix) -getBreakpointVar :: HscEnv -> ForeignHValue -> Int -> IO (Maybe ForeignHValue)-getBreakpointVar hsc_env ref ix =+getBreakpointVar :: Interp -> ForeignHValue -> Int -> IO (Maybe ForeignHValue)+getBreakpointVar interp ref ix = withForeignRef ref $ \apStack -> do- mb <- iservCmd hsc_env (GetBreakpointVar apStack ix)- mapM (mkFinalizedHValue hsc_env) mb+ mb <- interpCmd interp (GetBreakpointVar apStack ix)+ mapM (mkFinalizedHValue interp) mb -getClosure :: HscEnv -> ForeignHValue -> IO (Heap.GenClosure ForeignHValue)-getClosure hsc_env ref =+getClosure :: Interp -> ForeignHValue -> IO (Heap.GenClosure ForeignHValue)+getClosure interp ref = withForeignRef ref $ \hval -> do- mb <- iservCmd hsc_env (GetClosure hval)- mapM (mkFinalizedHValue hsc_env) mb+ mb <- interpCmd interp (GetClosure hval)+ mapM (mkFinalizedHValue interp) mb -- | Send a Seq message to the iserv process to force a value #2950-seqHValue :: HscEnv -> ForeignHValue -> IO (EvalResult ())-seqHValue hsc_env ref =- withForeignRef ref $ \hval ->- iservCmd hsc_env (Seq hval) >>= handleSeqHValueStatus hsc_env+seqHValue :: Interp -> HscEnv -> ForeignHValue -> IO (EvalResult ())+seqHValue interp hsc_env ref =+ withForeignRef ref $ \hval -> do+ status <- interpCmd interp (Seq hval)+ handleSeqHValueStatus interp hsc_env status -- | Process the result of a Seq or ResumeSeq message. #2950-handleSeqHValueStatus :: HscEnv -> EvalStatus () -> IO (EvalResult ())-handleSeqHValueStatus hsc_env eval_status =+handleSeqHValueStatus :: Interp -> HscEnv -> EvalStatus () -> IO (EvalResult ())+handleSeqHValueStatus interp hsc_env eval_status = case eval_status of (EvalBreak is_exception _ ix mod_uniq resume_ctxt _) -> do -- A breakpoint was hit; inform the user and tell them -- which breakpoint was hit.- resume_ctxt_fhv <- liftIO $ mkFinalizedHValue hsc_env resume_ctxt+ resume_ctxt_fhv <- liftIO $ mkFinalizedHValue interp resume_ctxt let hmi = expectJust "handleRunStatus" $ lookupHptDirectly (hsc_HPT hsc_env) (mkUniqueGrimily mod_uniq)@@ -425,8 +428,9 @@ putStrLn ("*** Ignoring breakpoint " ++ (showSDoc (hsc_dflags hsc_env) $ sdocBpLoc bp)) -- resume the seq (:force) processing in the iserv process- withForeignRef resume_ctxt_fhv $ \hval ->- iservCmd hsc_env (ResumeSeq hval) >>= handleSeqHValueStatus hsc_env+ withForeignRef resume_ctxt_fhv $ \hval -> do+ status <- interpCmd interp (ResumeSeq hval)+ handleSeqHValueStatus interp hsc_env status (EvalComplete _ r) -> return r where getSeqBpSpan :: Maybe BreakInfo -> SrcSpan@@ -444,11 +448,11 @@ -- ----------------------------------------------------------------------------- -- Interface to the object-code linker -initObjLinker :: HscEnv -> IO ()-initObjLinker hsc_env = iservCmd hsc_env InitLinker+initObjLinker :: Interp -> IO ()+initObjLinker interp = interpCmd interp InitLinker -lookupSymbol :: HscEnv -> FastString -> IO (Maybe (Ptr ()))-lookupSymbol hsc_env str = withInterp hsc_env $ \case+lookupSymbol :: Interp -> FastString -> IO (Maybe (Ptr ()))+lookupSymbol interp str = case interpInstance interp of #if defined(HAVE_INTERNAL_INTERPRETER) InternalInterp -> fmap fromRemotePtr <$> run (LookupSymbol (unpackFS str)) #endif@@ -472,17 +476,16 @@ iserv' = iserv {iservLookupSymbolCache = cache'} return (iserv', Just p) -lookupClosure :: HscEnv -> String -> IO (Maybe HValueRef)-lookupClosure hsc_env str =- iservCmd hsc_env (LookupClosure str)+lookupClosure :: Interp -> String -> IO (Maybe HValueRef)+lookupClosure interp str =+ interpCmd interp (LookupClosure str) -purgeLookupSymbolCache :: HscEnv -> IO ()-purgeLookupSymbolCache hsc_env = case hsc_interp hsc_env of- Nothing -> pure ()+purgeLookupSymbolCache :: Interp -> IO ()+purgeLookupSymbolCache interp = case interpInstance interp of #if defined(HAVE_INTERNAL_INTERPRETER)- Just InternalInterp -> pure ()+ InternalInterp -> pure () #endif- Just (ExternalInterp _ (IServ mstate)) ->+ ExternalInterp _ (IServ mstate) -> modifyMVar_ mstate $ \state -> pure $ case state of IServPending -> state IServRunning iserv -> IServRunning@@ -499,42 +502,42 @@ -- -- Nothing => success -- Just err_msg => failure-loadDLL :: HscEnv -> String -> IO (Maybe String)-loadDLL hsc_env str = iservCmd hsc_env (LoadDLL str)+loadDLL :: Interp -> String -> IO (Maybe String)+loadDLL interp str = interpCmd interp (LoadDLL str) -loadArchive :: HscEnv -> String -> IO ()-loadArchive hsc_env path = do+loadArchive :: Interp -> String -> IO ()+loadArchive interp path = do path' <- canonicalizePath path -- Note [loadObj and relative paths]- iservCmd hsc_env (LoadArchive path')+ interpCmd interp (LoadArchive path') -loadObj :: HscEnv -> String -> IO ()-loadObj hsc_env path = do+loadObj :: Interp -> String -> IO ()+loadObj interp path = do path' <- canonicalizePath path -- Note [loadObj and relative paths]- iservCmd hsc_env (LoadObj path')+ interpCmd interp (LoadObj path') -unloadObj :: HscEnv -> String -> IO ()-unloadObj hsc_env path = do+unloadObj :: Interp -> String -> IO ()+unloadObj interp path = do path' <- canonicalizePath path -- Note [loadObj and relative paths]- iservCmd hsc_env (UnloadObj path')+ interpCmd interp (UnloadObj path') -- Note [loadObj and relative paths] -- the iserv process might have a different current directory from the -- GHC process, so we must make paths absolute before sending them -- over. -addLibrarySearchPath :: HscEnv -> String -> IO (Ptr ())-addLibrarySearchPath hsc_env str =- fromRemotePtr <$> iservCmd hsc_env (AddLibrarySearchPath str)+addLibrarySearchPath :: Interp -> String -> IO (Ptr ())+addLibrarySearchPath interp str =+ fromRemotePtr <$> interpCmd interp (AddLibrarySearchPath str) -removeLibrarySearchPath :: HscEnv -> Ptr () -> IO Bool-removeLibrarySearchPath hsc_env p =- iservCmd hsc_env (RemoveLibrarySearchPath (toRemotePtr p))+removeLibrarySearchPath :: Interp -> Ptr () -> IO Bool+removeLibrarySearchPath interp p =+ interpCmd interp (RemoveLibrarySearchPath (toRemotePtr p)) -resolveObjs :: HscEnv -> IO SuccessFlag-resolveObjs hsc_env = successIf <$> iservCmd hsc_env ResolveObjs+resolveObjs :: Interp -> IO SuccessFlag+resolveObjs interp = successIf <$> interpCmd interp ResolveObjs -findSystemLibrary :: HscEnv -> String -> IO (Maybe String)-findSystemLibrary hsc_env str = iservCmd hsc_env (FindSystemLibrary str)+findSystemLibrary :: Interp -> String -> IO (Maybe String)+findSystemLibrary interp str = interpCmd interp (FindSystemLibrary str) -- -----------------------------------------------------------------------------@@ -588,22 +591,21 @@ } -- | Stop the interpreter-stopInterp :: HscEnv -> IO ()-stopInterp hsc_env = case hsc_interp hsc_env of- Nothing -> pure ()+stopInterp :: Interp -> IO ()+stopInterp interp = case interpInstance interp of #if defined(HAVE_INTERNAL_INTERPRETER)- Just InternalInterp -> pure ()+ InternalInterp -> pure () #endif- Just (ExternalInterp _ (IServ mstate)) ->- MC.mask $ \_restore -> modifyMVar_ mstate $ \state -> do- case state of- IServPending -> pure state -- already stopped- IServRunning i -> do- ex <- getProcessExitCode (iservProcess i)- if isJust ex- then pure ()- else iservCall i Shutdown- pure IServPending+ ExternalInterp _ (IServ mstate) ->+ MC.mask $ \_restore -> modifyMVar_ mstate $ \state -> do+ case state of+ IServPending -> pure state -- already stopped+ IServRunning i -> do+ ex <- getProcessExitCode (iservProcess i)+ if isJust ex+ then pure ()+ else iservCall i Shutdown+ pure IServPending runWithPipes :: (CreateProcess -> IO ProcessHandle) -> FilePath -> [String] -> IO (ProcessHandle, Handle, Handle)@@ -676,24 +678,23 @@ on the GHC side. The finalizer adds the RemoteRef to the iservPendingFrees list in the-IServ record. The next call to iservCmd will free any RemoteRefs in-the list. It was done this way rather than calling iservCmd directly,-because I didn't want to have arbitrary threads calling iservCmd. In+IServ record. The next call to interpCmd will free any RemoteRefs in+the list. It was done this way rather than calling interpCmd directly,+because I didn't want to have arbitrary threads calling interpCmd. In principle it would probably be ok, but it seems less hairy this way. -} -- | Creates a 'ForeignRef' that will automatically release the -- 'RemoteRef' when it is no longer referenced.-mkFinalizedHValue :: HscEnv -> RemoteRef a -> IO (ForeignRef a)-mkFinalizedHValue hsc_env rref = do+mkFinalizedHValue :: Interp -> RemoteRef a -> IO (ForeignRef a)+mkFinalizedHValue interp rref = do let hvref = toHValueRef rref - free <- case hsc_interp hsc_env of- Nothing -> return (pure ())+ free <- case interpInstance interp of #if defined(HAVE_INTERNAL_INTERPRETER)- Just InternalInterp -> return (freeRemoteRef hvref)+ InternalInterp -> return (freeRemoteRef hvref) #endif- Just (ExternalInterp _ (IServ i)) -> return $ modifyMVar_ i $ \state ->+ ExternalInterp _ (IServ i) -> return $ modifyMVar_ i $ \state -> case state of IServPending {} -> pure state -- already shut down IServRunning inst -> do@@ -703,9 +704,9 @@ mkForeignRef rref free -freeHValueRefs :: HscEnv -> [HValueRef] -> IO ()+freeHValueRefs :: Interp -> [HValueRef] -> IO () freeHValueRefs _ [] = return ()-freeHValueRefs hsc_env refs = iservCmd hsc_env (FreeHValueRefs refs)+freeHValueRefs interp refs = interpCmd interp (FreeHValueRefs refs) -- | Convert a 'ForeignRef' to the value it references directly. This -- only works when the interpreter is running in the same process as@@ -717,12 +718,12 @@ -- only works when the interpreter is running in the same process as -- the compiler, so it fails when @-fexternal-interpreter@ is on. wormholeRef :: Interp -> RemoteRef a -> IO a+wormholeRef interp _r = case interpInstance interp of #if defined(HAVE_INTERNAL_INTERPRETER)-wormholeRef InternalInterp _r = localRef _r+ InternalInterp -> localRef _r #endif-wormholeRef (ExternalInterp {}) _r- = throwIO (InstallationError- "this operation requires -fno-external-interpreter")+ ExternalInterp {}+ -> throwIO (InstallationError "this operation requires -fno-external-interpreter") -- ----------------------------------------------------------------------------- -- Misc utils@@ -749,14 +750,16 @@ -- | Interpreter uses Profiling way interpreterProfiled :: Interp -> Bool+interpreterProfiled interp = case interpInstance interp of #if defined(HAVE_INTERNAL_INTERPRETER)-interpreterProfiled InternalInterp = hostIsProfiled+ InternalInterp -> hostIsProfiled #endif-interpreterProfiled (ExternalInterp c _) = iservConfProfiled c+ ExternalInterp c _ -> iservConfProfiled c -- | Interpreter uses Dynamic way interpreterDynamic :: Interp -> Bool+interpreterDynamic interp = case interpInstance interp of #if defined(HAVE_INTERNAL_INTERPRETER)-interpreterDynamic InternalInterp = hostIsDynamic+ InternalInterp -> hostIsDynamic #endif-interpreterDynamic (ExternalInterp c _) = iservConfDynamic c+ ExternalInterp c _ -> iservConfDynamic c
compiler/GHC/Runtime/Loader.hs view
@@ -28,7 +28,7 @@ import GHC.Driver.Plugins import GHC.Linker.Loader ( loadModule, loadName )-import GHC.Runtime.Interpreter ( wormhole, withInterp )+import GHC.Runtime.Interpreter ( wormhole, hscInterp ) import GHC.Runtime.Interpreter.Types import GHC.Tc.Utils.Monad ( initTcInteractive, initIfaceTcRn )@@ -113,11 +113,10 @@ -- #14335 checkExternalInterpreter :: HscEnv -> IO ()-checkExternalInterpreter hsc_env- | Just (ExternalInterp {}) <- hsc_interp hsc_env- = throwIO (InstallationError "Plugins require -fno-external-interpreter")- | otherwise- = pure ()+checkExternalInterpreter hsc_env = case interpInstance <$> hsc_interp hsc_env of+ Just (ExternalInterp {})+ -> throwIO (InstallationError "Plugins require -fno-external-interpreter")+ _ -> pure () loadPlugin' :: OccName -> Name -> HscEnv -> ModuleName -> IO (a, ModIface) loadPlugin' occ_name plugin_name hsc_env mod_name@@ -189,20 +188,21 @@ getValueSafely :: HscEnv -> Name -> Type -> IO (Maybe a) getValueSafely hsc_env val_name expected_type = do mb_hval <- case getValueSafelyHook hooks of- Nothing -> getHValueSafely hsc_env val_name expected_type- Just h -> h hsc_env val_name expected_type+ Nothing -> getHValueSafely interp hsc_env val_name expected_type+ Just h -> h hsc_env val_name expected_type case mb_hval of Nothing -> return Nothing Just hval -> do value <- lessUnsafeCoerce logger dflags "getValueSafely" hval return (Just value) where+ interp = hscInterp hsc_env dflags = hsc_dflags hsc_env logger = hsc_logger hsc_env hooks = hsc_hooks hsc_env -getHValueSafely :: HscEnv -> Name -> Type -> IO (Maybe HValue)-getHValueSafely hsc_env val_name expected_type = do+getHValueSafely :: Interp -> HscEnv -> Name -> Type -> IO (Maybe HValue)+getHValueSafely interp hsc_env val_name expected_type = do forceLoadNameModuleInterface hsc_env (text "contains a name used in an invocation of getHValueSafely") val_name -- Now look up the names for the value and type constructor in the type environment mb_val_thing <- lookupType hsc_env val_name@@ -215,11 +215,13 @@ then do -- Link in the module that contains the value, if it has such a module case nameModule_maybe val_name of- Just mod -> do loadModule hsc_env mod+ Just mod -> do loadModule interp hsc_env mod return () Nothing -> return () -- Find the value that we just linked in and cast it given that we have proved it's type- hval <- withInterp hsc_env $ \interp -> loadName hsc_env val_name >>= wormhole interp+ hval <- do+ v <- loadName interp hsc_env val_name+ wormhole interp v return (Just hval) else return Nothing Just val_thing -> throwCmdLineErrorS dflags $ wrongTyThingError val_name val_thing@@ -257,8 +259,12 @@ lookupRdrNameInModuleForPlugins :: HscEnv -> ModuleName -> RdrName -> IO (Maybe (Name, ModIface)) lookupRdrNameInModuleForPlugins hsc_env mod_name rdr_name = do+ let dflags = hsc_dflags hsc_env+ let fc = hsc_FC hsc_env+ let units = hsc_units hsc_env+ let home_unit = hsc_home_unit hsc_env -- First find the unit the module resides in by searching exposed units and home modules- found_module <- findPluginModule hsc_env mod_name+ found_module <- findPluginModule fc units home_unit dflags mod_name case found_module of Found _ mod -> do -- Find the exports of the module@@ -280,7 +286,6 @@ Nothing -> throwCmdLineErrorS dflags $ hsep [text "Could not determine the exports of the module", ppr mod_name] err -> throwCmdLineErrorS dflags $ cannotFindModule hsc_env mod_name err where- dflags = hsc_dflags hsc_env doc = text "contains a name used in an invocation of lookupRdrNameInModule" wrongTyThingError :: Name -> TyThing -> SDoc
compiler/GHC/Stg/CSE.hs view
@@ -292,8 +292,8 @@ stgCseTopLvlRhs in_scope (StgRhsClosure ext ccs upd args body) = let body' = stgCseExpr (initEnv in_scope) body in StgRhsClosure ext ccs upd args body'-stgCseTopLvlRhs _ (StgRhsCon ccs dataCon args)- = StgRhsCon ccs dataCon args+stgCseTopLvlRhs _ (StgRhsCon ccs dataCon mu ticks args)+ = StgRhsCon ccs dataCon mu ticks args ------------------------------ -- The actual AST traversal --@@ -326,11 +326,11 @@ -- A constructor application. -- To be removed by a variable use when found in the CSE environment-stgCseExpr env (StgConApp dataCon args tys)+stgCseExpr env (StgConApp dataCon n args tys) | Just bndr' <- envLookup dataCon args' env = StgApp bndr' [] | otherwise- = StgConApp dataCon args' tys+ = StgConApp dataCon n args' tys where args' = substArgs env args -- Let bindings@@ -395,7 +395,7 @@ -- The RHS of a binding. -- If it is a constructor application, either short-cut it or extend the environment stgCseRhs :: CseEnv -> OutId -> InStgRhs -> (Maybe (OutId, OutStgRhs), CseEnv)-stgCseRhs env bndr (StgRhsCon ccs dataCon args)+stgCseRhs env bndr (StgRhsCon ccs dataCon mu ticks args) | Just other_bndr <- envLookup dataCon args' env , not (isWeakLoopBreaker (idOccInfo bndr)) -- See Note [Care with loop breakers] = let env' = addSubst bndr other_bndr env@@ -403,7 +403,7 @@ | otherwise = let env' = addDataCon bndr dataCon args' env -- see note [Case 1: CSEing allocated closures]- pair = (bndr, StgRhsCon ccs dataCon args')+ pair = (bndr, StgRhsCon ccs dataCon mu ticks args') in (Just pair, env') where args' = substArgs env args
+ compiler/GHC/Stg/Debug.hs view
@@ -0,0 +1,240 @@+{-# LANGUAGE TupleSections #-}+-- This module contains functions which implement+-- the -finfo-table-map and -fdistinct-constructor-tables flags+module GHC.Stg.Debug(collectDebugInformation) where+++import GHC.Prelude++import GHC.Stg.Syntax++import GHC.Types.Id+import GHC.Types.Tickish+import GHC.Core.DataCon+import GHC.Types.IPE+import GHC.Unit.Module+import GHC.Types.Name ( getName, getOccName, occNameString, nameSrcSpan)+import GHC.Data.FastString+import GHC.Driver.Session++import Control.Monad (when)+import Control.Monad.Trans.Reader+import Control.Monad.Trans.State+import Control.Monad.Trans.Class+import GHC.Types.Unique.Map+import GHC.Types.SrcLoc+import Control.Applicative+import qualified Data.List.NonEmpty as NE+import Data.List.NonEmpty (NonEmpty(..))++data SpanWithLabel = SpanWithLabel RealSrcSpan String++data R = R { rDynFlags :: DynFlags, rModLocation :: ModLocation, rSpan :: Maybe SpanWithLabel }++type M a = ReaderT R (State InfoTableProvMap) a++withSpan :: (RealSrcSpan, String) -> M a -> M a+withSpan (new_s, new_l) act = local maybe_replace act+ where+ maybe_replace r@R{ rModLocation = cur_mod, rSpan = Just (SpanWithLabel old_s _old_l) }+ -- prefer spans from the current module+ | Just (unpackFS $ srcSpanFile old_s) == ml_hs_file cur_mod+ , Just (unpackFS $ srcSpanFile new_s) /= ml_hs_file cur_mod+ = r+ maybe_replace r+ = r { rSpan = Just (SpanWithLabel new_s new_l) }++collectDebugInformation :: DynFlags -> ModLocation -> [StgTopBinding] -> ([StgTopBinding], InfoTableProvMap)+collectDebugInformation dflags ml bs =+ runState (runReaderT (mapM collectTop bs) (R dflags ml Nothing)) emptyInfoTableProvMap++collectTop :: StgTopBinding -> M StgTopBinding+collectTop (StgTopLifted t) = StgTopLifted <$> collectStgBind t+collectTop tb = return tb++collectStgBind :: StgBinding -> M StgBinding+collectStgBind (StgNonRec bndr rhs) = do+ rhs' <- collectStgRhs bndr rhs+ return (StgNonRec bndr rhs')+collectStgBind (StgRec pairs) = do+ es <- mapM (\(b, e) -> (b,) <$> collectStgRhs b e) pairs+ return (StgRec es)++collectStgRhs :: Id -> StgRhs -> M StgRhs+collectStgRhs bndr (StgRhsClosure ext cc us bs e)= do+ e' <- collectExpr e+ recordInfo bndr e'+ return $ StgRhsClosure ext cc us bs e'+collectStgRhs _bndr (StgRhsCon cc dc _mn ticks args) = do+ n' <- numberDataCon dc ticks+ return (StgRhsCon cc dc n' ticks args)+++recordInfo :: Id -> StgExpr -> M ()+recordInfo bndr new_rhs = do+ modLoc <- asks rModLocation+ let+ thisFile = maybe nilFS mkFastString $ ml_hs_file modLoc+ -- A span from the ticks surrounding the new_rhs+ best_span = quickSourcePos thisFile new_rhs+ -- A back-up span if the bndr had a source position, many do not (think internally generated ids)+ bndr_span = (\s -> SpanWithLabel s (occNameString (getOccName bndr)))+ <$> srcSpanToRealSrcSpan (nameSrcSpan (getName bndr))+ recordStgIdPosition bndr best_span bndr_span++collectExpr :: StgExpr -> M StgExpr+collectExpr = go+ where+ go (StgApp occ as) = return $ StgApp occ as+ go (StgLit lit) = return $ StgLit lit+ go (StgConApp dc _mn as tys) = do+ n' <- numberDataCon dc []+ return (StgConApp dc n' as tys)+ go (StgOpApp op as ty) = return (StgOpApp op as ty)+ go (StgCase scrut bndr ty alts) =+ StgCase <$> collectExpr scrut <*> pure bndr <*> pure ty <*> mapM collectAlt alts+ go (StgLet ext bind body) = do+ bind' <- collectStgBind bind+ body' <- go body+ return (StgLet ext bind' body')+ go (StgLetNoEscape ext bind body) = do+ bind' <- collectStgBind bind+ body' <- go body+ return (StgLetNoEscape ext bind' body')++ go (StgTick tick e) = do+ let k = case tick of+ SourceNote ss fp -> withSpan (ss, fp)+ _ -> id+ e' <- k (go e)+ return (StgTick tick e')++collectAlt :: StgAlt -> M StgAlt+collectAlt (ac, bs, e) = (ac, bs, ) <$> collectExpr e++-- | Try to find the best source position surrounding a 'StgExpr'. The+-- heuristic strips ticks from the current expression until it finds one which+-- is from the module currently being compiled. This is the same method that+-- the DWARF information uses to give locations to info tables.+--+-- It is usually a better alternative than using the 'RealSrcSpan' which is carefully+-- propagated downwards by 'withSpan'. It's "quick" because it works only using immediate context rather+-- than looking at the parent context like 'withSpan'+quickSourcePos :: FastString -> StgExpr -> Maybe SpanWithLabel+quickSourcePos cur_mod (StgTick (SourceNote ss m) e)+ | srcSpanFile ss == cur_mod = Just (SpanWithLabel ss m)+ | otherwise = quickSourcePos cur_mod e+quickSourcePos _ _ = Nothing++recordStgIdPosition :: Id -> Maybe SpanWithLabel -> Maybe SpanWithLabel -> M ()+recordStgIdPosition id best_span ss = do+ dflags <- asks rDynFlags+ when (gopt Opt_InfoTableMap dflags) $ do+ cc <- asks rSpan+ --Useful for debugging why a certain Id gets given a certain span+ --pprTraceM "recordStgIdPosition" (ppr id $$ ppr cc $$ ppr best_span $$ ppr ss)+ let mbspan = (\(SpanWithLabel rss d) -> (rss, d)) <$> (best_span <|> cc <|> ss)+ lift $ modify (\env -> env { provClosure = addToUniqMap (provClosure env) (idName id) (idType id, mbspan) })++numberDataCon :: DataCon -> [StgTickish] -> M ConstructorNumber+-- Unboxed tuples and sums do not allocate so they+-- have no info tables.+numberDataCon dc _ | isUnboxedTupleDataCon dc = return NoNumber+numberDataCon dc _ | isUnboxedSumDataCon dc = return NoNumber+numberDataCon dc ts = do+ dflags <- asks rDynFlags+ if not (gopt Opt_DistinctConstructorTables dflags) then return NoNumber else do+ env <- lift get+ mcc <- asks rSpan+ let !mbest_span = (\(SpanWithLabel rss l) -> (rss, l)) <$> (selectTick ts <|> mcc)+ let !dcMap' = alterUniqMap (maybe (Just ((0, mbest_span) :| [] ))+ (\xs@((k, _):|_) -> Just $! ((k + 1, mbest_span) `NE.cons` xs))) (provDC env) dc+ lift $ put (env { provDC = dcMap' })+ let r = lookupUniqMap dcMap' dc+ return $ case r of+ Nothing -> NoNumber+ Just res -> Numbered (fst (NE.head res))++selectTick :: [StgTickish] -> Maybe SpanWithLabel+selectTick [] = Nothing+selectTick (SourceNote rss d : ts ) = selectTick ts <|> Just (SpanWithLabel rss d)+selectTick (_:ts) = selectTick ts++{-+Note [Mapping Info Tables to Source Positions]+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~++This note describes what the `-finfo-table-map` flag achieves.++When debugging memory issues it is very useful to be able to map a specific closure+to a position in the source. The prime example is being able to map a THUNK to+a specific place in the source program, the mapping is usually quite precise because+a fresh info table is created for each distinct THUNK.++There are three parts to the implementation++1. In GHC.Stg.Debug, the SourceNote information is used in order to give a source location to+some specific closures.+2. In StgToCmm, the actually used info tables are recorded in an IORef, this+is important as it's hard to predict beforehand what code generation will do+and which ids will end up in the generated program.+3. During code generation, a mapping from the info table to the statically+determined location is emitted which can then be queried at runtime by+various tools.++-- Giving Source Locations to Closures++At the moment thunk and constructor closures are added to the map. This information+is collected in the `InfoTableProvMap` which provides a mapping from:++1. Data constructors to a list of where they are used.+2. `Name`s and where they originate from.++During the CoreToStg phase, this map is populated whenever something is turned into+a StgRhsClosure or an StgConApp. The current source position is recorded+depending on the location indicated by the surrounding SourceNote.++The functions which add information to the map are `recordStgIdPosition` and+`numberDataCon`.++When the -fdistinct-constructor-tables` flag is turned on then every+usage of a data constructor gets its own distinct info table. This is orchestrated+in `collectExpr` where an incrementing number is used to distinguish each+occurrence of a data constructor.++-- StgToCmm++The info tables which are actually used in the generated program are recorded during the+conversion from STG to Cmm. The used info tables are recorded in the `emitProc` function.+All the used info tables are recorded in the `cgs_used_info` field. This step+is necessary because when the information about names is collected in the previous+phase it's unpredictable about which names will end up needing info tables. If+you don't record which ones are actually used then you end up generating code+which references info tables which don't exist.++-- Code Generation++The output of these two phases is combined together during code generation.+A C stub is generated which+creates the static map from info table pointer to the information about where that+info table was created from. This is created by `ipInitCode` in the same manner as a+C stub is generated for cost centres.++This information can be consumed in two ways.++1. The complete mapping is emitted into the eventlog so that external tools such+as eventlog2html can use the information with the heap profile by info table mode.+2. The `lookupIPE` function can be used via the `whereFrom#` primop to introspect+information about a closure in a running Haskell program.++Note [Distinct Info Tables for Constructors]+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~++In the old times, each usage of a data constructor used the same info table.+This made it impossible to distinguish which actual usuage of a data constructor was+contributing primarily to the allocation in a program. Using the `-fdistinct-info-tables` flag you+can cause code generation to generate a distinct info table for each usage of+a constructor. Then, when inspecting the heap you can see precisely which usage of a constructor+was responsible for each allocation.++-}
compiler/GHC/Stg/DepAnal.hs view
@@ -62,7 +62,7 @@ rhs bounds (StgRhsClosure _ _ _ as e) = expr (extendVarSetList bounds as) e - rhs bounds (StgRhsCon _ _ as) =+ rhs bounds (StgRhsCon _ _ _ _ as) = args bounds as var :: BVs -> Var -> FVs@@ -87,7 +87,7 @@ expr _ StgLit{} = emptyVarSet - expr bounds (StgConApp _ as _) =+ expr bounds (StgConApp _ _ as _) = args bounds as expr bounds (StgOpApp _ as _) = args bounds as
compiler/GHC/Stg/FVs.hs view
@@ -1,3 +1,5 @@+{-# LANGUAGE TypeFamilies #-}+ {- | Non-global free variable analysis on STG terms. This pass annotates non-top-level closure bindings with captured variables. Global variables are not@@ -47,7 +49,7 @@ import GHC.Stg.Syntax import GHC.Types.Id import GHC.Types.Var.Set-import GHC.Core ( Tickish(Breakpoint) )+import GHC.Types.Tickish ( GenTickish(Breakpoint) ) import GHC.Utils.Misc import Data.Maybe ( mapMaybe )@@ -124,7 +126,7 @@ go (StgApp occ as) = (StgApp occ as, unionDVarSet (args env as) (mkFreeVarSet env [occ])) go (StgLit lit) = (StgLit lit, emptyDVarSet)- go (StgConApp dc as tys) = (StgConApp dc as tys, args env as)+ go (StgConApp dc n as tys) = (StgConApp dc n as tys, args env as) go (StgOpApp op as ty) = (StgOpApp op as ty, args env as) go (StgCase scrut bndr ty alts) = (StgCase scrut' bndr ty alts', fvs) where@@ -139,8 +141,8 @@ where (e', fvs) = go e fvs' = unionDVarSet (tickish tick) fvs- tickish (Breakpoint _ ids) = mkDVarSet ids- tickish _ = emptyDVarSet+ tickish (Breakpoint _ _ ids) = mkDVarSet ids+ tickish _ = emptyDVarSet go_bind dc bind body = (dc bind' body', fvs) where@@ -156,7 +158,7 @@ -- See Note [Tracking local binders] (body', body_fvs) = expr (addLocals bndrs env) body fvs = delDVarSetList body_fvs bndrs-rhs env (StgRhsCon ccs dc as) = (StgRhsCon ccs dc as, args env as)+rhs env (StgRhsCon ccs dc mu ts as) = (StgRhsCon ccs dc mu ts as, args env as) alt :: Env -> StgAlt -> (CgStgAlt, DIdSet) alt env (con, bndrs, e) = ((con, bndrs, e'), fvs)
compiler/GHC/Stg/Lift.hs view
@@ -199,9 +199,9 @@ -- as lambda binders, discarding all free vars. -> LlStgRhs -> LiftM OutStgRhs-liftRhs mb_former_fvs rhs@(StgRhsCon ccs con args)+liftRhs mb_former_fvs rhs@(StgRhsCon ccs con mn ts args) = ASSERT2(isNothing mb_former_fvs, text "Should never lift a constructor" $$ pprStgRhs panicStgPprOpts rhs)- StgRhsCon ccs con <$> traverse liftArgs args+ StgRhsCon ccs con mn ts <$> traverse liftArgs args liftRhs Nothing (StgRhsClosure _ ccs upd infos body) = -- This RHS wasn't lifted. withSubstBndrs (map binderInfoBndr infos) $ \bndrs' ->@@ -227,7 +227,7 @@ fvs' <- formerFreeVars f let top_lvl_args = map StgVarArg fvs' ++ args' pure (StgApp f' top_lvl_args)-liftExpr (StgConApp con args tys) = StgConApp con <$> traverse liftArgs args <*> pure tys+liftExpr (StgConApp con mn args tys) = StgConApp con mn <$> traverse liftArgs args <*> pure tys liftExpr (StgOpApp op args ty) = StgOpApp op <$> traverse liftArgs args <*> pure ty liftExpr (StgCase scrut info ty alts) = do scrut' <- liftExpr scrut
compiler/GHC/Stg/Lift/Analysis.hs view
@@ -116,7 +116,7 @@ type instance XLetNoEscape 'LiftLams = Skeleton freeVarsOfRhs :: (XRhsClosure pass ~ DIdSet) => GenStgRhs pass -> DIdSet-freeVarsOfRhs (StgRhsCon _ _ args) = mkDVarSet [ id | StgVarArg id <- args ]+freeVarsOfRhs (StgRhsCon _ _ _ _ args) = mkDVarSet [ id | StgVarArg id <- args ] freeVarsOfRhs (StgRhsClosure fvs _ _ _ _) = fvs -- | Captures details of the syntax tree relevant to the cost model, such as@@ -210,8 +210,8 @@ tagSkeletonExpr :: CgStgExpr -> (Skeleton, IdSet, LlStgExpr) tagSkeletonExpr (StgLit lit) = (NilSk, emptyVarSet, StgLit lit)-tagSkeletonExpr (StgConApp con args tys)- = (NilSk, mkArgOccs args, StgConApp con args tys)+tagSkeletonExpr (StgConApp con mn args tys)+ = (NilSk, mkArgOccs args, StgConApp con mn args tys) tagSkeletonExpr (StgOpApp op args ty) = (NilSk, mkArgOccs args, StgOpApp op args ty) tagSkeletonExpr (StgApp f args)@@ -314,8 +314,8 @@ bndr' = BindsClosure bndr (bndr `elemVarSet` scope_occs) tagSkeletonRhs :: Id -> CgStgRhs -> (Skeleton, IdSet, LlStgRhs)-tagSkeletonRhs _ (StgRhsCon ccs dc args)- = (NilSk, mkArgOccs args, StgRhsCon ccs dc args)+tagSkeletonRhs _ (StgRhsCon ccs dc mn ts args)+ = (NilSk, mkArgOccs args, StgRhsCon ccs dc mn ts args) tagSkeletonRhs bndr (StgRhsClosure fvs ccs upd bndrs body) = (rhs_skel, body_arg_occs, StgRhsClosure fvs ccs upd bndrs' body') where
compiler/GHC/Stg/Lift/Monad.hs view
@@ -194,9 +194,9 @@ removeRhsCCCS (StgRhsClosure ext ccs upd bndrs body) | isCurrentCCS ccs = StgRhsClosure ext dontCareCCS upd bndrs body-removeRhsCCCS (StgRhsCon ccs con args)+removeRhsCCCS (StgRhsCon ccs con mu ts args) | isCurrentCCS ccs- = StgRhsCon dontCareCCS con args+ = StgRhsCon dontCareCCS con mu ts args removeRhsCCCS rhs = rhs -- | The analysis monad consists of the following 'RWST' components:
compiler/GHC/Stg/Lint.hs view
@@ -42,21 +42,23 @@ import GHC.Stg.Syntax import GHC.Driver.Session+import GHC.Core.Lint ( interactiveInScope ) import GHC.Data.Bag ( Bag, emptyBag, isEmptyBag, snocBag, bagToList ) import GHC.Types.Basic ( TopLevelFlag(..), isTopLevel ) import GHC.Types.CostCentre ( isCurrentCCS )-import GHC.Types.Id ( Id, idType, isJoinId, idName )+import GHC.Types.Id import GHC.Types.Var.Set import GHC.Core.DataCon import GHC.Core ( AltCon(..) ) import GHC.Types.Name ( getSrcLoc, nameIsLocalOrFrom )-import GHC.Utils.Error ( Severity(..), mkLocMessage )+import GHC.Utils.Error ( mkLocMessage ) import GHC.Core.Type import GHC.Types.RepType import GHC.Types.SrcLoc import GHC.Utils.Logger import GHC.Utils.Outputable import GHC.Unit.Module ( Module )+import GHC.Runtime.Context ( InteractiveContext ) import qualified GHC.Utils.Error as Err import Control.Applicative ((<|>)) import Control.Monad@@ -64,19 +66,20 @@ lintStgTopBindings :: forall a . (OutputablePass a, BinderP a ~ Id) => Logger -> DynFlags+ -> InteractiveContext -> Module -- ^ module being compiled -> Bool -- ^ have we run Unarise yet? -> String -- ^ who produced the STG? -> [GenStgTopBinding a] -> IO () -lintStgTopBindings logger dflags this_mod unarised whodunnit binds+lintStgTopBindings logger dflags ictxt this_mod unarised whodunnit binds = {-# SCC "StgLint" #-} case initL this_mod unarised opts top_level_binds (lint_binds binds) of Nothing -> return () Just msg -> do- putLogMsg logger dflags NoReason Err.SevDump noSrcSpan+ putLogMsg logger dflags Err.MCDump noSrcSpan $ withPprStyle defaultDumpStyle (vcat [ text "*** Stg Lint ErrMsgs: in" <+> text whodunnit <+> text "***",@@ -89,7 +92,8 @@ opts = initStgPprOpts dflags -- Bring all top-level binds into scope because CoreToStg does not generate -- bindings in dependency order (so we may see a use before its definition).- top_level_binds = mkVarSet (bindersOfTopBinds binds)+ top_level_binds = extendVarSetList (mkVarSet (bindersOfTopBinds binds))+ (interactiveInScope ictxt) lint_binds :: [GenStgTopBinding a] -> LintM () @@ -134,8 +138,10 @@ lintStgRhs rhs opts <- getStgPprOpts -- Check binder doesn't have unlifted type or it's a join point- checkL (isJoinId binder || not (isUnliftedType (idType binder)))- (mkUnliftedTyMsg opts binder rhs)+ checkL ( isJoinId binder+ || not (isUnliftedType (idType binder))+ || isDataConWorkId binder || isDataConWrapId binder) -- until #17521 is fixed+ (mkUnliftedTyMsg opts binder rhs) -- | Top-level bindings can't inherit the cost centre stack from their -- (static) allocation site.@@ -150,7 +156,7 @@ StgRhsClosure _ ccs _ _ _ | isCurrentCCS ccs -> addErrL (text "Top-level StgRhsClosure with CurrentCCS" $$ rhs')- StgRhsCon ccs _ _+ StgRhsCon ccs _ _ _ _ | isCurrentCCS ccs -> addErrL (text "Top-level StgRhsCon with CurrentCCS" $$ rhs') _ -> return ()@@ -165,7 +171,7 @@ addInScopeVars binders $ lintStgExpr expr -lintStgRhs rhs@(StgRhsCon _ con args) = do+lintStgRhs rhs@(StgRhsCon _ con _ _ args) = do when (isUnboxedTupleDataCon con || isUnboxedSumDataCon con) $ do opts <- getStgPprOpts addErrL (text "StgRhsCon is an unboxed tuple or sum application" $$@@ -181,7 +187,7 @@ lintStgVar fun mapM_ lintStgArg args -lintStgExpr app@(StgConApp con args _arg_tys) = do+lintStgExpr app@(StgConApp con _n args _arg_tys) = do -- unboxed sums should vanish during unarise lf <- getLintFlags when (lf_unarised lf && isUnboxedSumDataCon con) $ do@@ -352,7 +358,8 @@ = errs_so_far `snocBag` mk_msg locs where mk_msg (loc:_) = let (l,hdr) = dumpLoc loc- in mkLocMessage SevWarning l (hdr $$ msg)+ in mkLocMessage (Err.mkMCDiagnostic WarningWithoutFlag)+ l (hdr $$ msg) mk_msg [] = msg addLoc :: LintLocInfo -> LintM a -> LintM a
compiler/GHC/Stg/Pipeline.hs view
@@ -24,6 +24,7 @@ import GHC.Stg.CSE ( stgCse ) import GHC.Stg.Lift ( stgLiftLams ) import GHC.Unit.Module ( Module )+import GHC.Runtime.Context ( InteractiveContext ) import GHC.Driver.Session import GHC.Utils.Error@@ -49,11 +50,11 @@ stg2stg :: Logger -> DynFlags -- includes spec of what stg-to-stg passes to do+ -> InteractiveContext -> Module -- module being compiled -> [StgTopBinding] -- input program -> IO [StgTopBinding] -- output program--stg2stg logger dflags this_mod binds+stg2stg logger dflags ictxt this_mod binds = do { dump_when Opt_D_dump_stg_from_core "Initial STG:" binds ; showPass logger dflags "Stg2Stg" -- Do the main business!@@ -75,7 +76,7 @@ where stg_linter unarised | gopt Opt_DoStgLinting dflags- = lintStgTopBindings logger dflags this_mod unarised+ = lintStgTopBindings logger dflags ictxt this_mod unarised | otherwise = \ _whodunnit _binds -> return ()
compiler/GHC/Stg/Stats.hs view
@@ -124,7 +124,7 @@ statRhs :: Bool -> (Id, StgRhs) -> StatEnv -statRhs top (_, StgRhsCon _ _ _)+statRhs top (_, StgRhsCon _ _ _ _ _) = countOne (ConstructorBinds top) statRhs top (_, StgRhsClosure _ _ u _ body)@@ -148,7 +148,7 @@ statExpr (StgApp _ _) = countOne Applications statExpr (StgLit _) = countOne Literals-statExpr (StgConApp _ _ _)= countOne ConstructorApps+statExpr (StgConApp _ _ _ _)= countOne ConstructorApps statExpr (StgOpApp _ _ _) = countOne PrimitiveApps statExpr (StgTick _ e) = statExpr e
compiler/GHC/Stg/Unarise.hs view
@@ -193,6 +193,9 @@ This means that it's safe to wrap `StgArg`s of DataCon applications with `GHC.StgToCmm.Env.NonVoid`, for example. + * Similar to unboxed tuples, Note [Rubbish values] of TupleRep may only+ appear in return position.+ * Alt binders (binders in patterns) are always non-void. * Binders always have zero (for void arguments) or one PrimRep.@@ -207,6 +210,7 @@ import GHC.Types.Basic import GHC.Core import GHC.Core.DataCon+import GHC.Core.TyCon ( isVoidRep ) import GHC.Data.FastString (FastString, mkFastString) import GHC.Types.Id import GHC.Types.Literal@@ -293,9 +297,9 @@ expr' <- unariseExpr rho' expr return (StgRhsClosure ext ccs update_flag args1 expr') -unariseRhs rho (StgRhsCon ccs con args)+unariseRhs rho (StgRhsCon ccs con mu ts args) = ASSERT(not (isUnboxedTupleDataCon con || isUnboxedSumDataCon con))- return (StgRhsCon ccs con (unariseConArgs rho args))+ return (StgRhsCon ccs con mu ts (unariseConArgs rho args)) -------------------------------------------------------------------------------- @@ -325,13 +329,13 @@ unariseExpr _ (StgLit l) = return (StgLit l) -unariseExpr rho (StgConApp dc args ty_args)+unariseExpr rho (StgConApp dc n args ty_args) | Just args' <- unariseMulti_maybe rho dc args ty_args = return (mkTuple args') | otherwise , let args' = unariseConArgs rho args- = return (StgConApp dc args' (map stgArgType args'))+ = return (StgConApp dc n args' (map stgArgType args')) unariseExpr rho (StgOpApp op args ty) = return (StgOpApp op (unariseFunArgs rho args) ty)@@ -345,10 +349,15 @@ -- Handle strict lets for tuples and sums: -- case (# a,b #) of r -> rhs -- and analogously for sums- | StgConApp dc args ty_args <- scrut+ | StgConApp dc _n args ty_args <- scrut , Just args' <- unariseMulti_maybe rho dc args ty_args = elimCase rho args' bndr alt_ty alts + -- See (3) of Note [Rubbish values] in GHC.Types.Literal+ | StgLit lit <- scrut+ , Just args' <- unariseRubbish_maybe lit+ = elimCase rho args' bndr alt_ty alts+ -- general case | otherwise = do scrut' <- unariseExpr rho scrut@@ -379,6 +388,22 @@ | otherwise = Nothing +-- Doesn't return void args.+unariseRubbish_maybe :: Literal -> Maybe [OutStgArg]+unariseRubbish_maybe lit+ | LitRubbish preps <- lit+ , [prep] <- preps+ , not (isVoidRep prep)+ -- Single, non-void PrimRep. Nothing to do!+ = Nothing++ | LitRubbish preps <- lit+ -- Multiple reps, possibly with VoidRep. Eliminate!+ = Just [ StgLitArg (LitRubbish [prep]) | prep <- preps, not (isVoidRep prep) ]++ | otherwise+ = Nothing+ -------------------------------------------------------------------------------- elimCase :: UnariseEnv@@ -719,8 +744,11 @@ -- Here realWorld# is not in the envt, but -- is a void, and so should be eliminated | otherwise -> [StgVarArg x]-unariseConArg _ arg@(StgLitArg lit) =- ASSERT(not (isVoidTy (literalType lit))) -- We have no void literals+unariseConArg _ arg@(StgLitArg lit)+ | Just as <- unariseRubbish_maybe lit+ = as+ | otherwise+ = ASSERT(not (isVoidTy (literalType lit))) -- We have no non-rubbish void literals [arg] unariseConArgs :: UnariseEnv -> [InStgArg] -> [OutStgArg]@@ -756,7 +784,7 @@ isUnboxedTupleBndr = isUnboxedTupleType . idType mkTuple :: [StgArg] -> StgExpr-mkTuple args = StgConApp (tupleDataCon Unboxed (length args)) args (map stgArgType args)+mkTuple args = StgConApp (tupleDataCon Unboxed (length args)) NoNumber args (map stgArgType args) tagAltTy :: AltType tagAltTy = PrimAlt IntRep
+ compiler/GHC/StgToByteCode.hs view
@@ -0,0 +1,2281 @@+{-# LANGUAGE CPP #-}+{-# LANGUAGE DeriveFunctor #-}+{-# LANGUAGE GeneralizedNewtypeDeriving #-}+{-# LANGUAGE RecordWildCards #-}++{-# OPTIONS_GHC -fprof-auto-top #-}+{-# OPTIONS_GHC -Wno-incomplete-uni-patterns #-}++--+-- (c) The University of Glasgow 2002-2006+--++-- | GHC.StgToByteCode: Generate bytecode from STG+module GHC.StgToByteCode ( UnlinkedBCO, byteCodeGen, stgExprToBCOs ) where++#include "GhclibHsVersions.h"++import GHC.Prelude++import GHC.Driver.Session+import GHC.Driver.Env++import GHC.ByteCode.Instr+import GHC.ByteCode.Asm+import GHC.ByteCode.Types++import GHC.Cmm.CallConv+import GHC.Cmm.Expr+import GHC.Cmm.Node+import GHC.Cmm.Utils++import GHC.Platform+import GHC.Platform.Profile++import GHC.Runtime.Interpreter+import GHCi.FFI+import GHCi.RemoteTypes+import GHC.Types.Basic+import GHC.Utils.Outputable+import GHC.Types.Name+import GHC.Types.Id.Make+import GHC.Types.Id+import GHC.Types.ForeignCall+import GHC.Core+import GHC.Types.Literal+import GHC.Builtin.PrimOps+import GHC.Core.Type+import GHC.Types.RepType+import GHC.Core.DataCon+import GHC.Core.TyCon+import GHC.Utils.Misc+import GHC.Utils.Logger+import GHC.Types.Var.Set+import GHC.Builtin.Types ( unboxedUnitTy )+import GHC.Builtin.Types.Prim+import GHC.Core.TyCo.Ppr ( pprType )+import GHC.Utils.Error+import GHC.Types.Unique+import GHC.Builtin.Uniques+import GHC.Builtin.Utils ( primOpId )+import GHC.Data.FastString+import GHC.Utils.Panic+import GHC.StgToCmm.Closure ( NonVoid(..), fromNonVoid, nonVoidIds )+import GHC.StgToCmm.Layout+import GHC.Runtime.Heap.Layout hiding (WordOff, ByteOff, wordsToBytes)+import GHC.Data.Bitmap+import GHC.Data.OrdList+import GHC.Data.Maybe+import GHC.Types.Var.Env+import GHC.Types.Tickish++import Data.List ( genericReplicate, genericLength, intersperse+ , partition, scanl', sort, sortBy, zip4, zip6, nub )+import Foreign+import Control.Monad+import Data.Char++import GHC.Types.Unique.Supply+import GHC.Unit.Module++import Control.Exception+import Data.Array+import Data.Coerce (coerce)+import Data.ByteString (ByteString)+import Data.Map (Map)+import Data.IntMap (IntMap)+import qualified Data.Map as Map+import qualified Data.IntMap as IntMap+import qualified GHC.Data.FiniteMap as Map+import Data.Ord+import GHC.Stack.CCS+import Data.Either ( partitionEithers )++import qualified GHC.Types.CostCentre as CC+import GHC.Stg.Syntax+import GHC.Stg.FVs++-- -----------------------------------------------------------------------------+-- Generating byte code for a complete module++byteCodeGen :: HscEnv+ -> Module+ -> [StgTopBinding]+ -> [TyCon]+ -> Maybe ModBreaks+ -> IO CompiledByteCode+byteCodeGen hsc_env this_mod binds tycs mb_modBreaks+ = withTiming logger dflags+ (text "GHC.StgToByteCode"<+>brackets (ppr this_mod))+ (const ()) $ do+ -- Split top-level binds into strings and others.+ -- See Note [generating code for top-level string literal bindings].+ let (strings, lifted_binds) = partitionEithers $ do -- list monad+ bnd <- binds+ case bnd of+ StgTopLifted bnd -> [Right bnd]+ StgTopStringLit b str -> [Left (b, str)]+ flattenBind (StgNonRec b e) = [(b,e)]+ flattenBind (StgRec bs) = bs+ stringPtrs <- allocateTopStrings interp strings++ us <- mkSplitUniqSupply 'y'+ (BcM_State{..}, proto_bcos) <-+ runBc hsc_env us this_mod mb_modBreaks (mkVarEnv stringPtrs) $ do+ prepd_binds <- mapM bcPrepBind lifted_binds+ let flattened_binds =+ concatMap (flattenBind . annBindingFreeVars) (reverse prepd_binds)+ mapM schemeTopBind flattened_binds++ when (notNull ffis)+ (panic "GHC.StgToByteCode.byteCodeGen: missing final emitBc?")++ dumpIfSet_dyn logger dflags Opt_D_dump_BCOs+ "Proto-BCOs" FormatByteCode+ (vcat (intersperse (char ' ') (map ppr proto_bcos)))++ cbc <- assembleBCOs interp profile proto_bcos tycs (map snd stringPtrs)+ (case modBreaks of+ Nothing -> Nothing+ Just mb -> Just mb{ modBreaks_breakInfo = breakInfo })++ -- Squash space leaks in the CompiledByteCode. This is really+ -- important, because when loading a set of modules into GHCi+ -- we don't touch the CompiledByteCode until the end when we+ -- do linking. Forcing out the thunks here reduces space+ -- usage by more than 50% when loading a large number of+ -- modules.+ evaluate (seqCompiledByteCode cbc)++ return cbc++ where dflags = hsc_dflags hsc_env+ logger = hsc_logger hsc_env+ interp = hscInterp hsc_env+ profile = targetProfile dflags++allocateTopStrings+ :: Interp+ -> [(Id, ByteString)]+ -> IO [(Var, RemotePtr ())]+allocateTopStrings interp topStrings = do+ let !(bndrs, strings) = unzip topStrings+ ptrs <- interpCmd interp $ MallocStrings strings+ return $ zip bndrs ptrs++{-+Note [generating code for top-level string literal bindings]++Here is a summary on how the byte code generator deals with top-level string+literals:++1. Top-level string literal bindings are separated from the rest of the module.++2. The strings are allocated via interpCmd, in allocateTopStrings++3. The mapping from binders to allocated strings (topStrings) are maintained in+ BcM and used when generating code for variable references.+-}++-- -----------------------------------------------------------------------------+-- Generating byte code for an expression++-- Returns: the root BCO for this expression+stgExprToBCOs :: HscEnv+ -> Module+ -> Type+ -> StgRhs+ -> IO UnlinkedBCO+stgExprToBCOs hsc_env this_mod expr_ty expr+ = withTiming logger dflags+ (text "GHC.StgToByteCode"<+>brackets (ppr this_mod))+ (const ()) $ do++ -- the uniques are needed to generate fresh variables when we introduce new+ -- let bindings for ticked expressions+ us <- mkSplitUniqSupply 'y'+ (BcM_State _dflags _us _this_mod _final_ctr mallocd _ _ _, proto_bco)+ <- runBc hsc_env us this_mod Nothing emptyVarEnv $ do+ prepd_expr <- annBindingFreeVars <$>+ bcPrepBind (StgNonRec dummy_id expr)+ case prepd_expr of+ (StgNonRec _ cg_expr) -> schemeR [] (idName dummy_id, cg_expr)+ _ ->+ panic "GHC.StgByteCode.stgExprToBCOs"++ when (notNull mallocd)+ (panic "GHC.StgToByteCode.stgExprToBCOs: missing final emitBc?")++ dumpIfSet_dyn logger dflags Opt_D_dump_BCOs "Proto-BCOs" FormatByteCode+ (ppr proto_bco)++ assembleOneBCO interp profile proto_bco+ where dflags = hsc_dflags hsc_env+ logger = hsc_logger hsc_env+ profile = targetProfile dflags+ interp = hscInterp hsc_env+ -- we need an otherwise unused Id for bytecode generation+ dummy_id = mkSysLocal (fsLit "BCO_toplevel")+ (mkPseudoUniqueE 0)+ Many+ expr_ty+{-+ Prepare the STG for bytecode generation:++ - Ensure that all breakpoints are directly under+ a let-binding, introducing a new binding for+ those that aren't already.++ - Protect Not-necessarily lifted join points, see+ Note [Not-necessarily-lifted join points]++ -}++bcPrepRHS :: StgRhs -> BcM StgRhs+-- explicitly match all constructors so we get a warning if we miss any+bcPrepRHS (StgRhsClosure fvs cc upd args (StgTick bp@Breakpoint{} expr)) = do+ {- If we have a breakpoint directly under an StgRhsClosure we don't+ need to introduce a new binding for it.+ -}+ expr' <- bcPrepExpr expr+ pure (StgRhsClosure fvs cc upd args (StgTick bp expr'))+bcPrepRHS (StgRhsClosure fvs cc upd args expr) =+ StgRhsClosure fvs cc upd args <$> bcPrepExpr expr+bcPrepRHS con@StgRhsCon{} = pure con++bcPrepExpr :: StgExpr -> BcM StgExpr+-- explicitly match all constructors so we get a warning if we miss any+bcPrepExpr (StgTick bp@(Breakpoint tick_ty _ _) rhs)+ | isLiftedTypeKind (typeKind tick_ty) = do+ id <- newId tick_ty+ rhs' <- bcPrepExpr rhs+ let expr' = StgTick bp rhs'+ bnd = StgNonRec id (StgRhsClosure noExtFieldSilent+ CC.dontCareCCS+ ReEntrant+ []+ expr'+ )+ letExp = StgLet noExtFieldSilent bnd (StgApp id [])+ pure letExp+ | otherwise = do+ id <- newId (mkVisFunTyMany realWorldStatePrimTy tick_ty)+ st <- newId realWorldStatePrimTy+ rhs' <- bcPrepExpr rhs+ let expr' = StgTick bp rhs'+ bnd = StgNonRec id (StgRhsClosure noExtFieldSilent+ CC.dontCareCCS+ ReEntrant+ [voidArgId]+ expr'+ )+ pure $ StgLet noExtFieldSilent bnd (StgApp id [StgVarArg st])+bcPrepExpr (StgTick tick rhs) =+ StgTick tick <$> bcPrepExpr rhs+bcPrepExpr (StgLet xlet bnds expr) =+ StgLet xlet <$> bcPrepBind bnds+ <*> bcPrepExpr expr+bcPrepExpr (StgLetNoEscape xlne bnds expr) =+ StgLet xlne <$> bcPrepBind bnds+ <*> bcPrepExpr expr+bcPrepExpr (StgCase expr bndr alt_type alts) =+ StgCase <$> bcPrepExpr expr+ <*> pure bndr+ <*> pure alt_type+ <*> mapM bcPrepAlt alts+bcPrepExpr lit@StgLit{} = pure lit+-- See Note [Not-necessarily-lifted join points], step 3.+bcPrepExpr (StgApp x [])+ | isNNLJoinPoint x = pure $+ StgApp (protectNNLJoinPointId x) [StgVarArg voidPrimId]+bcPrepExpr app@StgApp{} = pure app+bcPrepExpr app@StgConApp{} = pure app+bcPrepExpr app@StgOpApp{} = pure app++bcPrepAlt :: StgAlt -> BcM StgAlt+bcPrepAlt (ac, bndrs, expr) = (,,) ac bndrs <$> bcPrepExpr expr++bcPrepBind :: StgBinding -> BcM StgBinding+-- explicitly match all constructors so we get a warning if we miss any+bcPrepBind (StgNonRec bndr rhs) =+ let (bndr', rhs') = bcPrepSingleBind (bndr, rhs)+ in StgNonRec bndr' <$> bcPrepRHS rhs'+bcPrepBind (StgRec bnds) =+ StgRec <$> mapM ((\(b,r) -> (,) b <$> bcPrepRHS r) . bcPrepSingleBind)+ bnds++bcPrepSingleBind :: (Id, StgRhs) -> (Id, StgRhs)+-- If necessary, modify this Id and body to protect not-necessarily-lifted join points.+-- See Note [Not-necessarily-lifted join points], step 2.+bcPrepSingleBind (x, StgRhsClosure ext cc upd_flag args body)+ | isNNLJoinPoint x+ = ( protectNNLJoinPointId x+ , StgRhsClosure ext cc upd_flag (args ++ [voidArgId]) body)+bcPrepSingleBind bnd = bnd++-- -----------------------------------------------------------------------------+-- Compilation schema for the bytecode generator++type BCInstrList = OrdList BCInstr++wordsToBytes :: Platform -> WordOff -> ByteOff+wordsToBytes platform = fromIntegral . (* platformWordSizeInBytes platform) . fromIntegral++-- Used when we know we have a whole number of words+bytesToWords :: Platform -> ByteOff -> WordOff+bytesToWords platform (ByteOff bytes) =+ let (q, r) = bytes `quotRem` (platformWordSizeInBytes platform)+ in if r == 0+ then fromIntegral q+ else panic $ "GHC.StgToByteCode.bytesToWords: bytes=" ++ show bytes++wordSize :: Platform -> ByteOff+wordSize platform = ByteOff (platformWordSizeInBytes platform)++type Sequel = ByteOff -- back off to this depth before ENTER++type StackDepth = ByteOff++-- | Maps Ids to their stack depth. This allows us to avoid having to mess with+-- it after each push/pop.+type BCEnv = Map Id StackDepth -- To find vars on the stack++{-+ppBCEnv :: BCEnv -> SDoc+ppBCEnv p+ = text "begin-env"+ $$ nest 4 (vcat (map pp_one (sortBy cmp_snd (Map.toList p))))+ $$ text "end-env"+ where+ pp_one (var, ByteOff offset) = int offset <> colon <+> ppr var <+> ppr (bcIdArgReps var)+ cmp_snd x y = compare (snd x) (snd y)+-}++-- Create a BCO and do a spot of peephole optimisation on the insns+-- at the same time.+mkProtoBCO+ :: Platform+ -> name+ -> BCInstrList+ -> Either [CgStgAlt] (CgStgRhs)+ -- ^ original expression; for debugging only+ -> Int+ -> Word16+ -> [StgWord]+ -> Bool -- True <=> is a return point, rather than a function+ -> [FFIInfo]+ -> ProtoBCO name+mkProtoBCO platform nm instrs_ordlist origin arity bitmap_size bitmap is_ret ffis+ = ProtoBCO {+ protoBCOName = nm,+ protoBCOInstrs = maybe_with_stack_check,+ protoBCOBitmap = bitmap,+ protoBCOBitmapSize = bitmap_size,+ protoBCOArity = arity,+ protoBCOExpr = origin,+ protoBCOFFIs = ffis+ }+ where+ -- Overestimate the stack usage (in words) of this BCO,+ -- and if >= iNTERP_STACK_CHECK_THRESH, add an explicit+ -- stack check. (The interpreter always does a stack check+ -- for iNTERP_STACK_CHECK_THRESH words at the start of each+ -- BCO anyway, so we only need to add an explicit one in the+ -- (hopefully rare) cases when the (overestimated) stack use+ -- exceeds iNTERP_STACK_CHECK_THRESH.+ maybe_with_stack_check+ | is_ret && stack_usage < fromIntegral (pc_AP_STACK_SPLIM (platformConstants platform)) = peep_d+ -- don't do stack checks at return points,+ -- everything is aggregated up to the top BCO+ -- (which must be a function).+ -- That is, unless the stack usage is >= AP_STACK_SPLIM,+ -- see bug #1466.+ | stack_usage >= fromIntegral iNTERP_STACK_CHECK_THRESH+ = STKCHECK stack_usage : peep_d+ | otherwise+ = peep_d -- the supposedly common case++ -- We assume that this sum doesn't wrap+ stack_usage = sum (map bciStackUse peep_d)++ -- Merge local pushes+ peep_d = peep (fromOL instrs_ordlist)++ peep (PUSH_L off1 : PUSH_L off2 : PUSH_L off3 : rest)+ = PUSH_LLL off1 (off2-1) (off3-2) : peep rest+ peep (PUSH_L off1 : PUSH_L off2 : rest)+ = PUSH_LL off1 (off2-1) : peep rest+ peep (i:rest)+ = i : peep rest+ peep []+ = []++argBits :: Platform -> [ArgRep] -> [Bool]+argBits _ [] = []+argBits platform (rep : args)+ | isFollowableArg rep = False : argBits platform args+ | otherwise = take (argRepSizeW platform rep) (repeat True) ++ argBits platform args++non_void :: [ArgRep] -> [ArgRep]+non_void = filter nv+ where nv V = False+ nv _ = True++-- -----------------------------------------------------------------------------+-- schemeTopBind++-- Compile code for the right-hand side of a top-level binding++schemeTopBind :: (Id, CgStgRhs) -> BcM (ProtoBCO Name)+schemeTopBind (id, rhs)+ | Just data_con <- isDataConWorkId_maybe id,+ isNullaryRepDataCon data_con = do+ platform <- profilePlatform <$> getProfile+ -- Special case for the worker of a nullary data con.+ -- It'll look like this: Nil = /\a -> Nil a+ -- If we feed it into schemeR, we'll get+ -- Nil = Nil+ -- because mkConAppCode treats nullary constructor applications+ -- by just re-using the single top-level definition. So+ -- for the worker itself, we must allocate it directly.+ -- ioToBc (putStrLn $ "top level BCO")+ emitBc (mkProtoBCO platform (getName id) (toOL [PACK data_con 0, ENTER])+ (Right rhs) 0 0 [{-no bitmap-}] False{-not alts-})++ | otherwise+ = schemeR [{- No free variables -}] (getName id, rhs)+++-- -----------------------------------------------------------------------------+-- schemeR++-- Compile code for a right-hand side, to give a BCO that,+-- when executed with the free variables and arguments on top of the stack,+-- will return with a pointer to the result on top of the stack, after+-- removing the free variables and arguments.+--+-- Park the resulting BCO in the monad. Also requires the+-- name of the variable to which this value was bound,+-- so as to give the resulting BCO a name.+schemeR :: [Id] -- Free vars of the RHS, ordered as they+ -- will appear in the thunk. Empty for+ -- top-level things, which have no free vars.+ -> (Name, CgStgRhs)+ -> BcM (ProtoBCO Name)+schemeR fvs (nm, rhs)+ = schemeR_wrk fvs nm rhs (collect rhs)++-- If an expression is a lambda (after apply bcView), return the+-- list of arguments to the lambda (in R-to-L order) and the+-- underlying expression++collect :: CgStgRhs -> ([Var], CgStgExpr)+collect (StgRhsClosure _ _ _ args body) = (args, body)+collect (StgRhsCon _cc dc cnum _ticks args) = ([], StgConApp dc cnum args [])++schemeR_wrk+ :: [Id]+ -> Name+ -> CgStgRhs -- expression e, for debugging only+ -> ([Var], CgStgExpr) -- result of collect on e+ -> BcM (ProtoBCO Name)+schemeR_wrk fvs nm original_body (args, body)+ = do+ profile <- getProfile+ let+ platform = profilePlatform profile+ all_args = reverse args ++ fvs+ arity = length all_args+ -- all_args are the args in reverse order. We're compiling a function+ -- \fv1..fvn x1..xn -> e+ -- i.e. the fvs come first++ -- Stack arguments always take a whole number of words, we never pack+ -- them unlike constructor fields.+ szsb_args = map (wordsToBytes platform . idSizeW platform) all_args+ sum_szsb_args = sum szsb_args+ p_init = Map.fromList (zip all_args (mkStackOffsets 0 szsb_args))++ -- make the arg bitmap+ bits = argBits platform (reverse (map (bcIdArgRep platform) all_args))+ bitmap_size = genericLength bits+ bitmap = mkBitmap platform bits+ body_code <- schemeER_wrk sum_szsb_args p_init body++ emitBc (mkProtoBCO platform nm body_code (Right original_body)+ arity bitmap_size bitmap False{-not alts-})++-- introduce break instructions for ticked expressions+schemeER_wrk :: StackDepth -> BCEnv -> CgStgExpr -> BcM BCInstrList+schemeER_wrk d p (StgTick (Breakpoint tick_ty tick_no fvs) rhs)+ = do code <- schemeE d 0 p rhs+ cc_arr <- getCCArray+ this_mod <- moduleName <$> getCurrentModule+ platform <- profilePlatform <$> getProfile+ let idOffSets = getVarOffSets platform d p fvs+ let breakInfo = CgBreakInfo+ { cgb_vars = idOffSets+ , cgb_resty = tick_ty+ }+ newBreakInfo tick_no breakInfo+ hsc_env <- getHscEnv+ let cc | Just interp <- hsc_interp hsc_env+ , interpreterProfiled interp+ = cc_arr ! tick_no+ | otherwise = toRemotePtr nullPtr+ let breakInstr = BRK_FUN (fromIntegral tick_no) (getUnique this_mod) cc+ return $ breakInstr `consOL` code+schemeER_wrk d p rhs = schemeE d 0 p rhs++getVarOffSets :: Platform -> StackDepth -> BCEnv -> [Id] -> [Maybe (Id, Word16)]+getVarOffSets platform depth env = map getOffSet+ where+ getOffSet id = case lookupBCEnv_maybe id env of+ Nothing -> Nothing+ Just offset ->+ -- michalt: I'm not entirely sure why we need the stack+ -- adjustment by 2 here. I initially thought that there's+ -- something off with getIdValFromApStack (the only user of this+ -- value), but it looks ok to me. My current hypothesis is that+ -- this "adjustment" is needed due to stack manipulation for+ -- BRK_FUN in Interpreter.c In any case, this is used only when+ -- we trigger a breakpoint.+ let !var_depth_ws =+ trunc16W $ bytesToWords platform (depth - offset) + 2+ in Just (id, var_depth_ws)++truncIntegral16 :: Integral a => a -> Word16+truncIntegral16 w+ | w > fromIntegral (maxBound :: Word16)+ = panic "stack depth overflow"+ | otherwise+ = fromIntegral w++trunc16B :: ByteOff -> Word16+trunc16B = truncIntegral16++trunc16W :: WordOff -> Word16+trunc16W = truncIntegral16++fvsToEnv :: BCEnv -> CgStgRhs -> [Id]+-- Takes the free variables of a right-hand side, and+-- delivers an ordered list of the local variables that will+-- be captured in the thunk for the RHS+-- The BCEnv argument tells which variables are in the local+-- environment: these are the ones that should be captured+--+-- The code that constructs the thunk, and the code that executes+-- it, have to agree about this layout++fvsToEnv p (StgRhsClosure fvs _ _ _ _) =+ [v | v <- dVarSetElems fvs,+ v `Map.member` p]+fvsToEnv _ _ = []++-- -----------------------------------------------------------------------------+-- schemeE++-- Returning an unlifted value.+-- Heave it on the stack, SLIDE, and RETURN.+returnUnboxedAtom+ :: StackDepth+ -> Sequel+ -> BCEnv+ -> StgArg+ -> BcM BCInstrList+returnUnboxedAtom d s p e = do+ let reps = case e of+ StgLitArg lit -> typePrimRepArgs (literalType lit)+ StgVarArg i -> bcIdPrimReps i+ (push, szb) <- pushAtom d p e+ ret <- returnUnboxedReps d s szb reps+ return (push `appOL` ret)++-- return an unboxed value from the top of the stack+returnUnboxedReps+ :: StackDepth+ -> Sequel+ -> ByteOff -- size of the thing we're returning+ -> [PrimRep] -- representations+ -> BcM BCInstrList+returnUnboxedReps d s szb reps = do+ profile <- getProfile+ let platform = profilePlatform profile+ non_void VoidRep = False+ non_void _ = True+ ret <- case filter non_void reps of+ -- use RETURN_UBX for unary representations+ [] -> return (unitOL $ RETURN_UBX V)+ [rep] -> return (unitOL $ RETURN_UBX (toArgRep platform rep))+ -- otherwise use RETURN_TUPLE with a tuple descriptor+ nv_reps -> do+ let (tuple_info, args_offsets) = layoutTuple profile 0 (primRepCmmType platform) nv_reps+ args_ptrs = map (\(rep, off) -> (isFollowableArg (toArgRep platform rep), off)) args_offsets+ tuple_bco <- emitBc (tupleBCO platform tuple_info args_ptrs)+ return $ PUSH_UBX (mkTupleInfoLit platform tuple_info) 1 `consOL`+ PUSH_BCO tuple_bco `consOL`+ unitOL RETURN_TUPLE+ return ( mkSlideB platform szb (d - s) -- clear to sequel+ `appOL` ret) -- go++-- construct and return an unboxed tuple+returnUnboxedTuple+ :: StackDepth+ -> Sequel+ -> BCEnv+ -> [StgArg]+ -> BcM BCInstrList+returnUnboxedTuple d s p es = do+ profile <- getProfile+ let platform = profilePlatform profile+ arg_ty e = primRepCmmType platform (atomPrimRep e)+ (tuple_info, tuple_components) = layoutTuple profile d arg_ty es+ go _ pushes [] = return (reverse pushes)+ go !dd pushes ((a, off):cs) = do (push, szb) <- pushAtom dd p a+ MASSERT(off == dd + szb)+ go (dd + szb) (push:pushes) cs+ pushes <- go d [] tuple_components+ ret <- returnUnboxedReps d+ s+ (wordsToBytes platform $ tupleSize tuple_info)+ (map atomPrimRep es)+ return (mconcat pushes `appOL` ret)++-- Compile code to apply the given expression to the remaining args+-- on the stack, returning a HNF.+schemeE+ :: StackDepth -> Sequel -> BCEnv -> CgStgExpr -> BcM BCInstrList+schemeE d s p (StgLit lit) = returnUnboxedAtom d s p (StgLitArg lit)+schemeE d s p (StgApp x [])+ | isUnliftedType (idType x) = returnUnboxedAtom d s p (StgVarArg x)+-- Delegate tail-calls to schemeT.+schemeE d s p e@(StgApp {}) = schemeT d s p e+schemeE d s p e@(StgConApp {}) = schemeT d s p e+schemeE d s p e@(StgOpApp {}) = schemeT d s p e+schemeE d s p (StgLetNoEscape xlet bnd body)+ = schemeE d s p (StgLet xlet bnd body)+schemeE d s p (StgLet _xlet+ (StgNonRec x (StgRhsCon _cc data_con _cnum _ticks args))+ body)+ = do -- Special case for a non-recursive let whose RHS is a+ -- saturated constructor application.+ -- Just allocate the constructor and carry on+ alloc_code <- mkConAppCode d s p data_con args+ platform <- targetPlatform <$> getDynFlags+ let !d2 = d + wordSize platform+ body_code <- schemeE d2 s (Map.insert x d2 p) body+ return (alloc_code `appOL` body_code)+-- General case for let. Generates correct, if inefficient, code in+-- all situations.+schemeE d s p (StgLet _ext binds body) = do+ platform <- targetPlatform <$> getDynFlags+ let (xs,rhss) = case binds of StgNonRec x rhs -> ([x],[rhs])+ StgRec xs_n_rhss -> unzip xs_n_rhss+ n_binds = genericLength xs++ fvss = map (fvsToEnv p') rhss++ -- Sizes of free vars+ size_w = trunc16W . idSizeW platform+ sizes = map (\rhs_fvs -> sum (map size_w rhs_fvs)) fvss++ -- the arity of each rhs+ arities = map (genericLength . fst . collect) rhss++ -- This p', d' defn is safe because all the items being pushed+ -- are ptrs, so all have size 1 word. d' and p' reflect the stack+ -- after the closures have been allocated in the heap (but not+ -- filled in), and pointers to them parked on the stack.+ offsets = mkStackOffsets d (genericReplicate n_binds (wordSize platform))+ p' = Map.insertList (zipE xs offsets) p+ d' = d + wordsToBytes platform n_binds+ zipE = zipEqual "schemeE"++ -- ToDo: don't build thunks for things with no free variables+ build_thunk+ :: StackDepth+ -> [Id]+ -> Word16+ -> ProtoBCO Name+ -> Word16+ -> Word16+ -> BcM BCInstrList+ build_thunk _ [] size bco off arity+ = return (PUSH_BCO bco `consOL` unitOL (mkap (off+size) size))+ where+ mkap | arity == 0 = MKAP+ | otherwise = MKPAP+ build_thunk dd (fv:fvs) size bco off arity = do+ (push_code, pushed_szb) <- pushAtom dd p' (StgVarArg fv)+ more_push_code <-+ build_thunk (dd + pushed_szb) fvs size bco off arity+ return (push_code `appOL` more_push_code)++ alloc_code = toOL (zipWith mkAlloc sizes arities)+ where mkAlloc sz 0+ | is_tick = ALLOC_AP_NOUPD sz+ | otherwise = ALLOC_AP sz+ mkAlloc sz arity = ALLOC_PAP arity sz++ is_tick = case binds of+ StgNonRec id _ -> occNameFS (getOccName id) == tickFS+ _other -> False++ compile_bind d' fvs x (rhs::CgStgRhs) size arity off = do+ bco <- schemeR fvs (getName x,rhs)+ build_thunk d' fvs size bco off arity++ compile_binds =+ [ compile_bind d' fvs x rhs size arity (trunc16W n)+ | (fvs, x, rhs, size, arity, n) <-+ zip6 fvss xs rhss sizes arities [n_binds, n_binds-1 .. 1]+ ]+ body_code <- schemeE d' s p' body+ thunk_codes <- sequence compile_binds+ return (alloc_code `appOL` concatOL thunk_codes `appOL` body_code)++schemeE _d _s _p (StgTick (Breakpoint _ bp_id _) _rhs)+ = panic ("schemeE: Breakpoint without let binding: " +++ show bp_id +++ " forgot to run bcPrep?")++-- ignore other kinds of tick+schemeE d s p (StgTick _ rhs) = schemeE d s p rhs++-- no alts: scrut is guaranteed to diverge+schemeE d s p (StgCase scrut _ _ []) = schemeE d s p scrut++schemeE d s p (StgCase scrut bndr _ alts)+ = doCase d s p scrut bndr alts++-- Is this Id a not-necessarily-lifted join point?+-- See Note [Not-necessarily-lifted join points], step 1+isNNLJoinPoint :: Id -> Bool+isNNLJoinPoint x = isJoinId x &&+ Just True /= isLiftedType_maybe (idType x)++-- Update an Id's type to take a Void# argument.+-- Precondition: the Id is a not-necessarily-lifted join point.+-- See Note [Not-necessarily-lifted join points]+protectNNLJoinPointId :: Id -> Id+protectNNLJoinPointId x+ = ASSERT( isNNLJoinPoint x )+ updateIdTypeButNotMult (unboxedUnitTy `mkVisFunTyMany`) x++{-+ Ticked Expressions+ ------------------++ The idea is that the "breakpoint<n,fvs> E" is really just an annotation on+ the code. When we find such a thing, we pull out the useful information,+ and then compile the code as if it was just the expression E.++Note [Not-necessarily-lifted join points]+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+A join point variable is essentially a goto-label: it is, for example,+never used as an argument to another function, and it is called only+in tail position. See Note [Join points] and Note [Invariants on join points],+both in GHC.Core. Because join points do not compile to true, red-blooded+variables (with, e.g., registers allocated to them), they are allowed+to be levity-polymorphic. (See invariant #6 in Note [Invariants on join points]+in GHC.Core.)++However, in this byte-code generator, join points *are* treated just as+ordinary variables. There is no check whether a binding is for a join point+or not; they are all treated uniformly. (Perhaps there is a missed optimization+opportunity here, but that is beyond the scope of my (Richard E's) Thursday.)++We thus must have *some* strategy for dealing with levity-polymorphic and+unlifted join points. Levity-polymorphic variables are generally not allowed+(though levity-polymorphic join points *are*; see Note [Invariants on join points]+in GHC.Core, point 6), and we don't wish to evaluate unlifted join points eagerly.+The questionable join points are *not-necessarily-lifted join points*+(NNLJPs). (Not having such a strategy led to #16509, which panicked in the+isUnliftedType check in the AnnVar case of schemeE.) Here is the strategy:++1. Detect NNLJPs. This is done in isNNLJoinPoint.++2. When binding an NNLJP, add a `\ (_ :: (# #)) ->` to its RHS, and modify the+ type to tack on a `(# #) ->`.+ Note that functions are never levity-polymorphic, so this transformation+ changes an NNLJP to a non-levity-polymorphic join point. This is done+ in bcPrepSingleBind.++3. At an occurrence of an NNLJP, add an application to void# (called voidPrimId),+ being careful to note the new type of the NNLJP. This is done in the AnnVar+ case of schemeE, with help from protectNNLJoinPointId.++Here is an example. Suppose we have++ f = \(r :: RuntimeRep) (a :: TYPE r) (x :: T).+ join j :: a+ j = error @r @a "bloop"+ in case x of+ A -> j+ B -> j+ C -> error @r @a "blurp"++Our plan is to behave is if the code was++ f = \(r :: RuntimeRep) (a :: TYPE r) (x :: T).+ let j :: (Void# -> a)+ j = \ _ -> error @r @a "bloop"+ in case x of+ A -> j void#+ B -> j void#+ C -> error @r @a "blurp"++It's a bit hacky, but it works well in practice and is local. I suspect the+Right Fix is to take advantage of join points as goto-labels.++-}++-- Compile code to do a tail call. Specifically, push the fn,+-- slide the on-stack app back down to the sequel depth,+-- and enter. Four cases:+--+-- 0. (Nasty hack).+-- An application "GHC.Prim.tagToEnum# <type> unboxed-int".+-- The int will be on the stack. Generate a code sequence+-- to convert it to the relevant constructor, SLIDE and ENTER.+--+-- 1. The fn denotes a ccall. Defer to generateCCall.+--+-- 2. An unboxed tuple: push the components on the top of+-- the stack and return.+--+-- 3. Application of a constructor, by defn saturated.+-- Split the args into ptrs and non-ptrs, and push the nonptrs,+-- then the ptrs, and then do PACK and RETURN.+--+-- 4. Otherwise, it must be a function call. Push the args+-- right to left, SLIDE and ENTER.++schemeT :: StackDepth -- Stack depth+ -> Sequel -- Sequel depth+ -> BCEnv -- stack env+ -> CgStgExpr+ -> BcM BCInstrList++ -- Case 0+schemeT d s p app+ | Just (arg, constr_names) <- maybe_is_tagToEnum_call app+ = implement_tagToId d s p arg constr_names++ -- Case 1+schemeT d s p (StgOpApp (StgFCallOp (CCall ccall_spec) _ty) args result_ty)+ = if isSupportedCConv ccall_spec+ then generateCCall d s p ccall_spec result_ty (reverse args)+ else unsupportedCConvException++schemeT d s p (StgOpApp (StgPrimOp op) args _ty)+ = doTailCall d s p (primOpId op) (reverse args)++schemeT _d _s _p (StgOpApp StgPrimCallOp{} _args _ty)+ = unsupportedCConvException++ -- Case 2: Unboxed tuple+schemeT d s p (StgConApp con _ext args _tys)+ | isUnboxedTupleDataCon con || isUnboxedSumDataCon con+ = returnUnboxedTuple d s p args++ -- Case 3: Ordinary data constructor+ | otherwise+ = do alloc_con <- mkConAppCode d s p con args+ platform <- profilePlatform <$> getProfile+ return (alloc_con `appOL`+ mkSlideW 1 (bytesToWords platform $ d - s) `snocOL`+ ENTER)++ -- Case 4: Tail call of function+schemeT d s p (StgApp fn args)+ = doTailCall d s p fn (reverse args)++schemeT _ _ _ e = pprPanic "GHC.StgToByteCode.schemeT"+ (pprStgExpr shortStgPprOpts e)++-- -----------------------------------------------------------------------------+-- Generate code to build a constructor application,+-- leaving it on top of the stack++mkConAppCode+ :: StackDepth+ -> Sequel+ -> BCEnv+ -> DataCon -- The data constructor+ -> [StgArg] -- Args, in *reverse* order+ -> BcM BCInstrList+mkConAppCode orig_d _ p con args = app_code+ where+ app_code = do+ profile <- getProfile+ let platform = profilePlatform profile++ non_voids =+ [ NonVoid (prim_rep, arg)+ | arg <- args+ , let prim_rep = atomPrimRep arg+ , not (isVoidRep prim_rep)+ ]+ (_, _, args_offsets) =+ mkVirtHeapOffsetsWithPadding profile StdHeader non_voids++ do_pushery !d (arg : args) = do+ (push, arg_bytes) <- case arg of+ (Padding l _) -> return $! pushPadding l+ (FieldOff a _) -> pushConstrAtom d p (fromNonVoid a)+ more_push_code <- do_pushery (d + arg_bytes) args+ return (push `appOL` more_push_code)+ do_pushery !d [] = do+ let !n_arg_words = trunc16W $ bytesToWords platform (d - orig_d)+ return (unitOL (PACK con n_arg_words))++ -- Push on the stack in the reverse order.+ do_pushery orig_d (reverse args_offsets)++-- -----------------------------------------------------------------------------+-- Generate code for a tail-call++doTailCall+ :: StackDepth+ -> Sequel+ -> BCEnv+ -> Id+ -> [StgArg]+ -> BcM BCInstrList+doTailCall init_d s p fn args = do+ platform <- profilePlatform <$> getProfile+ do_pushes init_d args (map (atomRep platform) args)+ where+ do_pushes !d [] reps = do+ ASSERT( null reps ) return ()+ (push_fn, sz) <- pushAtom d p (StgVarArg fn)+ platform <- profilePlatform <$> getProfile+ ASSERT( sz == wordSize platform ) return ()+ let slide = mkSlideB platform (d - init_d + wordSize platform) (init_d - s)+ return (push_fn `appOL` (slide `appOL` unitOL ENTER))+ do_pushes !d args reps = do+ let (push_apply, n, rest_of_reps) = findPushSeq reps+ (these_args, rest_of_args) = splitAt n args+ (next_d, push_code) <- push_seq d these_args+ platform <- profilePlatform <$> getProfile+ instrs <- do_pushes (next_d + wordSize platform) rest_of_args rest_of_reps+ -- ^^^ for the PUSH_APPLY_ instruction+ return (push_code `appOL` (push_apply `consOL` instrs))++ push_seq d [] = return (d, nilOL)+ push_seq d (arg:args) = do+ (push_code, sz) <- pushAtom d p arg+ (final_d, more_push_code) <- push_seq (d + sz) args+ return (final_d, push_code `appOL` more_push_code)++-- v. similar to CgStackery.findMatch, ToDo: merge+findPushSeq :: [ArgRep] -> (BCInstr, Int, [ArgRep])+findPushSeq (P: P: P: P: P: P: rest)+ = (PUSH_APPLY_PPPPPP, 6, rest)+findPushSeq (P: P: P: P: P: rest)+ = (PUSH_APPLY_PPPPP, 5, rest)+findPushSeq (P: P: P: P: rest)+ = (PUSH_APPLY_PPPP, 4, rest)+findPushSeq (P: P: P: rest)+ = (PUSH_APPLY_PPP, 3, rest)+findPushSeq (P: P: rest)+ = (PUSH_APPLY_PP, 2, rest)+findPushSeq (P: rest)+ = (PUSH_APPLY_P, 1, rest)+findPushSeq (V: rest)+ = (PUSH_APPLY_V, 1, rest)+findPushSeq (N: rest)+ = (PUSH_APPLY_N, 1, rest)+findPushSeq (F: rest)+ = (PUSH_APPLY_F, 1, rest)+findPushSeq (D: rest)+ = (PUSH_APPLY_D, 1, rest)+findPushSeq (L: rest)+ = (PUSH_APPLY_L, 1, rest)+findPushSeq _+ = panic "GHC.StgToByteCode.findPushSeq"++-- -----------------------------------------------------------------------------+-- Case expressions++doCase+ :: StackDepth+ -> Sequel+ -> BCEnv+ -> CgStgExpr+ -> Id+ -> [CgStgAlt]+ -> BcM BCInstrList+doCase d s p scrut bndr alts+ = do+ profile <- getProfile+ hsc_env <- getHscEnv+ let+ platform = profilePlatform profile++ -- Are we dealing with an unboxed tuple with a tuple return frame?+ --+ -- 'Simple' tuples with at most one non-void component,+ -- like (# Word# #) or (# Int#, State# RealWorld# #) do not have a+ -- tuple return frame. This is because (# foo #) and (# foo, Void# #)+ -- have the same runtime rep. We have more efficient specialized+ -- return frames for the situations with one non-void element.++ ubx_tuple_frame =+ (isUnboxedTupleType bndr_ty || isUnboxedSumType bndr_ty) &&+ length non_void_arg_reps > 1++ non_void_arg_reps = non_void (typeArgReps platform bndr_ty)++ profiling+ | Just interp <- hsc_interp hsc_env+ = interpreterProfiled interp+ | otherwise = False++ -- Top of stack is the return itbl, as usual.+ -- underneath it is the pointer to the alt_code BCO.+ -- When an alt is entered, it assumes the returned value is+ -- on top of the itbl.+ ret_frame_size_b :: StackDepth+ ret_frame_size_b | ubx_tuple_frame =+ (if profiling then 5 else 4) * wordSize platform+ | otherwise = 2 * wordSize platform++ -- The stack space used to save/restore the CCCS when profiling+ save_ccs_size_b | profiling &&+ not ubx_tuple_frame = 2 * wordSize platform+ | otherwise = 0++ -- An unlifted value gets an extra info table pushed on top+ -- when it is returned.+ unlifted_itbl_size_b :: StackDepth+ unlifted_itbl_size_b | isAlgCase = 0+ | ubx_tuple_frame = 3 * wordSize platform+ | otherwise = wordSize platform++ (bndr_size, tuple_info, args_offsets)+ | ubx_tuple_frame =+ let bndr_ty = primRepCmmType platform+ bndr_reps = filter (not.isVoidRep) (bcIdPrimReps bndr)+ (tuple_info, args_offsets) =+ layoutTuple profile 0 bndr_ty bndr_reps+ in ( wordsToBytes platform (tupleSize tuple_info)+ , tuple_info+ , args_offsets+ )+ | otherwise = ( wordsToBytes platform (idSizeW platform bndr)+ , voidTupleInfo+ , []+ )++ -- depth of stack after the return value has been pushed+ d_bndr =+ d + ret_frame_size_b + bndr_size++ -- depth of stack after the extra info table for an unboxed return+ -- has been pushed, if any. This is the stack depth at the+ -- continuation.+ d_alts = d + ret_frame_size_b + bndr_size + unlifted_itbl_size_b++ -- Env in which to compile the alts, not including+ -- any vars bound by the alts themselves+ p_alts = Map.insert bndr d_bndr p++ bndr_ty = idType bndr+ isAlgCase = not (isUnliftedType bndr_ty)++ -- given an alt, return a discr and code for it.+ codeAlt (DEFAULT, _, rhs)+ = do rhs_code <- schemeE d_alts s p_alts rhs+ return (NoDiscr, rhs_code)++ codeAlt alt@(_, bndrs, rhs)+ -- primitive or nullary constructor alt: no need to UNPACK+ | null real_bndrs = do+ rhs_code <- schemeE d_alts s p_alts rhs+ return (my_discr alt, rhs_code)+ | isUnboxedTupleType bndr_ty || isUnboxedSumType bndr_ty =+ let bndr_ty = primRepCmmType platform . bcIdPrimRep+ tuple_start = d_bndr+ (tuple_info, args_offsets) =+ layoutTuple profile+ 0+ bndr_ty+ bndrs++ stack_bot = d_alts++ p' = Map.insertList+ [ (arg, tuple_start -+ wordsToBytes platform (tupleSize tuple_info) ++ offset)+ | (arg, offset) <- args_offsets+ , not (isVoidRep $ bcIdPrimRep arg)]+ p_alts+ in do+ rhs_code <- schemeE stack_bot s p' rhs+ return (NoDiscr, rhs_code)+ -- algebraic alt with some binders+ | otherwise =+ let (tot_wds, _ptrs_wds, args_offsets) =+ mkVirtHeapOffsets profile NoHeader+ [ NonVoid (bcIdPrimRep id, id)+ | NonVoid id <- nonVoidIds real_bndrs+ ]+ size = WordOff tot_wds++ stack_bot = d_alts + wordsToBytes platform size++ -- convert offsets from Sp into offsets into the virtual stack+ p' = Map.insertList+ [ (arg, stack_bot - ByteOff offset)+ | (NonVoid arg, offset) <- args_offsets ]+ p_alts+ in do+ MASSERT(isAlgCase)+ rhs_code <- schemeE stack_bot s p' rhs+ return (my_discr alt,+ unitOL (UNPACK (trunc16W size)) `appOL` rhs_code)+ where+ real_bndrs = filterOut isTyVar bndrs++ my_discr (DEFAULT, _, _) = NoDiscr {-shouldn't really happen-}+ my_discr (DataAlt dc, _, _)+ | isUnboxedTupleDataCon dc || isUnboxedSumDataCon dc+ = NoDiscr+ | otherwise+ = DiscrP (fromIntegral (dataConTag dc - fIRST_TAG))+ my_discr (LitAlt l, _, _)+ = case l of LitNumber LitNumInt i -> DiscrI (fromInteger i)+ LitNumber LitNumWord w -> DiscrW (fromInteger w)+ LitFloat r -> DiscrF (fromRational r)+ LitDouble r -> DiscrD (fromRational r)+ LitChar i -> DiscrI (ord i)+ _ -> pprPanic "schemeE(StgCase).my_discr" (ppr l)++ maybe_ncons+ | not isAlgCase = Nothing+ | otherwise+ = case [dc | (DataAlt dc, _, _) <- alts] of+ [] -> Nothing+ (dc:_) -> Just (tyConFamilySize (dataConTyCon dc))++ -- the bitmap is relative to stack depth d, i.e. before the+ -- BCO, info table and return value are pushed on.+ -- This bit of code is v. similar to buildLivenessMask in CgBindery,+ -- except that here we build the bitmap from the known bindings of+ -- things that are pointers, whereas in CgBindery the code builds the+ -- bitmap from the free slots and unboxed bindings.+ -- (ToDo: merge?)+ --+ -- NOTE [7/12/2006] bug #1013, testcase ghci/should_run/ghci002.+ -- The bitmap must cover the portion of the stack up to the sequel only.+ -- Previously we were building a bitmap for the whole depth (d), but we+ -- really want a bitmap up to depth (d-s). This affects compilation of+ -- case-of-case expressions, which is the only time we can be compiling a+ -- case expression with s /= 0.++ -- unboxed tuples get two more words, the second is a pointer (tuple_bco)+ (extra_pointers, extra_slots)+ | ubx_tuple_frame && profiling = ([1], 3) -- tuple_info, tuple_BCO, CCCS+ | ubx_tuple_frame = ([1], 2) -- tuple_info, tuple_BCO+ | otherwise = ([], 0)++ bitmap_size = trunc16W $ fromIntegral extra_slots ++ bytesToWords platform (d - s)++ bitmap_size' :: Int+ bitmap_size' = fromIntegral bitmap_size+++ pointers =+ extra_pointers +++ sort (filter (< bitmap_size') (map (+extra_slots) rel_slots))+ where+ binds = Map.toList p+ -- NB: unboxed tuple cases bind the scrut binder to the same offset+ -- as one of the alt binders, so we have to remove any duplicates here:+ rel_slots = nub $ map fromIntegral $ concatMap spread binds+ spread (id, offset) | isUnboxedTupleType (idType id) ||+ isUnboxedSumType (idType id) = []+ | isFollowableArg (bcIdArgRep platform id) = [ rel_offset ]+ | otherwise = []+ where rel_offset = trunc16W $ bytesToWords platform (d - offset)++ bitmap = intsToReverseBitmap platform bitmap_size'{-size-} pointers++ alt_stuff <- mapM codeAlt alts+ alt_final <- mkMultiBranch maybe_ncons alt_stuff++ let+ alt_bco_name = getName bndr+ alt_bco = mkProtoBCO platform alt_bco_name alt_final (Left alts)+ 0{-no arity-} bitmap_size bitmap True{-is alts-}+ scrut_code <- schemeE (d + ret_frame_size_b + save_ccs_size_b)+ (d + ret_frame_size_b + save_ccs_size_b)+ p scrut+ alt_bco' <- emitBc alt_bco+ if ubx_tuple_frame+ then do+ let args_ptrs =+ map (\(rep, off) -> (isFollowableArg (toArgRep platform rep), off))+ args_offsets+ tuple_bco <- emitBc (tupleBCO platform tuple_info args_ptrs)+ return (PUSH_ALTS_TUPLE alt_bco' tuple_info tuple_bco+ `consOL` scrut_code)+ else let push_alts+ | isAlgCase+ = PUSH_ALTS alt_bco'+ | otherwise+ = let unlifted_rep =+ case non_void_arg_reps of+ [] -> V+ [rep] -> rep+ _ -> panic "schemeE(StgCase).push_alts"+ in PUSH_ALTS_UNLIFTED alt_bco' unlifted_rep+ in return (push_alts `consOL` scrut_code)+++-- -----------------------------------------------------------------------------+-- Deal with tuples++-- The native calling convention uses registers for tuples, but in the+-- bytecode interpreter, all values live on the stack.++layoutTuple :: Profile+ -> ByteOff+ -> (a -> CmmType)+ -> [a]+ -> ( TupleInfo -- See Note [GHCi TupleInfo]+ , [(a, ByteOff)] -- argument, offset on stack+ )+layoutTuple profile start_off arg_ty reps =+ let platform = profilePlatform profile+ (orig_stk_bytes, pos) = assignArgumentsPos profile+ 0+ NativeReturn+ arg_ty+ reps++ -- keep the stack parameters in the same place+ orig_stk_params = [(x, fromIntegral off) | (x, StackParam off) <- pos]++ -- sort the register parameters by register and add them to the stack+ (regs, reg_params)+ = unzip $ sortBy (comparing fst)+ [(reg, x) | (x, RegisterParam reg) <- pos]++ (new_stk_bytes, new_stk_params) = assignStack platform+ orig_stk_bytes+ arg_ty+ reg_params++ -- make live register bitmaps+ bmp_reg r ~(v, f, d, l)+ = case r of VanillaReg n _ -> (a v n, f, d, l )+ FloatReg n -> (v, a f n, d, l )+ DoubleReg n -> (v, f, a d n, l )+ LongReg n -> (v, f, d, a l n)+ _ ->+ pprPanic "GHC.StgToByteCode.layoutTuple unsupported register type"+ (ppr r)+ where a bmp n = bmp .|. (1 `shiftL` (n-1))++ (vanilla_regs, float_regs, double_regs, long_regs)+ = foldr bmp_reg (0, 0, 0, 0) regs++ get_byte_off (x, StackParam y) = (x, fromIntegral y)+ get_byte_off _ =+ panic "GHC.StgToByteCode.layoutTuple get_byte_off"++ in ( TupleInfo+ { tupleSize = bytesToWords platform (ByteOff new_stk_bytes)+ , tupleVanillaRegs = vanilla_regs+ , tupleLongRegs = long_regs+ , tupleFloatRegs = float_regs+ , tupleDoubleRegs = double_regs+ , tupleNativeStackSize = bytesToWords platform+ (ByteOff orig_stk_bytes)+ }+ , sortBy (comparing snd) $+ map (\(x, o) -> (x, o + start_off))+ (orig_stk_params ++ map get_byte_off new_stk_params)+ )++{- Note [unboxed tuple bytecodes and tuple_BCO]+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~++ We have the bytecode instructions RETURN_TUPLE and PUSH_ALTS_TUPLE to+ return and receive arbitrary unboxed tuples, respectively. These+ instructions use the helper data tuple_BCO and tuple_info.++ The helper data is used to convert tuples between GHCs native calling+ convention (object code), which uses stack and registers, and the bytecode+ calling convention, which only uses the stack. See Note [GHCi TupleInfo]+ for more details.+++ Returning a tuple+ =================++ Bytecode that returns a tuple first pushes all the tuple fields followed+ by the appropriate tuple_info and tuple_BCO onto the stack. It then+ executes the RETURN_TUPLE instruction, which causes the interpreter+ to push stg_ret_t_info to the top of the stack. The stack (growing down)+ then looks as follows:++ ...+ next_frame+ tuple_field_1+ tuple_field_2+ ...+ tuple_field_n+ tuple_info+ tuple_BCO+ stg_ret_t_info <- Sp++ If next_frame is bytecode, the interpreter will start executing it. If+ it's object code, the interpreter jumps back to the scheduler, which in+ turn jumps to stg_ret_t. stg_ret_t converts the tuple to the native+ calling convention using the description in tuple_info, and then jumps+ to next_frame.+++ Receiving a tuple+ =================++ Bytecode that receives a tuple uses the PUSH_ALTS_TUPLE instruction to+ push a continuation, followed by jumping to the code that produces the+ tuple. The PUSH_ALTS_TUPLE instuction contains three pieces of data:++ * cont_BCO: the continuation that receives the tuple+ * tuple_info: see below+ * tuple_BCO: see below++ The interpreter pushes these onto the stack when the PUSH_ALTS_TUPLE+ instruction is executed, followed by stg_ctoi_tN_info, with N depending+ on the number of stack words used by the tuple in the GHC native calling+ convention. N is derived from tuple_info.++ For example if we expect a tuple with three words on the stack, the stack+ looks as follows after PUSH_ALTS_TUPLE:++ ...+ next_frame+ cont_free_var_1+ cont_free_var_2+ ...+ cont_free_var_n+ tuple_info+ tuple_BCO+ cont_BCO+ stg_ctoi_t3_info <- Sp++ If the tuple is returned by object code, stg_ctoi_t3 will deal with+ adjusting the stack pointer and converting the tuple to the bytecode+ calling convention. See Note [GHCi unboxed tuples stack spills] for more+ details.+++ The tuple_BCO+ =============++ The tuple_BCO is a helper bytecode object. Its main purpose is describing+ the contents of the stack frame containing the tuple for the storage+ manager. It contains only instructions to immediately return the tuple+ that is already on the stack.+++ The tuple_info word+ ===================++ The tuple_info word describes the stack and STG register (e.g. R1..R6,+ D1..D6) usage for the tuple. tuple_info contains enough information to+ convert the tuple between the stack-only bytecode and stack+registers+ GHC native calling conventions.++ See Note [GHCi tuple layout] for more details of how the data is packed+ in a single word.++ -}++tupleBCO :: Platform -> TupleInfo -> [(Bool, ByteOff)] -> [FFIInfo] -> ProtoBCO Name+tupleBCO platform info pointers =+ mkProtoBCO platform invented_name body_code (Left [])+ 0{-no arity-} bitmap_size bitmap False{-is alts-}++ where+ {-+ The tuple BCO is never referred to by name, so we can get away+ with using a fake name here. We will need to change this if we want+ to save some memory by sharing the BCO between places that have+ the same tuple shape+ -}+ invented_name = mkSystemVarName (mkPseudoUniqueE 0) (fsLit "tuple")++ -- the first word in the frame is the tuple_info word,+ -- which is not a pointer+ bitmap_size = trunc16W $ 1 + tupleSize info+ bitmap = intsToReverseBitmap platform (fromIntegral bitmap_size) $+ map ((+1) . fromIntegral . bytesToWords platform . snd)+ (filter fst pointers)+ body_code = mkSlideW 0 1 -- pop frame header+ `snocOL` RETURN_TUPLE -- and add it again++-- -----------------------------------------------------------------------------+-- Deal with a CCall.++-- Taggedly push the args onto the stack R->L,+-- deferencing ForeignObj#s and adjusting addrs to point to+-- payloads in Ptr/Byte arrays. Then, generate the marshalling+-- (machine) code for the ccall, and create bytecodes to call that and+-- then return in the right way.++generateCCall+ :: StackDepth+ -> Sequel+ -> BCEnv+ -> CCallSpec -- where to call+ -> Type+ -> [StgArg] -- args (atoms)+ -> BcM BCInstrList+generateCCall d0 s p (CCallSpec target cconv safety) result_ty args_r_to_l+ = do+ profile <- getProfile++ let+ platform = profilePlatform profile+ -- useful constants+ addr_size_b :: ByteOff+ addr_size_b = wordSize platform++ arrayish_rep_hdr_size :: TyCon -> Maybe Int+ arrayish_rep_hdr_size t+ | t == arrayPrimTyCon || t == mutableArrayPrimTyCon+ = Just (arrPtrsHdrSize profile)+ | t == smallArrayPrimTyCon || t == smallMutableArrayPrimTyCon+ = Just (smallArrPtrsHdrSize profile)+ | t == byteArrayPrimTyCon || t == mutableByteArrayPrimTyCon+ = Just (arrWordsHdrSize profile)+ | otherwise+ = Nothing++ -- Get the args on the stack, with tags and suitably+ -- dereferenced for the CCall. For each arg, return the+ -- depth to the first word of the bits for that arg, and the+ -- ArgRep of what was actually pushed.++ pargs+ :: ByteOff -> [StgArg] -> BcM [(BCInstrList, PrimRep)]+ pargs _ [] = return []+ pargs d (aa@(StgVarArg a):az)+ | Just t <- tyConAppTyCon_maybe (idType a)+ , Just hdr_sz <- arrayish_rep_hdr_size t+ -- Do magic for Ptr/Byte arrays. Push a ptr to the array on+ -- the stack but then advance it over the headers, so as to+ -- point to the payload.+ = do rest <- pargs (d + addr_size_b) az+ (push_fo, _) <- pushAtom d p aa+ -- The ptr points at the header. Advance it over the+ -- header and then pretend this is an Addr#.+ let code = push_fo `snocOL` SWIZZLE 0 (fromIntegral hdr_sz)+ return ((code, AddrRep) : rest)+ pargs d (aa:az) = do (code_a, sz_a) <- pushAtom d p aa+ rest <- pargs (d + sz_a) az+ return ((code_a, atomPrimRep aa) : rest)++ code_n_reps <- pargs d0 args_r_to_l+ let+ (pushs_arg, a_reps_pushed_r_to_l) = unzip code_n_reps+ a_reps_sizeW = sum (map (repSizeWords platform) a_reps_pushed_r_to_l)++ push_args = concatOL pushs_arg+ !d_after_args = d0 + wordsToBytes platform a_reps_sizeW+ a_reps_pushed_RAW+ | null a_reps_pushed_r_to_l || not (isVoidRep (head a_reps_pushed_r_to_l))+ = panic "GHC.StgToByteCode.generateCCall: missing or invalid World token?"+ | otherwise+ = reverse (tail a_reps_pushed_r_to_l)++ -- Now: a_reps_pushed_RAW are the reps which are actually on the stack.+ -- push_args is the code to do that.+ -- d_after_args is the stack depth once the args are on.++ -- Get the result rep.+ (returns_void, r_rep)+ = case maybe_getCCallReturnRep result_ty of+ Nothing -> (True, VoidRep)+ Just rr -> (False, rr)+ {-+ Because the Haskell stack grows down, the a_reps refer to+ lowest to highest addresses in that order. The args for the call+ are on the stack. Now push an unboxed Addr# indicating+ the C function to call. Then push a dummy placeholder for the+ result. Finally, emit a CCALL insn with an offset pointing to the+ Addr# just pushed, and a literal field holding the mallocville+ address of the piece of marshalling code we generate.+ So, just prior to the CCALL insn, the stack looks like this+ (growing down, as usual):++ <arg_n>+ ...+ <arg_1>+ Addr# address_of_C_fn+ <placeholder-for-result#> (must be an unboxed type)++ The interpreter then calls the marshall code mentioned+ in the CCALL insn, passing it (& <placeholder-for-result#>),+ that is, the addr of the topmost word in the stack.+ When this returns, the placeholder will have been+ filled in. The placeholder is slid down to the sequel+ depth, and we RETURN.++ This arrangement makes it simple to do f-i-dynamic since the Addr#+ value is the first arg anyway.++ The marshalling code is generated specifically for this+ call site, and so knows exactly the (Haskell) stack+ offsets of the args, fn address and placeholder. It+ copies the args to the C stack, calls the stacked addr,+ and parks the result back in the placeholder. The interpreter+ calls it as a normal C call, assuming it has a signature+ void marshall_code ( StgWord* ptr_to_top_of_stack )+ -}+ -- resolve static address+ maybe_static_target :: Maybe Literal+ maybe_static_target =+ case target of+ DynamicTarget -> Nothing+ StaticTarget _ _ _ False ->+ panic "generateCCall: unexpected FFI value import"+ StaticTarget _ target _ True ->+ Just (LitLabel target mb_size IsFunction)+ where+ mb_size+ | OSMinGW32 <- platformOS platform+ , StdCallConv <- cconv+ = Just (fromIntegral a_reps_sizeW * platformWordSizeInBytes platform)+ | otherwise+ = Nothing++ let+ is_static = isJust maybe_static_target++ -- Get the arg reps, zapping the leading Addr# in the dynamic case+ a_reps -- | trace (showSDoc (ppr a_reps_pushed_RAW)) False = error "???"+ | is_static = a_reps_pushed_RAW+ | otherwise = if null a_reps_pushed_RAW+ then panic "GHC.StgToByteCode.generateCCall: dyn with no args"+ else tail a_reps_pushed_RAW++ -- push the Addr#+ (push_Addr, d_after_Addr)+ | Just machlabel <- maybe_static_target+ = (toOL [PUSH_UBX machlabel 1], d_after_args + addr_size_b)+ | otherwise -- is already on the stack+ = (nilOL, d_after_args)++ -- Push the return placeholder. For a call returning nothing,+ -- this is a V (tag).+ r_sizeW = repSizeWords platform r_rep+ d_after_r = d_after_Addr + wordsToBytes platform r_sizeW+ push_r =+ if returns_void+ then nilOL+ else unitOL (PUSH_UBX (mkDummyLiteral platform r_rep) (trunc16W r_sizeW))++ -- generate the marshalling code we're going to call++ -- Offset of the next stack frame down the stack. The CCALL+ -- instruction needs to describe the chunk of stack containing+ -- the ccall args to the GC, so it needs to know how large it+ -- is. See comment in Interpreter.c with the CCALL instruction.+ stk_offset = trunc16W $ bytesToWords platform (d_after_r - s)++ conv = case cconv of+ CCallConv -> FFICCall+ StdCallConv -> FFIStdCall+ _ -> panic "GHC.StgToByteCode: unexpected calling convention"++ -- the only difference in libffi mode is that we prepare a cif+ -- describing the call type by calling libffi, and we attach the+ -- address of this to the CCALL instruction.+++ let ffires = primRepToFFIType platform r_rep+ ffiargs = map (primRepToFFIType platform) a_reps+ interp <- hscInterp <$> getHscEnv+ token <- ioToBc $ interpCmd interp (PrepFFI conv ffiargs ffires)+ recordFFIBc token++ let+ -- do the call+ do_call = unitOL (CCALL stk_offset token flags)+ where flags = case safety of+ PlaySafe -> 0x0+ PlayInterruptible -> 0x1+ PlayRisky -> 0x2++ -- slide and return+ d_after_r_min_s = bytesToWords platform (d_after_r - s)+ wrapup = mkSlideW (trunc16W r_sizeW) (d_after_r_min_s - r_sizeW)+ `snocOL` RETURN_UBX (toArgRep platform r_rep)+ --trace (show (arg1_offW, args_offW , (map argRepSizeW a_reps) )) $+ return (+ push_args `appOL`+ push_Addr `appOL` push_r `appOL` do_call `appOL` wrapup+ )++primRepToFFIType :: Platform -> PrimRep -> FFIType+primRepToFFIType platform r+ = case r of+ VoidRep -> FFIVoid+ IntRep -> signed_word+ WordRep -> unsigned_word+ Int8Rep -> FFISInt8+ Word8Rep -> FFIUInt8+ Int16Rep -> FFISInt16+ Word16Rep -> FFIUInt16+ Int32Rep -> FFISInt32+ Word32Rep -> FFIUInt32+ Int64Rep -> FFISInt64+ Word64Rep -> FFIUInt64+ AddrRep -> FFIPointer+ FloatRep -> FFIFloat+ DoubleRep -> FFIDouble+ _ -> panic "primRepToFFIType"+ where+ (signed_word, unsigned_word) = case platformWordSize platform of+ PW4 -> (FFISInt32, FFIUInt32)+ PW8 -> (FFISInt64, FFIUInt64)++-- Make a dummy literal, to be used as a placeholder for FFI return+-- values on the stack.+mkDummyLiteral :: Platform -> PrimRep -> Literal+mkDummyLiteral platform pr+ = case pr of+ IntRep -> mkLitInt platform 0+ WordRep -> mkLitWord platform 0+ Int8Rep -> mkLitInt8 0+ Word8Rep -> mkLitWord8 0+ Int16Rep -> mkLitInt16 0+ Word16Rep -> mkLitWord16 0+ Int32Rep -> mkLitInt32 0+ Word32Rep -> mkLitWord32 0+ Int64Rep -> mkLitInt64 0+ Word64Rep -> mkLitWord64 0+ AddrRep -> LitNullAddr+ DoubleRep -> LitDouble 0+ FloatRep -> LitFloat 0+ _ -> pprPanic "mkDummyLiteral" (ppr pr)+++-- Convert (eg)+-- GHC.Prim.Char# -> GHC.Prim.State# GHC.Prim.RealWorld+-- -> (# GHC.Prim.State# GHC.Prim.RealWorld, GHC.Prim.Int# #)+--+-- to Just IntRep+-- and check that an unboxed pair is returned wherein the first arg is V'd.+--+-- Alternatively, for call-targets returning nothing, convert+--+-- GHC.Prim.Char# -> GHC.Prim.State# GHC.Prim.RealWorld+-- -> (# GHC.Prim.State# GHC.Prim.RealWorld #)+--+-- to Nothing++maybe_getCCallReturnRep :: Type -> Maybe PrimRep+maybe_getCCallReturnRep fn_ty+ = let+ (_a_tys, r_ty) = splitFunTys (dropForAlls fn_ty)+ r_reps = typePrimRepArgs r_ty++ blargh :: a -- Used at more than one type+ blargh = pprPanic "maybe_getCCallReturn: can't handle:"+ (pprType fn_ty)+ in+ case r_reps of+ [] -> panic "empty typePrimRepArgs"+ [VoidRep] -> Nothing+ [rep]+ | isGcPtrRep rep -> blargh+ | otherwise -> Just rep++ -- if it was, it would be impossible to create a+ -- valid return value placeholder on the stack+ _ -> blargh++maybe_is_tagToEnum_call :: CgStgExpr -> Maybe (Id, [Name])+-- Detect and extract relevant info for the tagToEnum kludge.+maybe_is_tagToEnum_call (StgOpApp (StgPrimOp TagToEnumOp) [StgVarArg v] t)+ = Just (v, extract_constr_Names t)+ where+ extract_constr_Names ty+ | rep_ty <- unwrapType ty+ , Just tyc <- tyConAppTyCon_maybe rep_ty+ , isDataTyCon tyc+ = map (getName . dataConWorkId) (tyConDataCons tyc)+ -- NOTE: use the worker name, not the source name of+ -- the DataCon. See "GHC.Core.DataCon" for details.+ | otherwise+ = pprPanic "maybe_is_tagToEnum_call.extract_constr_Ids" (ppr ty)+maybe_is_tagToEnum_call _ = Nothing++{- -----------------------------------------------------------------------------+Note [Implementing tagToEnum#]+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+(implement_tagToId arg names) compiles code which takes an argument+'arg', (call it i), and enters the i'th closure in the supplied list+as a consequence. The [Name] is a list of the constructors of this+(enumeration) type.++The code we generate is this:+ push arg+ push bogus-word++ TESTEQ_I 0 L1+ PUSH_G <lbl for first data con>+ JMP L_Exit++ L1: TESTEQ_I 1 L2+ PUSH_G <lbl for second data con>+ JMP L_Exit+ ...etc...+ Ln: TESTEQ_I n L_fail+ PUSH_G <lbl for last data con>+ JMP L_Exit++ L_fail: CASEFAIL++ L_exit: SLIDE 1 n+ ENTER++The 'bogus-word' push is because TESTEQ_I expects the top of the stack+to have an info-table, and the next word to have the value to be+tested. This is very weird, but it's the way it is right now. See+Interpreter.c. We don't actually need an info-table here; we just+need to have the argument to be one-from-top on the stack, hence pushing+a 1-word null. See #8383.+-}+++implement_tagToId+ :: StackDepth+ -> Sequel+ -> BCEnv+ -> Id+ -> [Name]+ -> BcM BCInstrList+-- See Note [Implementing tagToEnum#]+implement_tagToId d s p arg names+ = ASSERT( notNull names )+ do (push_arg, arg_bytes) <- pushAtom d p (StgVarArg arg)+ labels <- getLabelsBc (genericLength names)+ label_fail <- getLabelBc+ label_exit <- getLabelBc+ dflags <- getDynFlags+ let infos = zip4 labels (tail labels ++ [label_fail])+ [0 ..] names+ platform = targetPlatform dflags+ steps = map (mkStep label_exit) infos+ slide_ws = bytesToWords platform (d - s + arg_bytes)++ return (push_arg+ `appOL` unitOL (PUSH_UBX LitNullAddr 1)+ -- Push bogus word (see Note [Implementing tagToEnum#])+ `appOL` concatOL steps+ `appOL` toOL [ LABEL label_fail, CASEFAIL,+ LABEL label_exit ]+ `appOL` mkSlideW 1 (slide_ws + 1)+ -- "+1" to account for bogus word+ -- (see Note [Implementing tagToEnum#])+ `appOL` unitOL ENTER)+ where+ mkStep l_exit (my_label, next_label, n, name_for_n)+ = toOL [LABEL my_label,+ TESTEQ_I n next_label,+ PUSH_G name_for_n,+ JMP l_exit]+++-- -----------------------------------------------------------------------------+-- pushAtom++-- Push an atom onto the stack, returning suitable code & number of+-- stack words used.+--+-- The env p must map each variable to the highest- numbered stack+-- slot for it. For example, if the stack has depth 4 and we+-- tagged-ly push (v :: Int#) on it, the value will be in stack[4],+-- the tag in stack[5], the stack will have depth 6, and p must map v+-- to 5 and not to 4. Stack locations are numbered from zero, so a+-- depth 6 stack has valid words 0 .. 5.++pushAtom+ :: StackDepth -> BCEnv -> StgArg -> BcM (BCInstrList, ByteOff)++-- See Note [Empty case alternatives] in GHC.Core+-- and Note [Bottoming expressions] in GHC.Core.Utils:+-- The scrutinee of an empty case evaluates to bottom+pushAtom d p (StgVarArg var)+ | [] <- typePrimRep (idType var)+ = return (nilOL, 0)++ | isFCallId var+ = pprPanic "pushAtom: shouldn't get an FCallId here" (ppr var)++ | Just primop <- isPrimOpId_maybe var+ = do+ platform <- targetPlatform <$> getDynFlags+ return (unitOL (PUSH_PRIMOP primop), wordSize platform)++ | Just d_v <- lookupBCEnv_maybe var p -- var is a local variable+ = do platform <- targetPlatform <$> getDynFlags++ let !szb = idSizeCon platform var+ with_instr instr = do+ let !off_b = trunc16B $ d - d_v+ return (unitOL (instr off_b), wordSize platform)++ case szb of+ 1 -> with_instr PUSH8_W+ 2 -> with_instr PUSH16_W+ 4 -> with_instr PUSH32_W+ _ -> do+ let !szw = bytesToWords platform szb+ !off_w = trunc16W $ bytesToWords platform (d - d_v) + szw - 1+ return (toOL (genericReplicate szw (PUSH_L off_w)), szb)+ -- d - d_v offset from TOS to the first slot of the object+ --+ -- d - d_v + sz - 1 offset from the TOS of the last slot of the object+ --+ -- Having found the last slot, we proceed to copy the right number of+ -- slots on to the top of the stack.++ | otherwise -- var must be a global variable+ = do topStrings <- getTopStrings+ platform <- targetPlatform <$> getDynFlags+ case lookupVarEnv topStrings var of+ Just ptr -> pushAtom d p $ StgLitArg $ mkLitWord platform $+ fromIntegral $ ptrToWordPtr $ fromRemotePtr ptr+ Nothing -> do+ let sz = idSizeCon platform var+ MASSERT( sz == wordSize platform )+ return (unitOL (PUSH_G (getName var)), sz)++pushAtom _ _ (StgLitArg lit) = do+ platform <- targetPlatform <$> getDynFlags+ let code :: PrimRep -> BcM (BCInstrList, ByteOff)+ code rep =+ return (unitOL instr, size_bytes)+ where+ size_bytes = ByteOff $ primRepSizeB platform rep+ -- Here we handle the non-word-width cases specifically since we+ -- must emit different bytecode for them.+ instr =+ case size_bytes of+ 1 -> PUSH_UBX8 lit+ 2 -> PUSH_UBX16 lit+ 4 -> PUSH_UBX32 lit+ _ -> PUSH_UBX lit (trunc16W $ bytesToWords platform size_bytes)++ case lit of+ LitLabel {} -> code AddrRep+ LitFloat {} -> code FloatRep+ LitDouble {} -> code DoubleRep+ LitChar {} -> code WordRep+ LitNullAddr -> code AddrRep+ LitString {} -> code AddrRep+ LitRubbish {} -> code WordRep+ LitNumber nt _ -> case nt of+ LitNumInt -> code IntRep+ LitNumWord -> code WordRep+ LitNumInt8 -> code Int8Rep+ LitNumWord8 -> code Word8Rep+ LitNumInt16 -> code Int16Rep+ LitNumWord16 -> code Word16Rep+ LitNumInt32 -> code Int32Rep+ LitNumWord32 -> code Word32Rep+ LitNumInt64 -> code Int64Rep+ LitNumWord64 -> code Word64Rep+ -- No LitInteger's or LitNatural's should be left by the time this is+ -- called. CorePrep should have converted them all to a real core+ -- representation.+ LitNumInteger -> panic "pushAtom: LitInteger"+ LitNumNatural -> panic "pushAtom: LitNatural"++-- | Push an atom for constructor (i.e., PACK instruction) onto the stack.+-- This is slightly different to @pushAtom@ due to the fact that we allow+-- packing constructor fields. See also @mkConAppCode@ and @pushPadding@.+pushConstrAtom+ :: StackDepth -> BCEnv -> StgArg -> BcM (BCInstrList, ByteOff)+pushConstrAtom _ _ (StgLitArg lit@(LitFloat _)) =+ return (unitOL (PUSH_UBX32 lit), 4)++pushConstrAtom d p va@(StgVarArg v)+ | Just d_v <- lookupBCEnv_maybe v p = do -- v is a local variable+ platform <- targetPlatform <$> getDynFlags+ let !szb = idSizeCon platform v+ done instr = do+ let !off = trunc16B $ d - d_v+ return (unitOL (instr off), szb)+ case szb of+ 1 -> done PUSH8+ 2 -> done PUSH16+ 4 -> done PUSH32+ _ -> pushAtom d p va++pushConstrAtom d p expr = pushAtom d p expr++pushPadding :: Int -> (BCInstrList, ByteOff)+pushPadding !n = go n (nilOL, 0)+ where+ go n acc@(!instrs, !off) = case n of+ 0 -> acc+ 1 -> (instrs `mappend` unitOL PUSH_PAD8, off + 1)+ 2 -> (instrs `mappend` unitOL PUSH_PAD16, off + 2)+ 3 -> go 1 (go 2 acc)+ 4 -> (instrs `mappend` unitOL PUSH_PAD32, off + 4)+ _ -> go (n - 4) (go 4 acc)++-- -----------------------------------------------------------------------------+-- Given a bunch of alts code and their discrs, do the donkey work+-- of making a multiway branch using a switch tree.+-- What a load of hassle!++mkMultiBranch :: Maybe Int -- # datacons in tycon, if alg alt+ -- a hint; generates better code+ -- Nothing is always safe+ -> [(Discr, BCInstrList)]+ -> BcM BCInstrList+mkMultiBranch maybe_ncons raw_ways = do+ lbl_default <- getLabelBc++ let+ mkTree :: [(Discr, BCInstrList)] -> Discr -> Discr -> BcM BCInstrList+ mkTree [] _range_lo _range_hi = return (unitOL (JMP lbl_default))+ -- shouldn't happen?++ mkTree [val] range_lo range_hi+ | range_lo == range_hi+ = return (snd val)+ | null defaults -- Note [CASEFAIL]+ = do lbl <- getLabelBc+ return (testEQ (fst val) lbl+ `consOL` (snd val+ `appOL` (LABEL lbl `consOL` unitOL CASEFAIL)))+ | otherwise+ = return (testEQ (fst val) lbl_default `consOL` snd val)++ -- Note [CASEFAIL] It may be that this case has no default+ -- branch, but the alternatives are not exhaustive - this+ -- happens for GADT cases for example, where the types+ -- prove that certain branches are impossible. We could+ -- just assume that the other cases won't occur, but if+ -- this assumption was wrong (because of a bug in GHC)+ -- then the result would be a segfault. So instead we+ -- emit an explicit test and a CASEFAIL instruction that+ -- causes the interpreter to barf() if it is ever+ -- executed.++ mkTree vals range_lo range_hi+ = let n = length vals `div` 2+ vals_lo = take n vals+ vals_hi = drop n vals+ v_mid = fst (head vals_hi)+ in do+ label_geq <- getLabelBc+ code_lo <- mkTree vals_lo range_lo (dec v_mid)+ code_hi <- mkTree vals_hi v_mid range_hi+ return (testLT v_mid label_geq+ `consOL` (code_lo+ `appOL` unitOL (LABEL label_geq)+ `appOL` code_hi))++ the_default+ = case defaults of+ [] -> nilOL+ [(_, def)] -> LABEL lbl_default `consOL` def+ _ -> panic "mkMultiBranch/the_default"+ instrs <- mkTree notd_ways init_lo init_hi+ return (instrs `appOL` the_default)+ where+ (defaults, not_defaults) = partition (isNoDiscr.fst) raw_ways+ notd_ways = sortBy (comparing fst) not_defaults++ testLT (DiscrI i) fail_label = TESTLT_I i fail_label+ testLT (DiscrW i) fail_label = TESTLT_W i fail_label+ testLT (DiscrF i) fail_label = TESTLT_F i fail_label+ testLT (DiscrD i) fail_label = TESTLT_D i fail_label+ testLT (DiscrP i) fail_label = TESTLT_P i fail_label+ testLT NoDiscr _ = panic "mkMultiBranch NoDiscr"++ testEQ (DiscrI i) fail_label = TESTEQ_I i fail_label+ testEQ (DiscrW i) fail_label = TESTEQ_W i fail_label+ testEQ (DiscrF i) fail_label = TESTEQ_F i fail_label+ testEQ (DiscrD i) fail_label = TESTEQ_D i fail_label+ testEQ (DiscrP i) fail_label = TESTEQ_P i fail_label+ testEQ NoDiscr _ = panic "mkMultiBranch NoDiscr"++ -- None of these will be needed if there are no non-default alts+ (init_lo, init_hi)+ | null notd_ways+ = panic "mkMultiBranch: awesome foursome"+ | otherwise+ = case fst (head notd_ways) of+ DiscrI _ -> ( DiscrI minBound, DiscrI maxBound )+ DiscrW _ -> ( DiscrW minBound, DiscrW maxBound )+ DiscrF _ -> ( DiscrF minF, DiscrF maxF )+ DiscrD _ -> ( DiscrD minD, DiscrD maxD )+ DiscrP _ -> ( DiscrP algMinBound, DiscrP algMaxBound )+ NoDiscr -> panic "mkMultiBranch NoDiscr"++ (algMinBound, algMaxBound)+ = case maybe_ncons of+ -- XXX What happens when n == 0?+ Just n -> (0, fromIntegral n - 1)+ Nothing -> (minBound, maxBound)++ isNoDiscr NoDiscr = True+ isNoDiscr _ = False++ dec (DiscrI i) = DiscrI (i-1)+ dec (DiscrW w) = DiscrW (w-1)+ dec (DiscrP i) = DiscrP (i-1)+ dec other = other -- not really right, but if you+ -- do cases on floating values, you'll get what you deserve++ -- same snotty comment applies to the following+ minF, maxF :: Float+ minD, maxD :: Double+ minF = -1.0e37+ maxF = 1.0e37+ minD = -1.0e308+ maxD = 1.0e308+++-- -----------------------------------------------------------------------------+-- Supporting junk for the compilation schemes++-- Describes case alts+data Discr+ = DiscrI Int+ | DiscrW Word+ | DiscrF Float+ | DiscrD Double+ | DiscrP Word16+ | NoDiscr+ deriving (Eq, Ord)++instance Outputable Discr where+ ppr (DiscrI i) = int i+ ppr (DiscrW w) = text (show w)+ ppr (DiscrF f) = text (show f)+ ppr (DiscrD d) = text (show d)+ ppr (DiscrP i) = ppr i+ ppr NoDiscr = text "DEF"+++lookupBCEnv_maybe :: Id -> BCEnv -> Maybe ByteOff+lookupBCEnv_maybe = Map.lookup++idSizeW :: Platform -> Id -> WordOff+idSizeW platform = WordOff . argRepSizeW platform . bcIdArgRep platform++idSizeCon :: Platform -> Id -> ByteOff+idSizeCon platform var+ -- unboxed tuple components are padded to word size+ | isUnboxedTupleType (idType var) ||+ isUnboxedSumType (idType var) =+ wordsToBytes platform .+ WordOff . sum . map (argRepSizeW platform . toArgRep platform) .+ bcIdPrimReps $ var+ | otherwise = ByteOff (primRepSizeB platform (bcIdPrimRep var))++bcIdArgRep :: Platform -> Id -> ArgRep+bcIdArgRep platform = toArgRep platform . bcIdPrimRep++bcIdPrimRep :: Id -> PrimRep+bcIdPrimRep id+ | [rep] <- typePrimRepArgs (idType id)+ = rep+ | otherwise+ = pprPanic "bcIdPrimRep" (ppr id <+> dcolon <+> ppr (idType id))+++bcIdPrimReps :: Id -> [PrimRep]+bcIdPrimReps id = typePrimRepArgs (idType id)++repSizeWords :: Platform -> PrimRep -> WordOff+repSizeWords platform rep = WordOff $ argRepSizeW platform (toArgRep platform rep)++isFollowableArg :: ArgRep -> Bool+isFollowableArg P = True+isFollowableArg _ = False++-- | Indicate if the calling convention is supported+isSupportedCConv :: CCallSpec -> Bool+isSupportedCConv (CCallSpec _ cconv _) = case cconv of+ CCallConv -> True -- we explicitly pattern match on every+ StdCallConv -> True -- convention to ensure that a warning+ PrimCallConv -> False -- is triggered when a new one is added+ JavaScriptCallConv -> False+ CApiConv -> False++-- See bug #10462+unsupportedCConvException :: a+unsupportedCConvException = throwGhcException (ProgramError+ ("Error: bytecode compiler can't handle some foreign calling conventions\n"+++ " Workaround: use -fobject-code, or compile this module to .o separately."))++mkSlideB :: Platform -> ByteOff -> ByteOff -> OrdList BCInstr+mkSlideB platform !nb !db = mkSlideW n d+ where+ !n = trunc16W $ bytesToWords platform nb+ !d = bytesToWords platform db++mkSlideW :: Word16 -> WordOff -> OrdList BCInstr+mkSlideW !n !ws+ | ws > fromIntegral limit+ -- If the amount to slide doesn't fit in a Word16, generate multiple slide+ -- instructions+ = SLIDE n limit `consOL` mkSlideW n (ws - fromIntegral limit)+ | ws == 0+ = nilOL+ | otherwise+ = unitOL (SLIDE n $ fromIntegral ws)+ where+ limit :: Word16+ limit = maxBound++atomPrimRep :: StgArg -> PrimRep+atomPrimRep (StgVarArg v) = bcIdPrimRep v+atomPrimRep (StgLitArg l) = typePrimRep1 (literalType l)++atomRep :: Platform -> StgArg -> ArgRep+atomRep platform e = toArgRep platform (atomPrimRep e)++-- | Let szsw be the sizes in bytes of some items pushed onto the stack, which+-- has initial depth @original_depth@. Return the values which the stack+-- environment should map these items to.+mkStackOffsets :: ByteOff -> [ByteOff] -> [ByteOff]+mkStackOffsets original_depth szsb = tail (scanl' (+) original_depth szsb)++typeArgReps :: Platform -> Type -> [ArgRep]+typeArgReps platform = map (toArgRep platform) . typePrimRepArgs++-- -----------------------------------------------------------------------------+-- The bytecode generator's monad++data BcM_State+ = BcM_State+ { bcm_hsc_env :: HscEnv+ , uniqSupply :: UniqSupply -- for generating fresh variable names+ , thisModule :: Module -- current module (for breakpoints)+ , nextlabel :: Word32 -- for generating local labels+ , ffis :: [FFIInfo] -- ffi info blocks, to free later+ -- Should be free()d when it is GCd+ , modBreaks :: Maybe ModBreaks -- info about breakpoints+ , breakInfo :: IntMap CgBreakInfo+ , topStrings :: IdEnv (RemotePtr ()) -- top-level string literals+ -- See Note [generating code for top-level string literal bindings].+ }++newtype BcM r = BcM (BcM_State -> IO (BcM_State, r)) deriving (Functor)++ioToBc :: IO a -> BcM a+ioToBc io = BcM $ \st -> do+ x <- io+ return (st, x)++runBc :: HscEnv -> UniqSupply -> Module -> Maybe ModBreaks+ -> IdEnv (RemotePtr ())+ -> BcM r+ -> IO (BcM_State, r)+runBc hsc_env us this_mod modBreaks topStrings (BcM m)+ = m (BcM_State hsc_env us this_mod 0 [] modBreaks IntMap.empty topStrings)++thenBc :: BcM a -> (a -> BcM b) -> BcM b+thenBc (BcM expr) cont = BcM $ \st0 -> do+ (st1, q) <- expr st0+ let BcM k = cont q+ (st2, r) <- k st1+ return (st2, r)++thenBc_ :: BcM a -> BcM b -> BcM b+thenBc_ (BcM expr) (BcM cont) = BcM $ \st0 -> do+ (st1, _) <- expr st0+ (st2, r) <- cont st1+ return (st2, r)++returnBc :: a -> BcM a+returnBc result = BcM $ \st -> (return (st, result))++instance Applicative BcM where+ pure = returnBc+ (<*>) = ap+ (*>) = thenBc_++instance Monad BcM where+ (>>=) = thenBc+ (>>) = (*>)++instance HasDynFlags BcM where+ getDynFlags = BcM $ \st -> return (st, hsc_dflags (bcm_hsc_env st))++getHscEnv :: BcM HscEnv+getHscEnv = BcM $ \st -> return (st, bcm_hsc_env st)++getProfile :: BcM Profile+getProfile = targetProfile <$> getDynFlags++emitBc :: ([FFIInfo] -> ProtoBCO Name) -> BcM (ProtoBCO Name)+emitBc bco+ = BcM $ \st -> return (st{ffis=[]}, bco (ffis st))++recordFFIBc :: RemotePtr C_ffi_cif -> BcM ()+recordFFIBc a+ = BcM $ \st -> return (st{ffis = FFIInfo a : ffis st}, ())++getLabelBc :: BcM LocalLabel+getLabelBc+ = BcM $ \st -> do let nl = nextlabel st+ when (nl == maxBound) $+ panic "getLabelBc: Ran out of labels"+ return (st{nextlabel = nl + 1}, LocalLabel nl)++getLabelsBc :: Word32 -> BcM [LocalLabel]+getLabelsBc n+ = BcM $ \st -> let ctr = nextlabel st+ in return (st{nextlabel = ctr+n}, coerce [ctr .. ctr+n-1])++getCCArray :: BcM (Array BreakIndex (RemotePtr CostCentre))+getCCArray = BcM $ \st ->+ let breaks = expectJust "GHC.StgToByteCode.getCCArray" $ modBreaks st in+ return (st, modBreaks_ccs breaks)+++newBreakInfo :: BreakIndex -> CgBreakInfo -> BcM ()+newBreakInfo ix info = BcM $ \st ->+ return (st{breakInfo = IntMap.insert ix info (breakInfo st)}, ())++newUnique :: BcM Unique+newUnique = BcM $+ \st -> case takeUniqFromSupply (uniqSupply st) of+ (uniq, us) -> let newState = st { uniqSupply = us }+ in return (newState, uniq)++getCurrentModule :: BcM Module+getCurrentModule = BcM $ \st -> return (st, thisModule st)++getTopStrings :: BcM (IdEnv (RemotePtr ()))+getTopStrings = BcM $ \st -> return (st, topStrings st)++newId :: Type -> BcM Id+newId ty = do+ uniq <- newUnique+ return $ mkSysLocal tickFS uniq Many ty++tickFS :: FastString+tickFS = fsLit "ticked"
compiler/GHC/StgToCmm.hs view
@@ -1,6 +1,7 @@ {-# LANGUAGE CPP #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE BangPatterns #-}+{-# LANGUAGE LambdaCase #-} ----------------------------------------------------------------------------- --@@ -19,7 +20,7 @@ import GHC.Driver.Backend import GHC.Driver.Session -import GHC.StgToCmm.Prof (initCostCentres, ldvEnter)+import GHC.StgToCmm.Prof (initInfoTableProv, initCostCentres, ldvEnter) import GHC.StgToCmm.Monad import GHC.StgToCmm.Env import GHC.StgToCmm.Bind@@ -39,6 +40,7 @@ import GHC.Stg.Syntax import GHC.Types.CostCentre+import GHC.Types.IPE import GHC.Types.HpcInfo import GHC.Types.Id import GHC.Types.Id.Info@@ -47,6 +49,7 @@ import GHC.Types.Var.Set ( isEmptyDVarSet ) import GHC.Types.Unique.FM import GHC.Types.Name.Env+import GHC.Types.ForeignStubs import GHC.Core.DataCon import GHC.Core.TyCon@@ -59,46 +62,63 @@ import GHC.Utils.Panic import GHC.Utils.Logger -import GHC.SysTools.FileCleanup+import GHC.Utils.TmpFs import GHC.Data.Stream import GHC.Data.OrdList+import GHC.Types.Unique.Map -import Data.IORef-import Control.Monad (when,void)+import Control.Monad (when,void, forM_) import GHC.Utils.Misc import System.IO.Unsafe import qualified Data.ByteString as BS+import Data.Maybe+import Data.IORef +data CodeGenState = CodeGenState { codegen_used_info :: !(OrdList CmmInfoTable)+ , codegen_state :: !CgState }++ codeGen :: Logger+ -> TmpFs -> DynFlags -> Module+ -> InfoTableProvMap -> [TyCon] -> CollectedCCs -- (Local/global) cost-centres needing declaring/registering. -> [CgStgTopBinding] -- Bindings to convert -> HpcInfo- -> Stream IO CmmGroup ModuleLFInfos- -- Output as a stream, so codegen can+ -> Stream IO CmmGroup (CStub, ModuleLFInfos) -- Output as a stream, so codegen can -- be interleaved with output -codeGen logger dflags this_mod data_tycons+codeGen logger tmpfs dflags this_mod ip_map@(InfoTableProvMap (UniqMap denv) _) data_tycons cost_centre_info stg_binds hpc_info = do { -- cg: run the code generator, and yield the resulting CmmGroup -- Using an IORef to store the state is a bit crude, but otherwise- -- we would need to add a state monad layer.- ; cgref <- liftIO $ newIORef =<< initC- ; let cg :: FCode () -> Stream IO CmmGroup ()+ -- we would need to add a state monad layer which regresses+ -- allocations by 0.5-2%.+ ; cgref <- liftIO $ initC >>= \s -> newIORef (CodeGenState mempty s)+ ; let cg :: FCode a -> Stream IO CmmGroup a cg fcode = do- cmm <- liftIO . withTimingSilent logger dflags (text "STG -> Cmm") (`seq` ()) $ do- st <- readIORef cgref+ (a, cmm) <- liftIO . withTimingSilent logger dflags (text "STG -> Cmm") (`seq` ()) $ do+ CodeGenState ts st <- readIORef cgref let (a,st') = runC dflags this_mod st (getCmm fcode) -- NB. stub-out cgs_tops and cgs_stmts. This fixes -- a big space leak. DO NOT REMOVE!- writeIORef cgref $! st'{ cgs_tops = nilOL,- cgs_stmts = mkNop }+ -- This is observed by the #3294 test+ let !used_info+ | gopt Opt_InfoTableMap dflags = toOL (mapMaybe topInfoTable (snd a)) `mappend` ts+ | otherwise = mempty+ writeIORef cgref $!+ CodeGenState used_info+ (st'{ cgs_tops = nilOL,+ cgs_stmts = mkNop+ })+ return a yield cmm+ return a -- Note [codegen-split-init] the cmm_init block must come -- FIRST. This is because when -split-objs is on we need to@@ -106,8 +126,7 @@ -- Note [pipeline-split-init]. ; cg (mkModuleInit cost_centre_info this_mod hpc_info) - ; mapM_ (cg . cgTopBinding logger dflags) stg_binds-+ ; mapM_ (cg . cgTopBinding logger tmpfs dflags) stg_binds -- Put datatype_stuff after code_stuff, because the -- datatype closure table (for enumeration types) to -- (say) PrelBase_True_closure, which is defined in@@ -117,12 +136,21 @@ -- enumeration type Note that the closure pointers are -- tagged. when (isEnumerationTyCon tycon) $ cg (cgEnumerationTyCon tycon)- mapM_ (cg . cgDataCon) (tyConDataCons tycon)+ -- Emit normal info_tables, for data constructors defined in this module.+ mapM_ (cg . cgDataCon DefinitionSite) (tyConDataCons tycon) ; mapM_ do_tycon data_tycons - ; cg_id_infos <- cgs_binds <$> liftIO (readIORef cgref)+ -- Emit special info tables for everything used in this module+ -- This will only do something if `-fdistinct-info-tables` is turned on.+ ; mapM_ (\(dc, ns) -> forM_ ns $ \(k, _ss) -> cg (cgDataCon (UsageSite this_mod k) dc)) (nonDetEltsUFM denv) + ; final_state <- liftIO (readIORef cgref)+ ; let cg_id_infos = cgs_binds . codegen_state $ final_state+ used_info = fromOL . codegen_used_info $ final_state++ ; !foreign_stub <- cg (initInfoTableProv used_info ip_map this_mod)+ -- See Note [Conveying CAF-info and LFInfo between modules] in -- GHC.StgToCmm.Types ; let extractInfo info = (name, lf)@@ -136,7 +164,7 @@ | otherwise = mkNameEnv (Prelude.map extractInfo (eltsUFM cg_id_infos)) - ; return generatedInfo+ ; return (foreign_stub, generatedInfo) } ---------------------------------------------------------------@@ -153,46 +181,45 @@ style, with the increasing static environment being plumbed as a state variable. -} -cgTopBinding :: Logger -> DynFlags -> CgStgTopBinding -> FCode ()-cgTopBinding _logger dflags (StgTopLifted (StgNonRec id rhs))- = do { let (info, fcode) = cgTopRhs dflags NonRecursive id rhs- ; fcode- ; addBindC info- }+cgTopBinding :: Logger -> TmpFs -> DynFlags -> CgStgTopBinding -> FCode ()+cgTopBinding logger tmpfs dflags = \case+ StgTopLifted (StgNonRec id rhs) -> do+ let (info, fcode) = cgTopRhs dflags NonRecursive id rhs+ fcode+ addBindC info -cgTopBinding _logger dflags (StgTopLifted (StgRec pairs))- = do { let (bndrs, rhss) = unzip pairs- ; let pairs' = zip bndrs rhss- r = unzipWith (cgTopRhs dflags Recursive) pairs'- (infos, fcodes) = unzip r- ; addBindsC infos- ; sequence_ fcodes- }+ StgTopLifted (StgRec pairs) -> do+ let (bndrs, rhss) = unzip pairs+ let pairs' = zip bndrs rhss+ r = unzipWith (cgTopRhs dflags Recursive) pairs'+ (infos, fcodes) = unzip r+ addBindsC infos+ sequence_ fcodes -cgTopBinding logger dflags (StgTopStringLit id str) = do- let label = mkBytesLabel (idName id)- -- emit either a CmmString literal or dump the string in a file and emit a- -- CmmFileEmbed literal.- -- See Note [Embedding large binary blobs] in GHC.CmmToAsm.Ppr- let isNCG = backend dflags == NCG- isSmall = fromIntegral (BS.length str) <= binBlobThreshold dflags- asString = binBlobThreshold dflags == 0 || isSmall+ StgTopStringLit id str -> do+ let label = mkBytesLabel (idName id)+ -- emit either a CmmString literal or dump the string in a file and emit a+ -- CmmFileEmbed literal.+ -- See Note [Embedding large binary blobs] in GHC.CmmToAsm.Ppr+ let isNCG = backend dflags == NCG+ isSmall = fromIntegral (BS.length str) <= binBlobThreshold dflags+ asString = binBlobThreshold dflags == 0 || isSmall - (lit,decl) = if not isNCG || asString- then mkByteStringCLit label str- else mkFileEmbedLit label $ unsafePerformIO $ do- bFile <- newTempName logger dflags TFL_CurrentModule ".dat"- BS.writeFile bFile str- return bFile- emitDecl decl- addBindC (litIdInfo (targetPlatform dflags) id mkLFStringLit lit)+ (lit,decl) = if not isNCG || asString+ then mkByteStringCLit label str+ else mkFileEmbedLit label $ unsafePerformIO $ do+ bFile <- newTempName logger tmpfs dflags TFL_CurrentModule ".dat"+ BS.writeFile bFile str+ return bFile+ emitDecl decl+ addBindC (litIdInfo (targetPlatform dflags) id mkLFStringLit lit) cgTopRhs :: DynFlags -> RecFlag -> Id -> CgStgRhs -> (CgIdInfo, FCode ()) -- The Id is passed along for setting up a binding... -cgTopRhs dflags _rec bndr (StgRhsCon _cc con args)- = cgTopRhsCon dflags bndr con (assertNonVoidStgArgs args)+cgTopRhs dflags _rec bndr (StgRhsCon _cc con mn _ts args)+ = cgTopRhsCon dflags bndr con mn (assertNonVoidStgArgs args) -- con args are always non-void, -- see Note [Post-unarisation invariants] in GHC.Stg.Unarise @@ -231,11 +258,12 @@ | con <- tyConDataCons tycon] --- | Generate the entry code, info tables, and (for niladic constructor)+cgDataCon :: ConInfoTableLocation -> DataCon -> FCode ()+-- Generate the entry code, info tables, and (for niladic constructor) -- the static closure, for a constructor.-cgDataCon :: DataCon -> FCode ()-cgDataCon data_con- = do { profile <- getProfile+cgDataCon mn data_con+ = do { MASSERT( not (isUnboxedTupleDataCon data_con || isUnboxedSumDataCon data_con) )+ ; profile <- getProfile ; platform <- getPlatform ; let (tot_wds, -- #ptr_wds + #nonptr_wds@@ -245,7 +273,7 @@ nonptr_wds = tot_wds - ptr_wds dyn_info_tbl =- mkDataConInfoTable profile data_con False ptr_wds nonptr_wds+ mkDataConInfoTable profile data_con mn False ptr_wds nonptr_wds -- We're generating info tables, so we don't know and care about -- what the actual arguments are. Using () here as the place holder.
compiler/GHC/StgToCmm/ArgRep.hs view
@@ -87,7 +87,7 @@ PW8 -> N FloatRep -> F DoubleRep -> D- (VecRep len elem) -> case len*primElemRepSizeB elem of+ (VecRep len elem) -> case len*primElemRepSizeB platform elem of 16 -> V16 32 -> V32 64 -> V64
compiler/GHC/StgToCmm/Bind.hs view
@@ -32,7 +32,7 @@ import GHC.StgToCmm.Foreign (emitPrimCall) import GHC.Cmm.Graph-import GHC.Core ( AltCon(..), tickishIsCode )+import GHC.Core ( AltCon(..) ) import GHC.Cmm.BlockId import GHC.Runtime.Heap.Layout import GHC.Cmm@@ -49,6 +49,7 @@ import GHC.Utils.Misc import GHC.Types.Var.Set import GHC.Types.Basic+import GHC.Types.Tickish ( tickishIsCode ) import GHC.Utils.Outputable import GHC.Utils.Panic import GHC.Data.FastString@@ -205,9 +206,9 @@ -- (see above) ) -cgRhs id (StgRhsCon cc con args)+cgRhs id (StgRhsCon cc con mn _ts args) = withNewTickyCounterCon (idName id) con $- buildDynCon id True cc con (assertNonVoidStgArgs args)+ buildDynCon id mn True cc con (assertNonVoidStgArgs args) -- con args are always non-void, -- see Note [Post-unarisation invariants] in GHC.Stg.Unarise
compiler/GHC/StgToCmm/Closure.hs view
@@ -905,8 +905,8 @@ -- CmmInfoTable-related things -------------------------------------- -mkDataConInfoTable :: Profile -> DataCon -> Bool -> Int -> Int -> CmmInfoTable-mkDataConInfoTable profile data_con is_static ptr_wds nonptr_wds+mkDataConInfoTable :: Profile -> DataCon -> ConInfoTableLocation -> Bool -> Int -> Int -> CmmInfoTable+mkDataConInfoTable profile data_con mn is_static ptr_wds nonptr_wds = CmmInfoTable { cit_lbl = info_lbl , cit_rep = sm_rep , cit_prof = prof@@ -914,7 +914,7 @@ , cit_clo = Nothing } where name = dataConName data_con- info_lbl = mkConInfoTableLabel name NoCafRefs+ info_lbl = mkConInfoTableLabel name mn -- NoCAFRefs sm_rep = mkHeapRep profile is_static ptr_wds nonptr_wds cl_type cl_type = Constr (dataConTagZ data_con) (dataConIdentity data_con) -- We keep the *zero-indexed* tag in the srt_len field
compiler/GHC/StgToCmm/DataCon.hs view
@@ -62,9 +62,10 @@ cgTopRhsCon :: DynFlags -> Id -- Name of thing bound to this RHS -> DataCon -- Id+ -> ConstructorNumber -> [NonVoid StgArg] -- Args -> (CgIdInfo, FCode ())-cgTopRhsCon dflags id con args+cgTopRhsCon dflags id con mn args | Just static_info <- precomputedStaticConInfo_maybe dflags id con args , let static_code | isInternalName name = pure () | otherwise = gen_code@@ -129,7 +130,7 @@ -- we're not really going to emit an info table, so having -- to make a CmmInfoTable is a bit overkill, but mkStaticClosureFields -- needs to poke around inside it.- info_tbl = mkDataConInfoTable profile con True ptr_wds nonptr_wds+ info_tbl = mkDataConInfoTable profile con (addModuleLoc this_mod mn) True ptr_wds nonptr_wds ; payload <- mapM mk_payload (fix_padding nv_args_w_offsets)@@ -138,8 +139,17 @@ -- TODO (osa): Why? -- BUILD THE OBJECT+ --+ -- We're generating info tables, so we don't know and care about+ -- what the actual arguments are. Using () here as the place holder.+ ; emitDataCon closure_label info_tbl dontCareCCS payload } +addModuleLoc :: Module -> ConstructorNumber -> ConInfoTableLocation+addModuleLoc this_mod mn = do+ case mn of+ NoNumber -> DefinitionSite+ Numbered n -> UsageSite this_mod n --------------------------------------------------------------- -- Lay out and allocate non-top-level constructors@@ -147,6 +157,7 @@ buildDynCon :: Id -- Name of the thing to which this constr will -- be bound+ -> ConstructorNumber -> Bool -- is it genuinely bound to that name, or just -- for profiling? -> CostCentreStack -- Where to grab cost centre from;@@ -155,13 +166,14 @@ -> [NonVoid StgArg] -- Its args -> FCode (CgIdInfo, FCode CmmAGraph) -- Return details about how to find it and initialization code-buildDynCon binder actually_bound cc con args+buildDynCon binder mn actually_bound cc con args = do dflags <- getDynFlags- buildDynCon' dflags binder actually_bound cc con args+ buildDynCon' dflags binder mn actually_bound cc con args buildDynCon' :: DynFlags- -> Id -> Bool+ -> Id -> ConstructorNumber+ -> Bool -> CostCentreStack -> DataCon -> [NonVoid StgArg]@@ -178,13 +190,13 @@ premature looking at the args will cause the compiler to black-hole! -} -buildDynCon' dflags binder _ _cc con args+buildDynCon' dflags binder _ _ _cc con args | Just cgInfo <- precomputedStaticConInfo_maybe dflags binder con args -- , pprTrace "noCodeLocal:" (ppr (binder,con,args,cgInfo)) True = return (cgInfo, return mkNop) -------- buildDynCon': the general case ------------buildDynCon' _ binder actually_bound ccs con args+buildDynCon' _ binder mn actually_bound ccs con args = do { (id_info, reg) <- rhsIdInfo binder lf_info ; return (id_info, gen_code reg) }@@ -192,12 +204,13 @@ lf_info = mkConLFInfo con gen_code reg- = do { profile <- getProfile+ = do { modu <- getModuleName+ ; profile <- getProfile ; let platform = profilePlatform profile (tot_wds, ptr_wds, args_w_offsets)- = mkVirtConstrOffsets profile (addArgReps args)+ = mkVirtConstrOffsets profile (addArgReps args) nonptr_wds = tot_wds - ptr_wds- info_tbl = mkDataConInfoTable profile con False+ info_tbl = mkDataConInfoTable profile con (addModuleLoc modu mn) False ptr_wds nonptr_wds ; let ticky_name | actually_bound = Just binder | otherwise = Nothing
compiler/GHC/StgToCmm/Env.hs view
@@ -17,7 +17,6 @@ bindArgsToRegs, bindToReg, rebindToReg, bindArgToReg, idToReg,- getArgAmode, getNonVoidArgAmodes, getCgIdInfo, maybeLetNoEscape, ) where@@ -26,10 +25,8 @@ import GHC.Prelude -import GHC.Core.TyCon import GHC.Platform import GHC.StgToCmm.Monad-import GHC.StgToCmm.Utils import GHC.StgToCmm.Closure import GHC.Cmm.CLabel@@ -40,7 +37,6 @@ import GHC.Types.Id import GHC.Cmm.Graph import GHC.Types.Name-import GHC.Stg.Syntax import GHC.Core.Type import GHC.Builtin.Types.Prim import GHC.Types.Unique.FM@@ -136,12 +132,15 @@ let name = idName id ; if isExternalName name then let ext_lbl- | isUnliftedType (idType id) =+ | isBoxedType (idType id)+ = mkClosureLabel name $ idCafInfo id+ | isUnliftedType (idType id) -- An unlifted external Id must refer to a top-level -- string literal. See Note [Bytes label] in "GHC.Cmm.CLabel".- ASSERT( idType id `eqType` addrPrimTy )- mkBytesLabel name- | otherwise = mkClosureLabel name $ idCafInfo id+ = ASSERT( idType id `eqType` addrPrimTy )+ mkBytesLabel name+ | otherwise+ = pprPanic "GHC.StgToCmm.Env: label not found" (ppr id <+> dcolon <+> ppr (idType id)) in return $ litIdInfo platform id (mkLFImported id) (CmmLabel ext_lbl) else@@ -157,22 +156,6 @@ pprUFM local_binds $ \infos -> vcat [ ppr (cg_id info) | info <- infos ] ])------------------------getArgAmode :: NonVoid StgArg -> FCode CmmExpr-getArgAmode (NonVoid (StgVarArg var)) = idInfoToAmode <$> getCgIdInfo var-getArgAmode (NonVoid (StgLitArg lit)) = CmmLit <$> cgLit lit--getNonVoidArgAmodes :: [StgArg] -> FCode [CmmExpr]--- NB: Filters out void args,--- so the result list may be shorter than the argument list-getNonVoidArgAmodes [] = return []-getNonVoidArgAmodes (arg:args)- | isVoidRep (argPrimRep arg) = getNonVoidArgAmodes args- | otherwise = do { amode <- getArgAmode (NonVoid arg)- ; amodes <- getNonVoidArgAmodes args- ; return ( amode : amodes ) } ------------------------------------------------------------------------
compiler/GHC/StgToCmm/Expr.hs view
@@ -10,7 +10,7 @@ -- ----------------------------------------------------------------------------- -module GHC.StgToCmm.Expr ( cgExpr ) where+module GHC.StgToCmm.Expr ( cgExpr, cgLit ) where #include "GhclibHsVersions.h" @@ -24,6 +24,7 @@ import GHC.StgToCmm.DataCon import GHC.StgToCmm.Prof (saveCurrentCostCentre, restoreCurrentCostCentre, emitSetCCC) import GHC.StgToCmm.Layout+import GHC.StgToCmm.Lit import GHC.StgToCmm.Prim import GHC.StgToCmm.Hpc import GHC.StgToCmm.Ticky@@ -46,6 +47,7 @@ import GHC.Core.Type ( isUnliftedType ) import GHC.Types.RepType ( isVoidTy, countConRepArgs ) import GHC.Types.CostCentre ( CostCentreStack, currentCCS )+import GHC.Types.Tickish import GHC.Data.Maybe import GHC.Utils.Misc import GHC.Data.FastString@@ -112,10 +114,10 @@ cgExpr (StgOpApp op args ty) = cgOpApp op args ty-cgExpr (StgConApp con args _)= cgConApp con args+cgExpr (StgConApp con mn args _) = cgConApp con mn args cgExpr (StgTick t e) = cgTick t >> cgExpr e-cgExpr (StgLit lit) = do cmm_lit <- cgLit lit- emitReturn [CmmLit cmm_lit]+cgExpr (StgLit lit) = do cmm_expr <- cgLit lit+ emitReturn [cmm_expr] cgExpr (StgLet _ binds expr) = do { cgBind binds; cgExpr expr } cgExpr (StgLetNoEscape _ binds expr) =@@ -187,9 +189,9 @@ -> FCode (CgIdInfo, FCode ()) cgLetNoEscapeRhsBody local_cc bndr (StgRhsClosure _ cc _upd args body) = cgLetNoEscapeClosure bndr local_cc cc (nonVoidIds args) body-cgLetNoEscapeRhsBody local_cc bndr (StgRhsCon cc con args)+cgLetNoEscapeRhsBody local_cc bndr (StgRhsCon cc con mn _ts args) = cgLetNoEscapeClosure bndr local_cc cc []- (StgConApp con args (pprPanic "cgLetNoEscapeRhsBody" $+ (StgConApp con mn args (pprPanic "cgLetNoEscapeRhsBody" $ text "StgRhsCon doesn't have type args")) -- For a constructor RHS we want to generate a single chunk of -- code which can be jumped to from many places, which will@@ -862,8 +864,8 @@ -- Tail calls ----------------------------------------------------------------------------- -cgConApp :: DataCon -> [StgArg] -> FCode ReturnKind-cgConApp con stg_args+cgConApp :: DataCon -> ConstructorNumber -> [StgArg] -> FCode ReturnKind+cgConApp con mn stg_args | isUnboxedTupleDataCon con -- Unboxed tuple: assign and return = do { arg_exprs <- getNonVoidArgAmodes stg_args ; tickyUnboxedTupleReturn (length arg_exprs)@@ -871,7 +873,7 @@ | otherwise -- Boxed constructors; allocate and return = ASSERT2( stg_args `lengthIs` countConRepArgs con, ppr con <> parens (ppr (countConRepArgs con)) <+> ppr stg_args )- do { (idinfo, fcode_init) <- buildDynCon (dataConWorkId con) False+ do { (idinfo, fcode_init) <- buildDynCon (dataConWorkId con) mn False currentCCS con (assertNonVoidStgArgs stg_args) -- con args are always non-void, -- see Note [Post-unarisation invariants] in GHC.Stg.Unarise@@ -1113,7 +1115,7 @@ -- | Generate Cmm code for a tick. Depending on the type of Tickish, -- this will either generate actual Cmm instrumentation code, or -- simply pass on the annotation as a @CmmTickish@.-cgTick :: Tickish Id -> FCode ()+cgTick :: StgTickish -> FCode () cgTick tick = do { platform <- getPlatform ; case tick of
+ compiler/GHC/StgToCmm/Expr.hs-boot view
@@ -0,0 +1,7 @@+module GHC.StgToCmm.Expr where++import GHC.Cmm.Expr+import GHC.StgToCmm.Monad+import GHC.Types.Literal++cgLit :: Literal -> FCode CmmExpr
compiler/GHC/StgToCmm/Foreign.hs view
@@ -27,7 +27,6 @@ import GHC.Stg.Syntax import GHC.StgToCmm.Prof (storeCurCCS, ccsType)-import GHC.StgToCmm.Env import GHC.StgToCmm.Monad import GHC.StgToCmm.Utils import GHC.StgToCmm.Closure
compiler/GHC/StgToCmm/Heap.hs view
@@ -32,7 +32,6 @@ import GHC.StgToCmm.Prof (profDynAlloc, dynProfHdr, staticProfHdr) import GHC.StgToCmm.Ticky import GHC.StgToCmm.Closure-import GHC.StgToCmm.Env import GHC.Cmm.Graph
compiler/GHC/StgToCmm/Layout.hs view
@@ -26,7 +26,8 @@ mkVirtConstrSizes, getHpRelOffset, - ArgRep(..), toArgRep, argRepSizeW -- re-exported from GHC.StgToCmm.ArgRep+ ArgRep(..), toArgRep, argRepSizeW, -- re-exported from GHC.StgToCmm.ArgRep+ getArgAmode, getNonVoidArgAmodes ) where @@ -42,6 +43,7 @@ import GHC.StgToCmm.ArgRep -- notably: ( slowCallPattern ) import GHC.StgToCmm.Ticky import GHC.StgToCmm.Monad+import GHC.StgToCmm.Lit import GHC.StgToCmm.Utils import GHC.Cmm.Graph@@ -589,6 +591,24 @@ [P,P,P,P,P,P] -> Just ARG_PPPPPP _ -> Nothing++-------------------------------------------------------------------------+-- Amodes for arguments+-------------------------------------------------------------------------++getArgAmode :: NonVoid StgArg -> FCode CmmExpr+getArgAmode (NonVoid (StgVarArg var)) = idInfoToAmode <$> getCgIdInfo var+getArgAmode (NonVoid (StgLitArg lit)) = cgLit lit++getNonVoidArgAmodes :: [StgArg] -> FCode [CmmExpr]+-- NB: Filters out void args,+-- so the result list may be shorter than the argument list+getNonVoidArgAmodes [] = return []+getNonVoidArgAmodes (arg:args)+ | isVoidRep (argPrimRep arg) = getNonVoidArgAmodes args+ | otherwise = do { amode <- getArgAmode (NonVoid arg)+ ; amodes <- getNonVoidArgAmodes args+ ; return ( amode : amodes ) } ------------------------------------------------------------------------- --
+ compiler/GHC/StgToCmm/Lit.hs view
@@ -0,0 +1,105 @@+{-# LANGUAGE CPP, LambdaCase #-}++-----------------------------------------------------------------------------+--+-- Stg to C-- code generation: literals+--+-- (c) The University of Glasgow 2004-2006+--+-----------------------------------------------------------------------------++module GHC.StgToCmm.Lit (+ cgLit, mkSimpleLit,+ newStringCLit, newByteStringCLit+ ) where++#include "GhclibHsVersions.h"++import GHC.Prelude++import GHC.Platform+import GHC.StgToCmm.Monad+import GHC.StgToCmm.Env+import GHC.Cmm+import GHC.Cmm.CLabel+import GHC.Cmm.Utils++import GHC.Types.Literal+import GHC.Builtin.Types ( unitDataConId )+import GHC.Core.TyCon+import GHC.Utils.Misc+import GHC.Utils.Outputable+import GHC.Utils.Panic++import Data.ByteString (ByteString)+import qualified Data.ByteString.Char8 as BS8+import Data.Char (ord)++newStringCLit :: String -> FCode CmmLit+-- ^ Make a global definition for the string,+-- and return its label+newStringCLit str = newByteStringCLit (BS8.pack str)++newByteStringCLit :: ByteString -> FCode CmmLit+newByteStringCLit bytes+ = do { uniq <- newUnique+ ; let (lit, decl) = mkByteStringCLit (mkStringLitLabel uniq) bytes+ ; emitDecl decl+ ; return lit }++cgLit :: Literal -> FCode CmmExpr+cgLit (LitString s) =+ CmmLit <$> newByteStringCLit s+ -- not unpackFS; we want the UTF-8 byte stream.+cgLit (LitRubbish preps) =+ case expectOnly "cgLit:Rubbish" preps of -- Note [Post-unarisation invariants]+ VoidRep -> panic "cgLit:VoidRep" -- dito+ LiftedRep -> idInfoToAmode <$> getCgIdInfo unitDataConId+ UnliftedRep -> idInfoToAmode <$> getCgIdInfo unitDataConId+ AddrRep -> cgLit LitNullAddr+ VecRep n elem -> do+ platform <- getPlatform+ let elem_lit = mkSimpleLit platform (num_rep_lit (primElemRepToPrimRep elem))+ pure (CmmLit (CmmVec (replicate n elem_lit)))+ prep -> cgLit (num_rep_lit prep)+ where+ num_rep_lit IntRep = mkLitIntUnchecked 0+ num_rep_lit Int8Rep = mkLitInt8Unchecked 0+ num_rep_lit Int16Rep = mkLitInt16Unchecked 0+ num_rep_lit Int32Rep = mkLitInt32Unchecked 0+ num_rep_lit Int64Rep = mkLitInt64Unchecked 0+ num_rep_lit WordRep = mkLitWordUnchecked 0+ num_rep_lit Word8Rep = mkLitWord8Unchecked 0+ num_rep_lit Word16Rep = mkLitWord16Unchecked 0+ num_rep_lit Word32Rep = mkLitWord32Unchecked 0+ num_rep_lit Word64Rep = mkLitWord64Unchecked 0+ num_rep_lit FloatRep = LitFloat 0+ num_rep_lit DoubleRep = LitDouble 0+ num_rep_lit other = pprPanic "num_rep_lit: Not a num lit" (ppr other)+cgLit other_lit = do+ platform <- getPlatform+ pure (CmmLit (mkSimpleLit platform other_lit))++mkSimpleLit :: Platform -> Literal -> CmmLit+mkSimpleLit platform = \case+ (LitChar c) -> CmmInt (fromIntegral (ord c))+ (wordWidth platform)+ LitNullAddr -> zeroCLit platform+ (LitNumber LitNumInt i) -> CmmInt i (wordWidth platform)+ (LitNumber LitNumInt8 i) -> CmmInt i W8+ (LitNumber LitNumInt16 i) -> CmmInt i W16+ (LitNumber LitNumInt32 i) -> CmmInt i W32+ (LitNumber LitNumInt64 i) -> CmmInt i W64+ (LitNumber LitNumWord i) -> CmmInt i (wordWidth platform)+ (LitNumber LitNumWord8 i) -> CmmInt i W8+ (LitNumber LitNumWord16 i) -> CmmInt i W16+ (LitNumber LitNumWord32 i) -> CmmInt i W32+ (LitNumber LitNumWord64 i) -> CmmInt i W64+ (LitFloat r) -> CmmFloat r W32+ (LitDouble r) -> CmmFloat r W64+ (LitLabel fs ms fod)+ -> let -- TODO: Literal labels might not actually be in the current package...+ labelSrc = ForeignLabelInThisPackage+ in CmmLabel (mkForeignLabel fs ms labelSrc fod)+ other -> pprPanic "mkSimpleLit" (ppr other)+
compiler/GHC/StgToCmm/Monad.hs view
@@ -1,10 +1,8 @@-{-# LANGUAGE DeriveFunctor #-}+{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE MultiParamTypeClasses #-}-{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE PatternSynonyms #-} - ----------------------------------------------------------------------------- -- -- Monad for Stg to C-- code generation@@ -26,6 +24,8 @@ emitOutOfLine, emitAssign, emitStore, emitComment, emitTick, emitUnwind, + newTemp,+ getCmm, aGraphToGraph, getPlatform, getProfile, getCodeR, getCode, getCodeScoped, getHeapUsage, getCallOpts, getPtrOpts,@@ -59,9 +59,8 @@ -- more localised access to monad state CgIdInfo(..), getBinds, setBinds,- -- out of general friendliness, we also export ...- CgInfoDownwards(..), CgState(..) -- non-abstract+ CgInfoDownwards(..), CgState(..) -- non-abstract ) where import GHC.Prelude hiding( sequence, succ )@@ -94,7 +93,6 @@ import Data.List (mapAccumL) - -------------------------------------------------------- -- The FCode monad and its types --@@ -335,6 +333,9 @@ cgs_hp_usg :: HeapUsage, cgs_uniqs :: UniqSupply }+-- If you are wondering why you have to be careful forcing CgState then+-- the reason is the knot-tying in 'getHeapUsage'. This problem is tracked+-- in #19245 data HeapUsage -- See Note [Virtual and real heap pointers] = HeapUsage {@@ -400,7 +401,6 @@ = s1 { cgs_stmts = cgs_stmts s1 CmmGraph.<*> cgs_stmts s2, cgs_tops = cgs_tops s1 `appOL` cgs_tops s2 } - -- The heap high water mark is the larger of virtHp and hwHp. The latter is -- only records the high water marks of forked-off branches, so to find the -- heap high water mark you have to take the max of virtHp and hwHp. Remember,@@ -481,6 +481,10 @@ setState $ state { cgs_uniqs = us' } return u +newTemp :: MonadUnique m => CmmType -> m LocalReg+newTemp rep = do { uniq <- getUniqueM+ ; return (LocalReg uniq rep) }+ ------------------ getInfoDown :: FCode CgInfoDownwards getInfoDown = FCode $ \info_down state -> (info_down,state)@@ -828,15 +832,15 @@ ; state <- getState ; setState $ state { cgs_tops = cgs_tops state `snocOL` proc_block } } -getCmm :: FCode () -> FCode CmmGroup+getCmm :: FCode a -> FCode (a, CmmGroup) -- Get all the CmmTops (there should be no stmts) -- Return a single Cmm which may be split from other Cmms by -- object splitting (at a later stage) getCmm code = do { state1 <- getState- ; ((), state2) <- withState code (state1 { cgs_tops = nilOL })+ ; (a, state2) <- withState code (state1 { cgs_tops = nilOL }) ; setState $ state2 { cgs_tops = cgs_tops state1 }- ; return (fromOL (cgs_tops state2)) }+ ; return (a, fromOL (cgs_tops state2)) } mkCmmIfThenElse :: CmmExpr -> CmmAGraph -> CmmAGraph -> FCode CmmAGraph
compiler/GHC/StgToCmm/Prim.hs view
@@ -1,12 +1,6 @@ {-# LANGUAGE CPP #-} {-# LANGUAGE LambdaCase #-} -#if __GLASGOW_HASKELL__ <= 808--- GHC 8.10 deprecates this flag, but GHC 8.8 needs it--- emitPrimOp is quite large-{-# OPTIONS_GHC -fmax-pmcheck-iterations=4000000 #-}-#endif- {-# OPTIONS_GHC -Wno-incomplete-uni-patterns #-} ----------------------------------------------------------------------------@@ -31,7 +25,6 @@ import GHC.StgToCmm.Layout import GHC.StgToCmm.Foreign-import GHC.StgToCmm.Env import GHC.StgToCmm.Monad import GHC.StgToCmm.Utils import GHC.StgToCmm.Ticky@@ -341,6 +334,10 @@ ByteArrayContents_Char -> \[arg] -> opIntoRegs $ \[res] -> emitAssign (CmmLocal res) (cmmOffsetB platform arg (arrWordsHdrSize profile)) +-- #define mutableByteArrayContentszh(r,a) r = BYTE_ARR_CTS(a)+ MutableByteArrayContents_Char -> \[arg] -> opIntoRegs $ \[res] ->+ emitAssign (CmmLocal res) (cmmOffsetB platform arg (arrWordsHdrSize profile))+ -- #define stableNameToIntzh(r,s) (r = ((StgStableName *)s)->sn) StableNameToIntOp -> \[arg] -> opIntoRegs $ \[res] -> emitAssign (CmmLocal res) (cmmLoadIndexW platform arg (fixedHdrSizeW profile) (bWord platform))@@ -457,19 +454,19 @@ IndexOffAddrOp_StablePtr -> \args -> opIntoRegs $ \res -> doIndexOffAddrOp Nothing (bWord platform) res args IndexOffAddrOp_Int8 -> \args -> opIntoRegs $ \res ->- doIndexOffAddrOp (Just (mo_s_8ToWord platform)) b8 res args+ doIndexOffAddrOp Nothing b8 res args IndexOffAddrOp_Int16 -> \args -> opIntoRegs $ \res ->- doIndexOffAddrOp (Just (mo_s_16ToWord platform)) b16 res args+ doIndexOffAddrOp Nothing b16 res args IndexOffAddrOp_Int32 -> \args -> opIntoRegs $ \res ->- doIndexOffAddrOp (Just (mo_s_32ToWord platform)) b32 res args+ doIndexOffAddrOp Nothing b32 res args IndexOffAddrOp_Int64 -> \args -> opIntoRegs $ \res -> doIndexOffAddrOp Nothing b64 res args IndexOffAddrOp_Word8 -> \args -> opIntoRegs $ \res ->- doIndexOffAddrOp (Just (mo_u_8ToWord platform)) b8 res args+ doIndexOffAddrOp Nothing b8 res args IndexOffAddrOp_Word16 -> \args -> opIntoRegs $ \res ->- doIndexOffAddrOp (Just (mo_u_16ToWord platform)) b16 res args+ doIndexOffAddrOp Nothing b16 res args IndexOffAddrOp_Word32 -> \args -> opIntoRegs $ \res ->- doIndexOffAddrOp (Just (mo_u_32ToWord platform)) b32 res args+ doIndexOffAddrOp Nothing b32 res args IndexOffAddrOp_Word64 -> \args -> opIntoRegs $ \res -> doIndexOffAddrOp Nothing b64 res args @@ -492,19 +489,19 @@ ReadOffAddrOp_StablePtr -> \args -> opIntoRegs $ \res -> doIndexOffAddrOp Nothing (bWord platform) res args ReadOffAddrOp_Int8 -> \args -> opIntoRegs $ \res ->- doIndexOffAddrOp (Just (mo_s_8ToWord platform)) b8 res args+ doIndexOffAddrOp Nothing b8 res args ReadOffAddrOp_Int16 -> \args -> opIntoRegs $ \res ->- doIndexOffAddrOp (Just (mo_s_16ToWord platform)) b16 res args+ doIndexOffAddrOp Nothing b16 res args ReadOffAddrOp_Int32 -> \args -> opIntoRegs $ \res ->- doIndexOffAddrOp (Just (mo_s_32ToWord platform)) b32 res args+ doIndexOffAddrOp Nothing b32 res args ReadOffAddrOp_Int64 -> \args -> opIntoRegs $ \res -> doIndexOffAddrOp Nothing b64 res args ReadOffAddrOp_Word8 -> \args -> opIntoRegs $ \res ->- doIndexOffAddrOp (Just (mo_u_8ToWord platform)) b8 res args+ doIndexOffAddrOp Nothing b8 res args ReadOffAddrOp_Word16 -> \args -> opIntoRegs $ \res ->- doIndexOffAddrOp (Just (mo_u_16ToWord platform)) b16 res args+ doIndexOffAddrOp Nothing b16 res args ReadOffAddrOp_Word32 -> \args -> opIntoRegs $ \res ->- doIndexOffAddrOp (Just (mo_u_32ToWord platform)) b32 res args+ doIndexOffAddrOp Nothing b32 res args ReadOffAddrOp_Word64 -> \args -> opIntoRegs $ \res -> doIndexOffAddrOp Nothing b64 res args @@ -527,19 +524,19 @@ IndexByteArrayOp_StablePtr -> \args -> opIntoRegs $ \res -> doIndexByteArrayOp Nothing (bWord platform) res args IndexByteArrayOp_Int8 -> \args -> opIntoRegs $ \res ->- doIndexByteArrayOp (Just (mo_s_8ToWord platform)) b8 res args+ doIndexByteArrayOp Nothing b8 res args IndexByteArrayOp_Int16 -> \args -> opIntoRegs $ \res ->- doIndexByteArrayOp (Just (mo_s_16ToWord platform)) b16 res args+ doIndexByteArrayOp Nothing b16 res args IndexByteArrayOp_Int32 -> \args -> opIntoRegs $ \res ->- doIndexByteArrayOp (Just (mo_s_32ToWord platform)) b32 res args+ doIndexByteArrayOp Nothing b32 res args IndexByteArrayOp_Int64 -> \args -> opIntoRegs $ \res -> doIndexByteArrayOp Nothing b64 res args IndexByteArrayOp_Word8 -> \args -> opIntoRegs $ \res ->- doIndexByteArrayOp (Just (mo_u_8ToWord platform)) b8 res args+ doIndexByteArrayOp Nothing b8 res args IndexByteArrayOp_Word16 -> \args -> opIntoRegs $ \res ->- doIndexByteArrayOp (Just (mo_u_16ToWord platform)) b16 res args+ doIndexByteArrayOp Nothing b16 res args IndexByteArrayOp_Word32 -> \args -> opIntoRegs $ \res ->- doIndexByteArrayOp (Just (mo_u_32ToWord platform)) b32 res args+ doIndexByteArrayOp Nothing b32 res args IndexByteArrayOp_Word64 -> \args -> opIntoRegs $ \res -> doIndexByteArrayOp Nothing b64 res args @@ -562,19 +559,19 @@ ReadByteArrayOp_StablePtr -> \args -> opIntoRegs $ \res -> doIndexByteArrayOp Nothing (bWord platform) res args ReadByteArrayOp_Int8 -> \args -> opIntoRegs $ \res ->- doIndexByteArrayOp (Just (mo_s_8ToWord platform)) b8 res args+ doIndexByteArrayOp Nothing b8 res args ReadByteArrayOp_Int16 -> \args -> opIntoRegs $ \res ->- doIndexByteArrayOp (Just (mo_s_16ToWord platform)) b16 res args+ doIndexByteArrayOp Nothing b16 res args ReadByteArrayOp_Int32 -> \args -> opIntoRegs $ \res ->- doIndexByteArrayOp (Just (mo_s_32ToWord platform)) b32 res args+ doIndexByteArrayOp Nothing b32 res args ReadByteArrayOp_Int64 -> \args -> opIntoRegs $ \res -> doIndexByteArrayOp Nothing b64 res args ReadByteArrayOp_Word8 -> \args -> opIntoRegs $ \res ->- doIndexByteArrayOp (Just (mo_u_8ToWord platform)) b8 res args+ doIndexByteArrayOp Nothing b8 res args ReadByteArrayOp_Word16 -> \args -> opIntoRegs $ \res ->- doIndexByteArrayOp (Just (mo_u_16ToWord platform)) b16 res args+ doIndexByteArrayOp Nothing b16 res args ReadByteArrayOp_Word32 -> \args -> opIntoRegs $ \res ->- doIndexByteArrayOp (Just (mo_u_32ToWord platform)) b32 res args+ doIndexByteArrayOp Nothing b32 res args ReadByteArrayOp_Word64 -> \args -> opIntoRegs $ \res -> doIndexByteArrayOp Nothing b64 res args @@ -597,15 +594,15 @@ IndexByteArrayOp_Word8AsStablePtr -> \args -> opIntoRegs $ \res -> doIndexByteArrayOpAs Nothing (bWord platform) b8 res args IndexByteArrayOp_Word8AsInt16 -> \args -> opIntoRegs $ \res ->- doIndexByteArrayOpAs (Just (mo_s_16ToWord platform)) b16 b8 res args+ doIndexByteArrayOpAs Nothing b16 b8 res args IndexByteArrayOp_Word8AsInt32 -> \args -> opIntoRegs $ \res ->- doIndexByteArrayOpAs (Just (mo_s_32ToWord platform)) b32 b8 res args+ doIndexByteArrayOpAs Nothing b32 b8 res args IndexByteArrayOp_Word8AsInt64 -> \args -> opIntoRegs $ \res -> doIndexByteArrayOpAs Nothing b64 b8 res args IndexByteArrayOp_Word8AsWord16 -> \args -> opIntoRegs $ \res ->- doIndexByteArrayOpAs (Just (mo_u_16ToWord platform)) b16 b8 res args+ doIndexByteArrayOpAs Nothing b16 b8 res args IndexByteArrayOp_Word8AsWord32 -> \args -> opIntoRegs $ \res ->- doIndexByteArrayOpAs (Just (mo_u_32ToWord platform)) b32 b8 res args+ doIndexByteArrayOpAs Nothing b32 b8 res args IndexByteArrayOp_Word8AsWord64 -> \args -> opIntoRegs $ \res -> doIndexByteArrayOpAs Nothing b64 b8 res args @@ -628,15 +625,15 @@ ReadByteArrayOp_Word8AsStablePtr -> \args -> opIntoRegs $ \res -> doIndexByteArrayOpAs Nothing (bWord platform) b8 res args ReadByteArrayOp_Word8AsInt16 -> \args -> opIntoRegs $ \res ->- doIndexByteArrayOpAs (Just (mo_s_16ToWord platform)) b16 b8 res args+ doIndexByteArrayOpAs Nothing b16 b8 res args ReadByteArrayOp_Word8AsInt32 -> \args -> opIntoRegs $ \res ->- doIndexByteArrayOpAs (Just (mo_s_32ToWord platform)) b32 b8 res args+ doIndexByteArrayOpAs Nothing b32 b8 res args ReadByteArrayOp_Word8AsInt64 -> \args -> opIntoRegs $ \res -> doIndexByteArrayOpAs Nothing b64 b8 res args ReadByteArrayOp_Word8AsWord16 -> \args -> opIntoRegs $ \res ->- doIndexByteArrayOpAs (Just (mo_u_16ToWord platform)) b16 b8 res args+ doIndexByteArrayOpAs Nothing b16 b8 res args ReadByteArrayOp_Word8AsWord32 -> \args -> opIntoRegs $ \res ->- doIndexByteArrayOpAs (Just (mo_u_32ToWord platform)) b32 b8 res args+ doIndexByteArrayOpAs Nothing b32 b8 res args ReadByteArrayOp_Word8AsWord64 -> \args -> opIntoRegs $ \res -> doIndexByteArrayOpAs Nothing b64 b8 res args @@ -659,19 +656,19 @@ WriteOffAddrOp_StablePtr -> \args -> opIntoRegs $ \res -> doWriteOffAddrOp Nothing (bWord platform) res args WriteOffAddrOp_Int8 -> \args -> opIntoRegs $ \res ->- doWriteOffAddrOp (Just (mo_WordTo8 platform)) b8 res args+ doWriteOffAddrOp Nothing b8 res args WriteOffAddrOp_Int16 -> \args -> opIntoRegs $ \res ->- doWriteOffAddrOp (Just (mo_WordTo16 platform)) b16 res args+ doWriteOffAddrOp Nothing b16 res args WriteOffAddrOp_Int32 -> \args -> opIntoRegs $ \res ->- doWriteOffAddrOp (Just (mo_WordTo32 platform)) b32 res args+ doWriteOffAddrOp Nothing b32 res args WriteOffAddrOp_Int64 -> \args -> opIntoRegs $ \res -> doWriteOffAddrOp Nothing b64 res args WriteOffAddrOp_Word8 -> \args -> opIntoRegs $ \res ->- doWriteOffAddrOp (Just (mo_WordTo8 platform)) b8 res args+ doWriteOffAddrOp Nothing b8 res args WriteOffAddrOp_Word16 -> \args -> opIntoRegs $ \res ->- doWriteOffAddrOp (Just (mo_WordTo16 platform)) b16 res args+ doWriteOffAddrOp Nothing b16 res args WriteOffAddrOp_Word32 -> \args -> opIntoRegs $ \res ->- doWriteOffAddrOp (Just (mo_WordTo32 platform)) b32 res args+ doWriteOffAddrOp Nothing b32 res args WriteOffAddrOp_Word64 -> \args -> opIntoRegs $ \res -> doWriteOffAddrOp Nothing b64 res args @@ -694,19 +691,19 @@ WriteByteArrayOp_StablePtr -> \args -> opIntoRegs $ \res -> doWriteByteArrayOp Nothing (bWord platform) res args WriteByteArrayOp_Int8 -> \args -> opIntoRegs $ \res ->- doWriteByteArrayOp (Just (mo_WordTo8 platform)) b8 res args+ doWriteByteArrayOp Nothing b8 res args WriteByteArrayOp_Int16 -> \args -> opIntoRegs $ \res ->- doWriteByteArrayOp (Just (mo_WordTo16 platform)) b16 res args+ doWriteByteArrayOp Nothing b16 res args WriteByteArrayOp_Int32 -> \args -> opIntoRegs $ \res ->- doWriteByteArrayOp (Just (mo_WordTo32 platform)) b32 res args+ doWriteByteArrayOp Nothing b32 res args WriteByteArrayOp_Int64 -> \args -> opIntoRegs $ \res -> doWriteByteArrayOp Nothing b64 res args WriteByteArrayOp_Word8 -> \args -> opIntoRegs $ \res ->- doWriteByteArrayOp (Just (mo_WordTo8 platform)) b8 res args+ doWriteByteArrayOp Nothing b8 res args WriteByteArrayOp_Word16 -> \args -> opIntoRegs $ \res ->- doWriteByteArrayOp (Just (mo_WordTo16 platform)) b16 res args+ doWriteByteArrayOp Nothing b16 res args WriteByteArrayOp_Word32 -> \args -> opIntoRegs $ \res ->- doWriteByteArrayOp (Just (mo_WordTo32 platform)) b32 res args+ doWriteByteArrayOp Nothing b32 res args WriteByteArrayOp_Word64 -> \args -> opIntoRegs $ \res -> doWriteByteArrayOp Nothing b64 res args @@ -729,15 +726,15 @@ WriteByteArrayOp_Word8AsStablePtr -> \args -> opIntoRegs $ \res -> doWriteByteArrayOp Nothing b8 res args WriteByteArrayOp_Word8AsInt16 -> \args -> opIntoRegs $ \res ->- doWriteByteArrayOp (Just (mo_WordTo16 platform)) b8 res args+ doWriteByteArrayOp Nothing b8 res args WriteByteArrayOp_Word8AsInt32 -> \args -> opIntoRegs $ \res ->- doWriteByteArrayOp (Just (mo_WordTo32 platform)) b8 res args+ doWriteByteArrayOp Nothing b8 res args WriteByteArrayOp_Word8AsInt64 -> \args -> opIntoRegs $ \res -> doWriteByteArrayOp Nothing b8 res args WriteByteArrayOp_Word8AsWord16 -> \args -> opIntoRegs $ \res ->- doWriteByteArrayOp (Just (mo_WordTo16 platform)) b8 res args+ doWriteByteArrayOp Nothing b8 res args WriteByteArrayOp_Word8AsWord32 -> \args -> opIntoRegs $ \res ->- doWriteByteArrayOp (Just (mo_WordTo32 platform)) b8 res args+ doWriteByteArrayOp Nothing b8 res args WriteByteArrayOp_Word8AsWord64 -> \args -> opIntoRegs $ \res -> doWriteByteArrayOp Nothing b8 res args @@ -1616,6 +1613,7 @@ NewBCOOp -> alwaysExternal UnpackClosureOp -> alwaysExternal ClosureSizeOp -> alwaysExternal+ WhereFromOp -> alwaysExternal GetApStackValOp -> alwaysExternal ClearCCSOp -> alwaysExternal TraceEventOp -> alwaysExternal
compiler/GHC/StgToCmm/Prof.hs view
@@ -10,6 +10,9 @@ initCostCentres, ccType, ccsType, mkCCostCentre, mkCCostCentreStack, + -- infoTablePRov+ initInfoTableProv, emitInfoTableProv,+ -- Cost-centre Profiling dynProfHdr, profDynAlloc, profAlloc, staticProfHdr, initUpdFrameProf, enterCostCentreThunk, enterCostCentreFun,@@ -33,6 +36,7 @@ import GHC.StgToCmm.Closure import GHC.StgToCmm.Utils import GHC.StgToCmm.Monad+import GHC.StgToCmm.Lit import GHC.Runtime.Heap.Layout import GHC.Cmm.Graph@@ -41,11 +45,16 @@ import GHC.Cmm.CLabel import GHC.Types.CostCentre+import GHC.Types.IPE+import GHC.Types.ForeignStubs import GHC.Data.FastString import GHC.Unit.Module as Module import GHC.Utils.Outputable import GHC.Utils.Panic+import GHC.Driver.CodeOutput ( ipInitCode ) +import GHC.Utils.Encoding+ import Control.Monad import Data.Char (ord) @@ -224,9 +233,8 @@ ; modl <- newByteStringCLit (bytesFS $ moduleNameFS $ moduleName $ cc_mod cc)- ; loc <- newByteStringCLit $ bytesFS $ mkFastString $+ ; loc <- newByteStringCLit $ utf8EncodeString $ showPpr dflags (costCentreSrcSpan cc)- -- XXX going via FastString to get UTF-8 encoding is silly ; let lits = [ zero platform, -- StgInt ccID, label, -- char *label,@@ -269,6 +277,50 @@ where (ws,ms) = pc_SIZEOF_CostCentreStack (platformConstants platform) `divMod` platformWordSizeInBytes platform ++initInfoTableProv :: [CmmInfoTable] -> InfoTableProvMap -> Module -> FCode CStub+-- Emit the declarations+initInfoTableProv infos itmap this_mod+ = do+ dflags <- getDynFlags+ let ents = convertInfoProvMap dflags infos this_mod itmap+ --pprTraceM "UsedInfo" (ppr (length infos))+ --pprTraceM "initInfoTable" (ppr (length ents))+ -- Output the actual IPE data+ mapM_ emitInfoTableProv ents+ -- Create the C stub which initialises the IPE_LIST+ return (ipInitCode dflags this_mod ents)++--- Info Table Prov stuff+emitInfoTableProv :: InfoProvEnt -> FCode ()+emitInfoTableProv ip = do+ { dflags <- getDynFlags+ ; let mod = infoProvModule ip+ ; let (src, label) = maybe ("", "") (\(s, l) -> (showPpr dflags s, l)) (infoTableProv ip)+ ; platform <- getPlatform+ ; let mk_string = newByteStringCLit . utf8EncodeString+ ; label <- mk_string label+ ; modl <- newByteStringCLit (bytesFS $ moduleNameFS+ $ moduleName+ $ mod)++ ; ty_string <- mk_string (infoTableType ip)+ ; loc <- mk_string src+ ; table_name <- mk_string (showPpr dflags (pprCLabel platform CStyle (infoTablePtr ip)))+ ; closure_type <- mk_string+ (showPpr dflags (text $ show $ infoProvEntClosureType ip))+ ; let+ lits = [ CmmLabel (infoTablePtr ip), -- Info table pointer+ table_name, -- char *table_name+ closure_type, -- char *closure_desc -- Filled in from the InfoTable+ ty_string, -- char *ty_string+ label, -- char *label,+ modl, -- char *module,+ loc, -- char *srcloc,+ zero platform -- struct _InfoProvEnt *link+ ]+ ; emitDataLits (mkIPELabel ip) lits+ } -- --------------------------------------------------------------------------- -- Set the current cost centre stack
compiler/GHC/StgToCmm/Ticky.hs view
@@ -109,6 +109,7 @@ import GHC.StgToCmm.Closure import GHC.StgToCmm.Utils import GHC.StgToCmm.Monad+import GHC.StgToCmm.Lit ( newStringCLit ) import GHC.Stg.Syntax import GHC.Cmm.Expr
compiler/GHC/StgToCmm/Utils.hs view
@@ -1,5 +1,4 @@ {-# LANGUAGE CPP #-}-{-# LANGUAGE LambdaCase #-} ----------------------------------------------------------------------------- --@@ -10,11 +9,10 @@ ----------------------------------------------------------------------------- module GHC.StgToCmm.Utils (- cgLit, mkSimpleLit, emitDataLits, emitRODataLits, emitDataCon, emitRtsCall, emitRtsCallWithResult, emitRtsCallGen,- assignTemp, newTemp,+ assignTemp, newUnboxedTupleRegs, @@ -38,12 +36,13 @@ cmmUntag, cmmIsTagged, addToMem, addToMemE, addToMemLblE, addToMemLbl,- newStringCLit, newByteStringCLit, -- * Update remembered set operations whenUpdRemSetEnabled, emitUpdRemSetPush, emitUpdRemSetPushThunk,++ convertInfoProvMap, cmmInfoTableToInfoProvEnt ) where #include "GhclibHsVersions.h"@@ -53,6 +52,7 @@ import GHC.Platform import GHC.StgToCmm.Monad import GHC.StgToCmm.Closure+import GHC.StgToCmm.Lit (mkSimpleLit) import GHC.Cmm import GHC.Cmm.BlockId import GHC.Cmm.Graph as CmmGraph@@ -72,57 +72,25 @@ import GHC.Data.Graph.Directed import GHC.Utils.Misc import GHC.Types.Unique-import GHC.Types.Unique.Supply (MonadUnique(..)) import GHC.Driver.Session import GHC.Data.FastString import GHC.Utils.Outputable import GHC.Utils.Panic import GHC.Types.RepType import GHC.Types.CostCentre+import GHC.Types.IPE -import Data.ByteString (ByteString)-import qualified Data.ByteString.Char8 as BS8 import qualified Data.Map as M-import Data.Char import Data.List (sortBy) import Data.Ord---------------------------------------------------------------------------------- Literals-------------------------------------------------------------------------------cgLit :: Literal -> FCode CmmLit-cgLit (LitString s) = newByteStringCLit s- -- not unpackFS; we want the UTF-8 byte stream.-cgLit other_lit = do platform <- getPlatform- return (mkSimpleLit platform other_lit)--mkSimpleLit :: Platform -> Literal -> CmmLit-mkSimpleLit platform = \case- (LitChar c) -> CmmInt (fromIntegral (ord c))- (wordWidth platform)- LitNullAddr -> zeroCLit platform- (LitNumber LitNumInt i) -> CmmInt i (wordWidth platform)- (LitNumber LitNumInt8 i) -> CmmInt i W8- (LitNumber LitNumInt16 i) -> CmmInt i W16- (LitNumber LitNumInt32 i) -> CmmInt i W32- (LitNumber LitNumInt64 i) -> CmmInt i W64- (LitNumber LitNumWord i) -> CmmInt i (wordWidth platform)- (LitNumber LitNumWord8 i) -> CmmInt i W8- (LitNumber LitNumWord16 i) -> CmmInt i W16- (LitNumber LitNumWord32 i) -> CmmInt i W32- (LitNumber LitNumWord64 i) -> CmmInt i W64- (LitFloat r) -> CmmFloat r W32- (LitDouble r) -> CmmFloat r W64- (LitLabel fs ms fod)- -> let -- TODO: Literal labels might not actually be in the current package...- labelSrc = ForeignLabelInThisPackage- in CmmLabel (mkForeignLabel fs ms labelSrc fod)- -- NB: LitRubbish should have been lowered in "CoreToStg"- other -> pprPanic "mkSimpleLit" (ppr other)+import GHC.Types.Unique.Map+import Data.Maybe+import GHC.Driver.Ppr+import qualified Data.List.NonEmpty as NE+import GHC.Core.DataCon+import GHC.Types.Unique.FM+import GHC.Data.Maybe+import Control.Monad -------------------------------------------------------------------------- --@@ -289,19 +257,8 @@ emitRODataLits lbl lits = emitDecl (mkRODataLits lbl lits) emitDataCon :: CLabel -> CmmInfoTable -> CostCentreStack -> [CmmLit] -> FCode ()-emitDataCon lbl itbl ccs payload = emitDecl (CmmData (Section Data lbl) (CmmStatics lbl itbl ccs payload))--newStringCLit :: String -> FCode CmmLit--- Make a global definition for the string,--- and return its label-newStringCLit str = newByteStringCLit (BS8.pack str)--newByteStringCLit :: ByteString -> FCode CmmLit-newByteStringCLit bytes- = do { uniq <- newUnique- ; let (lit, decl) = mkByteStringCLit (mkStringLitLabel uniq) bytes- ; emitDecl decl- ; return lit }+emitDataCon lbl itbl ccs payload =+ emitDecl (CmmData (Section Data lbl) (CmmStatics lbl itbl ccs payload)) ------------------------------------------------------------------------- --@@ -324,10 +281,6 @@ ; emitAssign (CmmLocal reg) e ; return reg } -newTemp :: MonadUnique m => CmmType -> m LocalReg-newTemp rep = do { uniq <- getUniqueM- ; return (LocalReg uniq rep) }- newUnboxedTupleRegs :: Type -> FCode ([LocalReg], [ForeignHint]) -- Choose suitable local regs to use for the components -- of an unboxed tuple that we are about to return to@@ -594,7 +547,6 @@ emitAssign reg e return (CmmReg reg) - --------------------------------------------------------------------------- -- Pushing to the update remembered set ---------------------------------------------------------------------------@@ -631,3 +583,39 @@ [(CmmReg (CmmGlobal BaseReg), AddrHint), (ptr, AddrHint)] False++-- | A bare bones InfoProvEnt for things which don't have a good source location+cmmInfoTableToInfoProvEnt :: Module -> CmmInfoTable -> InfoProvEnt+cmmInfoTableToInfoProvEnt this_mod cmit =+ let cl = cit_lbl cmit+ cn = rtsClosureType (cit_rep cmit)+ in InfoProvEnt cl cn "" this_mod Nothing++-- | Convert source information collected about identifiers in 'GHC.STG.Debug'+-- to entries suitable for placing into the info table provenenance table.+convertInfoProvMap :: DynFlags -> [CmmInfoTable] -> Module -> InfoTableProvMap -> [InfoProvEnt]+convertInfoProvMap dflags defns this_mod (InfoTableProvMap (UniqMap dcenv) denv) =+ map (\cmit ->+ let cl = cit_lbl cmit+ cn = rtsClosureType (cit_rep cmit)++ tyString :: Outputable a => a -> String+ tyString t = showPpr dflags t++ lookupClosureMap :: Maybe InfoProvEnt+ lookupClosureMap = case hasHaskellName cl >>= lookupUniqMap denv of+ Just (ty, mbspan) -> Just (InfoProvEnt cl cn (tyString ty) this_mod mbspan)+ Nothing -> Nothing++ lookupDataConMap = do+ UsageSite _ n <- hasIdLabelInfo cl >>= getConInfoTableLocation+ -- This is a bit grimy, relies on the DataCon and Name having the same Unique, which they do+ (dc, ns) <- (hasHaskellName cl >>= lookupUFM_Directly dcenv . getUnique)+ -- Lookup is linear but lists will be small (< 100)+ return $ InfoProvEnt cl cn (tyString (dataConTyCon dc)) this_mod (join $ lookup n (NE.toList ns))++ -- This catches things like prim closure types and anything else which doesn't have a+ -- source location+ simpleFallback = cmmInfoTableToInfoProvEnt this_mod cmit++ in fromMaybe simpleFallback (lookupDataConMap `firstJust` lookupClosureMap)) defns
compiler/GHC/SysTools/Process.hs view
@@ -10,16 +10,19 @@ #include "GhclibHsVersions.h" +import GHC.Prelude++import GHC.Driver.Session+ import GHC.Utils.Exception import GHC.Utils.Error-import GHC.Driver.Session-import GHC.Data.FastString import GHC.Utils.Outputable import GHC.Utils.Panic-import GHC.Prelude import GHC.Utils.Misc import GHC.Utils.Logger+ import GHC.Types.SrcLoc ( SrcLoc, mkSrcLoc, mkSrcSpan )+import GHC.Data.FastString import Control.Concurrent import Data.Char@@ -31,20 +34,16 @@ import System.IO.Error as IO import System.Process -import GHC.SysTools.FileCleanup+import GHC.Utils.TmpFs -- | Enable process jobs support on Windows if it can be expected to work (e.g. -- @process >= 1.6.9.0@). enableProcessJobs :: CreateProcess -> CreateProcess #if defined(MIN_VERSION_process)-#if MIN_VERSION_process(1,6,9) enableProcessJobs opts = opts { use_process_jobs = True } #else enableProcessJobs opts = opts #endif-#else-enableProcessJobs opts = opts-#endif #if !MIN_VERSION_base(4,15,0) -- TODO: This can be dropped with GHC 8.16@@ -155,10 +154,16 @@ -- https://gcc.gnu.org/wiki/Response_Files -- https://gitlab.haskell.org/ghc/ghc/issues/10777 runSomethingResponseFile- :: Logger -> DynFlags -> (String->String) -> String -> String -> [Option]- -> Maybe [(String,String)] -> IO ()--runSomethingResponseFile logger dflags filter_fn phase_name pgm args mb_env =+ :: Logger+ -> TmpFs+ -> DynFlags+ -> (String->String)+ -> String+ -> String+ -> [Option]+ -> Maybe [(String,String)]+ -> IO ()+runSomethingResponseFile logger tmpfs dflags filter_fn phase_name pgm args mb_env = runSomethingWith logger dflags phase_name pgm args $ \real_args -> do fp <- getResponseFile real_args let args = ['@':fp]@@ -166,7 +171,7 @@ return (r,()) where getResponseFile args = do- fp <- newTempName logger dflags TFL_CurrentModule "rsp"+ fp <- newTempName logger tmpfs dflags TFL_CurrentModule "rsp" withFile fp WriteMode $ \h -> do #if defined(mingw32_HOST_OS) hSetEncoding h latin1@@ -305,7 +310,7 @@ logInfo logger dflags $ withPprStyle defaultUserStyle msg log_loop chan t BuildError loc msg -> do- putLogMsg logger dflags NoReason SevError (mkSrcSpan loc loc)+ putLogMsg logger dflags (mkMCDiagnostic ErrorWithoutFlag) (mkSrcSpan loc loc) $ withPprStyle defaultUserStyle msg log_loop chan t EOF ->
compiler/GHC/SysTools/Tasks.hs view
@@ -13,7 +13,7 @@ import GHC.Platform import GHC.ForeignSrcLang -import GHC.CmmToLlvm.Base (LlvmVersion, llvmVersionStr, supportedLlvmVersion, parseLlvmVersion)+import GHC.CmmToLlvm.Base (LlvmVersion, llvmVersionStr, supportedLlvmVersionMin, supportedLlvmVersionMax, llvmVersionStr, parseLlvmVersion) import GHC.SysTools.Process import GHC.SysTools.Info@@ -25,6 +25,7 @@ import GHC.Utils.Outputable import GHC.Utils.Misc import GHC.Utils.Logger+import GHC.Utils.TmpFs import Data.List (tails, isPrefixOf) import System.IO@@ -62,15 +63,15 @@ runSomething logger dflags "Haskell pre-processor" prog (args ++ opts) -- | Run compiler of C-like languages and raw objects (such as gcc or clang).-runCc :: Maybe ForeignSrcLang -> Logger -> DynFlags -> [Option] -> IO ()-runCc mLanguage logger dflags args = traceToolCommand logger dflags "cc" $ do+runCc :: Maybe ForeignSrcLang -> Logger -> TmpFs -> DynFlags -> [Option] -> IO ()+runCc mLanguage logger tmpfs dflags args = traceToolCommand logger dflags "cc" $ do let p = pgm_c dflags args1 = map Option userOpts args2 = languageOptions ++ args ++ args1 -- We take care to pass -optc flags in args1 last to ensure that the -- user can override flags passed by GHC. See #14452. mb_env <- getGccEnv args2- runSomethingResponseFile logger dflags cc_filter "C Compiler" p args2 mb_env+ runSomethingResponseFile logger tmpfs dflags cc_filter "C Compiler" p args2 mb_env where -- discard some harmless warnings from gcc that we can't turn off cc_filter = unlines . doFilter . lines@@ -233,14 +234,16 @@ errorMsg logger dflags $ vcat [ text "Warning:", nest 9 $ text "Couldn't figure out LLVM version!" $$- text ("Make sure you have installed LLVM " ++- llvmVersionStr supportedLlvmVersion) ]+ text ("Make sure you have installed LLVM between "+ ++ llvmVersionStr supportedLlvmVersionMin+ ++ " and "+ ++ llvmVersionStr supportedLlvmVersionMax) ] return Nothing) -runLink :: Logger -> DynFlags -> [Option] -> IO ()-runLink logger dflags args = traceToolCommand logger dflags "linker" $ do+runLink :: Logger -> TmpFs -> DynFlags -> [Option] -> IO ()+runLink logger tmpfs dflags args = traceToolCommand logger dflags "linker" $ do -- See Note [Run-time linker info] -- -- `-optl` args come at the end, so that later `-l` options@@ -251,7 +254,7 @@ optl_args = map Option (getOpts dflags opt_l) args2 = args0 ++ linkargs ++ args ++ optl_args mb_env <- getGccEnv args2- runSomethingResponseFile logger dflags ld_filter "Linker" p args2 mb_env+ runSomethingResponseFile logger tmpfs dflags ld_filter "Linker" p args2 mb_env where ld_filter = case (platformOS (targetPlatform dflags)) of OSSolaris2 -> sunos_ld_filter@@ -303,18 +306,23 @@ ld_warning_found = not . null . snd . ld_warn_break -- See Note [Merging object files for GHCi] in GHC.Driver.Pipeline.-runMergeObjects :: Logger -> DynFlags -> [Option] -> IO ()-runMergeObjects logger dflags args = traceToolCommand logger dflags "merge-objects" $ do- let (p,args0) = pgm_lm dflags- optl_args = map Option (getOpts dflags opt_lm)- args2 = args0 ++ args ++ optl_args- -- N.B. Darwin's ld64 doesn't support response files. Consequently we only- -- use them on Windows where they are truly necessary.+runMergeObjects :: Logger -> TmpFs -> DynFlags -> [Option] -> IO () #if defined(mingw32_HOST_OS)- mb_env <- getGccEnv args2- runSomethingResponseFile logger dflags id "Merge objects" p args2 mb_env+runMergeObjects logger tmpfs dflags args = #else- runSomething logger dflags "Merge objects" p args2+runMergeObjects logger _tmpfs dflags args =+#endif+ traceToolCommand logger dflags "merge-objects" $ do+ let (p,args0) = pgm_lm dflags+ optl_args = map Option (getOpts dflags opt_lm)+ args2 = args0 ++ args ++ optl_args+ -- N.B. Darwin's ld64 doesn't support response files. Consequently we only+ -- use them on Windows where they are truly necessary.+#if defined(mingw32_HOST_OS)+ mb_env <- getGccEnv args2+ runSomethingResponseFile logger tmpfs dflags id "Merge objects" p args2 mb_env+#else+ runSomething logger dflags "Merge objects" p args2 #endif runLibtool :: Logger -> DynFlags -> [Option] -> IO ()
compiler/GHC/Tc/Deriv.hs view
@@ -294,7 +294,7 @@ -- before renaming the instances themselves ; traceTc "rnd" (vcat (map (\i -> pprInstInfoDetails i $$ text "") inst_infos)) ; (aux_binds, aux_sigs) <- mapAndUnzipBagM return bagBinds- ; let aux_val_binds = ValBinds noExtField aux_binds (bagToList aux_sigs)+ ; let aux_val_binds = ValBinds NoAnnSortKey aux_binds (bagToList aux_sigs) -- Importantly, we use rnLocalValBindsLHS, not rnTopBindsLHS, to rename -- auxiliary bindings as if they were defined locally. -- See Note [Auxiliary binders] in GHC.Tc.Deriv.Generate.@@ -502,7 +502,7 @@ -- We carefully set up uses of recoverM to minimize error message -- cascades. See Note [Recovering from failures in deriving clauses]. recoverM (pure Nothing) $- setSrcSpan (getLoc deriv_pred) $ do+ setSrcSpan (getLocA deriv_pred) $ do traceTc "derivePred" $ vcat [ text "tc" <+> ppr tc , text "tys" <+> ppr tys@@ -625,7 +625,7 @@ -- This returns a Maybe because the user might try to derive Typeable, which is -- a no-op nowadays. deriveStandalone (L loc (DerivDecl _ deriv_ty mb_lderiv_strat overlap_mode))- = setSrcSpan loc $+ = setSrcSpanA loc $ addErrCtxt (standaloneCtxt deriv_ty) $ do { traceTc "Standalone deriving decl for" (ppr deriv_ty) ; let ctxt = GHC.Tc.Types.Origin.InstDeclCtxt True@@ -723,14 +723,14 @@ (HsWC { hswc_body = deriv_ty@(L loc (HsSig { sig_bndrs = outer_bndrs , sig_body = deriv_ty_body }))}) | (theta, rho) <- splitLHsQualTy deriv_ty_body- , L _ [wc_pred] <- theta+ , [wc_pred] <- fromMaybeContext theta , L wc_span (HsWildCardTy _) <- ignoreParens wc_pred = do dfun_ty <- tcHsClsInstType ctxt $ L loc $ HsSig { sig_ext = noExtField , sig_bndrs = outer_bndrs , sig_body = rho } let (tvs, _theta, cls, inst_tys) = tcSplitDFunTy dfun_ty- pure (tvs, InferContext (Just wc_span), cls, inst_tys)+ pure (tvs, InferContext (Just (locA wc_span)), cls, inst_tys) | otherwise = do dfun_ty <- tcHsClsInstType ctxt deriv_ty let (tvs, theta, cls, inst_tys) = tcSplitDFunTy dfun_ty@@ -739,7 +739,7 @@ warnUselessTypeable :: TcM () warnUselessTypeable = do { warn <- woptM Opt_WarnDerivingTypeable- ; when warn $ addWarnTc (Reason Opt_WarnDerivingTypeable)+ ; when warn $ addDiagnosticTc (WarningWithFlag Opt_WarnDerivingTypeable) $ text "Deriving" <+> quotes (ppr typeableClassName) <+> text "has no effect: all types now auto-derive Typeable" } @@ -1171,18 +1171,18 @@ DerivEnv { denv_inst_tys = cls_args , denv_strat = mb_strat } <- ask case mb_strat of- Just StockStrategy -> do+ Just (StockStrategy _) -> do (cls_tys, inst_ty) <- expectNonNullaryClsArgs cls_args dit <- expectAlgTyConApp cls_tys inst_ty mk_eqn_stock dit - Just AnyclassStrategy -> mk_eqn_anyclass+ Just (AnyclassStrategy _) -> mk_eqn_anyclass Just (ViaStrategy via_ty) -> do (cls_tys, inst_ty) <- expectNonNullaryClsArgs cls_args mk_eqn_via cls_tys inst_ty via_ty - Just NewtypeStrategy -> do+ Just (NewtypeStrategy _) -> do (cls_tys, inst_ty) <- expectNonNullaryClsArgs cls_args dit <- expectAlgTyConApp cls_tys inst_ty unless (isNewTyCon (dit_rep_tc dit)) $@@ -1611,7 +1611,7 @@ -- See Note [Deriving strategies] when (newtype_deriving && deriveAnyClass) $ lift $ whenWOptM Opt_WarnDerivingDefaults $- addWarnTc (Reason Opt_WarnDerivingDefaults) $ sep+ addDiagnosticTc (WarningWithFlag Opt_WarnDerivingDefaults) $ sep [ text "Both DeriveAnyClass and" <+> text "GeneralizedNewtypeDeriving are enabled" , text "Defaulting to the DeriveAnyClass strategy"@@ -2001,8 +2001,8 @@ Nothing -> pure () Just span -> setSrcSpan span $ do checkTc xpartial_sigs (hang partial_sig_msg 2 pts_suggestion)- warnTc (Reason Opt_WarnPartialTypeSignatures)- wpartial_sigs partial_sig_msg+ diagnosticTc (WarningWithFlag Opt_WarnPartialTypeSignatures)+ wpartial_sigs partial_sig_msg -- Check for Generic instances that are derived with an exotic -- deriving strategy like DAC
compiler/GHC/Tc/Deriv/Functor.hs view
@@ -158,7 +158,7 @@ | Phantom <- last (tyConRoles tycon) = (unitBag fmap_bind, emptyBag) where- fmap_name = L loc fmap_RDR+ fmap_name = L (noAnnSrcSpan loc) fmap_RDR fmap_bind = mkRdrFunBind fmap_name fmap_eqns fmap_eqns = [mkSimpleMatch fmap_match_ctxt [nlWildPat]@@ -169,7 +169,7 @@ = (listToBag [fmap_bind, replace_bind], emptyBag) where data_cons = getPossibleDataCons tycon tycon_args- fmap_name = L loc fmap_RDR+ fmap_name = L (noAnnSrcSpan loc) fmap_RDR -- See Note [EmptyDataDecls with Functor, Foldable, and Traversable] fmap_bind = mkRdrFunBindEC 2 id fmap_name fmap_eqns@@ -208,7 +208,7 @@ , ft_co_var = panic "contravariant in ft_fmap" } -- See Note [Deriving <$]- replace_name = L loc replace_RDR+ replace_name = L (noAnnSrcSpan loc) replace_RDR -- See Note [EmptyDataDecls with Functor, Foldable, and Traversable] replace_bind = mkRdrFunBindEC 2 id replace_name replace_eqns@@ -617,8 +617,7 @@ else nlParPat bare_pat rhs <- fold con_name (zipWith (\i v -> i $ nlHsVar v) insides vars_needed)- return $ mkMatch ctxt (extra_pats ++ [pat]) rhs- (noLoc emptyLocalBinds)+ return $ mkMatch ctxt (extra_pats ++ [pat]) rhs emptyLocalBinds -- "Con a1 a2 a3 -> fmap (\b2 -> Con a1 b2 a3) (traverse f a2)" --@@ -668,8 +667,7 @@ in mkHsLam (map nlVarPat bs) (nlHsApps con_name vars) rhs <- fold con_expr exps- return $ mkMatch ctxt (extra_pats ++ [pat]) rhs- (noLoc emptyLocalBinds)+ return $ mkMatch ctxt (extra_pats ++ [pat]) rhs emptyLocalBinds -- "case x of (a1,a2,a3) -> fold [x1 a1, x2 a2, x3 a3]" mkSimpleTupleCase :: Monad m => ([LPat GhcPs] -> DataCon -> [a]@@ -794,7 +792,7 @@ | Phantom <- last (tyConRoles tycon) = (unitBag foldMap_bind, emptyBag) where- foldMap_name = L loc foldMap_RDR+ foldMap_name = L (noAnnSrcSpan loc) foldMap_RDR foldMap_bind = mkRdrFunBind foldMap_name foldMap_eqns foldMap_eqns = [mkSimpleMatch foldMap_match_ctxt [nlWildPat, nlWildPat]@@ -811,14 +809,14 @@ where data_cons = getPossibleDataCons tycon tycon_args - foldr_bind = mkRdrFunBind (L loc foldable_foldr_RDR) eqns+ foldr_bind = mkRdrFunBind (L (noAnnSrcSpan loc) foldable_foldr_RDR) eqns eqns = map foldr_eqn data_cons foldr_eqn con = evalState (match_foldr z_Expr [f_Pat,z_Pat] con =<< parts) bs_RDRs where parts = sequence $ foldDataConArgs ft_foldr con - foldMap_name = L loc foldMap_RDR+ foldMap_name = L (noAnnSrcSpan loc) foldMap_RDR -- See Note [EmptyDataDecls with Functor, Foldable, and Traversable] foldMap_bind = mkRdrFunBindEC 2 (const mempty_Expr)@@ -841,7 +839,7 @@ go NotNull = Nothing go (NullM a) = Just (Just a) - null_name = L loc null_RDR+ null_name = L (noAnnSrcSpan loc) null_RDR null_match_ctxt = mkPrefixFunRhs null_name null_bind = mkRdrFunBind null_name null_eqns null_eqns = map null_eqn data_cons@@ -851,7 +849,7 @@ case convert parts of Nothing -> return $ mkMatch null_match_ctxt [nlParPat (nlWildConPat con)]- false_Expr (noLoc emptyLocalBinds)+ false_Expr emptyLocalBinds Just cp -> match_null [] con cp -- Yields 'Just' an expression if we're folding over a type that mentions@@ -1023,7 +1021,7 @@ | Phantom <- last (tyConRoles tycon) = (unitBag traverse_bind, emptyBag) where- traverse_name = L loc traverse_RDR+ traverse_name = L (noAnnSrcSpan loc) traverse_RDR traverse_bind = mkRdrFunBind traverse_name traverse_eqns traverse_eqns = [mkSimpleMatch traverse_match_ctxt@@ -1036,7 +1034,7 @@ where data_cons = getPossibleDataCons tycon tycon_args - traverse_name = L loc traverse_RDR+ traverse_name = L (noAnnSrcSpan loc) traverse_RDR -- See Note [EmptyDataDecls with Functor, Foldable, and Traversable] traverse_bind = mkRdrFunBindEC 2 (nlHsApp pure_Expr)
compiler/GHC/Tc/Deriv/Generate.hs view
@@ -223,7 +223,7 @@ no_tag_match_cons = null tag_match_cons -- (LHS patterns, result)- fall_through_eqn :: [([Located (Pat (GhcPass 'Parsed))] , LHsExpr GhcPs)]+ fall_through_eqn :: [([LPat (GhcPass 'Parsed)] , LHsExpr GhcPs)] fall_through_eqn | no_tag_match_cons -- All constructors have arguments = case pat_match_cons of@@ -498,7 +498,8 @@ , mkHsCaseAlt nlWildPat (gtResult op) ] where tag = get_tag data_con- tag_lit = noLoc (HsLit noExtField (HsIntPrim NoSourceText (toInteger tag)))+ tag_lit+ = noLocA (HsLit noComments (HsIntPrim NoSourceText (toInteger tag))) mkInnerEqAlt :: OrdOp -> DataCon -> LMatch GhcPs (LHsExpr GhcPs) -- First argument 'a' known to be built with K@@ -577,15 +578,15 @@ -- mean more tests (dynamically) nlHsIf (ascribeBool $ genPrimOpApp a_expr eq_op b_expr) eq gt where- ascribeBool e = noLoc $ ExprWithTySig noExtField e- $ mkHsWildCardBndrs $ noLoc $ mkHsImplicitSigType- $ nlHsTyVar boolTyCon_RDR+ ascribeBool e = noLocA $ ExprWithTySig noAnn e+ $ mkHsWildCardBndrs $ noLocA $ mkHsImplicitSigType+ $ nlHsTyVar boolTyCon_RDR nlConWildPat :: DataCon -> LPat GhcPs -- The pattern (K {})-nlConWildPat con = noLoc $ ConPat- { pat_con_ext = noExtField- , pat_con = noLoc $ getRdrName con+nlConWildPat con = noLocA $ ConPat+ { pat_con_ext = noAnn+ , pat_con = noLocA $ getRdrName con , pat_args = RecCon $ HsRecFields { rec_flds = [] , rec_dotdot = Nothing }@@ -841,7 +842,7 @@ enum_index = mkSimpleGeneratedFunBind loc unsafeIndex_RDR- [noLoc (AsPat noExtField (noLoc c_RDR)+ [noLocA (AsPat noAnn (noLocA c_RDR) (nlTuplePat [a_Pat, nlWildPat] Boxed)), d_Pat] ( untag_Expr [(a_RDR, ah_RDR)] (@@ -892,13 +893,13 @@ single_con_range = mkSimpleGeneratedFunBind loc range_RDR [nlTuplePat [con_pat as_needed, con_pat bs_needed] Boxed] $- noLoc (mkHsComp ListComp stmts con_expr)+ noLocA (mkHsComp ListComp stmts con_expr) where stmts = zipWith3Equal "single_con_range" mk_qual as_needed bs_needed cs_needed - mk_qual a b c = noLoc $ mkPsBindStmt (nlVarPat c)+ mk_qual a b c = noLocA $ mkPsBindStmt noAnn (nlVarPat c) (nlHsApp (nlHsVar range_RDR)- (mkLHsVarTuple [a,b]))+ (mkLHsVarTuple [a,b] noAnn)) ---------------- single_con_index@@ -920,11 +921,11 @@ ) plus_RDR ( genOpApp ( (nlHsApp (nlHsVar unsafeRangeSize_RDR)- (mkLHsVarTuple [l,u]))+ (mkLHsVarTuple [l,u] noAnn)) ) times_RDR (mk_index rest) ) mk_one l u i- = nlHsApps unsafeIndex_RDR [mkLHsVarTuple [l,u], nlHsVar i]+ = nlHsApps unsafeIndex_RDR [mkLHsVarTuple [l,u] noAnn, nlHsVar i] ------------------ single_con_inRange@@ -938,7 +939,8 @@ else foldl1 and_Expr (zipWith3Equal "single_con_inRange" in_range as_needed bs_needed cs_needed) where- in_range a b c = nlHsApps inRange_RDR [mkLHsVarTuple [a,b], nlHsVar c]+ in_range a b c+ = nlHsApps inRange_RDR [mkLHsVarTuple [a,b] noAnn, nlHsVar c] {- ************************************************************************@@ -1043,7 +1045,7 @@ read_nullary_cons = case nullary_cons of [] -> []- [con] -> [nlHsDo (DoExpr Nothing) (match_con con ++ [noLoc $ mkLastStmt (result_expr con [])])]+ [con] -> [nlHsDo (DoExpr Nothing) (match_con con ++ [noLocA $ mkLastStmt (result_expr con [])])] _ -> [nlHsApp (nlHsVar choose_RDR) (nlList (map mk_pair nullary_cons))] -- NB For operators the parens around (:=:) are matched by the@@ -1058,7 +1060,7 @@ -- and Symbol s for operators mk_pair con = mkLHsTupleExpr [nlHsLit (mkHsString (data_con_str con)),- result_expr con []]+ result_expr con []] noAnn read_non_nullary_con data_con | is_infix = mk_parser infix_prec infix_stmts body@@ -1117,7 +1119,7 @@ ------------------------------------------------------------------------ mk_alt e1 e2 = genOpApp e1 alt_RDR e2 -- e1 +++ e2 mk_parser p ss b = nlHsApps prec_RDR [nlHsIntLit p -- prec p (do { ss ; b })- , nlHsDo (DoExpr Nothing) (ss ++ [noLoc $ mkLastStmt b])]+ , nlHsDo (DoExpr Nothing) (ss ++ [noLocA $ mkLastStmt b])] con_app con as = nlHsVarApps (getRdrName con) as -- con as result_expr con as = nlHsApp (nlHsVar returnM_RDR) (con_app con as) -- return (con as) @@ -1127,7 +1129,7 @@ ident_h_pat s | Just (ss, '#') <- snocView s = [ ident_pat ss, symbol_pat "#" ] | otherwise = [ ident_pat s ] - bindLex pat = noLoc (mkBodyStmt (nlHsApp (nlHsVar expectP_RDR) pat)) -- expectP p+ bindLex pat = noLocA (mkBodyStmt (nlHsApp (nlHsVar expectP_RDR) pat)) -- expectP p -- See Note [Use expectP] ident_pat s = bindLex $ nlHsApps ident_RDR [nlHsLit (mkHsString s)] -- expectP (Ident "foo") symbol_pat s = bindLex $ nlHsApps symbol_RDR [nlHsLit (mkHsString s)] -- expectP (Symbol ">>")@@ -1136,7 +1138,7 @@ data_con_str con = occNameString (getOccName con) read_arg a ty = ASSERT( not (isUnliftedType ty) )- noLoc (mkPsBindStmt (nlVarPat a) (nlHsVarApps step_RDR [readPrec_RDR]))+ noLocA (mkPsBindStmt noAnn (nlVarPat a) (nlHsVarApps step_RDR [readPrec_RDR])) -- When reading field labels we might encounter -- a = 3@@ -1144,8 +1146,8 @@ -- or (#) = 4 -- Note the parens! read_field lbl a =- [noLoc- (mkPsBindStmt+ [noLocA+ (mkPsBindStmt noAnn (nlVarPat a) (nlHsApp read_field@@ -1496,9 +1498,9 @@ eqAddr_RDR , ltAddr_RDR , geAddr_RDR , gtAddr_RDR , leAddr_RDR , eqFloat_RDR , ltFloat_RDR , geFloat_RDR , gtFloat_RDR , leFloat_RDR , eqDouble_RDR, ltDouble_RDR, geDouble_RDR, gtDouble_RDR, leDouble_RDR,- extendWord8_RDR, extendInt8_RDR,- extendWord16_RDR, extendInt16_RDR,- extendWord32_RDR, extendInt32_RDR+ word8ToWord_RDR , int8ToInt_RDR ,+ word16ToWord_RDR, int16ToInt_RDR,+ word32ToWord_RDR, int32ToInt_RDR :: RdrName gfoldl_RDR = varQual_RDR gENERICS (fsLit "gfoldl") gunfold_RDR = varQual_RDR gENERICS (fsLit "gunfold")@@ -1588,15 +1590,16 @@ gtDouble_RDR = varQual_RDR gHC_PRIM (fsLit ">##" ) geDouble_RDR = varQual_RDR gHC_PRIM (fsLit ">=##") -extendWord8_RDR = varQual_RDR gHC_PRIM (fsLit "extendWord8#")-extendInt8_RDR = varQual_RDR gHC_PRIM (fsLit "extendInt8#")+word8ToWord_RDR = varQual_RDR gHC_PRIM (fsLit "word8ToWord#")+int8ToInt_RDR = varQual_RDR gHC_PRIM (fsLit "int8ToInt#") -extendWord16_RDR = varQual_RDR gHC_PRIM (fsLit "extendWord16#")-extendInt16_RDR = varQual_RDR gHC_PRIM (fsLit "extendInt16#")+word16ToWord_RDR = varQual_RDR gHC_PRIM (fsLit "word16ToWord#")+int16ToInt_RDR = varQual_RDR gHC_PRIM (fsLit "int16ToInt#") -extendWord32_RDR = varQual_RDR gHC_PRIM (fsLit "extendWord32#")-extendInt32_RDR = varQual_RDR gHC_PRIM (fsLit "extendInt32#")+word32ToWord_RDR = varQual_RDR gHC_PRIM (fsLit "word32ToWord#")+int32ToInt_RDR = varQual_RDR gHC_PRIM (fsLit "int32ToInt#") + {- ************************************************************************ * *@@ -1638,7 +1641,7 @@ data_con_RDR = getRdrName data_con con_arity = dataConSourceArity data_con as_needed = take con_arity as_RDRs- lift_Expr = noLoc (HsBracket noExtField (mk_bracket br_body))+ lift_Expr = noLocA (HsBracket noAnn (mk_bracket br_body)) br_body = nlHsApps (Exact (dataConName data_con)) (map nlHsVar as_needed) @@ -1939,7 +1942,7 @@ -> Type -- the representation type -> TcM (LHsBinds GhcPs, [LSig GhcPs], BagDerivStuff) -- See Note [Newtype-deriving instances]-gen_Newtype_binds loc cls inst_tvs inst_tys rhs_ty+gen_Newtype_binds loc' cls inst_tvs inst_tys rhs_ty = do let ats = classATs cls (binds, sigs) = mapAndUnzip mk_bind_and_sig (classMethods cls) atf_insts <- ASSERT( all (not . isDataFamilyTyCon) ats )@@ -1948,6 +1951,8 @@ , sigs , listToBag $ map DerivFamInst atf_insts ) where+ locn = noAnnSrcSpan loc'+ loca = noAnnSrcSpan loc' -- For each class method, generate its derived binding and instance -- signature. Using the first example from -- Note [Newtype-deriving instances]:@@ -1978,10 +1983,10 @@ -- Make sure that `forall c` is in an HsOuterExplicit so that it -- scopes over the body of `op`. See "Wrinkle: Use HsOuterExplicit" in -- Note [GND and QuantifiedConstraints].- L loc $ ClassOpSig noExtField False [loc_meth_RDR]- $ L loc $ mkHsExplicitSigType- (map mk_hs_tvb to_tvbs)- (nlHsCoreTy to_rho)+ L loca $ ClassOpSig noAnn False [loc_meth_RDR]+ $ L loca $ mkHsExplicitSigType noAnn+ (map mk_hs_tvb to_tvbs)+ (nlHsCoreTy to_rho) ) where Pair from_ty to_ty = mkCoerceClassMethEqn cls inst_tvs inst_tys rhs_ty meth_id@@ -1994,13 +1999,13 @@ -- Note [GND and QuantifiedConstraints]. mk_hs_tvb :: VarBndr TyVar flag -> LHsTyVarBndr flag GhcPs- mk_hs_tvb (Bndr tv flag) = noLoc $ KindedTyVar noExtField- flag- (noLoc (getRdrName tv))- (nlHsCoreTy (tyVarKind tv))+ mk_hs_tvb (Bndr tv flag) = noLocA $ KindedTyVar noAnn+ flag+ (noLocA (getRdrName tv))+ (nlHsCoreTy (tyVarKind tv)) meth_RDR = getRdrName meth_id- loc_meth_RDR = L loc meth_RDR+ loc_meth_RDR = L locn meth_RDR rhs_expr = nlHsVar (getRdrName coerceId) `nlHsAppType` from_tau@@ -2017,7 +2022,7 @@ mk_atf_inst :: TyCon -> TcM FamInst mk_atf_inst fam_tc = do- rep_tc_name <- newFamInstTyConName (L loc (tyConName fam_tc))+ rep_tc_name <- newFamInstTyConName (L locn (tyConName fam_tc)) rep_lhs_tys let axiom = mkSingleCoAxiom Nominal rep_tc_name rep_tvs' [] rep_cvs' fam_tc rep_lhs_tys rep_rhs_ty@@ -2046,12 +2051,12 @@ underlying_inst_tys = changeLast inst_tys rhs_ty nlHsAppType :: LHsExpr GhcPs -> Type -> LHsExpr GhcPs-nlHsAppType e s = noLoc (HsAppType noExtField e hs_ty)+nlHsAppType e s = noLocA (HsAppType noSrcSpan e hs_ty) where hs_ty = mkHsWildCardBndrs $ parenthesizeHsType appPrec $ nlHsCoreTy s nlHsCoreTy :: HsCoreTy -> LHsType GhcPs-nlHsCoreTy = noLoc . XHsType+nlHsCoreTy = noLocA . XHsType mkCoerceClassMethEqn :: Class -- the class being derived -> [TyVar] -- the tvs in the instance head (this includes@@ -2100,9 +2105,11 @@ -> (LHsBind GhcPs, LSig GhcPs) genAuxBindSpecOriginal dflags loc spec = (gen_bind spec,- L loc (TypeSig noExtField [L loc (auxBindSpecRdrName spec)]+ L loca (TypeSig noAnn [L locn (auxBindSpecRdrName spec)] (genAuxBindSpecSig loc spec))) where+ loca = noAnnSrcSpan loc+ locn = noAnnSrcSpan loc gen_bind :: AuxBindSpec -> LHsBind GhcPs gen_bind (DerivTag2Con _ tag2con_RDR) = mkFunBindSE 0 loc tag2con_RDR@@ -2151,9 +2158,11 @@ -> (LHsBind GhcPs, LSig GhcPs) genAuxBindSpecDup loc original_rdr_name dup_spec = (mkHsVarBind loc dup_rdr_name (nlHsVar original_rdr_name),- L loc (TypeSig noExtField [L loc dup_rdr_name]+ L loca (TypeSig noAnn [L locn dup_rdr_name] (genAuxBindSpecSig loc dup_spec))) where+ loca = noAnnSrcSpan loc+ locn = noAnnSrcSpan loc dup_rdr_name = auxBindSpecRdrName dup_spec -- | Generate the type signature of an auxiliary binding.@@ -2161,17 +2170,17 @@ genAuxBindSpecSig :: SrcSpan -> AuxBindSpec -> LHsSigWcType GhcPs genAuxBindSpecSig loc spec = case spec of DerivTag2Con tycon _- -> mk_sig $ L loc $+ -> mk_sig $ L (noAnnSrcSpan loc) $ XHsType $ mkSpecForAllTys (tyConTyVars tycon) $ intTy `mkVisFunTyMany` mkParentType tycon DerivMaxTag _ _- -> mk_sig (L loc (XHsType intTy))+ -> mk_sig (L (noAnnSrcSpan loc) (XHsType intTy)) DerivDataDataType _ _ _ -> mk_sig (nlHsTyVar dataType_RDR) DerivDataConstr _ _ _ -> mk_sig (nlHsTyVar constr_RDR) where- mk_sig = mkHsWildCardBndrs . L loc . mkHsImplicitSigType+ mk_sig = mkHsWildCardBndrs . L (noAnnSrcSpan loc) . mkHsImplicitSigType type SeparateBagsDerivStuff = -- DerivAuxBinds@@ -2234,17 +2243,17 @@ -> [([LPat GhcPs], LHsExpr GhcPs)] -> LHsBind GhcPs mkFunBindSE arity loc fun pats_and_exprs- = mkRdrFunBindSE arity (L loc fun) matches+ = mkRdrFunBindSE arity (L (noAnnSrcSpan loc) fun) matches where- matches = [mkMatch (mkPrefixFunRhs (L loc fun))+ matches = [mkMatch (mkPrefixFunRhs (L (noAnnSrcSpan loc) fun)) (map (parenthesizePat appPrec) p) e- (noLoc emptyLocalBinds)+ emptyLocalBinds | (p,e) <-pats_and_exprs] -mkRdrFunBind :: Located RdrName -> [LMatch GhcPs (LHsExpr GhcPs)]+mkRdrFunBind :: LocatedN RdrName -> [LMatch GhcPs (LHsExpr GhcPs)] -> LHsBind GhcPs mkRdrFunBind fun@(L loc _fun_rdr) matches- = L loc (mkFunBind Generated fun matches)+ = L (na2la loc) (mkFunBind Generated fun matches) -- | Make a function binding. If no equations are given, produce a function -- with the given arity that uses an empty case expression for the last@@ -2255,11 +2264,11 @@ -> [([LPat GhcPs], LHsExpr GhcPs)] -> LHsBind GhcPs mkFunBindEC arity loc fun catch_all pats_and_exprs- = mkRdrFunBindEC arity catch_all (L loc fun) matches+ = mkRdrFunBindEC arity catch_all (L (noAnnSrcSpan loc) fun) matches where- matches = [ mkMatch (mkPrefixFunRhs (L loc fun))+ matches = [ mkMatch (mkPrefixFunRhs (L (noAnnSrcSpan loc) fun)) (map (parenthesizePat appPrec) p) e- (noLoc emptyLocalBinds)+ emptyLocalBinds | (p,e) <- pats_and_exprs ] -- | Produces a function binding. When no equations are given, it generates@@ -2268,11 +2277,11 @@ -- the right-hand side. mkRdrFunBindEC :: Arity -> (LHsExpr GhcPs -> LHsExpr GhcPs)- -> Located RdrName+ -> LocatedN RdrName -> [LMatch GhcPs (LHsExpr GhcPs)] -> LHsBind GhcPs-mkRdrFunBindEC arity catch_all- fun@(L loc _fun_rdr) matches = L loc (mkFunBind Generated fun matches')+mkRdrFunBindEC arity catch_all fun@(L loc _fun_rdr) matches+ = L (na2la loc) (mkFunBind Generated fun matches') where -- Catch-all eqn looks like -- fmap _ z = case z of {}@@ -2287,16 +2296,16 @@ then [mkMatch (mkPrefixFunRhs fun) (replicate (arity - 1) nlWildPat ++ [z_Pat]) (catch_all $ nlHsCase z_Expr [])- (noLoc emptyLocalBinds)]+ emptyLocalBinds] else matches -- | Produces a function binding. When there are no equations, it generates -- a binding with the given arity that produces an error based on the name of -- the type of the last argument.-mkRdrFunBindSE :: Arity -> Located RdrName ->+mkRdrFunBindSE :: Arity -> LocatedN RdrName -> [LMatch GhcPs (LHsExpr GhcPs)] -> LHsBind GhcPs-mkRdrFunBindSE arity- fun@(L loc fun_rdr) matches = L loc (mkFunBind Generated fun matches')+mkRdrFunBindSE arity fun@(L loc fun_rdr) matches+ = L (na2la loc) (mkFunBind Generated fun matches') where -- Catch-all eqn looks like -- compare _ _ = error "Void compare"@@ -2306,7 +2315,7 @@ matches' = if null matches then [mkMatch (mkPrefixFunRhs fun) (replicate arity nlWildPat)- (error_Expr str) (noLoc emptyLocalBinds)]+ (error_Expr str) emptyLocalBinds] else matches str = "Void " ++ occNameString (rdrNameOcc fun_rdr) @@ -2364,22 +2373,22 @@ , (doublePrimTy, nlHsApp (nlHsVar $ getRdrName doubleDataCon)) , (int8PrimTy, nlHsApp (nlHsVar $ getRdrName intDataCon)- . nlHsApp (nlHsVar extendInt8_RDR))+ . nlHsApp (nlHsVar int8ToInt_RDR)) , (word8PrimTy, nlHsApp (nlHsVar $ getRdrName wordDataCon)- . nlHsApp (nlHsVar extendWord8_RDR))+ . nlHsApp (nlHsVar word8ToWord_RDR)) , (int16PrimTy, nlHsApp (nlHsVar $ getRdrName intDataCon)- . nlHsApp (nlHsVar extendInt16_RDR))+ . nlHsApp (nlHsVar int16ToInt_RDR)) , (word16PrimTy, nlHsApp (nlHsVar $ getRdrName wordDataCon)- . nlHsApp (nlHsVar extendWord16_RDR))+ . nlHsApp (nlHsVar word16ToWord_RDR)) , (int32PrimTy, nlHsApp (nlHsVar $ getRdrName intDataCon)- . nlHsApp (nlHsVar extendInt32_RDR))+ . nlHsApp (nlHsVar int32ToInt_RDR)) , (word32PrimTy, nlHsApp (nlHsVar $ getRdrName wordDataCon)- . nlHsApp (nlHsVar extendWord32_RDR))+ . nlHsApp (nlHsVar word32ToWord_RDR)) ] @@ -2401,12 +2410,12 @@ primConvTbl :: [(Type, String)] primConvTbl =- [ (int8PrimTy, "narrowInt8#")- , (word8PrimTy, "narrowWord8#")- , (int16PrimTy, "narrowInt16#")- , (word16PrimTy, "narrowWord16#")- , (int32PrimTy, "narrowInt32#")- , (word32PrimTy, "narrowWord32#")+ [ (int8PrimTy, "intToInt8#")+ , (word8PrimTy, "wordToWord8#")+ , (int16PrimTy, "intToInt16#")+ , (word16PrimTy, "wordToWord16#")+ , (int32PrimTy, "intToInt32#")+ , (word32PrimTy, "wordToWord32#") ] litConTbl :: [(Type, LHsExpr GhcPs -> LHsExpr GhcPs)]
compiler/GHC/Tc/Deriv/Generics.hs view
@@ -340,9 +340,9 @@ mkBindsRep :: DynFlags -> GenericKind -> TyCon -> (LHsBinds GhcPs, [LSig GhcPs]) mkBindsRep dflags gk tycon = (binds, sigs) where- binds = unitBag (mkRdrFunBind (L loc from01_RDR) [from_eqn])+ binds = unitBag (mkRdrFunBind (L loc' from01_RDR) [from_eqn]) `unionBags`- unitBag (mkRdrFunBind (L loc to01_RDR) [to_eqn])+ unitBag (mkRdrFunBind (L loc' to01_RDR) [to_eqn]) -- See Note [Generics performance tricks] sigs = if gopt Opt_InlineGenericsAggressively dflags@@ -361,7 +361,7 @@ cons = length datacons max_fields = maximum $ map dataConSourceArity datacons - inline1 f = L loc . InlineSig noExtField (L loc f)+ inline1 f = L loc'' . InlineSig noAnn (L loc' f) $ alwaysInlinePragma { inl_act = ActiveAfter NoSourceText 1 } -- The topmost M1 (the datatype metadata) has the exact same type@@ -375,6 +375,8 @@ from_matches = [mkHsCaseAlt pat rhs | (pat,rhs) <- from_alts] to_matches = [mkHsCaseAlt pat rhs | (pat,rhs) <- to_alts ] loc = srcLocSpan (getSrcLoc tycon)+ loc' = noAnnSrcSpan loc+ loc'' = noAnnSrcSpan loc datacons = tyConDataCons tycon (from01_RDR, to01_RDR) = case gk of@@ -900,10 +902,17 @@ -- | Variant of foldr for producing balanced lists foldBal :: (a -> a -> a) -> a -> [a] -> a-foldBal _ x [] = x-foldBal _ _ [y] = y-foldBal op x l = let (a,b) = splitAt (length l `div` 2) l- in foldBal op x a `op` foldBal op x b+{-# INLINE foldBal #-} -- inlined to produce specialised code for each op+foldBal op0 x0 xs0 = fold_bal op0 x0 (length xs0) xs0+ where+ fold_bal op x !n xs = case xs of+ [] -> x+ [a] -> a+ _ -> let !nl = n `div` 2+ !nr = n - nl+ (l,r) = splitAt nl xs+ in fold_bal op x nl l+ `op` fold_bal op x nr r {- Note [Generics and unlifted types]
compiler/GHC/Tc/Deriv/Utils.hs view
@@ -269,9 +269,9 @@ -- | Convert a 'DerivSpecMechanism' to its corresponding 'DerivStrategy'. derivSpecMechanismToStrategy :: DerivSpecMechanism -> DerivStrategy GhcTc-derivSpecMechanismToStrategy DerivSpecStock{} = StockStrategy-derivSpecMechanismToStrategy DerivSpecNewtype{} = NewtypeStrategy-derivSpecMechanismToStrategy DerivSpecAnyClass = AnyclassStrategy+derivSpecMechanismToStrategy DerivSpecStock{} = StockStrategy noExtField+derivSpecMechanismToStrategy DerivSpecNewtype{} = NewtypeStrategy noExtField+derivSpecMechanismToStrategy DerivSpecAnyClass = AnyclassStrategy noExtField derivSpecMechanismToStrategy (DerivSpecVia{dsm_via_ty = t}) = ViaStrategy t isDerivSpecStock, isDerivSpecNewtype, isDerivSpecAnyClass, isDerivSpecVia
compiler/GHC/Tc/Errors.hs view
@@ -66,7 +66,7 @@ import qualified GHC.LanguageExtensions as LangExt import GHC.Utils.FV ( fvVarList, unionFV ) -import Control.Monad ( when )+import Control.Monad ( when, unless ) import Data.Foldable ( toList ) import Data.List ( partition, mapAccumL, sortBy, unfoldr ) @@ -132,27 +132,33 @@ = do { binds_var <- newTcEvBinds ; defer_errors <- goptM Opt_DeferTypeErrors ; warn_errors <- woptM Opt_WarnDeferredTypeErrors -- implement #10283- ; let type_errors | not defer_errors = TypeError- | warn_errors = TypeWarn (Reason Opt_WarnDeferredTypeErrors)- | otherwise = TypeDefer+ ; let type_errors | not defer_errors = Just ErrorWithoutFlag+ | warn_errors = Just (WarningWithFlag Opt_WarnDeferredTypeErrors)+ | otherwise = Nothing ; defer_holes <- goptM Opt_DeferTypedHoles ; warn_holes <- woptM Opt_WarnTypedHoles- ; let expr_holes | not defer_holes = HoleError- | warn_holes = HoleWarn- | otherwise = HoleDefer+ ; let expr_holes | not defer_holes = Just ErrorWithoutFlag+ | warn_holes = Just (WarningWithFlag Opt_WarnTypedHoles)+ | otherwise = Nothing ; partial_sigs <- xoptM LangExt.PartialTypeSignatures ; warn_partial_sigs <- woptM Opt_WarnPartialTypeSignatures- ; let type_holes | not partial_sigs = HoleError- | warn_partial_sigs = HoleWarn- | otherwise = HoleDefer+ ; let type_holes | not partial_sigs+ = Just ErrorWithoutFlag+ | warn_partial_sigs+ = Just (WarningWithFlag Opt_WarnPartialTypeSignatures)+ | otherwise+ = Nothing ; defer_out_of_scope <- goptM Opt_DeferOutOfScopeVariables ; warn_out_of_scope <- woptM Opt_WarnDeferredOutOfScopeVariables- ; let out_of_scope_holes | not defer_out_of_scope = HoleError- | warn_out_of_scope = HoleWarn- | otherwise = HoleDefer+ ; let out_of_scope_holes | not defer_out_of_scope+ = Just ErrorWithoutFlag+ | warn_out_of_scope+ = Just (WarningWithFlag Opt_WarnDeferredOutOfScopeVariables)+ | otherwise+ = Nothing ; report_unsolved type_errors expr_holes type_holes out_of_scope_holes@@ -174,11 +180,12 @@ ; partial_sigs <- xoptM LangExt.PartialTypeSignatures ; warn_partial_sigs <- woptM Opt_WarnPartialTypeSignatures- ; let type_holes | not partial_sigs = HoleError- | warn_partial_sigs = HoleWarn- | otherwise = HoleDefer+ ; let type_holes | not partial_sigs = Just ErrorWithoutFlag+ | warn_partial_sigs = Just (WarningWithFlag Opt_WarnPartialTypeSignatures)+ | otherwise = Nothing - ; report_unsolved TypeError HoleError type_holes HoleError+ ; report_unsolved (Just ErrorWithoutFlag)+ (Just ErrorWithoutFlag) type_holes (Just ErrorWithoutFlag) ev_binds wanted } -- | Report all unsolved goals as warnings (but without deferring any errors to@@ -187,14 +194,17 @@ warnAllUnsolved :: WantedConstraints -> TcM () warnAllUnsolved wanted = do { ev_binds <- newTcEvBinds- ; report_unsolved (TypeWarn NoReason) HoleWarn HoleWarn HoleWarn+ ; report_unsolved (Just WarningWithoutFlag)+ (Just WarningWithoutFlag)+ (Just WarningWithoutFlag)+ (Just WarningWithoutFlag) ev_binds wanted } -- | Report unsolved goals as errors or warnings.-report_unsolved :: TypeErrorChoice -- Deferred type errors- -> HoleChoice -- Expression holes- -> HoleChoice -- Type holes- -> HoleChoice -- Out of scope holes+report_unsolved :: Maybe DiagnosticReason -- Deferred type errors+ -> Maybe DiagnosticReason -- Expression holes+ -> Maybe DiagnosticReason -- Type holes+ -> Maybe DiagnosticReason -- Out of scope holes -> EvBindsVar -- cec_binds -> WantedConstraints -> TcM () report_unsolved type_errors expr_holes@@ -267,10 +277,11 @@ , text "valid:" <+> vcat val ] {- Note [Error report]+~~~~~~~~~~~~~~~~~~~~~~ The idea is that error msgs are divided into three parts: the main msg, the-context block (\"In the second argument of ...\"), and the relevant bindings-block, which are displayed in that order, with a mark to divide them. The-idea is that the main msg ('report_important') varies depending on the error+context block ("In the second argument of ..."), and the relevant bindings+block, which are displayed in that order, with a mark to divide them. The+the main msg ('report_important') varies depending on the error in question, but context and relevant bindings are always the same, which should simplify visual parsing. @@ -298,30 +309,6 @@ valid_hole_fits :: SDoc -> Report valid_hole_fits docs = mempty { report_valid_hole_fits = [docs] } -data TypeErrorChoice -- What to do for type errors found by the type checker- = TypeError -- A type error aborts compilation with an error message- | TypeWarn WarnReason- -- A type error is deferred to runtime, plus a compile-time warning- -- The WarnReason should usually be (Reason Opt_WarnDeferredTypeErrors)- -- but it isn't for the Safe Haskell Overlapping Instances warnings- -- see warnAllUnsolved- | TypeDefer -- A type error is deferred to runtime; no error or warning at compile time--data HoleChoice- = HoleError -- A hole is a compile-time error- | HoleWarn -- Defer to runtime, emit a compile-time warning- | HoleDefer -- Defer to runtime, no warning--instance Outputable HoleChoice where- ppr HoleError = text "HoleError"- ppr HoleWarn = text "HoleWarn"- ppr HoleDefer = text "HoleDefer"--instance Outputable TypeErrorChoice where- ppr TypeError = text "TypeError"- ppr (TypeWarn reason) = text "TypeWarn" <+> ppr reason- ppr TypeDefer = text "TypeDefer"- data ReportErrCtxt = CEC { cec_encl :: [Implication] -- Enclosing implications -- (innermost first)@@ -332,15 +319,15 @@ -- into warnings, and emit evidence bindings -- into 'cec_binds' for unsolved constraints - , cec_defer_type_errors :: TypeErrorChoice -- Defer type errors until runtime+ , cec_defer_type_errors :: Maybe DiagnosticReason -- Nothing: Defer type errors until runtime -- cec_expr_holes is a union of: -- cec_type_holes - a set of typed holes: '_', '_a', '_foo' -- cec_out_of_scope_holes - a set of variables which are -- out of scope: 'x', 'y', 'bar'- , cec_expr_holes :: HoleChoice -- Holes in expressions- , cec_type_holes :: HoleChoice -- Holes in types- , cec_out_of_scope_holes :: HoleChoice -- Out of scope holes+ , cec_expr_holes :: Maybe DiagnosticReason -- Holes in expressions. Nothing: defer/suppress errors.+ , cec_type_holes :: Maybe DiagnosticReason -- Holes in types. Nothing: defer/suppress errors.+ , cec_out_of_scope_holes :: Maybe DiagnosticReason -- Out of scope holes. Nothing: defer/suppress errors. , cec_warn_redundant :: Bool -- True <=> -Wredundant-constraints , cec_expand_syns :: Bool -- True <=> -fprint-expanded-synonyms@@ -373,19 +360,19 @@ -- | Returns True <=> the ReportErrCtxt indicates that something is deferred deferringAnyBindings :: ReportErrCtxt -> Bool -- Don't check cec_type_holes, as these don't cause bindings to be deferred-deferringAnyBindings (CEC { cec_defer_type_errors = TypeError- , cec_expr_holes = HoleError- , cec_out_of_scope_holes = HoleError }) = False-deferringAnyBindings _ = True+deferringAnyBindings (CEC { cec_defer_type_errors = Just ErrorWithoutFlag+ , cec_expr_holes = Just ErrorWithoutFlag+ , cec_out_of_scope_holes = Just ErrorWithoutFlag }) = False+deferringAnyBindings _ = True maybeSwitchOffDefer :: EvBindsVar -> ReportErrCtxt -> ReportErrCtxt -- Switch off defer-type-errors inside CoEvBindsVar -- See Note [Failing equalities with no evidence bindings] maybeSwitchOffDefer evb ctxt | CoEvBindsVar{} <- evb- = ctxt { cec_defer_type_errors = TypeError- , cec_expr_holes = HoleError- , cec_out_of_scope_holes = HoleError }+ = ctxt { cec_defer_type_errors = Just ErrorWithoutFlag+ , cec_expr_holes = Just ErrorWithoutFlag+ , cec_out_of_scope_holes = Just ErrorWithoutFlag } | otherwise = ctxt @@ -492,14 +479,14 @@ -- to the error context, which is a bit tiresome addErrCtxt (text "In" <+> ppr info) $ do { env <- getLclEnv- ; msg <- mkErrorReport ctxt env (important doc)- ; reportWarning (Reason Opt_WarnRedundantConstraints) msg }+ ; msg <- mkErrorReport (WarningWithFlag Opt_WarnRedundantConstraints) ctxt env (important doc)+ ; reportDiagnostic msg } | otherwise -- But for InstSkol there already *is* a surrounding -- "In the instance declaration for Eq [a]" context -- and we don't want to say it twice. Seems a bit ad-hoc- = do { msg <- mkErrorReport ctxt env (important doc)- ; reportWarning (Reason Opt_WarnRedundantConstraints) msg }+ = do { msg <- mkErrorReport (WarningWithFlag Opt_WarnRedundantConstraints) ctxt env (important doc)+ ; reportDiagnostic msg } where doc = text "Redundant constraint" <> plural redundant_evs <> colon <+> pprEvVarTheta redundant_evs@@ -518,8 +505,8 @@ reportBadTelescope :: ReportErrCtxt -> TcLclEnv -> SkolemInfo -> [TcTyVar] -> TcM () reportBadTelescope ctxt env (ForAllSkol telescope) skols- = do { msg <- mkErrorReport ctxt env (important doc)- ; reportError msg }+ = do { msg <- mkErrorReport ErrorWithoutFlag ctxt env (important doc)+ ; reportDiagnostic msg } where doc = hang (text "These kind and type variables:" <+> telescope $$ text "are out of dependency order. Perhaps try this ordering:")@@ -740,18 +727,43 @@ reportHoles :: [Ct] -- other (tidied) constraints -> ReportErrCtxt -> [Hole] -> TcM () reportHoles tidy_cts ctxt- = mapM_ $ \hole -> do { err <- mkHoleError tidy_cts ctxt hole- ; maybeReportHoleError ctxt hole err- ; maybeAddDeferredHoleBinding ctxt err hole }+ = mapM_ $ \hole -> unless (ignoreThisHole ctxt hole) $+ do { msg_mb <- mkHoleError tidy_cts ctxt hole+ ; whenIsJust msg_mb reportDiagnostic } +ignoreThisHole :: ReportErrCtxt -> Hole -> Bool+-- See Note [Skip type holes rapidly]+ignoreThisHole ctxt hole+ = case hole_sort hole of+ ExprHole {} -> False+ TypeHole -> ignore_type_hole+ ConstraintHole -> ignore_type_hole+ where+ ignore_type_hole = case cec_type_holes ctxt of+ Nothing -> True+ _ -> False++{- Note [Skip type holes rapidly]+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+Suppose we have module with a /lot/ of partial type signatures, and we+compile it while suppressing partial-type-signature warnings. Then+we don't want to spend ages constructing error messages and lists of+relevant bindings that we never display! This happened in #14766, in+which partial type signatures in a Happy-generated parser cause a huge+increase in compile time.++The function ignoreThisHole short-circuits the error/warning generation+machinery, in cases where it is definitely going to be a no-op.+-}+ mkUserTypeErrorReporter :: Reporter mkUserTypeErrorReporter ctxt = mapM_ $ \ct -> do { err <- mkUserTypeError ctxt ct ; maybeReportError ctxt err ; addDeferredBinding ctxt err ct } -mkUserTypeError :: ReportErrCtxt -> Ct -> TcM (MsgEnvelope DecoratedSDoc)-mkUserTypeError ctxt ct = mkErrorMsgFromCt ctxt ct+mkUserTypeError :: ReportErrCtxt -> Ct -> TcM (MsgEnvelope DiagnosticMessage)+mkUserTypeError ctxt ct = mkErrorMsgFromCt ErrorWithoutFlag ctxt ct $ important $ pprUserTypeErrorTy $ case getUserTypeErrorMsg ct of@@ -776,10 +788,10 @@ report = important inaccessible_msg `mappend` mk_relevant_bindings binds_msg - ; err <- mkEqErr_help dflags ctxt report ct' ty1 ty2+ ; err <- mkEqErr_help (WarningWithFlag Opt_WarnInaccessibleCode) dflags ctxt report ct' ty1 ty2 ; traceTc "mkGivenErrorReporter" (ppr ct)- ; reportWarning (Reason Opt_WarnInaccessibleCode) err }+ ; reportDiagnostic err } where (ct : _ ) = cts -- Never empty (ty1, ty2) = getEqPredTys (ctPred ct)@@ -826,7 +838,7 @@ find one, we report the insoluble Given. -} -mkGroupReporter :: (ReportErrCtxt -> [Ct] -> TcM (MsgEnvelope DecoratedSDoc))+mkGroupReporter :: (ReportErrCtxt -> [Ct] -> TcM (MsgEnvelope DiagnosticMessage)) -- Make error message for a group -> Reporter -- Deal with lots of constraints -- Group together errors from same location,@@ -835,7 +847,7 @@ = mapM_ (reportGroup mk_err ctxt . toList) (equivClasses cmp_loc cts) -- Like mkGroupReporter, but doesn't actually print error messages-mkSuppressReporter :: (ReportErrCtxt -> [Ct] -> TcM (MsgEnvelope DecoratedSDoc)) -> Reporter+mkSuppressReporter :: (ReportErrCtxt -> [Ct] -> TcM (MsgEnvelope DiagnosticMessage)) -> Reporter mkSuppressReporter mk_err ctxt cts = mapM_ (suppressGroup mk_err ctxt . toList) (equivClasses cmp_loc cts) @@ -853,7 +865,7 @@ -- Reduce duplication by reporting only one error from each -- /starting/ location even if the end location differs -reportGroup :: (ReportErrCtxt -> [Ct] -> TcM (MsgEnvelope DecoratedSDoc)) -> Reporter+reportGroup :: (ReportErrCtxt -> [Ct] -> TcM (MsgEnvelope DiagnosticMessage)) -> Reporter reportGroup mk_err ctxt cts = ASSERT( not (null cts)) do { err <- mk_err ctxt cts@@ -872,67 +884,40 @@ -- like reportGroup, but does not actually report messages. It still adds -- -fdefer-type-errors bindings, though.-suppressGroup :: (ReportErrCtxt -> [Ct] -> TcM (MsgEnvelope DecoratedSDoc)) -> Reporter+suppressGroup :: (ReportErrCtxt -> [Ct] -> TcM (MsgEnvelope DiagnosticMessage)) -> Reporter suppressGroup mk_err ctxt cts = do { err <- mk_err ctxt cts ; traceTc "Suppressing errors for" (ppr cts) ; mapM_ (addDeferredBinding ctxt err) cts } -maybeReportHoleError :: ReportErrCtxt -> Hole -> MsgEnvelope DecoratedSDoc -> TcM ()-maybeReportHoleError ctxt hole err- | isOutOfScopeHole hole- -- Always report an error for out-of-scope variables- -- Unless -fdefer-out-of-scope-variables is on,- -- in which case the messages are discarded.- -- See #12170, #12406- = -- If deferring, report a warning only if -Wout-of-scope-variables is on- case cec_out_of_scope_holes ctxt of- HoleError -> reportError err- HoleWarn ->- reportWarning (Reason Opt_WarnDeferredOutOfScopeVariables) err- HoleDefer -> return ()---- Unlike maybeReportError, these "hole" errors are--- /not/ suppressed by cec_suppress. We want to see them!-maybeReportHoleError ctxt (Hole { hole_sort = hole_sort }) err- | case hole_sort of TypeHole -> True- ConstraintHole -> True- _ -> False- -- When -XPartialTypeSignatures is on, warnings (instead of errors) are- -- generated for holes in partial type signatures.- -- Unless -fwarn-partial-type-signatures is not on,- -- in which case the messages are discarded.- = -- For partial type signatures, generate warnings only, and do that- -- only if -fwarn-partial-type-signatures is on- case cec_type_holes ctxt of- HoleError -> reportError err- HoleWarn -> reportWarning (Reason Opt_WarnPartialTypeSignatures) err- HoleDefer -> return ()--maybeReportHoleError ctxt hole err- -- Otherwise this is a typed hole in an expression,- -- but not for an out-of-scope variable (because that goes through a- -- different function)- = -- If deferring, report a warning only if -Wtyped-holes is on- ASSERT( not (isOutOfScopeHole hole) )- case cec_expr_holes ctxt of- HoleError -> reportError err- HoleWarn -> reportWarning (Reason Opt_WarnTypedHoles) err- HoleDefer -> return ()--maybeReportError :: ReportErrCtxt -> MsgEnvelope DecoratedSDoc -> TcM ()+maybeReportError :: ReportErrCtxt -> MsgEnvelope DiagnosticMessage -> TcM () -- Report the error and/or make a deferred binding for it-maybeReportError ctxt err+maybeReportError ctxt msg | cec_suppress ctxt -- Some worse error has occurred; = return () -- so suppress this error/warning + | Just reason <- cec_defer_type_errors ctxt+ = reportDiagnostic (reclassify reason msg) | otherwise- = case cec_defer_type_errors ctxt of- TypeDefer -> return ()- TypeWarn reason -> reportWarning reason err- TypeError -> reportError err+ = return ()+ where+ -- Reclassifies a 'DiagnosticMessage', by explicitly setting its 'Severity' and+ -- 'DiagnosticReason'. This function has to be considered unsafe and local to this+ -- module, and it's a temporary stop-gap in the context of #18516. In particular,+ -- diagnostic messages should have both their 'DiagnosticReason' and 'Severity' computed+ -- \"at birth\": the former is statically computer, the latter is computed using the+ -- 'DynFlags' in scope at the time of construction. However, due to the intricacies of+ -- the current error-deferring logic, we are not always able to enforce this invariant+ -- and we rather have to change one or the other /a posteriori/.+ reclassify :: DiagnosticReason+ -> MsgEnvelope DiagnosticMessage+ -> MsgEnvelope DiagnosticMessage+ reclassify rea msg =+ let set_reason r m = m { errMsgDiagnostic = (errMsgDiagnostic m) { diagReason = r } }+ set_severity s m = m { errMsgSeverity = s }+ in set_severity (defaultReasonSeverity rea) . set_reason rea $ msg -addDeferredBinding :: ReportErrCtxt -> MsgEnvelope DecoratedSDoc -> Ct -> TcM ()+addDeferredBinding :: ReportErrCtxt -> MsgEnvelope DiagnosticMessage -> Ct -> TcM () -- See Note [Deferring coercion errors to runtime] addDeferredBinding ctxt err ct | deferringAnyBindings ctxt@@ -955,31 +940,13 @@ = return () mkErrorTerm :: DynFlags -> Type -- of the error term- -> MsgEnvelope DecoratedSDoc -> EvTerm+ -> MsgEnvelope DiagnosticMessage -> EvTerm mkErrorTerm dflags ty err = evDelayedError ty err_fs where err_msg = pprLocMsgEnvelope err err_fs = mkFastString $ showSDoc dflags $ err_msg $$ text "(deferred type error)" -maybeAddDeferredHoleBinding :: ReportErrCtxt -> MsgEnvelope DecoratedSDoc -> Hole -> TcM ()-maybeAddDeferredHoleBinding ctxt err (Hole { hole_sort = ExprHole (HER ref ref_ty _) })--- Only add bindings for holes in expressions--- not for holes in partial type signatures--- cf. addDeferredBinding- | deferringAnyBindings ctxt- = do { dflags <- getDynFlags- ; let err_tm = mkErrorTerm dflags ref_ty err- -- NB: ref_ty, not hole_ty. hole_ty might be rewritten.- -- See Note [Holes] in GHC.Tc.Types.Constraint- ; writeMutVar ref err_tm }- | otherwise- = return ()-maybeAddDeferredHoleBinding _ _ (Hole { hole_sort = TypeHole })- = return ()-maybeAddDeferredHoleBinding _ _ (Hole { hole_sort = ConstraintHole })- = return ()- tryReporters :: ReportErrCtxt -> [ReporterSpec] -> [Ct] -> TcM (ReportErrCtxt, [Ct]) -- Use the first reporter in the list whose predicate says True tryReporters ctxt reporters cts@@ -1048,14 +1015,19 @@ ppr_one ct' = hang (parens (pprType (ctPred ct'))) 2 (pprCtLoc (ctLoc ct')) -mkErrorMsgFromCt :: ReportErrCtxt -> Ct -> Report -> TcM (MsgEnvelope DecoratedSDoc)-mkErrorMsgFromCt ctxt ct report- = mkErrorReport ctxt (ctLocEnv (ctLoc ct)) report+mkErrorMsgFromCt :: DiagnosticReason -> ReportErrCtxt -> Ct -> Report -> TcM (MsgEnvelope DiagnosticMessage)+mkErrorMsgFromCt rea ctxt ct report+ = mkErrorReport rea ctxt (ctLocEnv (ctLoc ct)) report -mkErrorReport :: ReportErrCtxt -> TcLclEnv -> Report -> TcM (MsgEnvelope DecoratedSDoc)-mkErrorReport ctxt tcl_env (Report important relevant_bindings valid_subs)+mkErrorReport :: DiagnosticReason+ -> ReportErrCtxt+ -> TcLclEnv+ -> Report+ -> TcM (MsgEnvelope DiagnosticMessage)+mkErrorReport rea ctxt tcl_env (Report important relevant_bindings valid_subs) = do { context <- mkErrInfo (cec_tidy ctxt) (tcl_ctxt tcl_env)- ; mkDecoratedSDocAt (RealSrcSpan (tcl_loc tcl_env) Nothing)+ ; mkDecoratedSDocAt rea+ (RealSrcSpan (tcl_loc tcl_env) Nothing) (vcat important) context (vcat $ relevant_bindings ++ valid_subs)@@ -1155,19 +1127,54 @@ ************************************************************************ -} -mkIrredErr :: ReportErrCtxt -> [Ct] -> TcM (MsgEnvelope DecoratedSDoc)+mkIrredErr :: ReportErrCtxt -> [Ct] -> TcM (MsgEnvelope DiagnosticMessage) mkIrredErr ctxt cts = do { (ctxt, binds_msg, ct1) <- relevantBindings True ctxt ct1 ; let orig = ctOrigin ct1 msg = couldNotDeduce (getUserGivens ctxt) (map ctPred cts, orig)- ; mkErrorMsgFromCt ctxt ct1 $+ ; mkErrorMsgFromCt ErrorWithoutFlag ctxt ct1 $ msg `mappend` mk_relevant_bindings binds_msg } where (ct1:_) = cts +{- Note [Constructing Hole Errors]+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~++Whether or not 'mkHoleError' returns an error is not influenced by cec_suppress. In other terms,+these "hole" errors are /not/ suppressed by cec_suppress. We want to see them!++There are two cases to consider:++1. For out-of-scope variables we always report an error, unless -fdefer-out-of-scope-variables is on,+ in which case the messages are discarded. See also #12170 and #12406. If deferring, report a warning+ only if -Wout-of-scope-variables is on.++2. For the general case, when -XPartialTypeSignatures is on, warnings (instead of errors) are generated+ for holes in partial type signatures, unless -Wpartial-type-signatures is not on, in which case+ the messages are discarded. If deferring, report a warning only if -Wtyped-holes is on.++The above can be summarised into the following table:++| Hole Type | Active Flags | Outcome |+|--------------|----------------------------------------------------------|------------------|+| out-of-scope | None | Error |+| out-of-scope | -fdefer-out-of-scope-variables, -Wout-of-scope-variables | Warning |+| out-of-scope | -fdefer-out-of-scope-variables | Ignore (discard) |+| type | None | Error |+| type | -XPartialTypeSignatures, -Wpartial-type-signatures | Warning |+| type | -XPartialTypeSignatures | Ignore (discard) |+| expression | None | Error |+| expression | -Wdefer-typed-holes, -Wtyped-holes | Warning |+| expression | -Wdefer-typed-holes | Ignore (discard) |++See also 'reportUnsolved'.++-}+ -----------------mkHoleError :: [Ct] -> ReportErrCtxt -> Hole -> TcM (MsgEnvelope DecoratedSDoc)-mkHoleError _tidy_simples _ctxt hole@(Hole { hole_occ = occ+-- | Constructs a new hole error, unless this is deferred. See Note [Constructing Hole Errors].+mkHoleError :: [Ct] -> ReportErrCtxt -> Hole -> TcM (Maybe (MsgEnvelope DiagnosticMessage))+mkHoleError _tidy_simples ctxt hole@(Hole { hole_occ = occ , hole_ty = hole_ty , hole_loc = ct_loc }) | isOutOfScopeHole hole@@ -1176,10 +1183,15 @@ ; imp_info <- getImports ; curr_mod <- getModule ; hpt <- getHpt- ; mkDecoratedSDocAt (RealSrcSpan (tcl_loc lcl_env) Nothing)- out_of_scope_msg O.empty- (unknownNameSuggestions dflags hpt curr_mod rdr_env- (tcl_rdr lcl_env) imp_info (mkRdrUnqual occ)) }+ ; let mk_err rea = do+ mkDecoratedSDocAt rea (RealSrcSpan (tcl_loc lcl_env) Nothing)+ out_of_scope_msg O.empty+ (unknownNameSuggestions dflags hpt curr_mod rdr_env+ (tcl_rdr lcl_env) imp_info (mkRdrUnqual occ))++ ; maybeAddDeferredBindings ctxt hole mk_err+ ; whenNotDeferring (cec_out_of_scope_holes ctxt) mk_err+ } where herald | isDataOcc occ = text "Data constructor not in scope:" | otherwise = text "Variable not in scope:"@@ -1191,7 +1203,6 @@ lcl_env = ctLocEnv ct_loc boring_type = isTyVarTy hole_ty - -- general case: not an out-of-scope error mkHoleError tidy_simples ctxt hole@(Hole { hole_occ = occ , hole_ty = hole_ty , hole_sort = sort@@ -1212,11 +1223,20 @@ then validHoleFits ctxt tidy_simples hole else return (ctxt, empty) - ; mkErrorReport ctxt lcl_env $- important hole_msg `mappend`- mk_relevant_bindings (binds_msg $$ constraints_msg) `mappend`- valid_hole_fits sub_msg }+ ; let mk_err rea =+ mkErrorReport rea ctxt lcl_env $+ important hole_msg `mappend`+ mk_relevant_bindings (binds_msg $$ constraints_msg) `mappend`+ valid_hole_fits sub_msg + ; maybeAddDeferredBindings ctxt hole mk_err++ ; let holes | ExprHole _ <- sort = cec_expr_holes ctxt+ | otherwise = cec_type_holes ctxt+ ; whenNotDeferring holes mk_err++ }+ where lcl_env = ctLocEnv ct_loc hole_kind = tcTypeKind hole_ty@@ -1251,7 +1271,7 @@ -- hole, via kind casts type_hole_hint- | HoleError <- cec_type_holes ctxt+ | Just ErrorWithoutFlag <- cec_type_holes ctxt = text "To use the inferred type, enable PartialTypeSignatures" | otherwise = empty@@ -1272,6 +1292,44 @@ = ppWhenOption sdocPrintExplicitCoercions $ quotes (ppr tv) <+> text "is a coercion variable" ++-- | Similar in spirit to 'whenIsJust', but the action returns a value of type @Maybe b@.+whenNotDeferring :: Monad m => Maybe a -> (a -> m b) -> m (Maybe b)+whenNotDeferring = flip traverse++{- Note [Adding deferred bindings]+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~++When working with typed holes we have to deal with the case where+we want holes to be reported as warnings to users during compile time but+as errors during runtime. Therefore, we have to call 'maybeAddDeferredBindings'+with a function which is able to override the 'DiagnosticReason' of a 'DiagnosticMessage',+so that the correct 'Severity' can be computed out of that later on.++-}+++-- | Adds deferred bindings (as errors).+-- See Note [Adding deferred bindings].+maybeAddDeferredBindings :: ReportErrCtxt+ -> Hole+ -> (DiagnosticReason -> TcM (MsgEnvelope DiagnosticMessage))+ -> TcM ()+maybeAddDeferredBindings ctxt hole mk_err = do+ case hole_sort hole of+ ExprHole (HER ref ref_ty _) -> do+ -- Only add bindings for holes in expressions+ -- not for holes in partial type signatures+ -- cf. addDeferredBinding+ when (deferringAnyBindings ctxt) $ do+ dflags <- getDynFlags+ err <- mk_err ErrorWithoutFlag+ let err_tm = mkErrorTerm dflags ref_ty err+ -- NB: ref_ty, not hole_ty. hole_ty might be rewritten.+ -- See Note [Holes] in GHC.Tc.Types.Constraint+ writeMutVar ref err_tm+ _ -> pure ()+ pp_occ_with_type :: OccName -> Type -> SDoc pp_occ_with_type occ hole_ty = hang (pprPrefixOcc occ) 2 (dcolon <+> pprType hole_ty) @@ -1307,7 +1365,7 @@ 2 (vcat $ map pprConstraint constraints) -----------------mkIPErr :: ReportErrCtxt -> [Ct] -> TcM (MsgEnvelope DecoratedSDoc)+mkIPErr :: ReportErrCtxt -> [Ct] -> TcM (MsgEnvelope DiagnosticMessage) mkIPErr ctxt cts = do { (ctxt, binds_msg, ct1) <- relevantBindings True ctxt ct1 ; let orig = ctOrigin ct1@@ -1320,7 +1378,7 @@ | otherwise = couldNotDeduce givens (preds, orig) - ; mkErrorMsgFromCt ctxt ct1 $+ ; mkErrorMsgFromCt ErrorWithoutFlag ctxt ct1 $ msg `mappend` mk_relevant_bindings binds_msg } where (ct1:_) = cts@@ -1384,11 +1442,11 @@ -- Don't have multiple equality errors from the same location -- E.g. (Int,Bool) ~ (Bool,Int) one error will do!-mkEqErr :: ReportErrCtxt -> [Ct] -> TcM (MsgEnvelope DecoratedSDoc)+mkEqErr :: ReportErrCtxt -> [Ct] -> TcM (MsgEnvelope DiagnosticMessage) mkEqErr ctxt (ct:_) = mkEqErr1 ctxt ct mkEqErr _ [] = panic "mkEqErr" -mkEqErr1 :: ReportErrCtxt -> Ct -> TcM (MsgEnvelope DecoratedSDoc)+mkEqErr1 :: ReportErrCtxt -> Ct -> TcM (MsgEnvelope DiagnosticMessage) mkEqErr1 ctxt ct -- Wanted or derived; -- givens handled in mkGivenErrorReporter = do { (ctxt, binds_msg, ct) <- relevantBindings True ctxt ct@@ -1401,7 +1459,7 @@ ; traceTc "mkEqErr1" (ppr ct $$ pprCtOrigin (ctOrigin ct)) ; let report = mconcat [ important coercible_msg , mk_relevant_bindings binds_msg]- ; mkEqErr_help dflags ctxt report ct ty1 ty2 }+ ; mkEqErr_help ErrorWithoutFlag dflags ctxt report ct ty1 ty2 } where (ty1, ty2) = getEqPredTys (ctPred ct) @@ -1452,41 +1510,42 @@ | otherwise = False -mkEqErr_help :: DynFlags -> ReportErrCtxt -> Report+mkEqErr_help :: DiagnosticReason -> DynFlags -> ReportErrCtxt -> Report -> Ct- -> TcType -> TcType -> TcM (MsgEnvelope DecoratedSDoc)-mkEqErr_help dflags ctxt report ct ty1 ty2+ -> TcType -> TcType -> TcM (MsgEnvelope DiagnosticMessage)+mkEqErr_help rea dflags ctxt report ct ty1 ty2 | Just (tv1, _) <- tcGetCastedTyVar_maybe ty1- = mkTyVarEqErr dflags ctxt report ct tv1 ty2+ = mkTyVarEqErr rea dflags ctxt report ct tv1 ty2 | Just (tv2, _) <- tcGetCastedTyVar_maybe ty2- = mkTyVarEqErr dflags ctxt report ct tv2 ty1+ = mkTyVarEqErr rea dflags ctxt report ct tv2 ty1 | otherwise- = reportEqErr ctxt report ct ty1 ty2+ = reportEqErr rea ctxt report ct ty1 ty2 -reportEqErr :: ReportErrCtxt -> Report+reportEqErr :: DiagnosticReason -> ReportErrCtxt -> Report -> Ct- -> TcType -> TcType -> TcM (MsgEnvelope DecoratedSDoc)-reportEqErr ctxt report ct ty1 ty2- = mkErrorMsgFromCt ctxt ct (mconcat [misMatch, report, eqInfo])+ -> TcType -> TcType -> TcM (MsgEnvelope DiagnosticMessage)+reportEqErr rea ctxt report ct ty1 ty2+ = mkErrorMsgFromCt rea ctxt ct (mconcat [misMatch, report, eqInfo]) where misMatch = misMatchOrCND False ctxt ct ty1 ty2 eqInfo = mkEqInfoMsg ct ty1 ty2 mkTyVarEqErr, mkTyVarEqErr'- :: DynFlags -> ReportErrCtxt -> Report -> Ct- -> TcTyVar -> TcType -> TcM (MsgEnvelope DecoratedSDoc)+ :: DiagnosticReason+ -> DynFlags -> ReportErrCtxt -> Report -> Ct+ -> TcTyVar -> TcType -> TcM (MsgEnvelope DiagnosticMessage) -- tv1 and ty2 are already tidied-mkTyVarEqErr dflags ctxt report ct tv1 ty2+mkTyVarEqErr reason dflags ctxt report ct tv1 ty2 = do { traceTc "mkTyVarEqErr" (ppr ct $$ ppr tv1 $$ ppr ty2)- ; mkTyVarEqErr' dflags ctxt report ct tv1 ty2 }+ ; mkTyVarEqErr' reason dflags ctxt report ct tv1 ty2 } -mkTyVarEqErr' dflags ctxt report ct tv1 ty2+mkTyVarEqErr' reason dflags ctxt report ct tv1 ty2 | isSkolemTyVar tv1 -- ty2 won't be a meta-tyvar; we would have -- swapped in Solver.Canonical.canEqTyVarHomo || isTyVarTyVar tv1 && not (isTyVarTy ty2) || ctEqRel ct == ReprEq -- The cases below don't really apply to ReprEq (except occurs check)- = mkErrorMsgFromCt ctxt ct $ mconcat+ = mkErrorMsgFromCt reason ctxt ct $ mconcat [ headline_msg , extraTyVarEqInfo ctxt tv1 ty2 , suggestAddSig ctxt ty1 ty2@@ -1511,7 +1570,7 @@ interesting_tyvars) tyvar_binding tv = ppr tv <+> dcolon <+> ppr (tyVarKind tv)- ; mkErrorMsgFromCt ctxt ct $+ ; mkErrorMsgFromCt ErrorWithoutFlag ctxt ct $ mconcat [headline_msg, extra2, extra3, report] } | CTE_Bad <- occ_check_expand@@ -1521,7 +1580,7 @@ -- Unlike the other reports, this discards the old 'report_important' -- instead of augmenting it. This is because the details are not likely -- to be helpful since this is just an unimplemented feature.- ; mkErrorMsgFromCt ctxt ct $ mconcat [ headline_msg, important msg, report ] }+ ; mkErrorMsgFromCt ErrorWithoutFlag ctxt ct $ mconcat [ headline_msg, important msg, report ] } -- If the immediately-enclosing implication has 'tv' a skolem, and -- we know by now its an InferSkol kind of skolem, then presumably@@ -1530,7 +1589,7 @@ | (implic:_) <- cec_encl ctxt , Implic { ic_skols = skols } <- implic , tv1 `elem` skols- = mkErrorMsgFromCt ctxt ct $ mconcat+ = mkErrorMsgFromCt ErrorWithoutFlag ctxt ct $ mconcat [ misMatchMsg ctxt ct ty1 ty2 , extraTyVarEqInfo ctxt tv1 ty2 , report@@ -1558,7 +1617,7 @@ , nest 2 $ ppr skol_info , nest 2 $ text "at" <+> ppr (tcl_loc (ic_env implic)) ] ]- ; mkErrorMsgFromCt ctxt ct (mconcat [msg, tv_extra, report]) }+ ; mkErrorMsgFromCt ErrorWithoutFlag ctxt ct (mconcat [msg, tv_extra, report]) } -- Nastiest case: attempt to unify an untouchable variable -- So tv is a meta tyvar (or started that way before we@@ -1579,11 +1638,11 @@ ppr (tcl_loc (ic_env implic)) ] tv_extra = extraTyVarEqInfo ctxt tv1 ty2 add_sig = suggestAddSig ctxt ty1 ty2- ; mkErrorMsgFromCt ctxt ct $ mconcat+ ; mkErrorMsgFromCt ErrorWithoutFlag ctxt ct $ mconcat [msg, tclvl_extra, tv_extra, add_sig, report] } | otherwise- = reportEqErr ctxt report ct (mkTyVarTy tv1) ty2+ = reportEqErr ErrorWithoutFlag ctxt report ct (mkTyVarTy tv1) ty2 -- This *can* happen (#6123, and test T2627b) -- Consider an ambiguous top-level constraint (a ~ F a) -- Not an occurs check, because F is a type function.@@ -1674,8 +1733,8 @@ -- always be another unsolved wanted around, which will ordinarily suppress -- this message. But this can still be printed out with -fdefer-type-errors -- (sigh), so we must produce a message.-mkBlockedEqErr :: ReportErrCtxt -> [Ct] -> TcM (MsgEnvelope DecoratedSDoc)-mkBlockedEqErr ctxt (ct:_) = mkErrorMsgFromCt ctxt ct report+mkBlockedEqErr :: ReportErrCtxt -> [Ct] -> TcM (MsgEnvelope DiagnosticMessage)+mkBlockedEqErr ctxt (ct:_) = mkErrorMsgFromCt ErrorWithoutFlag ctxt ct report where report = important msg msg = vcat [ hang (text "Cannot use equality for substitution:")@@ -1793,7 +1852,9 @@ headline_eq_msg add_ea ct ty1 ty2 | (isLiftedRuntimeRep ty1 && isUnliftedRuntimeRep ty2) ||- (isLiftedRuntimeRep ty2 && isUnliftedRuntimeRep ty1)+ (isLiftedRuntimeRep ty2 && isUnliftedRuntimeRep ty1) ||+ (isLiftedLevity ty1 && isUnliftedLevity ty2) ||+ (isLiftedLevity ty2 && isUnliftedLevity ty1) = text "Couldn't match a lifted type with an unlifted type" | isAtomicTy ty1 || isAtomicTy ty2@@ -1901,7 +1962,7 @@ count_args ty = count isVisibleBinder $ fst $ splitPiTys ty tk_eq_msg ctxt ct ty1 ty2- (KindEqOrigin cty1 mb_cty2 sub_o mb_sub_t_or_k)+ (KindEqOrigin cty1 cty2 sub_o mb_sub_t_or_k) = vcat [ headline_eq_msg False ct ty1 ty2 , supplementary_msg ] where@@ -1911,17 +1972,15 @@ supplementary_msg = sdocOption sdocPrintExplicitCoercions $ \printExplicitCoercions ->- case mb_cty2 of- Just cty2- | printExplicitCoercions- || not (cty1 `pickyEqType` cty2)- -> vcat [ hang (text "When matching" <+> sub_whats)- 2 (vcat [ ppr cty1 <+> dcolon <+>+ if printExplicitCoercions+ || not (cty1 `pickyEqType` cty2)+ then vcat [ hang (text "When matching" <+> sub_whats)+ 2 (vcat [ ppr cty1 <+> dcolon <+> ppr (tcTypeKind cty1) , ppr cty2 <+> dcolon <+> ppr (tcTypeKind cty2) ]) , mk_supplementary_ea_msg ctxt sub_t_or_k cty1 cty2 sub_o ]- _ -> text "When matching the kind of" <+> quotes (ppr cty1)+ else text "When matching the kind of" <+> quotes (ppr cty1) tk_eq_msg _ _ _ _ _ = panic "typeeq_mismatch_msg" @@ -2281,7 +2340,7 @@ ************************************************************************ -} -mkDictErr :: ReportErrCtxt -> [Ct] -> TcM (MsgEnvelope DecoratedSDoc)+mkDictErr :: ReportErrCtxt -> [Ct] -> TcM (MsgEnvelope DiagnosticMessage) mkDictErr ctxt cts = ASSERT( not (null cts) ) do { inst_envs <- tcGetInstEnvs@@ -2296,7 +2355,7 @@ -- have the same source-location origin, to try avoid a cascade -- of error from one location ; (ctxt, err) <- mk_dict_err ctxt (head (no_inst_cts ++ overlap_cts))- ; mkErrorMsgFromCt ctxt ct1 (important err) }+ ; mkErrorMsgFromCt ErrorWithoutFlag ctxt ct1 (important err) } where no_givens = null (getUserGivens ctxt) @@ -2873,8 +2932,7 @@ -- For *kind* errors, report the relevant bindings of the -- enclosing *type* equality, because that's more useful for the programmer ; let extra_tvs = case tidy_orig of- KindEqOrigin t1 m_t2 _ _ -> tyCoVarsOfTypes $- t1 : maybeToList m_t2+ KindEqOrigin t1 t2 _ _ -> tyCoVarsOfTypes [t1,t2] _ -> emptyVarSet ct_fvs = tyCoVarsOfCt ct `unionVarSet` extra_tvs @@ -3004,7 +3062,7 @@ , quotes (ppr default_ty) ]) 2 ppr_wanteds- ; setCtLocM loc $ warnTc (Reason Opt_WarnTypeDefaults) warn_default warn_msg }+ ; setCtLocM loc $ diagnosticTc (WarningWithFlag Opt_WarnTypeDefaults) warn_default warn_msg } {- Note [Runtime skolems]
compiler/GHC/Tc/Errors/Hole.hs view
@@ -419,7 +419,7 @@ addDocs fits = do { showDocs <- goptM Opt_ShowDocsOfHoleFits ; if showDocs- then do { (_, DeclDocMap lclDocs, _) <- extractDocs <$> getGblEnv+ then do { (_, DeclDocMap lclDocs, _) <- getGblEnv >>= extractDocs ; mapM (upd lclDocs) fits } else return fits } where@@ -785,7 +785,7 @@ Just (dataConWrapId con, dataConNonlinearType con) _ -> Nothing } where name = case hfc of-#if __GLASGOW_HASKELL__ <= 810+#if __GLASGOW_HASKELL__ < 901 IdHFCand id -> idName id #endif GreHFCand gre -> greMangledName gre
compiler/GHC/Tc/Gen/Annotation.hs view
@@ -43,7 +43,7 @@ --- No GHCI; emit a warning (not an error) and ignore. cf #4268 warnAnns [] = return [] warnAnns anns@(L loc _ : _)- = do { setSrcSpan loc $ addWarnTc NoReason $+ = do { setSrcSpanA loc $ addDiagnosticTc WarningWithoutFlag $ (text "Ignoring ANN annotation" <> plural anns <> comma <+> text "because this is a stage-1 compiler without -fexternal-interpreter or doesn't support GHCi") ; return [] }@@ -55,7 +55,7 @@ let target = annProvenanceToTarget mod provenance -- Run that annotation and construct the full Annotation data structure- setSrcSpan loc $ addErrCtxt (annCtxt ann) $ do+ setSrcSpanA loc $ addErrCtxt (annCtxt ann) $ do -- See #10826 -- Annotations allow one to bypass Safe Haskell. dflags <- getDynFlags when (safeLanguageOn dflags) $ failWithTc safeHsErr@@ -64,7 +64,7 @@ safeHsErr = vcat [ text "Annotations are not compatible with Safe Haskell." , text "See https://gitlab.haskell.org/ghc/ghc/issues/10826" ] -annProvenanceToTarget :: Module -> AnnProvenance Name+annProvenanceToTarget :: Module -> AnnProvenance GhcRn -> AnnTarget Name annProvenanceToTarget _ (ValueAnnProvenance (L _ name)) = NamedTarget name annProvenanceToTarget _ (TypeAnnProvenance (L _ name)) = NamedTarget name
compiler/GHC/Tc/Gen/App.hs view
@@ -138,7 +138,7 @@ tcInferSigma inst (L loc rn_expr) | (fun@(rn_fun,_), rn_args) <- splitHsApps rn_expr = addExprCtxt rn_expr $- setSrcSpan loc $+ setSrcSpanA loc $ do { do_ql <- wantQuickLook rn_fun ; (_tc_fun, fun_sigma) <- tcInferAppHead fun rn_args Nothing ; (_delta, inst_args, app_res_sigma) <- tcInstFun do_ql inst fun fun_sigma rn_args@@ -244,11 +244,15 @@ when in checking mode. This is the shaded part of APP-Downarrow in Fig 5. -5. Use tcValArgs to typecheck the value arguments+5. Use unifyResultType to match up the result type of the call+ with that expected by the context. See Note [Unify with+ expected type before typechecking arguments] -6. After a gruesome special case for tagToEnum, rebuild the result.+6. Use tcValArgs to typecheck the value arguments +7. After a gruesome special case for tagToEnum, rebuild the result. + Some cases that /won't/ work: 1. Consider this (which uses visible type application):@@ -274,6 +278,34 @@ the renamer (Note [Handling overloaded and rebindable constructs] in GHC.Rename.Expr), and we want them to be instantiated impredicatively so that (f `op`), say, will work OK even if `f` is higher rank.++Note [Unify with expected type before typechecking arguments]+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+Consider this (#19364)+ data Pair a b = Pair a b+ baz :: MkPair Int Bool+ baz = MkPair "yes" "no"++We instantiate MkPair with `alpha`, `beta`, and push its argument+types (`alpha` and `beta`) into the arguments ("yes" and "no").+But if we first unify the result type (Pair alpha beta) with the expected+type (Pair Int Bool) we will push the much more informative types+`Int` and `Bool` into the arguments. This makes a difference:++Unify result type /after/ typechecking the args+ • Couldn't match type ‘[Char]’ with ‘Bool’+ Expected type: Pair Foo Bar+ Actual type: Pair [Char] [Char]+ • In the expression: Pair "yes" "no"++Unify result type /before/ typechecking the args+ • Couldn't match type ‘[Char]’ with ‘Bool’+ Expected: Foo+ Actual: String+ • In the first argument of ‘Pair’, namely ‘"yes"’++The latter is much better. That is why we call unifyExpectedType+before tcValArgs. -} tcApp :: HsExpr GhcRn -> ExpRhoType -> TcM (HsExpr GhcTc)@@ -288,8 +320,27 @@ ; (delta, inst_args, app_res_rho) <- tcInstFun do_ql True fun fun_sigma rn_args -- Quick look at result- ; quickLookResultType do_ql delta app_res_rho exp_res_ty+ ; app_res_rho <- if do_ql+ then quickLookResultType delta app_res_rho exp_res_ty+ else return app_res_rho + -- Unify with expected type from the context+ -- See Note [Unify with expected type before typechecking arguments]+ --+ -- perhaps_add_res_ty_ctxt: Inside an expansion, the addFunResCtxt stuff is+ -- more confusing than helpful because the function at the head isn't in+ -- the source program; it was added by the renamer. See+ -- Note [Handling overloaded and rebindable constructs] in GHC.Rename.Expr+ ; let perhaps_add_res_ty_ctxt thing_inside+ | insideExpansion fun_ctxt+ = thing_inside+ | otherwise+ = addFunResCtxt rn_fun rn_args app_res_rho exp_res_ty $+ thing_inside++ ; res_co <- perhaps_add_res_ty_ctxt $+ unifyExpectedType rn_expr app_res_rho exp_res_ty+ ; whenDOptM Opt_D_dump_tc_trace $ do { inst_args <- mapM zonkArg inst_args -- Only when tracing ; traceTc "tcApp" (vcat [ text "rn_fun" <+> ppr rn_fun@@ -304,35 +355,13 @@ -- Typecheck the value arguments ; tc_args <- tcValArgs do_ql inst_args - -- Zonk the result type, to ensure that we substitute out- -- any filled-in instantiation variable before calling tcWrapResultMono- -- In the Check case, this isn't really necessary, because tcWrapResultMono- -- just drops to tcUnify; but in the Infer case a filled-in instantiation- -- variable might perhaps escape into the constraint generator. The safe- -- thing to do is to any instantaition variables away.- -- See Note [Instantiation variables are short lived]- ; app_res_rho <- zonkQuickLook do_ql app_res_rho-- -- Special case for tagToEnum#- ; if isTagToEnum rn_fun- then tcTagToEnum rn_expr tc_fun fun_ctxt tc_args app_res_rho exp_res_ty- else-- do { -- Reconstruct- ; let tc_expr = rebuildHsApps tc_fun fun_ctxt tc_args-- -- Set a context for the helpful- -- "Probably cause: f applied to too many args"- -- But not in generated code, where we don't want- -- to mention internal (rebindable syntax) function names- set_res_ctxt thing_inside- | insideExpansion tc_args- = thing_inside- | otherwise- = addFunResCtxt tc_fun tc_args app_res_rho exp_res_ty thing_inside+ -- Reconstruct, with special case for tagToEnum#+ ; tc_expr <- if isTagToEnum rn_fun+ then tcTagToEnum tc_fun fun_ctxt tc_args app_res_rho+ else return (rebuildHsApps tc_fun fun_ctxt tc_args) -- Wrap the result- ; set_res_ctxt $ tcWrapResultMono rn_expr tc_expr app_res_rho exp_res_ty } }+ ; return (mkHsWrapCo res_co tc_expr) } -------------------- wantQuickLook :: HsExpr GhcRn -> TcM Bool@@ -621,12 +650,12 @@ -- use "In the expression: arg" ---See Note [Rebindable syntax and HsExpansion] in GHC.Hs.Expr addArgCtxt (VACall fun arg_no _) (L arg_loc arg) thing_inside- = setSrcSpan arg_loc $+ = setSrcSpanA arg_loc $ addErrCtxt (funAppCtxt fun arg arg_no) $ thing_inside addArgCtxt (VAExpansion {}) (L arg_loc arg) thing_inside- = setSrcSpan arg_loc $+ = setSrcSpanA arg_loc $ addExprCtxt arg $ -- Auto-suppressed if arg_loc is generated thing_inside @@ -869,19 +898,29 @@ skipQuickLook delta larg = return (delta, ValArg larg) -----------------quickLookResultType :: Bool -> Delta -> TcRhoType -> ExpRhoType -> TcM ()+quickLookResultType :: Delta -> TcRhoType -> ExpRhoType -> TcM TcRhoType -- This function implements the shaded bit of rule APP-Downarrow in -- Fig 5 of the QL paper: "A quick look at impredicativity" (ICFP'20).+-- It returns its second argument, but with any variables in Delta+-- substituted out, so no variables in Delta escape -quickLookResultType do_ql delta app_res_rho exp_res_ty- | do_ql- , not (isEmptyVarSet delta) -- Optimisation only- , Just exp_rho <- checkingExpType_maybe exp_res_ty- -- In checking mode only- = qlUnify delta app_res_rho exp_rho- | otherwise- = return ()+quickLookResultType delta app_res_rho (Check exp_rho)+ = -- In checking mode only, do qlUnify with the expected result type+ do { unless (isEmptyVarSet delta) $ -- Optimisation only+ qlUnify delta app_res_rho exp_rho+ ; return app_res_rho } +quickLookResultType _ app_res_rho (Infer {})+ = zonkTcType app_res_rho+ -- Zonk the result type, to ensure that we substitute out any+ -- filled-in instantiation variable before calling+ -- unifyExpectedType. In the Check case, this isn't necessary,+ -- because unifyExpectedType just drops to tcUnify; but in the+ -- Infer case a filled-in instantiation variable (filled in by+ -- tcInstFun) might perhaps escape into the constraint+ -- generator. The safe thing to do is to zonk any instantiation+ -- variables away. See Note [Instantiation variables are short lived]+ --------------------- qlUnify :: Delta -> TcType -> TcType -> TcM () -- Unify ty1 with ty2, unifying only variables in delta@@ -1080,8 +1119,7 @@ {- Note [tagToEnum#] ~~~~~~~~~~~~~~~~~~~~ Nasty check to ensure that tagToEnum# is applied to a type that is an-enumeration TyCon. Unification may refine the type later, but this-check won't see that, alas. It's crude, because it relies on our+enumeration TyCon. It's crude, because it relies on our knowing *now* that the type is ok, which in turn relies on the eager-unification part of the type checker pushing enough information here. In theory the Right Thing to do is to have a new form of@@ -1109,54 +1147,48 @@ isTagToEnum (HsVar _ (L _ fun_id)) = fun_id `hasKey` tagToEnumKey isTagToEnum _ = False -tcTagToEnum :: HsExpr GhcRn- -> HsExpr GhcTc -> AppCtxt -> [HsExprArg 'TcpTc]- -> TcRhoType -> ExpRhoType+tcTagToEnum :: HsExpr GhcTc -> AppCtxt -> [HsExprArg 'TcpTc]+ -> TcRhoType -> TcM (HsExpr GhcTc) -- tagToEnum# :: forall a. Int# -> a -- See Note [tagToEnum#] Urgh!-tcTagToEnum expr fun fun_ctxt args app_res_ty res_ty- | null val_args- = failWithTc (text "tagToEnum# must appear applied to one argument")-- | otherwise- = do { res_ty <- readExpType res_ty- ; ty' <- zonkTcType res_ty+tcTagToEnum tc_fun fun_ctxt tc_args res_ty+ | [val_arg] <- dropWhile (not . isHsValArg) tc_args+ = do { res_ty <- zonkTcType res_ty -- Check that the type is algebraic- ; case tcSplitTyConApp_maybe ty' of {- Nothing -> do { addErrTc (mk_error ty' doc1)+ ; case tcSplitTyConApp_maybe res_ty of {+ Nothing -> do { addErrTc (mk_error res_ty doc1) ; vanilla_result } ; Just (tc, tc_args) -> do { -- Look through any type family ; fam_envs <- tcGetFamInstEnvs ; case tcLookupDataFamInst_maybe fam_envs tc tc_args of {- Nothing -> do { check_enumeration ty' tc+ Nothing -> do { check_enumeration res_ty tc ; vanilla_result } ; Just (rep_tc, rep_args, coi) -> do { -- coi :: tc tc_args ~R rep_tc rep_args- check_enumeration ty' rep_tc+ check_enumeration res_ty rep_tc ; let rep_ty = mkTyConApp rep_tc rep_args- fun' = mkHsWrap (WpTyApp rep_ty) fun- expr' = rebuildHsApps fun' fun_ctxt val_args+ tc_fun' = mkHsWrap (WpTyApp rep_ty) tc_fun+ tc_expr = rebuildHsApps tc_fun' fun_ctxt [val_arg] df_wrap = mkWpCastR (mkTcSymCo coi)- ; return (mkHsWrap df_wrap expr') }}}}}+ ; return (mkHsWrap df_wrap tc_expr) }}}}} - where- val_args = dropWhile (not . isHsValArg) args+ | otherwise+ = failWithTc (text "tagToEnum# must appear applied to one value argument") - vanilla_result- = do { let expr' = rebuildHsApps fun fun_ctxt args- ; tcWrapResultMono expr expr' app_res_ty res_ty }+ where+ vanilla_result = return (rebuildHsApps tc_fun fun_ctxt tc_args) check_enumeration ty' tc | isEnumerationTyCon tc = return () | otherwise = addErrTc (mk_error ty' doc2) doc1 = vcat [ text "Specify the type by giving a type signature"- , text "e.g. (tagToEnum# x) :: Bool" ]+ , text "e.g. (tagToEnum# x) :: Bool" ] doc2 = text "Result type must be an enumeration type" mk_error :: TcType -> SDoc -> SDoc@@ -1174,5 +1206,3 @@ tcExprPrag :: HsPragE GhcRn -> HsPragE GhcTc tcExprPrag (HsPragSCC x1 src ann) = HsPragSCC x1 src ann--
compiler/GHC/Tc/Gen/Arrow.hs view
@@ -140,7 +140,7 @@ tcCmd :: CmdEnv -> LHsCmd GhcRn -> CmdType -> TcM (LHsCmd GhcTc) -- The main recursive function tcCmd env (L loc cmd) res_ty- = setSrcSpan loc $ do+ = setSrcSpan (locA loc) $ do { cmd' <- tc_cmd env cmd res_ty ; return (L loc cmd') } @@ -149,11 +149,11 @@ = do { cmd' <- tcCmd env cmd res_ty ; return (HsCmdPar x cmd') } -tc_cmd env (HsCmdLet x (L l binds) (L body_loc body)) res_ty+tc_cmd env (HsCmdLet x binds (L body_loc body)) res_ty = do { (binds', body') <- tcLocalBinds binds $- setSrcSpan body_loc $+ setSrcSpan (locA body_loc) $ tc_cmd env body res_ty- ; return (HsCmdLet x (L l binds') (L body_loc body')) }+ ; return (HsCmdLet x binds' (L body_loc body')) } tc_cmd env in_cmd@(HsCmdCase x scrut matches) (stk, res_ty) = addErrCtxt (cmdCtxt in_cmd) $ do@@ -259,11 +259,11 @@ do { (co, arg_tys, cmd_stk') <- matchExpectedCmdArgs n_pats cmd_stk -- Check the patterns, and the GRHSs inside- ; (pats', grhss') <- setSrcSpan mtch_loc $+ ; (pats', grhss') <- setSrcSpanA mtch_loc $ tcPats LambdaExpr pats (map (unrestricted . mkCheckExpType) arg_tys) $ tc_grhss grhss cmd_stk' (mkCheckExpType res_ty) - ; let match' = L mtch_loc (Match { m_ext = noExtField+ ; let match' = L mtch_loc (Match { m_ext = noAnn , m_ctxt = LambdaExpr, m_pats = pats' , m_grhss = grhss' }) arg_tys = map (unrestricted . hsLPatType) pats'@@ -276,10 +276,10 @@ match_ctxt = (LambdaExpr :: HsMatchContext GhcRn) -- Maybe KappaExpr? pg_ctxt = PatGuard match_ctxt - tc_grhss (GRHSs x grhss (L l binds)) stk_ty res_ty+ tc_grhss (GRHSs x grhss binds) stk_ty res_ty = do { (binds', grhss') <- tcLocalBinds binds $ mapM (wrapLocM (tc_grhs stk_ty res_ty)) grhss- ; return (GRHSs x grhss' (L l binds')) }+ ; return (GRHSs x grhss' binds') } tc_grhs stk_ty res_ty (GRHS x guards body) = do { (guards', rhs') <- tcStmtsAndThen pg_ctxt tcGuardStmt guards res_ty $@@ -393,7 +393,7 @@ thing_inside res_ty ; return (mkTcBindStmt pat' rhs', thing) } -tcArrDoStmt env ctxt (RecStmt { recS_stmts = stmts, recS_later_ids = later_names+tcArrDoStmt env ctxt (RecStmt { recS_stmts = L l stmts, recS_later_ids = later_names , recS_rec_ids = rec_names }) res_ty thing_inside = do { let tup_names = rec_names ++ filterOut (`elem` rec_names) later_names ; tup_elt_tys <- newFlexiTyVarTys (length tup_names) liftedTypeKind@@ -417,13 +417,18 @@ ; let ret_table = zip tup_ids tup_rets ; let later_rets = [r | i <- later_ids, (j, r) <- ret_table, i == j] - ; return (emptyRecStmtId { recS_stmts = stmts'+ ; let+ stmt :: Stmt GhcTc (LocatedA (HsCmd GhcTc))+ stmt = emptyRecStmtId+ { recS_stmts = L l stmts'+ -- { recS_stmts = _ stmts' , recS_later_ids = later_ids , recS_rec_ids = rec_ids , recS_ext = unitRecStmtTc { recS_later_rets = later_rets , recS_rec_rets = rec_rets- , recS_ret_ty = res_ty} }, thing)+ , recS_ret_ty = res_ty} }+ ; return (stmt, thing) }} tcArrDoStmt _ _ stmt _ _
compiler/GHC/Tc/Gen/Bind.hs view
@@ -2,6 +2,7 @@ {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE TypeApplications #-} {-# LANGUAGE TypeFamilies #-} {-@@ -27,7 +28,7 @@ import {-# SOURCE #-} GHC.Tc.Gen.Expr ( tcCheckMonoExpr ) import {-# SOURCE #-} GHC.Tc.TyCl.PatSyn ( tcPatSynDecl, tcPatSynBuilderBind ) -import GHC.Core (Tickish (..))+import GHC.Types.Tickish (CoreTickish, GenTickish (..)) import GHC.Types.CostCentre (mkUserCC, CCFlavour(DeclCC)) import GHC.Driver.Session import GHC.Data.FastString@@ -65,6 +66,7 @@ import GHC.Data.Maybe import GHC.Utils.Misc import GHC.Types.Basic+import GHC.Types.CompleteMatch import GHC.Utils.Outputable as Outputable import GHC.Utils.Panic import GHC.Builtin.Names( ipClassName )@@ -203,11 +205,14 @@ let doOne :: LSig GhcRn -> TcM (Maybe CompleteMatch) -- We don't need to "type-check" COMPLETE signatures anymore; if their- -- combinations are invalid it will be found so at match sites. Hence we- -- keep '_mtc' only for backwards compatibility.- doOne (L loc c@(CompleteMatchSig _ext _src_txt (L _ ns) _mtc))- = fmap Just $ setSrcSpan loc $ addErrCtxt (text "In" <+> ppr c) $- mkUniqDSet <$> mapM (addLocM tcLookupConLike) ns+ -- combinations are invalid it will be found so at match sites.+ -- There it is also where we consider if the type of the pattern match is+ -- compatible with the result type constructor 'mb_tc'.+ doOne (L loc c@(CompleteMatchSig _ext _src_txt (L _ ns) mb_tc_nm))+ = fmap Just $ setSrcSpanA loc $ addErrCtxt (text "In" <+> ppr c) $ do+ cls <- mkUniqDSet <$> mapM (addLocMA tcLookupConLike) ns+ mb_tc <- traverse @Maybe tcLookupLocatedTyCon mb_tc_nm+ pure CompleteMatch { cmConLikes = cls, cmResultTyCon = mb_tc } doOne _ = return Nothing -- For some reason I haven't investigated further, the signatures come in@@ -220,7 +225,7 @@ -- signatures in it. The renamer checked all this tcHsBootSigs binds sigs = do { checkTc (null binds) badBootDeclErr- ; concatMapM (addLocM tc_boot_sig) (filter isTypeLSig sigs) }+ ; concatMapM (addLocMA tc_boot_sig) (filter isTypeLSig sigs) } where tc_boot_sig (TypeSig _ lnames hs_ty) = mapM f lnames where@@ -249,7 +254,7 @@ tcLocalBinds (HsIPBinds x (IPBinds _ ip_binds)) thing_inside = do { ipClass <- tcLookupClass ipClassName ; (given_ips, ip_binds') <-- mapAndUnzipM (wrapLocSndM (tc_ip_bind ipClass)) ip_binds+ mapAndUnzipM (wrapLocSndMA (tc_ip_bind ipClass)) ip_binds -- If the binding binds ?x = E, we must now -- discharge any ?x constraints in expr_lie@@ -270,7 +275,7 @@ ; ip_id <- newDict ipClass [ p, ty ] ; expr' <- tcCheckMonoExpr expr ty ; let d = toDict ipClass p ty `fmap` expr'- ; return (ip_id, (IPBind noExtField (Right ip_id) d)) }+ ; return (ip_id, (IPBind noAnn (Right ip_id) d)) } tc_ip_bind _ (IPBind _ (Right {}) _) = panic "tc_ip_bind" -- Coerces a `t` into a dictionary for `IP "x" t`.@@ -399,7 +404,7 @@ -- See Note [Polymorphic recursion] in "GHC.Hs.Binds". do { traceTc "tc_group rec" (pprLHsBinds binds) ; whenIsJust mbFirstPatSyn $ \lpat_syn ->- recursivePatSynErr (getLoc lpat_syn) binds+ recursivePatSynErr (locA $ getLoc lpat_syn) binds ; (binds1, thing) <- go sccs ; return ([(Recursive, binds1)], thing) } -- Rec them all together@@ -439,7 +444,7 @@ where pprLoc loc = parens (text "defined at" <+> ppr loc) pprLBind (L loc bind) = pprWithCommas ppr (collectHsBindBinders CollNoDictBinders bind)- <+> pprLoc loc+ <+> pprLoc (locA loc) tc_single :: forall thing. TopLevelFlag -> TcSigFun -> TcPragEnv@@ -532,7 +537,7 @@ ; return result } where binder_names = collectHsBindListBinders CollNoDictBinders bind_list- loc = foldr1 combineSrcSpans (map getLoc bind_list)+ loc = foldr1 combineSrcSpans (map (locA . getLoc) bind_list) -- The mbinds have been dependency analysed and -- may no longer be adjacent; so find the narrowest -- span that includes them all@@ -613,7 +618,7 @@ , fun_matches = matches })) = do { traceTc "tcPolyCheck" (ppr poly_id $$ ppr sig_loc) - ; mono_name <- newNameAt (nameOccName name) nm_loc+ ; mono_name <- newNameAt (nameOccName name) (locA nm_loc) ; (wrap_gen, (wrap_res, matches')) <- setSrcSpan sig_loc $ -- Sets the binding location for the skolems tcSkolemiseScoped ctxt (idType poly_id) $ \rho_ty ->@@ -627,7 +632,7 @@ -- Why mono_id in the BinderStack? -- See Note [Relevant bindings and the binder stack] - setSrcSpan bind_loc $+ setSrcSpanA bind_loc $ tcMatchesFun (L nm_loc mono_name) matches (mkCheckExpType rho_ty) @@ -643,7 +648,7 @@ ; poly_id <- addInlinePrags poly_id prag_sigs ; mod <- getModule- ; tick <- funBindTicks nm_loc poly_id mod prag_sigs+ ; tick <- funBindTicks (locA nm_loc) poly_id mod prag_sigs ; let bind' = FunBind { fun_id = L nm_loc poly_id2 , fun_matches = matches'@@ -671,7 +676,7 @@ = pprPanic "tcPolyCheck" (ppr sig $$ ppr bind) funBindTicks :: SrcSpan -> TcId -> Module -> [LSig GhcRn]- -> TcM [Tickish TcId]+ -> TcM [CoreTickish] funBindTicks loc fun_id mod sigs | (mb_cc_str : _) <- [ cc_name | L _ (SCCFunSig _ _ _ cc_name) <- sigs ] -- this can only be a singleton list, as duplicate pragmas are rejected@@ -738,7 +743,7 @@ ; loc <- getSrcSpanM ; let poly_ids = map abe_poly exports- abs_bind = L loc $+ abs_bind = L (noAnnSrcSpan loc) $ AbsBinds { abs_ext = noExtField , abs_tvs = qtvs , abs_ev_vars = givens, abs_ev_binds = [ev_binds]@@ -1010,7 +1015,7 @@ warnMissingSignatures flag msg id = do { env0 <- tcInitTidyEnv ; let (env1, tidy_ty) = tidyOpenType env0 (idType id)- ; addWarnTcM (Reason flag) (env1, mk_msg tidy_ty) }+ ; addDiagnosticTcM (WarningWithFlag flag) (env1, mk_msg tidy_ty) } where mk_msg ty = sep [ msg, nest 2 $ pprPrefixName (idName id) <+> dcolon <+> ppr ty ] @@ -1207,7 +1212,7 @@ -- Single function binding, | NonRecursive <- is_rec -- ...binder isn't mentioned in RHS , Nothing <- sig_fn name -- ...with no type signature- = setSrcSpan b_loc $+ = setSrcSpanA b_loc $ do { ((co_fn, matches'), rhs_ty) <- tcInfer $ \ exp_ty -> tcExtendBinderStack [TcIdBndr_ExpType name exp_ty NotTopLevel] $@@ -1249,7 +1254,7 @@ -- GENERAL CASE tcMonoBinds _ sig_fn no_gen binds- = do { tc_binds <- mapM (wrapLocM (tcLhs sig_fn no_gen)) binds+ = do { tc_binds <- mapM (wrapLocMA (tcLhs sig_fn no_gen)) binds -- Bring the monomorphic Ids, into scope for the RHSs ; let mono_infos = getMonoBindInfo tc_binds@@ -1266,7 +1271,7 @@ ; traceTc "tcMonoBinds" $ vcat [ ppr n <+> ppr id <+> ppr (idType id) | (n,id) <- rhs_id_env] ; binds' <- tcExtendRecIds rhs_id_env $- mapM (wrapLocM tcRhs) tc_binds+ mapM (wrapLocMA tcRhs) tc_binds ; return (listToBag binds', mono_infos) } @@ -1368,7 +1373,7 @@ -- Just g = ...f... -- Hence always typechecked with InferGen do { mono_info <- tcLhsSigId no_gen (name, sig)- ; return (TcFunBind mono_info nm_loc matches) }+ ; return (TcFunBind mono_info (locA nm_loc) matches) } | otherwise -- No type signature = do { mono_ty <- newOpenFlexiTyVarTy@@ -1379,7 +1384,7 @@ ; let mono_info = MBI { mbi_poly_name = name , mbi_sig = Nothing , mbi_mono_id = mono_id }- ; return (TcFunBind mono_info nm_loc matches) }+ ; return (TcFunBind mono_info (locA nm_loc) matches) } tcLhs sig_fn no_gen (PatBind { pat_lhs = pat, pat_rhs = grhss }) = -- See Note [Typechecking pattern bindings]@@ -1455,9 +1460,9 @@ = tcExtendIdBinderStackForRhs [info] $ tcExtendTyVarEnvForRhs mb_sig $ do { traceTc "tcRhs: fun bind" (ppr mono_id $$ ppr (idType mono_id))- ; (co_fn, matches') <- tcMatchesFun (L loc (idName mono_id))+ ; (co_fn, matches') <- tcMatchesFun (L (noAnnSrcSpan loc) (idName mono_id)) matches (mkCheckExpType $ idType mono_id)- ; return ( FunBind { fun_id = L loc mono_id+ ; return ( FunBind { fun_id = L (noAnnSrcSpan loc) mono_id , fun_matches = matches' , fun_ext = co_fn , fun_tick = [] } ) }@@ -1497,7 +1502,7 @@ -- NotTopLevel: it's a monomorphic binding ----------------------getMonoBindInfo :: [Located TcMonoBind] -> [MonoBindInfo]+getMonoBindInfo :: [LocatedA TcMonoBind] -> [MonoBindInfo] getMonoBindInfo tc_binds = foldr (get_info . unLoc) [] tc_binds where@@ -1670,10 +1675,10 @@ -- so we should apply the MR -- See Note [Partial type signatures and generalisation] partial_sig_mrs- = [ null theta+ = [ null $ fromMaybeContext mtheta | TcIdSig (PartialSig { psig_hs_ty = hs_ty }) <- mapMaybe sig_fn (collectHsBindListBinders CollNoDictBinders lbinds)- , let (L _ theta, _) = splitLHsQualTy (hsSigWcType hs_ty) ]+ , let (mtheta, _) = splitLHsQualTy (hsSigWcType hs_ty) ] has_partial_sigs = not (null partial_sig_mrs) @@ -1768,7 +1773,7 @@ -- This one is called on LHS, when pat and grhss are both Name -- and on RHS, when pat is TcId and grhss is still Name-patMonoBindsCtxt :: (OutputableBndrId p, Outputable body)- => LPat (GhcPass p) -> GRHSs GhcRn body -> SDoc+patMonoBindsCtxt :: (OutputableBndrId p)+ => LPat (GhcPass p) -> GRHSs GhcRn (LHsExpr GhcRn) -> SDoc patMonoBindsCtxt pat grhss = hang (text "In a pattern binding:") 2 (pprPatBind pat grhss)
compiler/GHC/Tc/Gen/Default.hs view
@@ -49,7 +49,7 @@ = return (Just []) -- Default declaration specifying no types tcDefaults [L locn (DefaultDecl _ mono_tys)]- = setSrcSpan locn $+ = setSrcSpan (locA locn) $ addErrCtxt defaultDeclCtxt $ do { ovl_str <- xoptM LangExt.OverloadedStrings ; ext_deflt <- xoptM LangExt.ExtendedDefaultRules@@ -67,7 +67,7 @@ ; return (Just tau_tys) } tcDefaults decls@(L locn (DefaultDecl _ _) : _)- = setSrcSpan locn $+ = setSrcSpan (locA locn) $ failWithTc (dupDefaultDeclErr decls) @@ -102,14 +102,14 @@ defaultDeclCtxt :: SDoc defaultDeclCtxt = text "When checking the types in a default declaration" -dupDefaultDeclErr :: [Located (DefaultDecl GhcRn)] -> SDoc+dupDefaultDeclErr :: [LDefaultDecl GhcRn] -> SDoc dupDefaultDeclErr (L _ (DefaultDecl _ _) : dup_things) = hang (text "Multiple default declarations") 2 (vcat (map pp dup_things)) where- pp :: Located (DefaultDecl GhcRn) -> SDoc+ pp :: LDefaultDecl GhcRn -> SDoc pp (L locn (DefaultDecl _ _))- = text "here was another default declaration" <+> ppr locn+ = text "here was another default declaration" <+> ppr (locA locn) dupDefaultDeclErr [] = panic "dupDefaultDeclErr []" badDefaultTy :: Type -> [Class] -> SDoc
compiler/GHC/Tc/Gen/Export.hs view
@@ -3,7 +3,7 @@ {-# LANGUAGE RankNTypes #-} {-# LANGUAGE TypeFamilies #-} -module GHC.Tc.Gen.Export (tcRnExports, exports_from_avail) where+module GHC.Tc.Gen.Export (rnExports, exports_from_avail) where import GHC.Prelude @@ -29,6 +29,7 @@ import GHC.Data.FastString (fsLit) import GHC.Driver.Env +import GHC.Types.TyThing( tyThingCategory ) import GHC.Types.Unique.Set import GHC.Types.SrcLoc as SrcLoc import GHC.Types.Name@@ -38,7 +39,6 @@ import GHC.Types.SourceFile import GHC.Types.Id import GHC.Types.Id.Info-import GHC.Types.TyThing import GHC.Types.Name.Reader import Control.Monad@@ -153,33 +153,35 @@ -- it came from. It's illegal to export two distinct things -- that have the same occurrence name -tcRnExports :: Bool -- False => no 'module M(..) where' header at all- -> Maybe (Located [LIE GhcPs]) -- Nothing => no explicit export list- -> TcGblEnv+rnExports :: Bool -- False => no 'module M(..) where' header at all+ -> Maybe (LocatedL [LIE GhcPs]) -- Nothing => no explicit export list -> RnM TcGblEnv -- Complains if two distinct exports have same OccName -- Warns about identical exports. -- Complains about exports items not in scope -tcRnExports explicit_mod exports- tcg_env@TcGblEnv { tcg_mod = this_mod,- tcg_rdr_env = rdr_env,- tcg_imports = imports,- tcg_src = hsc_src }- = unsetWOptM Opt_WarnWarningsDeprecations $+rnExports explicit_mod exports+ = checkNoErrs $ -- Fail if anything in rnExports finds+ -- an error fails, to avoid error cascade+ unsetWOptM Opt_WarnWarningsDeprecations $ -- Do not report deprecations arising from the export -- list, to avoid bleating about re-exporting a deprecated -- thing (especially via 'module Foo' export item)- do {- ; dflags <- getDynFlags- ; hsc_env <- getTopEnv- ; let is_main_mod = mainModIs hsc_env == this_mod- ; let default_main = case mainFunIs dflags of- Just main_fun- | is_main_mod -> mkUnqual varName (fsLit main_fun)- _ -> main_RDR_Unqual+ do { hsc_env <- getTopEnv+ ; tcg_env <- getGblEnv+ ; let dflags = hsc_dflags hsc_env+ TcGblEnv { tcg_mod = this_mod+ , tcg_rdr_env = rdr_env+ , tcg_imports = imports+ , tcg_src = hsc_src } = tcg_env+ default_main | mainModIs hsc_env == this_mod+ , Just main_fun <- mainFunIs dflags+ = mkUnqual varName (fsLit main_fun)+ | otherwise+ = main_RDR_Unqual ; has_main <- (not . null) <$> lookupInfoOccRn default_main -- #17832+ -- If a module has no explicit header, and it has one or more main -- functions in scope, then add a header like -- "module Main(main) where ..." #13839@@ -187,12 +189,13 @@ ; let real_exports | explicit_mod = exports | has_main- = Just (noLoc [noLoc (IEVar noExtField- (noLoc (IEName $ noLoc default_main)))])+ = Just (noLocA [noLocA (IEVar noExtField+ (noLocA (IEName $ noLocA default_main)))]) -- ToDo: the 'noLoc' here is unhelpful if 'main' -- turns out to be out of scope | otherwise = Nothing + -- Rename the export list ; let do_it = exports_from_avail real_exports rdr_env imports this_mod ; (rn_exports, final_avails) <- if hsc_src == HsigFile@@ -201,21 +204,20 @@ Just r -> return r Nothing -> addMessages msgs >> failM else checkNoErrs do_it- ; let final_ns = availsToNameSetWithSelectors final_avails + -- Final processing+ ; let final_ns = availsToNameSetWithSelectors final_avails+ ; traceRn "rnExports: Exports:" (ppr final_avails) - ; let new_tcg_env =- tcg_env { tcg_exports = final_avails,- tcg_rn_exports = case tcg_rn_exports tcg_env of+ ; return (tcg_env { tcg_exports = final_avails+ , tcg_rn_exports = case tcg_rn_exports tcg_env of Nothing -> Nothing- Just _ -> rn_exports,- tcg_dus = tcg_dus tcg_env `plusDU`- usesOnly final_ns }- ; failIfErrsM- ; return new_tcg_env }+ Just _ -> rn_exports+ , tcg_dus = tcg_dus tcg_env `plusDU`+ usesOnly final_ns }) } -exports_from_avail :: Maybe (Located [LIE GhcPs])+exports_from_avail :: Maybe (LocatedL [LIE GhcPs]) -- ^ 'Nothing' means no explicit export list -> GlobalRdrEnv -> ImportAvails@@ -261,7 +263,7 @@ where do_litem :: ExportAccum -> LIE GhcPs -> RnM (Maybe (ExportAccum, (LIE GhcRn, Avails)))- do_litem acc lie = setSrcSpan (getLoc lie) (exports_from_item acc lie)+ do_litem acc lie = setSrcSpan (getLocA lie) (exports_from_item acc lie) -- Maps a parent to its in-scope children kids_env :: NameEnv [GlobalRdrElt]@@ -343,14 +345,14 @@ lookup_ie (IEThingAbs _ (L l rdr)) = do (name, avail) <- lookupGreAvailRn $ ieWrappedName rdr- return (IEThingAbs noExtField (L l (replaceWrappedName rdr name))+ return (IEThingAbs noAnn (L l (replaceWrappedName rdr name)) , avail) lookup_ie ie@(IEThingAll _ n') = do (n, avail, flds) <- lookup_ie_all ie n' let name = unLoc n- return (IEThingAll noExtField (replaceLWrappedName n' (unLoc n))+ return (IEThingAll noAnn (replaceLWrappedName n' (unLoc n)) , availTC name (name:avail) flds) @@ -379,8 +381,8 @@ = do name <- lookupGlobalOccRn $ ieWrappedName rdr (non_flds, flds) <- lookupChildrenExport name sub_rdrs if isUnboundName name- then return (L l name, [], [name], [])- else return (L l name, non_flds+ then return (L (locA l) name, [], [name], [])+ else return (L (locA l) name, non_flds , map (ieWrappedName . unLoc) non_flds , flds) @@ -395,12 +397,12 @@ when (null gres) $ if isTyConName name then when warnDodgyExports $- addWarn (Reason Opt_WarnDodgyExports)- (dodgyExportWarn name)+ addDiagnostic (WarningWithFlag Opt_WarnDodgyExports)+ (dodgyExportWarn name) else -- This occurs when you export T(..), but -- only import T abstractly, or T is a synonym. addErr (exportItemErr ie)- return (L l name, non_flds, flds)+ return (L (locA l) name, non_flds, flds) ------------- lookup_doc_ie :: IE GhcPs -> Maybe (IE GhcRn)@@ -516,10 +518,10 @@ case name of NameNotFound -> do { ub <- reportUnboundName unboundName ; let l = getLoc n- ; return (Left (L l (IEName (L l ub))))}+ ; return (Left (L l (IEName (L (la2na l) ub))))} FoundChild par child -> do { checkPatSynParent spec_parent par child ; return $ case child of- FieldGreName fl -> Right (L (getLoc n) fl)+ FieldGreName fl -> Right (L (getLocA n) fl) NormalGreName name -> Left (replaceLWrappedName n name) } IncorrectParent p c gs -> failWithDcErr p c gs@@ -596,7 +598,7 @@ = return () | otherwise- = do { parent_ty_con <- tcLookupTyCon parent+ = do { parent_ty_con <- tcLookupTyCon parent ; mpat_syn_thing <- tcLookupGlobal (greNameMangledName gname) -- 1. Check that the Id was actually from a thing associated with patsyns@@ -793,7 +795,7 @@ <+> text "is not the parent of the" <+> text what_is <+> quotes thing <> char '.' $$ text (capitalise what_is)- <> text "s can only be exported with their parent type constructor."+ <> text "s can only be exported with their parent type constructor." $$ (case parents of [] -> empty [_] -> text "Parent:"@@ -802,13 +804,13 @@ failWithDcErr :: Name -> GreName -> [Name] -> TcM a failWithDcErr parent child parents = do ty_thing <- tcLookupGlobal (greNameMangledName child)- failWithTc $ dcErrMsg parent (tyThingCategory' ty_thing)+ failWithTc $ dcErrMsg parent (pp_category ty_thing) (ppr child) (map ppr parents) where- tyThingCategory' :: TyThing -> String- tyThingCategory' (AnId i)+ pp_category :: TyThing -> String+ pp_category (AnId i) | isRecordSelector i = "record selector"- tyThingCategory' i = tyThingCategory i+ pp_category i = tyThingCategory i exportClashErr :: GlobalRdrEnv
compiler/GHC/Tc/Gen/Expr.hs view
@@ -112,13 +112,13 @@ -> TcM (LHsExpr GhcTc) tcPolyLExpr (L loc expr) res_ty- = setSrcSpan loc $ -- Set location /first/; see GHC.Tc.Utils.Monad+ = setSrcSpanA loc $ -- Set location /first/; see GHC.Tc.Utils.Monad addExprCtxt expr $ -- Note [Error contexts in generated code] do { expr' <- tcPolyExpr expr res_ty ; return (L loc expr') } tcPolyLExprNC (L loc expr) res_ty- = setSrcSpan loc $+ = setSrcSpanA loc $ do { expr' <- tcPolyExpr expr res_ty ; return (L loc expr') } @@ -138,13 +138,13 @@ -> TcM (LHsExpr GhcTc) tcMonoExpr (L loc expr) res_ty- = setSrcSpan loc $ -- Set location /first/; see GHC.Tc.Utils.Monad+ = setSrcSpanA loc $ -- Set location /first/; see GHC.Tc.Utils.Monad addExprCtxt expr $ -- Note [Error contexts in generated code] do { expr' <- tcExpr expr res_ty ; return (L loc expr') } tcMonoExprNC (L loc expr) res_ty- = setSrcSpan loc $+ = setSrcSpanA loc $ do { expr' <- tcExpr expr res_ty ; return (L loc expr') } @@ -152,13 +152,13 @@ tcInferRho, tcInferRhoNC :: LHsExpr GhcRn -> TcM (LHsExpr GhcTc, TcRhoType) -- Infer a *rho*-type. The return type is always instantiated. tcInferRho (L loc expr)- = setSrcSpan loc $ -- Set location /first/; see GHC.Tc.Utils.Monad+ = setSrcSpanA loc $ -- Set location /first/; see GHC.Tc.Utils.Monad addExprCtxt expr $ -- Note [Error contexts in generated code] do { (expr', rho) <- tcInfer (tcExpr expr) ; return (L loc expr', rho) } tcInferRhoNC (L loc expr)- = setSrcSpan loc $+ = setSrcSpanA loc $ do { (expr', rho) <- tcInfer (tcExpr expr) ; return (L loc expr', rho) } @@ -206,7 +206,7 @@ = do { mb_res <- tcShortCutLit lit res_ty -- See Note [Short cut for overloaded literals] in GHC.Tc.Utils.Zonk ; case mb_res of- Just lit' -> return (HsOverLit noExtField lit')+ Just lit' -> return (HsOverLit noAnn lit') Nothing -> tcApp e res_ty } -- Typecheck an occurrence of an unbound Id@@ -249,7 +249,7 @@ ; ipClass <- tcLookupClass ipClassName ; ip_var <- emitWantedEvVar origin (mkClassPred ipClass [ip_name, ip_ty]) ; tcWrapResult e- (fromDict ipClass ip_name ip_ty (HsVar noExtField (noLoc ip_var)))+ (fromDict ipClass ip_name ip_ty (HsVar noExtField (noLocA ip_var))) ip_ty res_ty } where -- Coerces a dictionary for `IP "x" t` into `t`.@@ -257,9 +257,9 @@ unwrapIP $ mkClassPred ipClass [x,ty] origin = IPOccOrigin x -tcExpr (HsLam x match) res_ty+tcExpr (HsLam _ match) res_ty = do { (wrap, match') <- tcMatchLambda herald match_ctxt match res_ty- ; return (mkHsWrap wrap (HsLam x match')) }+ ; return (mkHsWrap wrap (HsLam noExtField match')) } where match_ctxt = MC { mc_what = LambdaExpr, mc_body = tcBody } herald = sep [ text "The lambda expression" <+>@@ -328,7 +328,7 @@ ; tup_args1 <- tcTupArgs tup_args arg_tys ; let expr' = ExplicitTuple x tup_args1 boxity- missing_tys = [Scaled mult ty | (L _ (Missing (Scaled mult _)), ty) <- zip tup_args1 arg_tys]+ missing_tys = [Scaled mult ty | (Missing (Scaled mult _), ty) <- zip tup_args1 arg_tys] -- See Note [Linear fields generalization] in GHC.Tc.Gen.App act_res_ty@@ -357,10 +357,10 @@ ************************************************************************ -} -tcExpr (HsLet x (L l binds) expr) res_ty+tcExpr (HsLet x binds expr) res_ty = do { (binds', expr') <- tcLocalBinds binds $ tcMonoExpr expr res_ty- ; return (HsLet x (L l binds') expr') }+ ; return (HsLet x binds' expr') } tcExpr (HsCase x scrut matches) res_ty = do { -- We used to typecheck the case alternatives first.@@ -372,9 +372,7 @@ -- -- But now, in the GADT world, we need to typecheck the scrutinee -- first, to get type info that may be refined in the case alternatives- let mult = Many- -- There is not yet syntax or inference mechanism for case- -- expressions to be anything else than unrestricted.+ mult <- newFlexiTyVarTy multiplicityTy -- Typecheck the scrutinee. We use tcInferRho but tcInferSigma -- would also be possible (tcMatchesCase accepts sigma-types)@@ -451,9 +449,9 @@ [p_ty] ; let wrap = mkWpTyApps [expr_ty] ; loc <- getSrcSpanM- ; return $ mkHsWrapCo co $ HsApp noExtField- (L loc $ mkHsWrap wrap fromStaticPtr)- (L loc (HsStatic fvs expr'))+ ; return $ mkHsWrapCo co $ HsApp noComments+ (L (noAnnSrcSpan loc) $ mkHsWrap wrap fromStaticPtr)+ (L (noAnnSrcSpan loc) (HsStatic fvs expr')) } {-@@ -641,7 +639,11 @@ -} -tcExpr expr@(RecordUpd { rupd_expr = record_expr, rupd_flds = rbnds }) res_ty+-- Record updates via dot syntax are replaced by desugared expressions+-- in the renamer. See Note [Overview of record dot syntax] in+-- GHC.Hs.Expr. This is why we match on 'rupd_flds = Left rbnds' here+-- and panic otherwise.+tcExpr expr@(RecordUpd { rupd_expr = record_expr, rupd_flds = Left rbnds }) res_ty = ASSERT( notNull rbnds ) do { -- STEP -2: typecheck the record_expr, the record to be updated (record_expr', record_rho) <- tcScalingUsage Many $ tcInferRho record_expr@@ -807,11 +809,12 @@ , rupd_out_tys = result_inst_tys , rupd_wrap = req_wrap } expr' = RecordUpd { rupd_expr = mkLHsWrap fam_co $- mkLHsWrapCo co_scrut record_expr'- , rupd_flds = rbinds'+ mkLHsWrapCo co_scrut record_expr'+ , rupd_flds = Left rbinds' , rupd_ext = upd_tc } ; tcWrapResult expr expr' rec_res_ty res_ty }+tcExpr (RecordUpd {}) _ = panic "GHC.Tc.Gen.Expr: tcExpr: The impossible happened!" {-@@ -830,6 +833,19 @@ {- ************************************************************************ * *+ Record dot syntax+* *+************************************************************************+-}++-- These terms have been replaced by desugaring in the renamer. See+-- Note [Overview of record dot syntax].+tcExpr (HsGetField _ _ _) _ = panic "GHC.Tc.Gen.Expr: tcExpr: HsGetField: Not implemented"+tcExpr (HsProjection _ _) _ = panic "GHC.Tc.Gen.Expr: tcExpr: HsProjection: Not implemented"++{-+************************************************************************+* * Template Haskell * * ************************************************************************@@ -925,16 +941,16 @@ ; return (idHsWrapper, elt_mult, elt_ty, Just fl') } -----------------tcTupArgs :: [LHsTupArg GhcRn] -> [TcSigmaType] -> TcM [LHsTupArg GhcTc]+tcTupArgs :: [HsTupArg GhcRn] -> [TcSigmaType] -> TcM [HsTupArg GhcTc] tcTupArgs args tys = do MASSERT( equalLength args tys ) checkTupSize (length args) mapM go (args `zip` tys) where- go (L l (Missing {}), arg_ty) = do { mult <- newFlexiTyVarTy multiplicityTy- ; return (L l (Missing (Scaled mult arg_ty))) }- go (L l (Present x expr), arg_ty) = do { expr' <- tcCheckPolyExpr expr arg_ty- ; return (L l (Present x expr')) }+ go (Missing {}, arg_ty) = do { mult <- newFlexiTyVarTy multiplicityTy+ ; return (Missing (Scaled mult arg_ty)) }+ go (Present x expr, arg_ty) = do { expr' <- tcCheckPolyExpr expr arg_ty+ ; return (Present x expr') } --------------------------- -- See TcType.SyntaxOpType also for commentary@@ -1172,7 +1188,7 @@ -- See Note [Disambiguating record fields] in GHC.Tc.Gen.Head disambiguateRecordBinds :: LHsExpr GhcRn -> TcRhoType -> [LHsRecUpdField GhcRn] -> ExpRhoType- -> TcM [LHsRecField' (AmbiguousFieldOcc GhcTc) (LHsExpr GhcRn)]+ -> TcM [LHsRecField' GhcTc (AmbiguousFieldOcc GhcTc) (LHsExpr GhcRn)] disambiguateRecordBinds record_expr record_rho rbnds res_ty -- Are all the fields unambiguous? = case mapM isUnambiguous rbnds of@@ -1237,7 +1253,7 @@ -- where T does not have field x. pickParent :: RecSelParent -> (LHsRecUpdField GhcRn, [(RecSelParent, GlobalRdrElt)])- -> TcM (LHsRecField' (AmbiguousFieldOcc GhcTc) (LHsExpr GhcRn))+ -> TcM (LHsRecField' GhcTc (AmbiguousFieldOcc GhcTc) (LHsExpr GhcRn)) pickParent p (upd, xs) = case lookup p xs of -- Phew! The parent is valid for this field.@@ -1258,13 +1274,21 @@ -- Given a (field update, selector name) pair, look up the -- selector to give a field update with an unambiguous Id lookupSelector :: (LHsRecUpdField GhcRn, Name)- -> TcM (LHsRecField' (AmbiguousFieldOcc GhcTc) (LHsExpr GhcRn))+ -> TcM (LHsRecField' GhcRn (AmbiguousFieldOcc GhcTc) (LHsExpr GhcRn)) lookupSelector (L l upd, n) = do { i <- tcLookupId n ; let L loc af = hsRecFieldLbl upd lbl = rdrNameAmbiguousFieldOcc af- ; return $ L l upd { hsRecFieldLbl- = L loc (Unambiguous i (L loc lbl)) } }+ -- ; return $ L l upd { hsRecFieldLbl+ -- = L loc (Unambiguous i (L (noAnnSrcSpan loc) lbl)) }+ ; return $ L l HsRecField+ { hsRecFieldAnn = hsRecFieldAnn upd+ , hsRecFieldLbl+ = L loc (Unambiguous i (L (noAnnSrcSpan loc) lbl))+ , hsRecFieldArg = hsRecFieldArg upd+ , hsRecPun = hsRecPun upd+ }+ } -- See Note [Deprecating ambiguous fields] in GHC.Tc.Gen.Head reportAmbiguousField :: TyCon -> TcM ()@@ -1276,8 +1300,8 @@ , text "This will not be supported by -XDuplicateRecordFields in future releases of GHC." ] where- rupd = RecordUpd { rupd_expr = record_expr, rupd_flds = rbnds, rupd_ext = noExtField }- loc = getLoc (head rbnds)+ rupd = RecordUpd { rupd_expr = record_expr, rupd_flds = Left rbnds, rupd_ext = noExtField }+ loc = getLocA (head rbnds) {- Game plan for record bindings@@ -1318,13 +1342,18 @@ = do { mb <- tcRecordField con_like flds_w_tys f rhs ; case mb of Nothing -> return Nothing- Just (f', rhs') -> return (Just (L l (fld { hsRecFieldLbl = f'- , hsRecFieldArg = rhs' }))) }+ -- Just (f', rhs') -> return (Just (L l (fld { hsRecFieldLbl = f'+ -- , hsRecFieldArg = rhs' }))) }+ Just (f', rhs') -> return (Just (L l (HsRecField+ { hsRecFieldAnn = hsRecFieldAnn fld+ , hsRecFieldLbl = f'+ , hsRecFieldArg = rhs'+ , hsRecPun = hsRecPun fld}))) } tcRecordUpd :: ConLike -> [TcType] -- Expected type for each field- -> [LHsRecField' (AmbiguousFieldOcc GhcTc) (LHsExpr GhcRn)]+ -> [LHsRecField' GhcTc (AmbiguousFieldOcc GhcTc) (LHsExpr GhcRn)] -> TcM [LHsRecUpdField GhcTc] tcRecordUpd con_like arg_tys rbinds = fmap catMaybes $ mapM do_bind rbinds@@ -1332,13 +1361,13 @@ fields = map flSelector $ conLikeFieldLabels con_like flds_w_tys = zipEqual "tcRecordUpd" fields arg_tys - do_bind :: LHsRecField' (AmbiguousFieldOcc GhcTc) (LHsExpr GhcRn)+ do_bind :: LHsRecField' GhcTc (AmbiguousFieldOcc GhcTc) (LHsExpr GhcRn) -> TcM (Maybe (LHsRecUpdField GhcTc)) do_bind (L l fld@(HsRecField { hsRecFieldLbl = L loc af , hsRecFieldArg = rhs })) = do { let lbl = rdrNameAmbiguousFieldOcc af sel_id = selectorAmbiguousFieldOcc af- f = L loc (FieldOcc (idName sel_id) (L loc lbl))+ f = L loc (FieldOcc (idName sel_id) (L (noAnnSrcSpan loc) lbl)) ; mb <- tcRecordField con_like flds_w_tys f rhs ; case mb of Nothing -> return Nothing@@ -1347,7 +1376,7 @@ (L l (fld { hsRecFieldLbl = L loc (Unambiguous (extFieldOcc (unLoc f'))- (L loc lbl))+ (L (noAnnSrcSpan loc) lbl)) , hsRecFieldArg = rhs' }))) } tcRecordField :: ConLike -> Assoc Name Type@@ -1382,8 +1411,8 @@ else do warn <- woptM Opt_WarnMissingFields when (warn && notNull field_strs && null field_labels)- (warnTc (Reason Opt_WarnMissingFields) True- (missingFields con_like []))+ (diagnosticTc (WarningWithFlag Opt_WarnMissingFields) True+ (missingFields con_like [])) | otherwise = do -- A record unless (null missing_s_fields) $ do@@ -1398,8 +1427,8 @@ -- It is not an error (though we may want) to omit a -- lazy field, because we can always use -- (error "Missing field f") instead.- warnTc (Reason Opt_WarnMissingFields) True- (missingFields con_like fs)+ diagnosticTc (WarningWithFlag Opt_WarnMissingFields) True+ (missingFields con_like fs) where -- we zonk the fields to get better types in error messages (#18869)@@ -1447,7 +1476,7 @@ 2 (vcat [ ppr f <+> dcolon <+> ppr ty | (f,ty) <- prs ]) badFieldsUpd- :: [LHsRecField' (AmbiguousFieldOcc GhcTc) (LHsExpr GhcRn)]+ :: [LHsRecField' GhcTc (AmbiguousFieldOcc GhcTc) (LHsExpr GhcRn)] -- Field names that don't belong to a single datacon -> [ConLike] -- Data cons of the type which the first field name belongs to -> SDoc
compiler/GHC/Tc/Gen/Foreign.hs view
@@ -235,7 +235,7 @@ -> TcM (Id, LForeignDecl GhcTc, Bag GlobalRdrElt) tcFImport (L dloc fo@(ForeignImport { fd_name = L nloc nm, fd_sig_ty = hs_ty , fd_fi = imp_decl }))- = setSrcSpan dloc $ addErrCtxt (foreignDeclCtxt fo) $+ = setSrcSpanA dloc $ addErrCtxt (foreignDeclCtxt fo) $ do { sig_ty <- tcHsSigType (ForSigCtxt nm) hs_ty ; (norm_co, norm_sig_ty, gres) <- normaliseFfiType sig_ty ; let@@ -347,8 +347,8 @@ checkMissingAmpersand dflags arg_tys res_ty | null arg_tys && isFunPtrTy res_ty && wopt Opt_WarnDodgyForeignImports dflags- = addWarn (Reason Opt_WarnDodgyForeignImports)- (text "possible missing & in foreign import of FunPtr")+ = addDiagnosticTc (WarningWithFlag Opt_WarnDodgyForeignImports)+ (text "possible missing & in foreign import of FunPtr") | otherwise = return () @@ -376,7 +376,7 @@ = foldlM combine (emptyLHsBinds, [], emptyBag) (filter isForeignExport decls) where combine (binds, fs, gres1) (L loc fe) = do- (b, f, gres2) <- setSrcSpan loc (tcFExport fe)+ (b, f, gres2) <- setSrcSpanA loc (tcFExport fe) return (b `consBag` binds, L loc f : fs, gres1 `unionBags` gres2) tcFExport :: ForeignDecl GhcRn@@ -400,7 +400,7 @@ -- We need to give a name to the new top-level binding that -- is *stable* (i.e. the compiler won't change it later), -- because this name will be referred to by the C code stub.- id <- mkStableIdFromName nm sig_ty loc mkForeignExportOcc+ id <- mkStableIdFromName nm sig_ty (locA loc) mkForeignExportOcc return ( mkVarBind id rhs , ForeignExport { fd_name = L loc id , fd_sig_ty = undefined@@ -535,7 +535,7 @@ then return StdCallConv else do -- This is a warning, not an error. see #3336 when (wopt Opt_WarnUnsupportedCallingConventions dflags) $- addWarnTc (Reason Opt_WarnUnsupportedCallingConventions)+ addDiagnosticTc (WarningWithFlag Opt_WarnUnsupportedCallingConventions) (text "the 'stdcall' calling convention is unsupported on this platform," $$ text "treating as ccall") return CCallConv checkCConv PrimCallConv = do addErrTc (text "The `prim' calling convention can only be used with `foreign import'")
compiler/GHC/Tc/Gen/Head.hs view
@@ -16,9 +16,10 @@ -} module GHC.Tc.Gen.Head- ( HsExprArg(..), EValArg(..), TcPass(..), AppCtxt(..), appCtxtLoc+ ( HsExprArg(..), EValArg(..), TcPass(..)+ , AppCtxt(..), appCtxtLoc, insideExpansion , splitHsApps, rebuildHsApps- , addArgWrap, isHsValArg, insideExpansion+ , addArgWrap, isHsValArg , countLeadingValArgs, isVisibleArg, pprHsExprArgTc , tcInferAppHead, tcInferAppHead_maybe@@ -204,6 +205,10 @@ appCtxtLoc (VAExpansion _ l) = l appCtxtLoc (VACall _ _ l) = l +insideExpansion :: AppCtxt -> Bool+insideExpansion (VAExpansion {}) = True+insideExpansion (VACall {}) = False+ instance Outputable AppCtxt where ppr (VAExpansion e _) = text "VAExpansion" <+> ppr e ppr (VACall f n _) = text "VACall" <+> int n <+> ppr f@@ -262,7 +267,7 @@ -- See Note [Desugar OpApp in the typechecker] go e@(OpApp _ arg1 (L l op) arg2) _ args- = ( (op, VACall op 0 l)+ = ( (op, VACall op 0 (locA l)) , mkEValArg (VACall op 1 generatedSrcSpan) arg1 : mkEValArg (VACall op 2 generatedSrcSpan) arg2 : EWrap (EExpand e)@@ -270,12 +275,12 @@ go e ctxt args = ((e,ctxt), args) - set :: SrcSpan -> AppCtxt -> AppCtxt- set l (VACall f n _) = VACall f n l+ set :: SrcSpanAnnA -> AppCtxt -> AppCtxt+ set l (VACall f n _) = VACall f n (locA l) set _ ctxt@(VAExpansion {}) = ctxt - dec :: SrcSpan -> AppCtxt -> AppCtxt- dec l (VACall f n _) = VACall f (n-1) l+ dec :: SrcSpanAnnA -> AppCtxt -> AppCtxt+ dec l (VACall f n _) = VACall f (n-1) (locA l) dec _ ctxt@(VAExpansion {}) = ctxt rebuildHsApps :: HsExpr GhcTc -> AppCtxt -> [HsExprArg 'TcpTc]-> HsExpr GhcTc@@ -283,19 +288,19 @@ rebuildHsApps fun ctxt (arg : args) = case arg of EValArg { eva_arg = ValArg arg, eva_ctxt = ctxt' }- -> rebuildHsApps (HsApp noExtField lfun arg) ctxt' args+ -> rebuildHsApps (HsApp noAnn lfun arg) ctxt' args ETypeArg { eva_hs_ty = hs_ty, eva_ty = ty, eva_ctxt = ctxt' } -> rebuildHsApps (HsAppType ty lfun hs_ty) ctxt' args EPrag ctxt' p -> rebuildHsApps (HsPragE noExtField p lfun) ctxt' args EWrap (EPar ctxt')- -> rebuildHsApps (HsPar noExtField lfun) ctxt' args+ -> rebuildHsApps (HsPar noAnn lfun) ctxt' args EWrap (EExpand orig) -> rebuildHsApps (XExpr (ExpansionExpr (HsExpanded orig fun))) ctxt args EWrap (EHsWrap wrap) -> rebuildHsApps (mkHsWrap wrap fun) ctxt args where- lfun = L (appCtxtLoc ctxt) fun+ lfun = L (noAnnSrcSpan $ appCtxtLoc ctxt) fun isHsValArg :: HsExprArg id -> Bool isHsValArg (EValArg {}) = True@@ -317,12 +322,6 @@ isVisibleArg (ETypeArg {}) = True isVisibleArg _ = False -insideExpansion :: [HsExprArg p] -> Bool-insideExpansion args = any is_expansion args- where- is_expansion (EWrap (EExpand {})) = True- is_expansion _ = False- instance OutputableBndrId (XPass p) => Outputable (HsExprArg p) where ppr (EValArg { eva_arg = arg }) = text "EValArg" <+> ppr arg ppr (EPrag _ p) = text "EPrag" <+> ppr p@@ -556,7 +555,7 @@ ; return (expr, idType sel_id) } -------------------------tc_rec_sel_id :: Located RdrName -> Name -> TcM TcId+tc_rec_sel_id :: LocatedN RdrName -> Name -> TcM TcId -- Like tc_infer_id, but returns an Id not a HsExpr, -- so we can wrap it back up into a HsRecFld tc_rec_sel_id lbl sel_name@@ -580,7 +579,7 @@ occ = rdrNameOcc (unLoc lbl) -------------------------tcInferAmbiguousRecSelId :: Located RdrName+tcInferAmbiguousRecSelId :: LocatedN RdrName -> [HsExprArg 'TcpRn] -> Maybe TcRhoType -> TcM Name -- Disgusting special case for ambiguous record selectors@@ -602,7 +601,7 @@ | otherwise = ambiguousSelector lbl -finish_ambiguous_selector :: Located RdrName -> Type -> TcM Name+finish_ambiguous_selector :: LocatedN RdrName -> Type -> TcM Name finish_ambiguous_selector lr@(L _ rdr) parent_type = do { fam_inst_envs <- tcGetFamInstEnvs ; case tyConOf fam_inst_envs parent_type of {@@ -632,7 +631,7 @@ -- This field name really is ambiguous, so add a suitable "ambiguous -- occurrence" error, then give up.-ambiguousSelector :: Located RdrName -> TcM a+ambiguousSelector :: LocatedN RdrName -> TcM a ambiguousSelector (L _ rdr) = do { addAmbiguousNameErr rdr ; failM }@@ -722,7 +721,7 @@ ; (expr', poly_ty) <- tcExprSig expr sig_info ; return (ExprWithTySig noExtField expr' hs_ty, poly_ty) } where- loc = getLoc (dropWildCards hs_ty)+ loc = getLocA (dropWildCards hs_ty) tcExprSig :: LHsExpr GhcRn -> TcIdSigInfo -> TcM (LHsExpr GhcTc, TcType) tcExprSig expr (CompleteSig { sig_bndr = poly_id, sig_loc = loc })@@ -823,13 +822,13 @@ ; hs_lit <- mkOverLit val ; co <- unifyType mb_doc (hsLitType hs_lit) (scaledThing sarg_ty) - ; let lit_expr = L loc $ mkHsWrapCo co $- HsLit noExtField hs_lit+ ; let lit_expr = L (l2l loc) $ mkHsWrapCo co $+ HsLit noAnn hs_lit from_expr = mkHsWrap (wrap2 <.> wrap1) $ HsVar noExtField (L loc from_id)- lit' = lit { ol_witness = HsApp noExtField (L loc from_expr) lit_expr+ lit' = lit { ol_witness = HsApp noAnn (L (l2l loc) from_expr) lit_expr , ol_ext = OverLitTc rebindable res_ty }- ; return (HsOverLit noExtField lit', res_ty) }+ ; return (HsOverLit noAnn lit', res_ty) } where orig = LiteralOrigin lit mb_doc = Just (ppr from_name)@@ -850,9 +849,10 @@ tcCheckId name res_ty = do { (expr, actual_res_ty) <- tcInferId name ; traceTc "tcCheckId" (vcat [ppr name, ppr actual_res_ty, ppr res_ty])- ; addFunResCtxt expr [] actual_res_ty res_ty $- tcWrapResultO (OccurrenceOf name) (HsVar noExtField (noLoc name)) expr- actual_res_ty res_ty }+ ; addFunResCtxt rn_fun [] actual_res_ty res_ty $+ tcWrapResultO (OccurrenceOf name) rn_fun expr actual_res_ty res_ty }+ where+ rn_fun = HsVar noExtField (noLocA name) ------------------------ tcInferId :: Name -> TcM (HsExpr GhcTc, TcSigmaType)@@ -877,7 +877,7 @@ = do { assert_error_id <- tcLookupId assertErrorName ; (wrap, id_rho) <- topInstantiate (OccurrenceOf assert_name) (idType assert_error_id)- ; return (mkHsWrap wrap (HsVar noExtField (noLoc assert_error_id)), id_rho)+ ; return (mkHsWrap wrap (HsVar noExtField (noLocA assert_error_id)), id_rho) } tc_infer_id :: Name -> TcM (HsExpr GhcTc, TcSigmaType)@@ -928,7 +928,7 @@ = text "Illegal term-level use of the type constructor" <+> quotes (ppr (tyConName ty_con)) - return_id id = return (HsVar noExtField (noLoc id), idType id)+ return_id id = return (HsVar noExtField (noLocA id), idType id) return_data_con con = do { let tvs = dataConUserTyVarBinders con@@ -1105,7 +1105,7 @@ ; lift <- if isStringTy id_ty then do { sid <- tcLookupId GHC.Builtin.Names.TH.liftStringName -- See Note [Lifting strings]- ; return (HsVar noExtField (noLoc sid)) }+ ; return (HsVar noExtField (noLocA sid)) } else setConstraintVar lie_var $ -- Put the 'lift' constraint into the right LIE@@ -1113,10 +1113,16 @@ GHC.Builtin.Names.TH.liftName [getRuntimeRep id_ty, id_ty] + -- Warning for implicit lift (#17804)+ ; whenWOptM Opt_WarnImplicitLift $+ addDiagnosticTc (WarningWithFlag Opt_WarnImplicitLift)+ (text "The variable" <+> quotes (ppr id) <+>+ text "is implicitly lifted in the TH quotation")+ -- Update the pending splices ; ps <- readMutVar ps_var ; let pending_splice = PendingTcSplice id_name- (nlHsApp (mkLHsWrap (applyQuoteWrapper q) (noLoc lift))+ (nlHsApp (mkLHsWrap (applyQuoteWrapper q) (noLocA lift)) (nlHsVar id)) ; writeMutVar ps_var (pending_splice : ps) @@ -1157,13 +1163,15 @@ * * ********************************************************************* -} -addFunResCtxt :: HsExpr GhcTc -> [HsExprArg 'TcpTc]+addFunResCtxt :: HsExpr GhcRn -> [HsExprArg 'TcpRn] -> TcType -> ExpRhoType -> TcM a -> TcM a -- When we have a mis-match in the return type of a function -- try to give a helpful message about too many/few arguments-addFunResCtxt fun args fun_res_ty env_ty- = addLandmarkErrCtxtM (\env -> (env, ) <$> mk_msg)+-- But not in generated code, where we don't want+-- to mention internal (rebindable syntax) function names+addFunResCtxt fun args fun_res_ty env_ty thing_inside+ = addLandmarkErrCtxtM (\env -> (env, ) <$> mk_msg) thing_inside -- NB: use a landmark error context, so that an empty context -- doesn't suppress some more useful context where
compiler/GHC/Tc/Gen/HsType.hs view
@@ -1,4 +1,6 @@ {-# LANGUAGE CPP #-}+{-# LANGUAGE DataKinds #-}+{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeFamilies #-}@@ -51,9 +53,9 @@ kcDeclHeader, tcHsLiftedType, tcHsOpenType, tcHsLiftedTypeNC, tcHsOpenTypeNC,- tcInferLHsTypeKind, tcInferLHsType, tcInferLHsTypeUnsaturated,+ tcInferLHsType, tcInferLHsTypeKind, tcInferLHsTypeUnsaturated, tcCheckLHsType,- tcHsMbContext, tcHsContext, tcLHsPredType,+ tcHsContext, tcLHsPredType, kindGeneralizeAll, kindGeneralizeSome, kindGeneralizeNone, @@ -121,7 +123,6 @@ import GHC.Builtin.Names hiding ( wildCardName ) import GHC.Driver.Session import qualified GHC.LanguageExtensions as LangExt-import GHC.Parser.Annotation import GHC.Data.Maybe import GHC.Data.Bag( unitBag )@@ -335,19 +336,19 @@ -} -funsSigCtxt :: [Located Name] -> UserTypeCtxt+funsSigCtxt :: [LocatedN Name] -> UserTypeCtxt -- Returns FunSigCtxt, with no redundant-context-reporting, -- form a list of located names funsSigCtxt (L _ name1 : _) = FunSigCtxt name1 False funsSigCtxt [] = panic "funSigCtxt" -addSigCtxt :: Outputable hs_ty => UserTypeCtxt -> Located hs_ty -> TcM a -> TcM a+addSigCtxt :: Outputable hs_ty => UserTypeCtxt -> LocatedA hs_ty -> TcM a -> TcM a addSigCtxt ctxt hs_ty thing_inside- = setSrcSpan (getLoc hs_ty) $+ = setSrcSpan (getLocA hs_ty) $ addErrCtxt (pprSigCtxt ctxt hs_ty) $ thing_inside -pprSigCtxt :: Outputable hs_ty => UserTypeCtxt -> Located hs_ty -> SDoc+pprSigCtxt :: Outputable hs_ty => UserTypeCtxt -> LocatedA hs_ty -> SDoc -- (pprSigCtxt ctxt <extra> <type>) -- prints In the type signature for 'f': -- f :: <type>@@ -367,7 +368,7 @@ -- already checked this, so we can simply ignore it. tcHsSigWcType ctxt sig_ty = tcHsSigType ctxt (dropWildCards sig_ty) -kcClassSigType :: [Located Name] -> LHsSigType GhcRn -> TcM ()+kcClassSigType :: [LocatedN Name] -> LHsSigType GhcRn -> TcM () -- This is a special form of tcClassSigType that is used during the -- kind-checking phase to infer the kind of class variables. Cf. tc_lhs_sig_type. -- Importantly, this does *not* kind-generalize. Consider@@ -387,7 +388,7 @@ tcLHsType hs_ty liftedTypeKind ; return () } -tcClassSigType :: [Located Name] -> LHsSigType GhcRn -> TcM Type+tcClassSigType :: [LocatedN Name] -> LHsSigType GhcRn -> TcM Type -- Does not do validity checking tcClassSigType names sig_ty = addSigCtxt sig_ctxt sig_ty $@@ -444,18 +445,23 @@ -- This will never emit constraints, as it uses solveEqualities internally. -- No validity checking or zonking -- Returns also an implication for the unsolved constraints-tc_lhs_sig_type skol_info (L loc (HsSig { sig_bndrs = hs_outer_bndrs- , sig_body = hs_ty })) ctxt_kind- = setSrcSpan loc $- do { (tc_lvl, wanted, (outer_bndrs, ty))+tc_lhs_sig_type skol_info full_hs_ty@(L loc (HsSig { sig_bndrs = hs_outer_bndrs+ , sig_body = hs_ty })) ctxt_kind+ = setSrcSpanA loc $+ do { (tc_lvl, wanted, (exp_kind, (outer_bndrs, ty))) <- pushLevelAndSolveEqualitiesX "tc_lhs_sig_type" $ -- See Note [Failure in local type signatures]- tcOuterTKBndrs skol_info hs_outer_bndrs $- do { kind <- newExpectedKind ctxt_kind- ; tcLHsType hs_ty kind }- -- Any remaining variables (unsolved in the solveEqualities)- -- should be in the global tyvars, and therefore won't be quantified+ do { exp_kind <- newExpectedKind ctxt_kind+ -- See Note [Escaping kind in type signatures]+ ; stuff <- tcOuterTKBndrs skol_info hs_outer_bndrs $+ tcLHsType hs_ty exp_kind+ ; return (exp_kind, stuff) } + -- Default any unconstrained variables free in the kind+ -- See Note [Escaping kind in type signatures]+ ; exp_kind_dvs <- candidateQTyVarsOfType exp_kind+ ; doNotQuantifyTyVars exp_kind_dvs (mk_doc exp_kind)+ ; traceTc "tc_lhs_sig_type" (ppr hs_outer_bndrs $$ ppr outer_bndrs) ; (outer_tv_bndrs :: [InvisTVBinder]) <- scopedSortOuter outer_bndrs @@ -468,9 +474,68 @@ ; implic <- buildTvImplication skol_info kvs tc_lvl wanted ; return (implic, mkInfForAllTys kvs ty1) }+ where+ mk_doc exp_kind tidy_env+ = do { (tidy_env2, exp_kind) <- zonkTidyTcType tidy_env exp_kind+ ; return (tidy_env2, hang (text "The kind" <+> ppr exp_kind)+ 2 (text "of type signature:" <+> ppr full_hs_ty)) } -{- Note [Skolem escape in type signatures]+++{- Note [Escaping kind in type signatures] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+Consider kind-checking the signature for `foo` (#19495):+ type family T (r :: RuntimeRep) :: TYPE r++ foo :: forall (r :: RuntimeRep). T r+ foo = ...++We kind-check the type with expected kind `TYPE delta` (see newExpectedKind),+where `delta :: RuntimeRep` is as-yet unknown. (We can't use `TYPE LiftedRep`+because we allow signatures like `foo :: Int#`.)++Suppose we are at level L currently. We do this+ * pushLevelAndSolveEqualitiesX: moves to level L+1+ * newExpectedKind: allocates delta{L+1}+ * tcOuterTKBndrs: pushes the level again to L+2, binds skolem r{L+2}+ * kind-check the body (T r) :: TYPE delta{L+1}++Then+* We can't unify delta{L+1} with r{L+2}.+ And rightly so: skolem would escape.++* If delta{L+1} is unified with some-kind{L}, that is fine.+ This can happen+ \(x::a) -> let y :: a; y = x in ...(x :: Int#)...+ Here (x :: a :: TYPE gamma) is in the environment when we check+ the signature y::a. We unify delta := gamma, and all is well.++* If delta{L+1} is unconstrained, we /must not/ quantify over it!+ E.g. Consider f :: Any where Any :: forall k. k+ We kind-check this with expected kind TYPE kappa. We get+ Any @(TYPE kappa) :: TYPE kappa+ We don't want to generalise to forall k. Any @k+ because that is ill-kinded: the kind of the body of the forall,+ (Any @k :: k) mentions the bound variable k.++ Instead we want to default it to LiftedRep.++ An alternative would be to promote it, similar to the monomorphism+ restriction, but the MR is pretty confusing. Defaulting seems better++How does that defaulting happen? Well, since we /currently/ default+RuntimeRep variables during generalisation, it'll happen in+kindGeneralize. But in principle we might allow generalisation over+RuntimeRep variables in future. Moreover, what if we had+ kappa{L+1} := F alpha{L+1}+where F :: Type -> RuntimeRep. Now it's alpha that is free in the kind+and it /won't/ be defaulted.++So we use doNotQuantifyTyVars to either default the free vars of+exp_kind (if possible), or error (if not).++Note [Skolem escape in type signatures]+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ tcHsSigType is tricky. Consider (T11142) foo :: forall b. (forall k (a :: k). SameKind a b) -> () This is ill-kinded because of a nested skolem-escape.@@ -523,7 +588,7 @@ -- Used for both types and kinds tc_top_lhs_type tyki ctxt (L loc sig_ty@(HsSig { sig_bndrs = hs_outer_bndrs , sig_body = body }))- = setSrcSpan loc $+ = setSrcSpanA loc $ do { traceTc "tc_top_lhs_type {" (ppr sig_ty) ; (tclvl, wanted, (outer_bndrs, ty)) <- pushLevelAndSolveEqualitiesX "tc_top_lhs_type" $@@ -580,9 +645,12 @@ where tc_deriv_strategy :: DerivStrategy GhcRn -> TcM (DerivStrategy GhcTc, [TyVar])- tc_deriv_strategy StockStrategy = boring_case StockStrategy- tc_deriv_strategy AnyclassStrategy = boring_case AnyclassStrategy- tc_deriv_strategy NewtypeStrategy = boring_case NewtypeStrategy+ tc_deriv_strategy (StockStrategy _)+ = boring_case (StockStrategy noExtField)+ tc_deriv_strategy (AnyclassStrategy _)+ = boring_case (AnyclassStrategy noExtField)+ tc_deriv_strategy (NewtypeStrategy _)+ = boring_case (NewtypeStrategy noExtField) tc_deriv_strategy (ViaStrategy ty) = do ty' <- checkNoErrs $ tcTopLHsType DerivClauseCtxt ty let (via_tvs, via_pred) = splitForAllTyCoVars ty'@@ -596,7 +664,7 @@ -> TcM Type -- Like tcHsSigType, but for a class instance declaration tcHsClsInstType user_ctxt hs_inst_ty- = setSrcSpan (getLoc hs_inst_ty) $+ = setSrcSpan (getLocA hs_inst_ty) $ do { -- Fail eagerly if tcTopLHsType fails. We are at top level so -- these constraints will never be solved later. And failing -- eagerly avoids follow-on errors when checkValidInstance@@ -690,7 +758,7 @@ where fam_name = tyConName fam_tc fam_arity = tyConArity fam_tc- lhs_fun = noLoc (HsTyVar noExtField NotPromoted (noLoc fam_name))+ lhs_fun = noLocA (HsTyVar noAnn NotPromoted (noLocA fam_name)) {- Note [tcFamTyPats: zonking the result kind] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~@@ -756,7 +824,7 @@ -- Eagerly instantiate any trailing invisible binders tcInferLHsTypeKind lhs_ty@(L loc hs_ty) = addTypeCtxt lhs_ty $- setSrcSpan loc $ -- Cover the tcInstInvisibleTyBinders+ setSrcSpanA loc $ -- Cover the tcInstInvisibleTyBinders do { (res_ty, res_kind) <- tc_infer_hs_type typeLevelMode hs_ty ; tcInstInvisibleTyBinders res_ty res_kind } -- See Note [Do not always instantiate eagerly in types]@@ -934,7 +1002,7 @@ -- level. tc_infer_lhs_type :: TcTyMode -> LHsType GhcRn -> TcM (TcType, TcKind) tc_infer_lhs_type mode (L span ty)- = setSrcSpan span $+ = setSrcSpanA span $ tc_infer_hs_type mode ty ---------------------------@@ -1051,7 +1119,7 @@ tc_lhs_type :: TcTyMode -> LHsType GhcRn -> TcKind -> TcM TcType tc_lhs_type mode (L span ty) exp_kind- = setSrcSpan span $+ = setSrcSpanA span $ tc_hs_type mode ty exp_kind tc_hs_type :: TcTyMode -> HsType GhcRn -> TcKind -> TcM TcType@@ -1112,7 +1180,7 @@ ; return (mkForAllTys tv_bndrs ty') } tc_hs_type mode (HsQualTy { hst_ctxt = ctxt, hst_body = rn_ty }) exp_kind- | null (unLoc ctxt)+ | null (fromMaybeContext ctxt) = tc_lhs_type mode rn_ty exp_kind -- See Note [Body kind of a HsQualTy]@@ -1159,7 +1227,7 @@ [] -> (liftedTypeKind, BoxedTuple) -- In the [] case, it's not clear what the kind is, so guess * - ; tys' <- sequence [ setSrcSpan loc $+ ; tys' <- sequence [ setSrcSpanA loc $ checkExpectedKind hs_ty ty kind arg_kind | ((L loc hs_ty),ty,kind) <- zip3 hs_tys tys kinds ] @@ -1279,13 +1347,13 @@ ; ty1' <- tc_lhs_type mode ty1 arg_k ; ty2' <- tc_lhs_type mode ty2 res_k ; mult' <- tc_mult mode mult- ; checkExpectedKind (HsFunTy noExtField mult ty1 ty2) (mkVisFunTy mult' ty1' ty2')+ ; checkExpectedKind (HsFunTy noAnn mult ty1 ty2) (mkVisFunTy mult' ty1' ty2') liftedTypeKind exp_kind } KindLevel -> -- no representation polymorphism in kinds. yet. do { ty1' <- tc_lhs_type mode ty1 liftedTypeKind ; ty2' <- tc_lhs_type mode ty2 liftedTypeKind ; mult' <- tc_mult mode mult- ; checkExpectedKind (HsFunTy noExtField mult ty1 ty2) (mkVisFunTy mult' ty1' ty2')+ ; checkExpectedKind (HsFunTy noAnn mult ty1 ty2) (mkVisFunTy mult' ty1' ty2') liftedTypeKind exp_kind } {- Note [Skolem escape and forall-types]@@ -1431,7 +1499,7 @@ splitHsAppTys :: HsType GhcRn -> Maybe (LHsType GhcRn, [LHsTypeArg GhcRn]) splitHsAppTys hs_ty- | is_app hs_ty = Just (go (noLoc hs_ty) [])+ | is_app hs_ty = Just (go (noLocA hs_ty) []) | otherwise = Nothing where is_app :: HsType GhcRn -> Bool@@ -1446,11 +1514,15 @@ is_app (HsParTy _ (L _ ty)) = is_app ty is_app _ = False + go :: LHsType GhcRn+ -> [HsArg (LHsType GhcRn) (LHsKind GhcRn)]+ -> (LHsType GhcRn,+ [HsArg (LHsType GhcRn) (LHsKind GhcRn)]) -- AZ temp go (L _ (HsAppTy _ f a)) as = go f (HsValArg a : as) go (L _ (HsAppKindTy l ty k)) as = go ty (HsTypeArg l k : as)- go (L sp (HsParTy _ f)) as = go f (HsArgPar sp : as)+ go (L sp (HsParTy _ f)) as = go f (HsArgPar (locA sp) : as) go (L _ (HsOpTy _ l op@(L sp _) r)) as- = ( L sp (HsTyVar noExtField NotPromoted op)+ = ( L (na2la sp) (HsTyVar noAnn NotPromoted op) , HsValArg l : HsValArg r : as ) go f as = (f, as) @@ -1860,18 +1932,16 @@ n_to_inst = n_act_invis_bndrs - n_exp_invis_bndrs ----------------------------tcHsMbContext :: Maybe (LHsContext GhcRn) -> TcM [PredType]-tcHsMbContext Nothing = return []-tcHsMbContext (Just cxt) = tcHsContext cxt -tcHsContext :: LHsContext GhcRn -> TcM [PredType]+tcHsContext :: Maybe (LHsContext GhcRn) -> TcM [PredType] tcHsContext cxt = tc_hs_context typeLevelMode cxt tcLHsPredType :: LHsType GhcRn -> TcM PredType tcLHsPredType pred = tc_lhs_pred typeLevelMode pred -tc_hs_context :: TcTyMode -> LHsContext GhcRn -> TcM [PredType]-tc_hs_context mode ctxt = mapM (tc_lhs_pred mode) (unLoc ctxt)+tc_hs_context :: TcTyMode -> Maybe (LHsContext GhcRn) -> TcM [PredType]+tc_hs_context _ Nothing = return []+tc_hs_context mode (Just ctxt) = mapM (tc_lhs_pred mode) (unLoc ctxt) tc_lhs_pred :: TcTyMode -> LHsType GhcRn -> TcM PredType tc_lhs_pred mode pred = tc_lhs_type mode pred constraintKind@@ -2910,9 +2980,9 @@ ----------------------- newExpectedKind :: ContextKind -> TcM Kind-newExpectedKind (TheKind k) = return k-newExpectedKind AnyKind = newMetaKindVar-newExpectedKind OpenKind = newOpenTypeKind+newExpectedKind (TheKind k) = return k+newExpectedKind AnyKind = newMetaKindVar+newExpectedKind OpenKind = newOpenTypeKind ----------------------- expectedKindInCtxt :: UserTypeCtxt -> ContextKind@@ -2964,7 +3034,7 @@ -- HsOuterTyVarBndrs -------------------------------------- -bindOuterTKBndrsX :: OutputableBndrFlag flag+bindOuterTKBndrsX :: OutputableBndrFlag flag 'Renamed => SkolemMode -> HsOuterTyVarBndrs flag GhcRn -> TcM a@@ -3036,7 +3106,7 @@ -- sm_clone=False: see Note [Cloning for type variable binders] ----------------tcOuterTKBndrs :: OutputableBndrFlag flag+tcOuterTKBndrs :: OutputableBndrFlag flag 'Renamed => SkolemInfo -> HsOuterTyVarBndrs flag GhcRn -> TcM a -> TcM (HsOuterTyVarBndrs flag GhcTc, a)@@ -3044,7 +3114,7 @@ -- Do not clone the outer binders -- See Note [Cloning for type variable binder] under "must not" -tcOuterTKBndrsX :: OutputableBndrFlag flag+tcOuterTKBndrsX :: OutputableBndrFlag flag 'Renamed => SkolemMode -> SkolemInfo -> HsOuterTyVarBndrs flag GhcRn -> TcM a -> TcM (HsOuterTyVarBndrs flag GhcTc, a)@@ -3065,13 +3135,13 @@ -- Explicit tyvar binders -------------------------------------- -tcExplicitTKBndrs :: OutputableBndrFlag flag+tcExplicitTKBndrs :: OutputableBndrFlag flag 'Renamed => [LHsTyVarBndr flag GhcRn] -> TcM a -> TcM ([VarBndr TyVar flag], a) tcExplicitTKBndrs = tcExplicitTKBndrsX (smVanilla { sm_clone = True }) -tcExplicitTKBndrsX :: OutputableBndrFlag flag+tcExplicitTKBndrsX :: OutputableBndrFlag flag 'Renamed => SkolemMode -> [LHsTyVarBndr flag GhcRn] -> TcM a@@ -3097,7 +3167,7 @@ -- | Skolemise the 'HsTyVarBndr's in an 'HsForAllTelescope' with the supplied -- 'TcTyMode'. bindExplicitTKBndrs_Skol, bindExplicitTKBndrs_Tv- :: (OutputableBndrFlag flag)+ :: (OutputableBndrFlag flag 'Renamed) => [LHsTyVarBndr flag GhcRn] -> TcM a -> TcM ([VarBndr TyVar flag], a)@@ -3126,7 +3196,7 @@ hs_bndrs thing_inside -- sm_clone=False: see Note [Cloning for type variable binders] -bindExplicitTKBndrsX :: (OutputableBndrFlag flag)+bindExplicitTKBndrsX :: (OutputableBndrFlag flag 'Renamed) => SkolemMode -> [LHsTyVarBndr flag GhcRn] -> TcM a@@ -3204,6 +3274,12 @@ -- and emit an implication constraint with a ForAllSkol ic_info, -- so that it is subject to a telescope test. tcImplicitTKBndrsX skol_mode skol_info bndrs thing_inside+ | null bndrs -- Short-cut the common case with no quantifiers+ -- E.g. f :: Int -> Int+ -- makes a HsOuterImplicit with empty bndrs,+ -- and tcOuterTKBndrsX goes via here+ = do { res <- thing_inside; return ([], res) }+ | otherwise = do { (tclvl, wanted, (skol_tvs, res)) <- pushLevelAndCaptureConstraints $ bindImplicitTKBndrsX skol_mode bndrs $@@ -3581,6 +3657,22 @@ | DataInstanceSort NewOrData | DataFamilySort +-- | Local helper type used in 'checkDataKindSig'.+--+-- Superficially similar to 'ContextKind', but it lacks 'AnyKind'+-- and 'AnyBoxedKind', and instead of @'TheKind' liftedTypeKind@+-- provides 'LiftedKind', which is much simpler to match on and+-- handle in 'isAllowedDataResKind'.+data AllowedDataResKind+ = AnyTYPEKind+ | AnyBoxedKind+ | LiftedKind++isAllowedDataResKind :: AllowedDataResKind -> Kind -> Bool+isAllowedDataResKind AnyTYPEKind kind = tcIsRuntimeTypeKind kind+isAllowedDataResKind AnyBoxedKind kind = tcIsBoxedTypeKind kind+isAllowedDataResKind LiftedKind kind = tcIsLiftedTypeKind kind+ -- | Checks that the return kind in a data declaration's kind signature is -- permissible. There are three cases: --@@ -3605,7 +3697,7 @@ checkDataKindSig data_sort kind = do { dflags <- getDynFlags ; traceTc "checkDataKindSig" (ppr kind)- ; checkTc (is_TYPE_or_Type dflags || is_kind_var)+ ; checkTc (tYPE_ok dflags || is_kind_var) (err_msg dflags) } where res_kind = snd (tcSplitPiTys kind)@@ -3628,6 +3720,13 @@ DataInstanceSort new_or_data -> new_or_data == NewType DataFamilySort -> False + is_datatype :: Bool+ is_datatype =+ case data_sort of+ DataDeclSort DataType -> True+ DataInstanceSort DataType -> True+ _ -> False+ is_data_family :: Bool is_data_family = case data_sort of@@ -3635,27 +3734,30 @@ DataInstanceSort{} -> False DataFamilySort -> True - tYPE_ok :: DynFlags -> Bool- tYPE_ok dflags =- (is_newtype && xopt LangExt.UnliftedNewtypes dflags)- -- With UnliftedNewtypes, we allow kinds other than Type, but they- -- must still be of the form `TYPE r` since we don't want to accept- -- Constraint or Nat.- -- See Note [Implementation of UnliftedNewtypes] in GHC.Tc.TyCl.- || is_data_family- -- If this is a `data family` declaration, we don't need to check if- -- UnliftedNewtypes is enabled, since data family declarations can- -- have return kind `TYPE r` unconditionally (#16827).-- is_TYPE :: Bool- is_TYPE = tcIsRuntimeTypeKind res_kind-- is_Type :: Bool- is_Type = tcIsLiftedTypeKind res_kind+ allowed_kind :: DynFlags -> AllowedDataResKind+ allowed_kind dflags+ | is_newtype && xopt LangExt.UnliftedNewtypes dflags+ -- With UnliftedNewtypes, we allow kinds other than Type, but they+ -- must still be of the form `TYPE r` since we don't want to accept+ -- Constraint or Nat.+ -- See Note [Implementation of UnliftedNewtypes] in GHC.Tc.TyCl.+ = AnyTYPEKind+ | is_data_family+ -- If this is a `data family` declaration, we don't need to check if+ -- UnliftedNewtypes is enabled, since data family declarations can+ -- have return kind `TYPE r` unconditionally (#16827).+ = AnyTYPEKind+ | is_datatype && xopt LangExt.UnliftedDatatypes dflags+ -- With UnliftedDatatypes, we allow kinds other than Type, but they+ -- must still be of the form `TYPE (BoxedRep l)`, so that we don't+ -- accept result kinds like `TYPE IntRep`.+ -- See Note [Implementation of UnliftedDatatypes] in GHC.Tc.TyCl.+ = AnyBoxedKind+ | otherwise+ = LiftedKind - is_TYPE_or_Type :: DynFlags -> Bool- is_TYPE_or_Type dflags | tYPE_ok dflags = is_TYPE- | otherwise = is_Type+ tYPE_ok :: DynFlags -> Bool+ tYPE_ok dflags = isAllowedDataResKind (allowed_kind dflags) res_kind -- In the particular case of a data family, permit a return kind of the -- form `:: k` (where `k` is a bare kind variable).@@ -3663,18 +3765,33 @@ is_kind_var | is_data_family = isJust (tcGetCastedTyVar_maybe res_kind) | otherwise = False + pp_allowed_kind dflags =+ case allowed_kind dflags of+ AnyTYPEKind -> ppr tYPETyCon+ AnyBoxedKind -> ppr boxedRepDataConTyCon+ LiftedKind -> ppr liftedTypeKind+ err_msg :: DynFlags -> SDoc err_msg dflags =- sep [ (sep [ pp_dec <+>- text "has non-" <>- (if tYPE_ok dflags then text "TYPE" else ppr liftedTypeKind)- , (if is_data_family then text "and non-variable" else empty) <+>- text "return kind" <+> quotes (ppr res_kind) ])- , if not (tYPE_ok dflags) && is_TYPE && is_newtype &&- not (xopt LangExt.UnliftedNewtypes dflags)- then text "Perhaps you intended to use UnliftedNewtypes"- else empty ]+ sep [ sep [ pp_dec <+>+ text "has non-" <>+ pp_allowed_kind dflags+ , (if is_data_family then text "and non-variable" else empty) <+>+ text "return kind" <+> quotes (ppr kind) ]+ , ext_hint dflags ] + ext_hint dflags+ | tcIsRuntimeTypeKind kind+ , is_newtype+ , not (xopt LangExt.UnliftedNewtypes dflags)+ = text "Perhaps you intended to use UnliftedNewtypes"+ | tcIsBoxedTypeKind kind+ , is_datatype+ , not (xopt LangExt.UnliftedDatatypes dflags)+ = text "Perhaps you intended to use UnliftedDatatypes"+ | otherwise+ = empty+ -- | Checks that the result kind of a class is exactly `Constraint`, rejecting -- type synonyms and type families that reduce to `Constraint`. See #16826. checkClassKindSig :: Kind -> TcM ()@@ -3775,7 +3892,7 @@ tcHsPartialSigType ctxt sig_ty | HsWC { hswc_ext = sig_wcs, hswc_body = sig_ty } <- sig_ty , L _ (HsSig{sig_bndrs = hs_outer_bndrs, sig_body = body_ty}) <- sig_ty- , (L _ hs_ctxt, hs_tau) <- splitLHsQualTy body_ty+ , (hs_ctxt, hs_tau) <- splitLHsQualTy body_ty = addSigCtxt ctxt sig_ty $ do { mode <- mkHoleMode TypeLevel HM_Sig ; (outer_bndrs, (wcs, wcx, theta, tau))@@ -3829,11 +3946,12 @@ ; traceTc "tcHsPartialSigType" (ppr tv_prs) ; return (wcs, wcx, tv_prs, theta, tau) } -tcPartialContext :: TcTyMode -> HsContext GhcRn -> TcM (TcThetaType, Maybe TcType)-tcPartialContext mode hs_theta+tcPartialContext :: TcTyMode -> Maybe (LHsContext GhcRn) -> TcM (TcThetaType, Maybe TcType)+tcPartialContext _ Nothing = return ([], Nothing)+tcPartialContext mode (Just (L _ hs_theta)) | Just (hs_theta1, hs_ctxt_last) <- snocView hs_theta , L wc_loc ty@(HsWildCardTy _) <- ignoreParens hs_ctxt_last- = do { wc_tv_ty <- setSrcSpan wc_loc $+ = do { wc_tv_ty <- setSrcSpanA wc_loc $ tcAnonWildCardOcc YesExtraConstraint mode ty constraintKind ; theta <- mapM (tc_lhs_pred mode) hs_theta1 ; return (theta, Just wc_tv_ty) }
compiler/GHC/Tc/Gen/Match.hs view
@@ -1,4 +1,5 @@ {-# LANGUAGE CPP #-}+{-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE RecordWildCards #-}@@ -90,7 +91,7 @@ same number of arguments before using @tcMatches@ to do the work. -} -tcMatchesFun :: Located Name+tcMatchesFun :: LocatedN Name -> MatchGroup GhcRn (LHsExpr GhcRn) -> ExpRhoType -- Expected type of function -> TcM (HsWrapper, MatchGroup GhcTc (LHsExpr GhcTc))@@ -136,12 +137,12 @@ parser guarantees that each equation has exactly one argument. -} -tcMatchesCase :: (Outputable (body GhcRn)) =>- TcMatchCtxt body -- Case context- -> Scaled TcSigmaType -- Type of scrutinee- -> MatchGroup GhcRn (Located (body GhcRn)) -- The case alternatives+tcMatchesCase :: (AnnoBody body) =>+ TcMatchCtxt body -- Case context+ -> Scaled TcSigmaType -- Type of scrutinee+ -> MatchGroup GhcRn (LocatedA (body GhcRn)) -- The case alternatives -> ExpRhoType -- Type of whole case expressions- -> TcM (MatchGroup GhcTc (Located (body GhcTc)))+ -> TcM (MatchGroup GhcTc (LocatedA (body GhcTc))) -- Translated alternatives -- wrapper goes from MatchGroup's ty to expected ty @@ -174,6 +175,7 @@ -- desugar to incorrect code. tcGRHSs match_ctxt grhss res_ty where+ match_ctxt :: TcMatchCtxt HsExpr -- AZ match_ctxt = MC { mc_what = PatBindRhs, mc_body = tcBody } @@ -185,17 +187,29 @@ data TcMatchCtxt body -- c.f. TcStmtCtxt, also in this module = MC { mc_what :: HsMatchContext GhcRn, -- What kind of thing this is- mc_body :: Located (body GhcRn) -- Type checker for a body of+ mc_body :: LocatedA (body GhcRn) -- Type checker for a body of -- an alternative -> ExpRhoType- -> TcM (Located (body GhcTc)) }+ -> TcM (LocatedA (body GhcTc)) } +type AnnoBody body+ = ( Outputable (body GhcRn)+ , Anno (Match GhcRn (LocatedA (body GhcRn))) ~ SrcSpanAnnA+ , Anno (Match GhcTc (LocatedA (body GhcTc))) ~ SrcSpanAnnA+ , Anno [LocatedA (Match GhcRn (LocatedA (body GhcRn)))] ~ SrcSpanAnnL+ , Anno [LocatedA (Match GhcTc (LocatedA (body GhcTc)))] ~ SrcSpanAnnL+ , Anno (GRHS GhcRn (LocatedA (body GhcRn))) ~ SrcSpan+ , Anno (GRHS GhcTc (LocatedA (body GhcTc))) ~ SrcSpan+ , Anno (StmtLR GhcRn GhcRn (LocatedA (body GhcRn))) ~ SrcSpanAnnA+ , Anno (StmtLR GhcTc GhcTc (LocatedA (body GhcTc))) ~ SrcSpanAnnA+ )+ -- | Type-check a MatchGroup.-tcMatches :: (Outputable (body GhcRn)) => TcMatchCtxt body+tcMatches :: (AnnoBody body ) => TcMatchCtxt body -> [Scaled ExpSigmaType] -- Expected pattern types- -> ExpRhoType -- Expected result-type of the Match.- -> MatchGroup GhcRn (Located (body GhcRn))- -> TcM (MatchGroup GhcTc (Located (body GhcTc)))+ -> ExpRhoType -- Expected result-type of the Match.+ -> MatchGroup GhcRn (LocatedA (body GhcRn))+ -> TcM (MatchGroup GhcTc (LocatedA (body GhcTc))) tcMatches ctxt pat_tys rhs_ty (MG { mg_alts = L l matches , mg_origin = origin })@@ -221,21 +235,21 @@ , mg_origin = origin }) } --------------tcMatch :: (Outputable (body GhcRn)) => TcMatchCtxt body+tcMatch :: (AnnoBody body) => TcMatchCtxt body -> [Scaled ExpSigmaType] -- Expected pattern types -> ExpRhoType -- Expected result-type of the Match.- -> LMatch GhcRn (Located (body GhcRn))- -> TcM (LMatch GhcTc (Located (body GhcTc)))+ -> LMatch GhcRn (LocatedA (body GhcRn))+ -> TcM (LMatch GhcTc (LocatedA (body GhcTc))) tcMatch ctxt pat_tys rhs_ty match- = wrapLocM (tc_match ctxt pat_tys rhs_ty) match+ = wrapLocMA (tc_match ctxt pat_tys rhs_ty) match where tc_match ctxt pat_tys rhs_ty match@(Match { m_pats = pats, m_grhss = grhss }) = add_match_ctxt match $ do { (pats', grhss') <- tcPats (mc_what ctxt) pats pat_tys $ tcGRHSs ctxt grhss rhs_ty- ; return (Match { m_ext = noExtField+ ; return (Match { m_ext = noAnn , m_ctxt = mc_what ctxt, m_pats = pats' , m_grhss = grhss' }) } @@ -247,8 +261,9 @@ _ -> addErrCtxt (pprMatchInCtxt match) thing_inside --------------tcGRHSs :: TcMatchCtxt body -> GRHSs GhcRn (Located (body GhcRn)) -> ExpRhoType- -> TcM (GRHSs GhcTc (Located (body GhcTc)))+tcGRHSs :: AnnoBody body+ => TcMatchCtxt body -> GRHSs GhcRn (LocatedA (body GhcRn)) -> ExpRhoType+ -> TcM (GRHSs GhcTc (LocatedA (body GhcTc))) -- Notice that we pass in the full res_ty, so that we get -- good inference from simple things like@@ -256,23 +271,23 @@ -- We used to force it to be a monotype when there was more than one guard -- but we don't need to do that any more -tcGRHSs ctxt (GRHSs _ grhss (L l binds)) res_ty+tcGRHSs ctxt (GRHSs _ grhss binds) res_ty = do { (binds', ugrhss) <- tcLocalBinds binds $ mapM (tcCollectingUsage . wrapLocM (tcGRHS ctxt res_ty)) grhss ; let (usages, grhss') = unzip ugrhss ; tcEmitBindingUsage $ supUEs usages- ; return (GRHSs noExtField grhss' (L l binds')) }+ ; return (GRHSs noExtField grhss' binds') } --------------tcGRHS :: TcMatchCtxt body -> ExpRhoType -> GRHS GhcRn (Located (body GhcRn))- -> TcM (GRHS GhcTc (Located (body GhcTc)))+tcGRHS :: TcMatchCtxt body -> ExpRhoType -> GRHS GhcRn (LocatedA (body GhcRn))+ -> TcM (GRHS GhcTc (LocatedA (body GhcTc))) tcGRHS ctxt res_ty (GRHS _ guards rhs) = do { (guards', rhs') <- tcStmtsAndThen stmt_ctxt tcGuardStmt guards res_ty $ mc_body ctxt rhs- ; return (GRHS noExtField guards' rhs') }+ ; return (GRHS noAnn guards' rhs') } where stmt_ctxt = PatGuard (mc_what ctxt) @@ -285,7 +300,7 @@ -} tcDoStmts :: HsStmtContext GhcRn- -> Located [LStmt GhcRn (LHsExpr GhcRn)]+ -> LocatedL [LStmt GhcRn (LHsExpr GhcRn)] -> ExpRhoType -> TcM (HsExpr GhcTc) -- Returns a HsDo tcDoStmts ListComp (L l stmts) res_ty@@ -332,27 +347,27 @@ type TcStmtChecker body rho_type = forall thing. HsStmtContext GhcRn- -> Stmt GhcRn (Located (body GhcRn))+ -> Stmt GhcRn (LocatedA (body GhcRn)) -> rho_type -- Result type for comprehension -> (rho_type -> TcM thing) -- Checker for what follows the stmt- -> TcM (Stmt GhcTc (Located (body GhcTc)), thing)+ -> TcM (Stmt GhcTc (LocatedA (body GhcTc)), thing) -tcStmts :: (Outputable (body GhcRn)) => HsStmtContext GhcRn+tcStmts :: (AnnoBody body) => HsStmtContext GhcRn -> TcStmtChecker body rho_type -- NB: higher-rank type- -> [LStmt GhcRn (Located (body GhcRn))]+ -> [LStmt GhcRn (LocatedA (body GhcRn))] -> rho_type- -> TcM [LStmt GhcTc (Located (body GhcTc))]+ -> TcM [LStmt GhcTc (LocatedA (body GhcTc))] tcStmts ctxt stmt_chk stmts res_ty = do { (stmts', _) <- tcStmtsAndThen ctxt stmt_chk stmts res_ty $ const (return ()) ; return stmts' } -tcStmtsAndThen :: (Outputable (body GhcRn)) => HsStmtContext GhcRn+tcStmtsAndThen :: (AnnoBody body) => HsStmtContext GhcRn -> TcStmtChecker body rho_type -- NB: higher-rank type- -> [LStmt GhcRn (Located (body GhcRn))]+ -> [LStmt GhcRn (LocatedA (body GhcRn))] -> rho_type -> (rho_type -> TcM thing)- -> TcM ([LStmt GhcTc (Located (body GhcTc))], thing)+ -> TcM ([LStmt GhcTc (LocatedA (body GhcTc))], thing) -- Note the higher-rank type. stmt_chk is applied at different -- types in the equations for tcStmts@@ -362,11 +377,11 @@ ; return ([], thing) } -- LetStmts are handled uniformly, regardless of context-tcStmtsAndThen ctxt stmt_chk (L loc (LetStmt x (L l binds)) : stmts)+tcStmtsAndThen ctxt stmt_chk (L loc (LetStmt x binds) : stmts) res_ty thing_inside = do { (binds', (stmts',thing)) <- tcLocalBinds binds $ tcStmtsAndThen ctxt stmt_chk stmts res_ty thing_inside- ; return (L loc (LetStmt x (L l binds')) : stmts', thing) }+ ; return (L loc (LetStmt x binds') : stmts', thing) } -- Don't set the error context for an ApplicativeStmt. It ought to be -- possible to do this with a popErrCtxt in the tcStmt case for@@ -382,7 +397,7 @@ -- For the vanilla case, handle the location-setting part | otherwise = do { (stmt', (stmts', thing)) <-- setSrcSpan loc $+ setSrcSpanA loc $ addErrCtxt (pprStmtInCtxt ctxt stmt) $ stmt_chk ctxt stmt res_ty $ \ res_ty' -> popErrCtxt $@@ -686,7 +701,7 @@ --------------- Typecheck the 'fmap' function ------------- ; fmap_op' <- case form of ThenForm -> return noExpr- _ -> fmap unLoc . tcCheckPolyExpr (noLoc fmap_op) $+ _ -> fmap unLoc . tcCheckPolyExpr (noLocA fmap_op) $ mkInfForAllTy alphaTyVar $ mkInfForAllTy betaTyVar $ (alphaTy `mkVisFunTyMany` betaTy)@@ -758,7 +773,7 @@ (m_ty `mkAppTy` betaTy) `mkVisFunTyMany` (m_ty `mkAppTy` mkBoxedTupleTy [alphaTy, betaTy])- ; mzip_op' <- unLoc `fmap` tcCheckPolyExpr (noLoc mzip_op) mzip_ty+ ; mzip_op' <- unLoc `fmap` tcCheckPolyExpr (noLocA mzip_op) mzip_ty -- type dummies since we don't know all binder types yet ; id_tys_s <- (mapM . mapM) (const (newFlexiTyVarTy liftedTypeKind))@@ -872,7 +887,7 @@ ; return (rhs', rhs_ty, thing) } ; return (BodyStmt rhs_ty rhs' then_op' noSyntaxExpr, thing) } -tcDoStmt ctxt (RecStmt { recS_stmts = stmts, recS_later_ids = later_names+tcDoStmt ctxt (RecStmt { recS_stmts = L l stmts, recS_later_ids = later_names , recS_rec_ids = rec_names, recS_ret_fn = ret_op , recS_mfix_fn = mfix_op, recS_bind_fn = bind_op }) res_ty thing_inside@@ -914,7 +929,7 @@ ; later_ids <- tcLookupLocalIds later_names ; traceTc "tcdo" $ vcat [ppr rec_ids <+> ppr (map idType rec_ids), ppr later_ids <+> ppr (map idType later_ids)]- ; return (RecStmt { recS_stmts = stmts', recS_later_ids = later_ids+ ; return (RecStmt { recS_stmts = L l stmts', recS_later_ids = later_ids , recS_rec_ids = rec_ids, recS_ret_fn = ret_op' , recS_mfix_fn = mfix_op', recS_bind_fn = bind_op' , recS_ext = RecStmtTc@@ -1036,7 +1051,7 @@ , arg_expr = rhs , .. }, pat_ty, exp_ty)- = setSrcSpan (combineSrcSpans (getLoc pat) (getLoc rhs)) $+ = setSrcSpan (combineSrcSpans (getLocA pat) (getLocA rhs)) $ addErrCtxt (pprStmtInCtxt ctxt (mkRnBindStmt pat rhs)) $ do { rhs' <- tcCheckMonoExprNC rhs exp_ty ; (pat', _) <- tcCheckPat (StmtCtxt ctxt) pat (unrestricted pat_ty) $@@ -1103,7 +1118,8 @@ number of args are used in each equation. -} -checkArgs :: Name -> MatchGroup GhcRn body -> TcM ()+checkArgs :: AnnoBody body+ => Name -> MatchGroup GhcRn (LocatedA (body GhcRn)) -> TcM () checkArgs _ (MG { mg_alts = L _ [] }) = return () checkArgs fun (MG { mg_alts = L _ (match1:matches) })@@ -1112,11 +1128,11 @@ | otherwise = failWithTc (vcat [ text "Equations for" <+> quotes (ppr fun) <+> text "have different numbers of arguments"- , nest 2 (ppr (getLoc match1))- , nest 2 (ppr (getLoc (head bad_matches)))])+ , nest 2 (ppr (getLocA match1))+ , nest 2 (ppr (getLocA (head bad_matches)))]) where n_args1 = args_in_match match1 bad_matches = [m | m <- matches, args_in_match m /= n_args1] - args_in_match :: LMatch GhcRn body -> Int+ args_in_match :: (LocatedA (Match GhcRn body1) -> Int) args_in_match (L _ (Match { m_pats = pats })) = length pats
compiler/GHC/Tc/Gen/Match.hs-boot view
@@ -4,14 +4,14 @@ import GHC.Types.Name ( Name ) import GHC.Tc.Utils.TcType( ExpSigmaType, ExpRhoType ) import GHC.Tc.Types ( TcM )-import GHC.Types.SrcLoc ( Located ) import GHC.Hs.Extension ( GhcRn, GhcTc )+import GHC.Parser.Annotation ( LocatedN ) tcGRHSsPat :: GRHSs GhcRn (LHsExpr GhcRn) -> ExpRhoType -> TcM (GRHSs GhcTc (LHsExpr GhcTc)) -tcMatchesFun :: Located Name+tcMatchesFun :: LocatedN Name -> MatchGroup GhcRn (LHsExpr GhcRn) -> ExpSigmaType -> TcM (HsWrapper, MatchGroup GhcTc (LHsExpr GhcTc))
compiler/GHC/Tc/Gen/Pat.hs view
@@ -331,7 +331,7 @@ tc_lpat :: Scaled ExpSigmaType -> Checker (LPat GhcRn) (LPat GhcTc) tc_lpat pat_ty penv (L span pat) thing_inside- = setSrcSpan span $+ = setSrcSpanA span $ do { (pat', res) <- maybeWrapPatCtxt pat (tc_pat pat_ty penv pat) thing_inside ; return (L span pat', res) }@@ -400,7 +400,7 @@ AsPat x (L nm_loc name) pat -> do { mult_wrap <- checkManyPattern pat_ty -- See Note [Wrapper returned from tcSubMult] in GHC.Tc.Utils.Unify.- ; (wrap, bndr_id) <- setSrcSpan nm_loc (tcPatBndr penv name pat_ty)+ ; (wrap, bndr_id) <- setSrcSpanA nm_loc (tcPatBndr penv name pat_ty) ; (pat', res) <- tcExtendIdEnv1 name bndr_id $ tc_lpat (pat_ty `scaledSet`(mkCheckExpType $ idType bndr_id)) penv pat thing_inside@@ -532,8 +532,8 @@ -- pat_ty /= pat_ty iff coi /= IdCo possibly_mangled_result | gopt Opt_IrrefutableTuples dflags &&- isBoxed boxity = LazyPat noExtField (noLoc unmangled_result)- | otherwise = unmangled_result+ isBoxed boxity = LazyPat noExtField (noLocA unmangled_result)+ | otherwise = unmangled_result ; pat_ty <- readExpType (scaledThing pat_ty) ; ASSERT( con_arg_tys `equalLength` pats ) -- Syntactically enforced@@ -653,7 +653,7 @@ <- tcSyntaxOpGen orig minus [SynType pat_exp_ty, SynRho] SynAny $ \ [lit2_ty, var_ty] _ -> do { lit2' <- newOverloadedLit lit (mkCheckExpType lit2_ty)- ; (wrap, bndr_id) <- setSrcSpan nm_loc $+ ; (wrap, bndr_id) <- setSrcSpanA nm_loc $ tcPatBndr penv name (unrestricted $ mkCheckExpType var_ty) -- co :: var_ty ~ idType bndr_id @@ -854,7 +854,7 @@ -- MkT :: forall a b c. (a~[b]) => b -> c -> T a -- with scrutinee of type (T ty) -tcConPat :: PatEnv -> Located Name+tcConPat :: PatEnv -> LocatedN Name -> Scaled ExpSigmaType -- Type of the pattern -> HsConPatDetails GhcRn -> TcM a -> TcM (Pat GhcTc, a)@@ -867,7 +867,7 @@ pat_ty arg_pats thing_inside } -tcDataConPat :: PatEnv -> Located Name -> DataCon+tcDataConPat :: PatEnv -> LocatedN Name -> DataCon -> Scaled ExpSigmaType -- Type of the pattern -> HsConPatDetails GhcRn -> TcM a -> TcM (Pat GhcTc, a)@@ -886,7 +886,7 @@ ; pat_ty <- readExpType (scaledThing pat_ty_scaled) -- Add the stupid theta- ; setSrcSpan con_span $ addDataConStupidTheta data_con ctxt_res_tys+ ; setSrcSpanA con_span $ addDataConStupidTheta data_con ctxt_res_tys ; let all_arg_tys = eqSpecPreds eq_spec ++ theta ++ (map scaledThing arg_tys) ; checkExistentials ex_tvs all_arg_tys penv@@ -971,7 +971,7 @@ ; return (mkHsWrapPat wrap res_pat pat_ty, res) } } -tcPatSynPat :: PatEnv -> Located Name -> PatSyn+tcPatSynPat :: PatEnv -> LocatedN Name -> PatSyn -> Scaled ExpSigmaType -- Type of the pattern -> HsConPatDetails GhcRn -> TcM a -> TcM (Pat GhcTc, a)@@ -1246,14 +1246,14 @@ tc_field :: Checker (LHsRecField GhcRn (LPat GhcRn)) (LHsRecField GhcTc (LPat GhcTc)) tc_field penv- (L l (HsRecField (L loc (FieldOcc sel (L lr rdr))) pat pun))+ (L l (HsRecField ann (L loc (FieldOcc sel (L lr rdr))) pat pun)) thing_inside = do { sel' <- tcLookupId sel ; pat_ty <- setSrcSpan loc $ find_field_ty sel (occNameFS $ rdrNameOcc rdr) ; (pat', res) <- tcConArg penv (pat, pat_ty) thing_inside- ; return (L l (HsRecField (L loc (FieldOcc sel' (L lr rdr))) pat'- pun), res) }+ ; return (L l (HsRecField ann (L loc (FieldOcc sel' (L lr rdr))) pat'+ pun), res) } find_field_ty :: Name -> FieldLabelString -> TcM (Scaled TcType)
compiler/GHC/Tc/Gen/Rule.hs view
@@ -99,12 +99,12 @@ -} tcRules :: [LRuleDecls GhcRn] -> TcM [LRuleDecls GhcTc]-tcRules decls = mapM (wrapLocM tcRuleDecls) decls+tcRules decls = mapM (wrapLocMA tcRuleDecls) decls tcRuleDecls :: RuleDecls GhcRn -> TcM (RuleDecls GhcTc) tcRuleDecls (HsRules { rds_src = src , rds_rules = decls })- = do { tc_decls <- mapM (wrapLocM tcRule) decls+ = do { tc_decls <- mapM (wrapLocMA tcRule) decls ; return $ HsRules { rds_ext = noExtField , rds_src = src , rds_rules = tc_decls } }@@ -175,7 +175,7 @@ , rd_name = rname , rd_act = act , rd_tyvs = ty_bndrs -- preserved for ppr-ing- , rd_tmvs = map (noLoc . RuleBndr noExtField . noLoc)+ , rd_tmvs = map (noLoc . RuleBndr noAnn . noLocA) (qtkvs ++ tpl_ids) , rd_lhs = mkHsDictLet lhs_binds lhs' , rd_rhs = mkHsDictLet rhs_binds rhs' } }
compiler/GHC/Tc/Gen/Sig.hs view
@@ -187,13 +187,13 @@ ; return [TcIdSig sig] } tcTySig (L loc (TypeSig _ names sig_ty))- = setSrcSpan loc $- do { sigs <- sequence [ tcUserTypeSig loc sig_ty (Just name)+ = setSrcSpanA loc $+ do { sigs <- sequence [ tcUserTypeSig (locA loc) sig_ty (Just name) | L _ name <- names ] ; return (map TcIdSig sigs) } tcTySig (L loc (PatSynSig _ names sig_ty))- = setSrcSpan loc $+ = setSrcSpanA loc $ do { tpsigs <- sequence [ tcPatSynSig name sig_ty | L _ name <- names ] ; return (map TcPatSynSig tpsigs) }@@ -286,9 +286,9 @@ HsForAllTy { hst_tele = tele , hst_body = ty } -> no_anon_wc_tele tele && go ty- HsQualTy { hst_ctxt = L _ ctxt- , hst_body = ty } -> gos ctxt && go ty- HsSpliceTy _ (HsSpliced _ _ (HsSplicedTy ty)) -> go $ L noSrcSpan ty+ HsQualTy { hst_ctxt = ctxt+ , hst_body = ty } -> gos (fromMaybeContext ctxt) && go ty+ HsSpliceTy _ (HsSpliced _ _ (HsSplicedTy ty)) -> go $ L noSrcSpanA ty HsSpliceTy{} -> True HsTyLit{} -> True HsTyVar{} -> True@@ -595,11 +595,11 @@ -- and inl2 is a user NOINLINE pragma; we don't want to complain warn_multiple_inlines inl2 inls | otherwise- = setSrcSpan loc $- addWarnTc NoReason- (hang (text "Multiple INLINE pragmas for" <+> ppr poly_id)- 2 (vcat (text "Ignoring all but the first"- : map pp_inl (inl1:inl2:inls))))+ = setSrcSpanA loc $+ addDiagnosticTc WarningWithoutFlag+ (hang (text "Multiple INLINE pragmas for" <+> ppr poly_id)+ 2 (vcat (text "Ignoring all but the first"+ : map pp_inl (inl1:inl2:inls)))) pp_inl (L loc prag) = ppr prag <+> parens (ppr loc) @@ -721,17 +721,17 @@ tcSpecPrags poly_id prag_sigs = do { traceTc "tcSpecPrags" (ppr poly_id <+> ppr spec_sigs) ; unless (null bad_sigs) warn_discarded_sigs- ; pss <- mapAndRecoverM (wrapLocM (tcSpecPrag poly_id)) spec_sigs- ; return $ concatMap (\(L l ps) -> map (L l) ps) pss }+ ; pss <- mapAndRecoverM (wrapLocMA (tcSpecPrag poly_id)) spec_sigs+ ; return $ concatMap (\(L l ps) -> map (L (locA l)) ps) pss } where spec_sigs = filter isSpecLSig prag_sigs bad_sigs = filter is_bad_sig prag_sigs is_bad_sig s = not (isSpecLSig s || isInlineLSig s || isSCCFunSig s) warn_discarded_sigs- = addWarnTc NoReason- (hang (text "Discarding unexpected pragmas for" <+> ppr poly_id)- 2 (vcat (map (ppr . getLoc) bad_sigs)))+ = addDiagnosticTc WarningWithoutFlag+ (hang (text "Discarding unexpected pragmas for" <+> ppr poly_id)+ 2 (vcat (map (ppr . getLoc) bad_sigs))) -------------- tcSpecPrag :: TcId -> Sig GhcRn -> TcM [TcSpecPrag]@@ -789,11 +789,11 @@ ; if (not_specialising dflags) then return [] else do- { pss <- mapAndRecoverM (wrapLocM tcImpSpec)+ { pss <- mapAndRecoverM (wrapLocMA tcImpSpec) [L loc (name,prag) | (L loc prag@(SpecSig _ (L _ name) _ _)) <- prags , not (nameIsLocalOrFrom this_mod name) ]- ; return $ concatMap (\(L l ps) -> map (L l) ps) pss } }+ ; return $ concatMap (\(L l ps) -> map (L (locA l)) ps) pss } } where -- Ignore SPECIALISE pragmas for imported things -- when we aren't specialising, or when we aren't generating@@ -812,7 +812,7 @@ ; if hasSomeUnfolding (realIdUnfolding id) -- See Note [SPECIALISE pragmas for imported Ids] then tcSpecPrag id prag- else do { addWarnTc NoReason (impSpecErr name)+ else do { addDiagnosticTc WarningWithoutFlag (impSpecErr name) ; return [] } } impSpecErr :: Name -> SDoc
compiler/GHC/Tc/Gen/Splice.hs view
@@ -68,6 +68,7 @@ import GHC.Builtin.Types import GHC.ThToHs+import GHC.HsToCore.Docs import GHC.HsToCore.Expr import GHC.HsToCore.Monad import GHC.IfaceToCore@@ -76,7 +77,6 @@ import GHCi.Message import GHCi.RemoteTypes import GHC.Runtime.Interpreter-import GHC.Runtime.Interpreter.Types import GHC.Rename.Splice( traceSplice, SpliceInfo(..)) import GHC.Rename.Expr@@ -122,7 +122,7 @@ import GHC.Utils.Outputable import GHC.Utils.Logger -import GHC.SysTools.FileCleanup ( newTempName, TempFileLifetime(..) )+import GHC.Utils.TmpFs ( newTempName, TempFileLifetime(..) ) import GHC.Data.FastString import GHC.Data.Maybe( MaybeErr(..) )@@ -147,6 +147,7 @@ import qualified Data.ByteString as B import qualified Data.ByteString.Lazy as LB import Data.Dynamic ( fromDynamic, toDyn )+import qualified Data.IntMap as IntMap import qualified Data.Map as Map import Data.Typeable ( typeOf, Typeable, TypeRep, typeRep ) import Data.Data (Data)@@ -213,7 +214,7 @@ rn_expr (unLoc (mkHsApp (mkLHsWrap (applyQuoteWrapper wrapper) (nlHsTyApp texpco [rep, expr_ty]))- (noLoc (HsTcBracketOut noExtField (Just wrapper) brack ps'))))+ (noLocA (HsTcBracketOut noExtField (Just wrapper) brack ps')))) meta_ty res_ty } tcTypedBracket _ other_brack _ = pprPanic "tcTypedBracket" (ppr other_brack)@@ -596,7 +597,7 @@ tcSpliceExpr splice@(HsTypedSplice _ _ name expr) res_ty = addErrCtxt (spliceCtxtDoc splice) $- setSrcSpan (getLoc expr) $ do+ setSrcSpan (getLocA expr) $ do { stage <- getStage ; case stage of Splice {} -> tcTopSplice expr res_ty@@ -643,7 +644,7 @@ -- But we still return a plausible expression -- (a) in case we print it in debug messages, and -- (b) because we test whether it is tagToEnum in Tc.Gen.Expr.tcApp- ; return (HsSpliceE noExtField $+ ; return (HsSpliceE noAnn $ HsSpliced noExtField (ThModFinalizers []) $ HsSplicedExpr (unLoc expr'')) } @@ -664,7 +665,7 @@ ; lcl_env <- getLclEnv ; let delayed_splice = DelayedSplice lcl_env expr res_ty q_expr- ; return (HsSpliceE noExtField (XSplice (HsSplicedT delayed_splice)))+ ; return (HsSpliceE noAnn (XSplice (HsSplicedT delayed_splice))) } @@ -774,10 +775,11 @@ -- LIE consulted by tcTopSpliceExpr -- and hence ensures the appropriate dictionary is bound by const_binds ; wrapper <- instCall AnnOrigin [expr_ty] [mkClassPred data_class [expr_ty]]+ ; let loc' = noAnnSrcSpan loc ; let specialised_to_annotation_wrapper_expr- = L loc (mkHsWrap wrapper- (HsVar noExtField (L loc to_annotation_wrapper_id)))- ; return (L loc (HsApp noExtField+ = L loc' (mkHsWrap wrapper+ (HsVar noExtField (L (noAnnSrcSpan loc) to_annotation_wrapper_id)))+ ; return (L loc' (HsApp noComments specialised_to_annotation_wrapper_expr expr')) }) @@ -794,11 +796,11 @@ convertAnnotationWrapper :: ForeignHValue -> TcM (Either SDoc Serialized) convertAnnotationWrapper fhv = do interp <- tcGetInterp- case interp of+ case interpInstance interp of ExternalInterp {} -> Right <$> runTH THAnnWrapper fhv #if defined(HAVE_INTERNAL_INTERPRETER) InternalInterp -> do- annotation_wrapper <- liftIO $ wormhole InternalInterp fhv+ annotation_wrapper <- liftIO $ wormhole interp fhv return $ Right $ case unsafeCoerce annotation_wrapper of AnnotationWrapper value | let serialized = toSerialized serializeWithData value ->@@ -833,7 +835,7 @@ withForeignRefs (x : xs) f = withForeignRef x $ \r -> withForeignRefs xs $ \rs -> f (r : rs) interp <- tcGetInterp- case interp of+ case interpInstance interp of #if defined(HAVE_INTERNAL_INTERPRETER) InternalInterp -> do qs <- liftIO (withForeignRefs finRefs $ mapM localRef)@@ -959,7 +961,7 @@ -- encounter them inside the try -- -- See Note [Exceptions in TH]- let expr_span = getLoc expr+ let expr_span = getLocA expr ; either_tval <- tryAllM $ setSrcSpan expr_span $ -- Set the span so that qLocation can -- see where this splice is@@ -1100,7 +1102,7 @@ -- 'msg' is forced to ensure exceptions don't escape, -- see Note [Exceptions in TH] qReport True msg = seqList msg $ addErr (text msg)- qReport False msg = seqList msg $ addWarn NoReason (text msg)+ qReport False msg = seqList msg $ addDiagnostic WarningWithoutFlag (text msg) qLocation = do { m <- getModule ; l <- getSrcSpanM@@ -1140,7 +1142,8 @@ qAddTempFile suffix = do dflags <- getDynFlags logger <- getLogger- liftIO $ newTempName logger dflags TFL_GhcSession suffix+ tmpfs <- hsc_tmpfs <$> getTopEnv+ liftIO $ newTempName logger tmpfs dflags TFL_GhcSession suffix qAddTopDecls thds = do l <- getSrcSpanM@@ -1189,7 +1192,10 @@ qAddCorePlugin plugin = do hsc_env <- getTopEnv- r <- liftIO $ findHomeModule hsc_env (mkModuleName plugin)+ let fc = hsc_FC hsc_env+ let home_unit = hsc_home_unit hsc_env+ let dflags = hsc_dflags hsc_env+ r <- liftIO $ findHomeModule fc home_unit dflags (mkModuleName plugin) let err = hang (text "addCorePlugin: invalid plugin module " <+> text (show plugin)@@ -1219,6 +1225,148 @@ qExtsEnabled = EnumSet.toList . extensionFlags . hsc_dflags <$> getTopEnv + qPutDoc doc_loc s = do+ th_doc_var <- tcg_th_docs <$> getGblEnv+ resolved_doc_loc <- resolve_loc doc_loc+ is_local <- checkLocalName resolved_doc_loc+ unless is_local $ failWithTc $ text+ "Can't add documentation to" <+> ppr_loc doc_loc <+>+ text "as it isn't inside the current module"+ updTcRef th_doc_var (Map.insert resolved_doc_loc s)+ where+ resolve_loc (TH.DeclDoc n) = DeclDoc <$> lookupThName n+ resolve_loc (TH.ArgDoc n i) = ArgDoc <$> lookupThName n <*> pure i+ resolve_loc (TH.InstDoc t) = InstDoc <$> fmap getName (lookupThInstName t)+ resolve_loc TH.ModuleDoc = pure ModuleDoc++ ppr_loc (TH.DeclDoc n) = ppr_th n+ ppr_loc (TH.ArgDoc n _) = ppr_th n+ ppr_loc (TH.InstDoc t) = ppr_th t+ ppr_loc TH.ModuleDoc = text "the module header"++ -- It doesn't make sense to add documentation to something not inside+ -- the current module. So check for it!+ checkLocalName (DeclDoc n) = nameIsLocalOrFrom <$> getModule <*> pure n+ checkLocalName (ArgDoc n _) = nameIsLocalOrFrom <$> getModule <*> pure n+ checkLocalName (InstDoc n) = nameIsLocalOrFrom <$> getModule <*> pure n+ checkLocalName ModuleDoc = pure True+++ qGetDoc (TH.DeclDoc n) = lookupThName n >>= lookupDeclDoc+ qGetDoc (TH.InstDoc t) = lookupThInstName t >>= lookupDeclDoc+ qGetDoc (TH.ArgDoc n i) = lookupThName n >>= lookupArgDoc i+ qGetDoc TH.ModuleDoc = do+ (moduleDoc, _, _) <- getGblEnv >>= extractDocs+ return (fmap unpackHDS moduleDoc)++-- | Looks up documentation for a declaration in first the current module,+-- otherwise tries to find it in another module via 'hscGetModuleInterface'.+lookupDeclDoc :: Name -> TcM (Maybe String)+lookupDeclDoc nm = do+ (_, DeclDocMap declDocs, _) <- getGblEnv >>= extractDocs+ fam_insts <- tcg_fam_insts <$> getGblEnv+ traceTc "lookupDeclDoc" (ppr nm <+> ppr declDocs <+> ppr fam_insts)+ case Map.lookup nm declDocs of+ Just doc -> pure $ Just (unpackHDS doc)+ Nothing -> do+ -- Wasn't in the current module. Try searching other external ones!+ mIface <- getExternalModIface nm+ case mIface of+ Nothing -> pure Nothing+ Just ModIface { mi_decl_docs = DeclDocMap dmap } ->+ pure $ unpackHDS <$> Map.lookup nm dmap++-- | Like 'lookupDeclDoc', looks up documentation for a function argument. If+-- it can't find any documentation for a function in this module, it tries to+-- find it in another module.+lookupArgDoc :: Int -> Name -> TcM (Maybe String)+lookupArgDoc i nm = do+ (_, _, ArgDocMap argDocs) <- getGblEnv >>= extractDocs+ case Map.lookup nm argDocs of+ Just m -> pure $ unpackHDS <$> IntMap.lookup i m+ Nothing -> do+ mIface <- getExternalModIface nm+ case mIface of+ Nothing -> pure Nothing+ Just ModIface { mi_arg_docs = ArgDocMap amap } ->+ pure $ unpackHDS <$> (Map.lookup nm amap >>= IntMap.lookup i)++-- | Returns the module a Name belongs to, if it is isn't local.+getExternalModIface :: Name -> TcM (Maybe ModIface)+getExternalModIface nm = do+ isLocal <- nameIsLocalOrFrom <$> getModule <*> pure nm+ if isLocal+ then pure Nothing+ else case nameModule_maybe nm of+ Nothing -> pure Nothing+ Just modNm -> do+ hsc_env <- getTopEnv+ iface <- liftIO $ hscGetModuleInterface hsc_env modNm+ pure (Just iface)++-- | Find the GHC name of the first instance that matches the TH type+lookupThInstName :: TH.Type -> TcM Name+lookupThInstName th_type = do+ cls_name <- inst_cls_name th_type+ insts <- reifyInstances' cls_name (inst_arg_types th_type)+ case insts of -- This expands any type synonyms+ Left (_, (inst:_)) -> return $ getName inst+ Left (_, []) -> noMatches+ Right (_, (inst:_)) -> return $ getName inst+ Right (_, []) -> noMatches+ where+ noMatches = failWithTc $+ text "Couldn't find any instances of"+ <+> ppr_th th_type+ <+> text "to add documentation to"++ -- | Get the name of the class for the instance we are documenting+ -- > inst_cls_name (Monad Maybe) == Monad+ -- > inst_cls_name C = C+ inst_cls_name :: TH.Type -> TcM TH.Name+ inst_cls_name (TH.AppT t _) = inst_cls_name t+ inst_cls_name (TH.SigT n _) = inst_cls_name n+ inst_cls_name (TH.VarT n) = pure n+ inst_cls_name (TH.ConT n) = pure n+ inst_cls_name (TH.PromotedT n) = pure n+ inst_cls_name (TH.InfixT _ n _) = pure n+ inst_cls_name (TH.UInfixT _ n _) = pure n+ inst_cls_name (TH.ParensT t) = inst_cls_name t++ inst_cls_name (TH.ForallT _ _ _) = inst_cls_name_err+ inst_cls_name (TH.ForallVisT _ _) = inst_cls_name_err+ inst_cls_name (TH.AppKindT _ _) = inst_cls_name_err+ inst_cls_name (TH.TupleT _) = inst_cls_name_err+ inst_cls_name (TH.UnboxedTupleT _) = inst_cls_name_err+ inst_cls_name (TH.UnboxedSumT _) = inst_cls_name_err+ inst_cls_name TH.ArrowT = inst_cls_name_err+ inst_cls_name TH.MulArrowT = inst_cls_name_err+ inst_cls_name TH.EqualityT = inst_cls_name_err+ inst_cls_name TH.ListT = inst_cls_name_err+ inst_cls_name (TH.PromotedTupleT _) = inst_cls_name_err+ inst_cls_name TH.PromotedNilT = inst_cls_name_err+ inst_cls_name TH.PromotedConsT = inst_cls_name_err+ inst_cls_name TH.StarT = inst_cls_name_err+ inst_cls_name TH.ConstraintT = inst_cls_name_err+ inst_cls_name (TH.LitT _) = inst_cls_name_err+ inst_cls_name TH.WildCardT = inst_cls_name_err+ inst_cls_name (TH.ImplicitParamT _ _) = inst_cls_name_err++ inst_cls_name_err = failWithTc $+ text "Couldn't work out what instance"+ <+> ppr_th th_type+ <+> text "is supposed to be"++ -- | Basically does the opposite of 'mkThAppTs'+ -- > inst_arg_types (Monad Maybe) == [Maybe]+ -- > inst_arg_types C == []+ inst_arg_types :: TH.Type -> [TH.Type]+ inst_arg_types (TH.AppT _ args) =+ let go (TH.AppT t ts) = t:go ts+ go t = [t]+ in go args+ inst_arg_types _ = []+ -- | Adds a mod finalizer reference to the local environment. addModFinalizerRef :: ForeignRef (TH.Q ()) -> TcM () addModFinalizerRef finRef = do@@ -1236,7 +1384,7 @@ finishTH :: TcM () finishTH = do hsc_env <- getTopEnv- case hsc_interp hsc_env of+ case interpInstance <$> hsc_interp hsc_env of Nothing -> pure () #if defined(HAVE_INTERNAL_INTERPRETER) Just InternalInterp -> pure ()@@ -1261,11 +1409,11 @@ runTH :: Binary a => THResultType -> ForeignHValue -> TcM a runTH ty fhv = do interp <- tcGetInterp- case interp of+ case interpInstance interp of #if defined(HAVE_INTERNAL_INTERPRETER) InternalInterp -> do -- Run it in the local TcM- hv <- liftIO $ wormhole InternalInterp fhv+ hv <- liftIO $ wormhole interp fhv r <- runQuasi (unsafeCoerce hv :: TH.Q a) return r #endif@@ -1290,7 +1438,7 @@ -- See Note [Remote Template Haskell] in libraries/ghci/GHCi/TH.hs. runRemoteTH :: IServInstance- -> [Messages DecoratedSDoc] -- saved from nested calls to qRecover+ -> [Messages DiagnosticMessage] -- saved from nested calls to qRecover -> TcM () runRemoteTH iserv recovers = do THMsg msg <- liftIO $ readIServ iserv getTHMessage@@ -1374,8 +1522,8 @@ case th_state of Just rhv -> return rhv Nothing -> do- hsc_env <- getTopEnv- fhv <- liftIO $ mkFinalizedHValue hsc_env =<< iservCall i StartTH+ interp <- tcGetInterp+ fhv <- liftIO $ mkFinalizedHValue interp =<< iservCall i StartTH writeTcRef (tcg_th_remote_state tcg) (Just fhv) return fhv @@ -1403,13 +1551,15 @@ AddDependentFile f -> wrapTHResult $ TH.qAddDependentFile f AddTempFile s -> wrapTHResult $ TH.qAddTempFile s AddModFinalizer r -> do- hsc_env <- getTopEnv- wrapTHResult $ liftIO (mkFinalizedHValue hsc_env r) >>= addModFinalizerRef+ interp <- hscInterp <$> getTopEnv+ wrapTHResult $ liftIO (mkFinalizedHValue interp r) >>= addModFinalizerRef AddCorePlugin str -> wrapTHResult $ TH.qAddCorePlugin str AddTopDecls decs -> wrapTHResult $ TH.qAddTopDecls decs AddForeignFilePath lang str -> wrapTHResult $ TH.qAddForeignFilePath lang str IsExtEnabled ext -> wrapTHResult $ TH.qIsExtEnabled ext ExtsEnabled -> wrapTHResult $ TH.qExtsEnabled+ PutDoc l s -> wrapTHResult $ TH.qPutDoc l s+ GetDoc l -> wrapTHResult $ TH.qGetDoc l FailIfErrs -> wrapTHResult failIfErrsM _ -> panic ("handleTHMessage: unexpected message " ++ show msg) @@ -1433,6 +1583,19 @@ reifyInstances :: TH.Name -> [TH.Type] -> TcM [TH.Dec] reifyInstances th_nm th_tys+ = do { insts <- reifyInstances' th_nm th_tys+ ; case insts of+ Left (cls, cls_insts) ->+ reifyClassInstances cls cls_insts+ Right (tc, fam_insts) ->+ reifyFamilyInstances tc fam_insts }++reifyInstances' :: TH.Name+ -> [TH.Type]+ -> TcM (Either (Class, [ClsInst]) (TyCon, [FamInst]))+ -- ^ Returns 'Left' in the case that the instances were found to+ -- be class instances, or 'Right' if they are family instances.+reifyInstances' th_nm th_tys = addErrCtxt (text "In the argument of reifyInstances:" <+> ppr_th th_nm <+> sep (map ppr_th th_tys)) $ do { loc <- getSrcSpanM@@ -1466,19 +1629,19 @@ -- In particular, the type might have kind -- variables inside it (#7477) - ; traceTc "reifyInstances" (ppr ty $$ ppr (tcTypeKind ty))+ ; traceTc "reifyInstances'" (ppr ty $$ ppr (tcTypeKind ty)) ; case splitTyConApp_maybe ty of -- This expands any type synonyms Just (tc, tys) -- See #7910 | Just cls <- tyConClass_maybe tc -> do { inst_envs <- tcGetInstEnvs ; let (matches, unifies, _) = lookupInstEnv False inst_envs cls tys- ; traceTc "reifyInstances1" (ppr matches)- ; reifyClassInstances cls (map fst matches ++ unifies) }+ ; traceTc "reifyInstances'1" (ppr matches)+ ; return $ Left (cls, map fst matches ++ unifies) } | isOpenFamilyTyCon tc -> do { inst_envs <- tcGetFamInstEnvs ; let matches = lookupFamInstEnv inst_envs tc tys- ; traceTc "reifyInstances2" (ppr matches)- ; reifyFamilyInstances tc (map fim_instance matches) }+ ; traceTc "reifyInstances'2" (ppr matches)+ ; return $ Right (tc, map fim_instance matches) } _ -> bale_out (hang (text "reifyInstances:" <+> quotes (ppr ty)) 2 (text "is not a class constraint or type family application")) } where
compiler/GHC/Tc/Instance/FunDeps.hs view
@@ -206,16 +206,11 @@ improveFromInstEnv :: InstEnvs -> (PredType -> SrcSpan -> loc)- -> PredType+ -> Class -> [Type] -> [FunDepEqn loc] -- Needs to be a FunDepEqn because -- of quantified variables -- Post: Equations oriented from the template (matching instance) to the workitem!-improveFromInstEnv inst_env mk_loc pred- | Just (cls, tys) <- ASSERT2( isClassPred pred, ppr pred )- getClassPredTys_maybe pred- , let (cls_tvs, cls_fds) = classTvsFds cls- instances = classInstances inst_env cls- rough_tcs = roughMatchTcs tys+improveFromInstEnv inst_env mk_loc cls tys = [ FDEqn { fd_qtvs = meta_tvs, fd_eqs = eqs , fd_pred1 = p_inst, fd_pred2 = pred , fd_loc = mk_loc p_inst (getSrcSpan (is_dfun ispec)) }@@ -231,7 +226,12 @@ tys trimmed_tcs -- NB: orientation , let p_inst = mkClassPred cls (is_tys ispec) ]-improveFromInstEnv _ _ _ = []+ where+ (cls_tvs, cls_fds) = classTvsFds cls+ instances = classInstances inst_env cls+ rough_tcs = roughMatchTcs tys+ pred = mkClassPred cls tys+ improveClsFD :: [TyVar] -> FunDep TyVar -- One functional dependency from the class
compiler/GHC/Tc/Instance/Typeable.hs view
@@ -4,8 +4,8 @@ -} {-# LANGUAGE CPP #-}-{-# LANGUAGE RecordWildCards #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-}+{-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} module GHC.Tc.Instance.Typeable(mkTypeableBinds, tyConIsTypeable) where@@ -28,7 +28,7 @@ import GHC.Builtin.Types.Prim ( primTyCons ) import GHC.Builtin.Types ( tupleTyCon, sumTyCon, runtimeRepTyCon- , vecCountTyCon, vecElemTyCon+ , levityTyCon, vecCountTyCon, vecElemTyCon , nilDataCon, consDataCon ) import GHC.Types.Name import GHC.Types.Id@@ -175,7 +175,7 @@ } } } where needs_typeable_binds tc- | tc `elem` [runtimeRepTyCon, vecCountTyCon, vecElemTyCon]+ | tc `elem` [runtimeRepTyCon, levityTyCon, vecCountTyCon, vecElemTyCon] = False | otherwise = isAlgTyCon tc@@ -351,7 +351,7 @@ -- Note [Built-in syntax and the OrigNameCache] in "GHC.Iface.Env" for more. ghcPrimTypeableTyCons :: [TyCon] ghcPrimTypeableTyCons = concat- [ [ runtimeRepTyCon, vecCountTyCon, vecElemTyCon ]+ [ [ runtimeRepTyCon, levityTyCon, vecCountTyCon, vecElemTyCon ] , map (tupleTyCon Unboxed) [0..mAX_TUPLE_SIZE] , map sumTyCon [2..mAX_SUM_SIZE] , primTyCons@@ -557,9 +557,9 @@ -> CmEnv -- ^ in-scope kind variables -> Kind -- ^ the kind we want a 'KindRep' for -> KindRepM (LHsExpr GhcTc) -- ^ RHS expression-mkKindRepRhs stuff@(Stuff {..}) in_scope = new_kind_rep+mkKindRepRhs stuff@(Stuff {..}) in_scope = new_kind_rep_shortcut where- new_kind_rep k+ new_kind_rep_shortcut k -- We handle (TYPE LiftedRep) etc separately to make it -- clear to consumers (e.g. serializers) that there is -- a loop here (as TYPE :: RuntimeRep -> TYPE 'LiftedRep)@@ -567,9 +567,20 @@ -- Typeable respects the Constraint/Type distinction -- so do not follow the special case here , Just arg <- kindRep_maybe k- , Just (tc, []) <- splitTyConApp_maybe arg- , Just dc <- isPromotedDataCon_maybe tc- = return $ nlHsDataCon kindRepTYPEDataCon `nlHsApp` nlHsDataCon dc+ = case splitTyConApp_maybe arg of+ Just (tc, [])+ | Just dc <- isPromotedDataCon_maybe tc+ -> return $ nlHsDataCon kindRepTYPEDataCon `nlHsApp` nlHsDataCon dc++ Just (rep, [levArg])+ | Just dcRep <- isPromotedDataCon_maybe rep+ , Just (lev, []) <- splitTyConApp_maybe levArg+ , Just dcLev <- isPromotedDataCon_maybe lev+ -> return $ nlHsDataCon kindRepTYPEDataCon `nlHsApp` (nlHsDataCon dcRep `nlHsApp` nlHsDataCon dcLev)++ _ -> new_kind_rep k+ | otherwise = new_kind_rep k+ new_kind_rep (TyVarTy v) | Just idx <- lookupCME in_scope v
compiler/GHC/Tc/Module.hs view
@@ -5,6 +5,7 @@ {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE FlexibleContexts #-}+{-# LANGUAGE MultiWayIf #-} {-# OPTIONS_GHC -Wno-incomplete-record-updates #-} @@ -57,7 +58,7 @@ import GHC.Tc.Gen.HsType import GHC.Tc.Validity( checkValidType ) import GHC.Tc.Gen.Match-import GHC.Tc.Utils.Unify( checkConstraints )+import GHC.Tc.Utils.Unify( checkConstraints, tcSubTypeSigma ) import GHC.Tc.Utils.Zonk import GHC.Tc.Gen.Expr import GHC.Tc.Gen.App( tcInferSigma )@@ -168,7 +169,7 @@ import GHC.Data.Bag import qualified GHC.Data.BooleanFormula as BF -import Data.List ( find, sortBy, sort )+import Data.List ( sortBy, sort ) import Data.Ord import Data.Data ( Data ) import qualified Data.Set as S@@ -190,7 +191,7 @@ -> ModSummary -> Bool -- True <=> save renamed syntax -> HsParsedModule- -> IO (Messages DecoratedSDoc, Maybe TcGblEnv)+ -> IO (Messages DiagnosticMessage, Maybe TcGblEnv) tcRnModule hsc_env mod_sum save_rn_syntax parsedModule@HsParsedModule {hpm_module= L loc this_module}@@ -211,7 +212,7 @@ dflags = hsc_dflags hsc_env logger = hsc_logger hsc_env home_unit = hsc_home_unit hsc_env- err_msg = mkPlainMsgEnvelope loc $+ err_msg = mkPlainMsgEnvelope ErrorWithoutFlag loc $ text "Module does not have a RealSrcSpan:" <+> ppr this_mod pair :: (Module, SrcSpan)@@ -235,7 +236,7 @@ tcRnModuleTcRnM hsc_env mod_sum (HsParsedModule { hpm_module =- (L loc (HsModule _ maybe_mod export_ies+ (L loc (HsModule _ _ maybe_mod export_ies import_decls local_decls mod_deprec maybe_doc_hdr)), hpm_src_files = src_files@@ -259,7 +260,7 @@ ; whenWOptM Opt_WarnImplicitPrelude $ when (notNull prel_imports) $- addWarn (Reason Opt_WarnImplicitPrelude) (implicitPreludeWarn)+ addDiagnostic (WarningWithFlag Opt_WarnImplicitPrelude) (implicitPreludeWarn) ; -- TODO This is a little skeevy; maybe handle a bit more directly let { simplifyImport (L _ idecl) =@@ -272,9 +273,9 @@ $ implicitRequirements hsc_env (map simplifyImport (prel_imports ++ import_decls))- ; let { mkImport (Nothing, L _ mod_name) = noLoc+ ; let { mkImport (Nothing, L _ mod_name) = noLocA $ (simpleImportDecl mod_name)- { ideclHiding = Just (False, noLoc [])}+ { ideclHiding = Just (False, noLocA [])} ; mkImport _ = panic "mkImport" } ; let { all_imports = prel_imports ++ import_decls ++ map mkImport (raw_sig_imports ++ raw_req_imports) }@@ -282,6 +283,14 @@ tcg_env <- {-# SCC "tcRnImports" #-} tcRnImports hsc_env all_imports + ; -- Don't need to rename the Haddock documentation,+ -- it's not parsed by GHC anymore.+ -- Make sure to do this before 'tcRnSrcDecls', because we need the+ -- module header when we're splicing TH, since it can be accessed via+ -- 'getDoc'.+ tcg_env <- return (tcg_env+ { tcg_doc_hdr = maybe_doc_hdr })+ ; -- If the whole module is warned about or deprecated -- (via mod_deprec) record that in tcg_warns. If we do thereby add -- a WarnAll, it will override any subsequent deprecations added to tcg_warns@@ -294,20 +303,22 @@ $ do { -- Rename and type check the declarations traceRn "rn1a" empty ; tcg_env <- if isHsBootOrSig hsc_src- then tcRnHsBootDecls hsc_src local_decls+ then do {+ ; tcg_env <- tcRnHsBootDecls hsc_src local_decls+ ; traceRn "rn4a: before exports" empty+ ; tcg_env <- setGblEnv tcg_env $+ rnExports explicit_mod_hdr export_ies+ ; traceRn "rn4b: after exports" empty+ ; return tcg_env+ } else {-# SCC "tcRnSrcDecls" #-}- tcRnSrcDecls explicit_mod_hdr local_decls export_ies+ tcRnSrcDecls explicit_mod_hdr export_ies local_decls ; whenM (goptM Opt_DoCoreLinting) $ lintGblEnv (hsc_logger hsc_env) (hsc_dflags hsc_env) tcg_env ; setGblEnv tcg_env- $ do { -- Process the export list- traceRn "rn4a: before exports" empty- ; tcg_env <- tcRnExports explicit_mod_hdr export_ies- tcg_env- ; traceRn "rn4b: after exports" empty- ; -- Compare hi-boot iface (if any) with the real thing+ $ do { -- Compare hi-boot iface (if any) with the real thing -- Must be done after processing the exports tcg_env <- checkHiBootIface tcg_env boot_info ; -- The new type env is already available to stuff@@ -317,13 +328,8 @@ -- because the latter might add new bindings for -- boot_dfuns, which may be mentioned in imported -- unfoldings.-- -- Don't need to rename the Haddock documentation,- -- it's not parsed by GHC anymore.- tcg_env <- return (tcg_env- { tcg_doc_hdr = maybe_doc_hdr })- ; -- Report unused names- -- Do this /after/ type inference, so that when reporting+ -- Report unused names+ -- Do this /after/ typeinference, so that when reporting -- a function with no type signature we can give the -- inferred type reportUnusedNames tcg_env hsc_src@@ -431,105 +437,117 @@ -} tcRnSrcDecls :: Bool -- False => no 'module M(..) where' header at all+ -> Maybe (LocatedL [LIE GhcPs]) -> [LHsDecl GhcPs] -- Declarations- -> Maybe (Located [LIE GhcPs]) -> TcM TcGblEnv-tcRnSrcDecls explicit_mod_hdr decls export_ies+tcRnSrcDecls explicit_mod_hdr export_ies decls = do { -- Do all the declarations ; (tcg_env, tcl_env, lie) <- tc_rn_src_decls decls - -- Check for the 'main' declaration- -- Must do this inside the captureTopConstraints- -- NB: always set envs *before* captureTopConstraints- ; (tcg_env, lie_main) <- setEnvs (tcg_env, tcl_env) $- captureTopConstraints $- checkMain explicit_mod_hdr export_ies-- ; setEnvs (tcg_env, tcl_env) $ do {-- -- Simplify constraints- --- -- We do this after checkMain, so that we use the type info- -- that checkMain adds- --- -- We do it with both global and local env in scope:- -- * the global env exposes the instances to simplifyTop- -- * the local env exposes the local Ids to simplifyTop,- -- so that we get better error messages (monomorphism restriction)+ ------ Simplify constraints ---------+ --+ -- We do this after checkMainType, so that we use the type+ -- info that checkMainType adds+ --+ -- We do it with both global and local env in scope:+ -- * the global env exposes the instances to simplifyTop,+ -- and affects how names are rendered in error messages+ -- * the local env exposes the local Ids to simplifyTop,+ -- so that we get better error messages (monomorphism restriction) ; new_ev_binds <- {-# SCC "simplifyTop" #-}- simplifyTop (lie `andWC` lie_main)+ setEnvs (tcg_env, tcl_env) $+ do { lie_main <- checkMainType tcg_env+ ; simplifyTop (lie `andWC` lie_main) } -- Emit Typeable bindings- ; tcg_env <- mkTypeableBinds-+ ; tcg_env <- setGblEnv tcg_env $+ mkTypeableBinds ; traceTc "Tc9" empty - ; failIfErrsM -- Don't zonk if there have been errors- -- It's a waste of time; and we may get debug warnings- -- about strangely-typed TyCons!- ; traceTc "Tc10" empty- -- Zonk the final code. This must be done last. -- Even simplifyTop may do some unification. -- This pass also warns about missing type signatures- ; (bind_env, ev_binds', binds', fords', imp_specs', rules')+ ; (id_env, ev_binds', binds', fords', imp_specs', rules') <- zonkTcGblEnv new_ev_binds tcg_env - -- Finalizers must run after constraints are simplified, or some types- -- might not be complete when using reify (see #12777).- -- and also after we zonk the first time because we run typed splices- -- in the zonker which gives rise to the finalisers.- ; (tcg_env_mf, _) <- setGblEnv (clearTcGblEnv tcg_env)- run_th_modfinalizers+ --------- Run finalizers --------------+ -- Finalizers must run after constraints are simplified, lest types+ -- might not be complete when using reify (see #12777).+ -- and also after we zonk the first time because we run typed splices+ -- in the zonker which gives rise to the finalisers.+ ; let -- init_tcg_env:+ -- * Remove accumulated bindings, rules and so on from+ -- TcGblEnv. They are now in ev_binds', binds', etc.+ -- * Add the zonked Ids from the value bindings to tcg_type_env+ -- Up to now these Ids are only in tcl_env's type-envt+ init_tcg_env = tcg_env { tcg_binds = emptyBag+ , tcg_ev_binds = emptyBag+ , tcg_imp_specs = []+ , tcg_rules = []+ , tcg_fords = []+ , tcg_type_env = tcg_type_env tcg_env+ `plusTypeEnv` id_env }+ ; (tcg_env, tcl_env) <- setGblEnv init_tcg_env+ run_th_modfinalizers ; finishTH ; traceTc "Tc11" empty - ; -- zonk the new bindings arising from running the finalisers.- -- This won't give rise to any more finalisers as you can't nest- -- finalisers inside finalisers.- ; (bind_env_mf, ev_binds_mf, binds_mf, fords_mf, imp_specs_mf, rules_mf)- <- zonkTcGblEnv emptyBag tcg_env_mf+ --------- Deal with the exports ----------+ -- Can't be done earlier, because the export list must "see"+ -- the declarations created by the finalizers+ ; tcg_env <- setEnvs (tcg_env, tcl_env) $+ rnExports explicit_mod_hdr export_ies - -- Force this or we retain an old reference to the previous- -- tcg_env- ; let { !final_type_env = plusTypeEnv (tcg_type_env tcg_env)- (plusTypeEnv bind_env_mf bind_env)- ; tcg_env' = tcg_env_mf- { tcg_binds = binds' `unionBags` binds_mf,- tcg_ev_binds = ev_binds' `unionBags` ev_binds_mf ,- tcg_imp_specs = imp_specs' ++ imp_specs_mf ,- tcg_rules = rules' ++ rules_mf ,- tcg_fords = fords' ++ fords_mf } } ;+ --------- Emit the ':Main.main = runMainIO main' declaration ----------+ -- Do this /after/ rnExports, so that it can consult+ -- the tcg_exports created by rnExports+ ; (tcg_env, main_ev_binds)+ <- setEnvs (tcg_env, tcl_env) $+ do { (tcg_env, lie) <- captureTopConstraints $+ checkMain explicit_mod_hdr export_ies+ ; ev_binds <- simplifyTop lie+ ; return (tcg_env, ev_binds) } - ; setGlobalTypeEnv tcg_env' final_type_env+ ---------- Final zonking ---------------+ -- Zonk the new bindings arising from running the finalisers,+ -- and main. This won't give rise to any more finalisers as you+ -- can't nest finalisers inside finalisers.+ ; (id_env_mf, ev_binds_mf, binds_mf, fords_mf, imp_specs_mf, rules_mf)+ <- zonkTcGblEnv main_ev_binds tcg_env - } }+ ; let { !final_type_env = tcg_type_env tcg_env+ `plusTypeEnv` id_env_mf+ -- Add the zonked Ids from the value bindings (they were in tcl_env)+ -- Force !final_type_env, lest we retain an old reference+ -- to the previous tcg_env + ; tcg_env' = tcg_env+ { tcg_binds = binds' `unionBags` binds_mf+ , tcg_ev_binds = ev_binds' `unionBags` ev_binds_mf+ , tcg_imp_specs = imp_specs' ++ imp_specs_mf+ , tcg_rules = rules' ++ rules_mf+ , tcg_fords = fords' ++ fords_mf } } ;++ ; setGlobalTypeEnv tcg_env' final_type_env+ }+ zonkTcGblEnv :: Bag EvBind -> TcGblEnv -> TcM (TypeEnv, Bag EvBind, LHsBinds GhcTc, [LForeignDecl GhcTc], [LTcSpecPrag], [LRuleDecl GhcTc])-zonkTcGblEnv new_ev_binds tcg_env =- let TcGblEnv { tcg_binds = binds,- tcg_ev_binds = cur_ev_binds,- tcg_imp_specs = imp_specs,- tcg_rules = rules,- tcg_fords = fords } = tcg_env-- all_ev_binds = cur_ev_binds `unionBags` new_ev_binds-- in {-# SCC "zonkTopDecls" #-}- zonkTopDecls all_ev_binds binds rules imp_specs fords----- | Remove accumulated bindings, rules and so on from TcGblEnv-clearTcGblEnv :: TcGblEnv -> TcGblEnv-clearTcGblEnv tcg_env- = tcg_env { tcg_binds = emptyBag,- tcg_ev_binds = emptyBag ,- tcg_imp_specs = [],- tcg_rules = [],- tcg_fords = [] }+zonkTcGblEnv ev_binds tcg_env@(TcGblEnv { tcg_binds = binds+ , tcg_ev_binds = cur_ev_binds+ , tcg_imp_specs = imp_specs+ , tcg_rules = rules+ , tcg_fords = fords })+ = {-# SCC "zonkTopDecls" #-}+ setGblEnv tcg_env $ -- This sets the GlobalRdrEnv which is used when rendering+ -- error messages during zonking (notably levity errors)+ do { failIfErrsM -- Don't zonk if there have been errors+ -- It's a waste of time; and we may get debug warnings+ -- about strangely-typed TyCons!+ ; let all_ev_binds = cur_ev_binds `unionBags` ev_binds+ ; zonkTopDecls all_ev_binds binds rules imp_specs fords } -- | Runs TH finalizers and renames and typechecks the top-level declarations -- that they could introduce.@@ -589,7 +607,7 @@ ; case th_group_tail of { Nothing -> return () ; Just (SpliceDecl _ (L loc _) _, _) ->- setSrcSpan loc+ setSrcSpanA loc $ addErr (text ("Declaration splices are not " ++ "permitted inside top-level "@@ -633,12 +651,9 @@ ; (spliced_decls, splice_fvs) <- rnTopSpliceDecls splice -- Glue them on the front of the remaining decls and loop- ; (tcg_env, tcl_env, lie2) <-- setGblEnv (tcg_env `addTcgDUs` usesOnly splice_fvs) $- addTopEvBinds ev_binds1 $- tc_rn_src_decls (spliced_decls ++ rest_ds)-- ; return (tcg_env, tcl_env, lie2)+ ; setGblEnv (tcg_env `addTcgDUs` usesOnly splice_fvs) $+ addTopEvBinds ev_binds1 $+ tc_rn_src_decls (spliced_decls ++ rest_ds) } } }@@ -713,9 +728,9 @@ }}} ; traceTc "boot" (ppr lie); return gbl_env } -badBootDecl :: HscSource -> String -> Located decl -> TcM ()+badBootDecl :: HscSource -> String -> LocatedA decl -> TcM () badBootDecl hsc_src what (L loc _)- = addErrAt loc (char 'A' <+> text what+ = addErrAt (locA loc) (char 'A' <+> text what <+> text "declaration is not (currently) allowed in a" <+> (case hsc_src of HsBootFile -> text "hs-boot"@@ -1577,7 +1592,7 @@ ; traceTc "tcPreludeClashWarn/prelude_functions" (hang (ppr name) 4 (sep [ppr clashingElts])) - ; let warn_msg x = addWarnAt (Reason warnFlag) (nameSrcSpan (greMangledName x)) (hsep+ ; let warn_msg x = addDiagnosticAt (WarningWithFlag warnFlag) (nameSrcSpan (greMangledName x)) (hsep [ text "Local definition of" , (quotes . ppr . nameOccName . greMangledName) x , text "clashes with a future Prelude name." ]@@ -1688,7 +1703,7 @@ -- <should>" e.g. "Foo is an instance of Monad but not Applicative" ; let instLoc = srcLocSpan . nameSrcLoc $ getName isInst warnMsg (KnownTc name:_) =- addWarnAt (Reason warnFlag) instLoc $+ addDiagnosticAt (WarningWithFlag warnFlag) instLoc $ hsep [ (quotes . ppr . nameOccName) name , text "is an instance of" , (ppr . nameOccName . className) isClass@@ -1747,246 +1762,248 @@ ************************************************************************ -} -checkMain :: Bool -- False => no 'module M(..) where' header at all- -> Maybe (Located [LIE GhcPs]) -- Export specs of Main module- -> TcM TcGblEnv--- If we are in module Main, check that 'main' is defined and exported.-checkMain explicit_mod_hdr export_ies- = do { hsc_env <- getTopEnv- ; tcg_env <- getGblEnv- ; check_main hsc_env tcg_env explicit_mod_hdr export_ies }--check_main :: HscEnv -> TcGblEnv -> Bool -> Maybe (Located [LIE GhcPs])- -> TcM TcGblEnv-check_main hsc_env tcg_env explicit_mod_hdr export_ies- | mod /= main_mod- = traceTc "checkMain not" (ppr main_mod <+> ppr mod) >>- return tcg_env+checkMainType :: TcGblEnv -> TcRn WantedConstraints+-- If this is the Main module, and it defines a function main,+-- check that its type is of form IO tau.+-- If not, do nothing+-- See Note [Dealing with main]+checkMainType tcg_env+ = do { hsc_env <- getTopEnv+ ; if tcg_mod tcg_env /= mainModIs hsc_env+ then return emptyWC else - | otherwise- -- Compare the list of main functions in scope with those- -- specified in the export list.- = do mains_all <- lookupInfoOccRn main_fn- -- get all 'main' functions in scope- -- They may also be imported from other modules!- case exportedMains of -- check the main(s) specified in the export list- [ ] -> do- -- The module has no main functions in the export spec, so we must give- -- some kind of error message. The tricky part is giving an error message- -- that accurately characterizes what the problem is.- -- See Note [Main module without a main function in the export spec]- traceTc "checkMain no main module exported" ppr_mod_mainfn- complain_no_main- -- In order to reduce the number of potential error messages, we check- -- to see if there are any main functions defined (but not exported)...- case getSomeMain mains_all of- Nothing -> return tcg_env- -- ...if there are no such main functions, there is nothing we can do...- Just some_main -> use_as_main some_main- -- ...if there is such a main function, then communicate this to the- -- typechecker. This can prevent a spurious "Ambiguous type variable"- -- error message in certain cases, as described in- -- Note [Main module without a main function in the export spec].- _ -> do -- The module has one or more main functions in the export spec- let mains = filterInsMains exportedMains mains_all- case mains of- [] -> do --- traceTc "checkMain fail" ppr_mod_mainfn- complain_no_main- return tcg_env- [main_name] -> use_as_main main_name- _ -> do -- multiple main functions are exported- addAmbiguousNameErr main_fn -- issue error msg- return tcg_env- where- dflags = hsc_dflags hsc_env- mod = tcg_mod tcg_env- main_mod = mainModIs hsc_env- main_mod_nm = moduleName main_mod- main_fn = getMainFun dflags- occ_main_fn = occName main_fn- interactive = ghcLink dflags == LinkInMemory- exportedMains = selExportMains export_ies- ppr_mod_mainfn = ppr main_mod <+> ppr main_fn+ do { rdr_env <- getGlobalRdrEnv+ ; let dflags = hsc_dflags hsc_env+ main_occ = getMainOcc dflags+ main_gres = lookupGlobalRdrEnv rdr_env main_occ+ ; case filter isLocalGRE main_gres of {+ [] -> return emptyWC ;+ (_:_:_) -> return emptyWC ;+ [main_gre] -> - -- There is a single exported 'main' function.- use_as_main :: Name -> TcM TcGblEnv- use_as_main main_name = do- { traceTc "checkMain found" (ppr main_mod <+> ppr main_fn)- ; let loc = srcLocSpan (getSrcLoc main_name)- ; ioTyCon <- tcLookupTyCon ioTyConName- ; res_ty <- newFlexiTyVarTy liftedTypeKind- ; let io_ty = mkTyConApp ioTyCon [res_ty]- skol_info = SigSkol (FunSigCtxt main_name False) io_ty []- main_expr_rn = L loc (HsVar noExtField (L loc main_name))- ; (ev_binds, main_expr)- <- checkConstraints skol_info [] [] $- addErrCtxt mainCtxt $- tcCheckMonoExpr main_expr_rn io_ty+ do { let main_name = greMangledName main_gre+ ctxt = FunSigCtxt main_name False+ ; main_id <- tcLookupId main_name+ ; (io_ty,_) <- getIOType+ ; (_, lie) <- captureTopConstraints $+ setMainCtxt main_name io_ty $+ tcSubTypeSigma ctxt (idType main_id) io_ty+ ; return lie } } } } - -- See Note [Root-main Id]- -- Construct the binding- -- :Main.main :: IO res_ty = runMainIO res_ty main- ; run_main_id <- tcLookupId runMainIOName- ; let { root_main_name = mkExternalName rootMainKey rOOT_MAIN- (mkVarOccFS (fsLit "main"))- (getSrcSpan main_name)- ; root_main_id = Id.mkExportedVanillaId root_main_name- (mkTyConApp ioTyCon [res_ty])- ; co = mkWpTyApps [res_ty]- -- The ev_binds of the `main` function may contain deferred- -- type error when type of `main` is not `IO a`. The `ev_binds`- -- must be put inside `runMainIO` to ensure the deferred type- -- error can be emitted correctly. See #13838.- ; rhs = nlHsApp (mkLHsWrap co (nlHsVar run_main_id)) $- mkHsDictLet ev_binds main_expr- ; main_bind = mkVarBind root_main_id rhs }+checkMain :: Bool -- False => no 'module M(..) where' header at all+ -> Maybe (LocatedL [LIE GhcPs]) -- Export specs of Main module+ -> TcM TcGblEnv+-- If we are in module Main, check that 'main' is exported,+-- and generate the runMainIO binding that calls it+-- See Note [Dealing with main]+checkMain explicit_mod_hdr export_ies+ = do { hsc_env <- getTopEnv+ ; tcg_env <- getGblEnv - ; return (tcg_env { tcg_main = Just main_name,- tcg_binds = tcg_binds tcg_env- `snocBag` main_bind,- tcg_dus = tcg_dus tcg_env- `plusDU` usesOnly (unitFV main_name)- -- Record the use of 'main', so that we don't- -- complain about it being defined but not used- })}+ ; let dflags = hsc_dflags hsc_env+ main_mod = mainModIs hsc_env+ main_occ = getMainOcc dflags - complain_no_main = unless (interactive && not explicit_mod_hdr)- (addErrTc noMainMsg) -- #12906- -- Without an explicit module header...- -- in interactive mode, don't worry about the absence of 'main'.- -- in other modes, add error message and go on with typechecking.+ exported_mains :: [Name]+ -- Exported things that are called 'main'+ exported_mains = [ name | avail <- tcg_exports tcg_env+ , name <- availNames avail+ , nameOccName name == main_occ ] - mainCtxt = text "When checking the type of the" <+> pp_main_fn- noMainMsg = text "The" <+> pp_main_fn- <+> text "is not" <+> text defOrExp <+> text "module"- <+> quotes (ppr main_mod)- defOrExp = if null exportedMains then "exported by" else "defined in"+ ; if | tcg_mod tcg_env /= main_mod+ -> -- Not the main module+ return tcg_env - pp_main_fn = ppMainFn main_fn+ | [main_name] <- exported_mains+ -> -- The module indeed exports a function called 'main'+ generateMainBinding tcg_env main_name - -- Select the main functions from the export list.- -- Only the module name is needed, the function name is fixed.- selExportMains :: Maybe (Located [LIE GhcPs]) -> [ModuleName] -- #16453- selExportMains Nothing = [main_mod_nm]- -- no main specified, but there is a header.- selExportMains (Just exps) = fmap fst $- filter (\(_,n) -> n == occ_main_fn ) texp+ | otherwise+ -> ASSERT( null exported_mains )+ -- A fully-checked export list can't contain more+ -- than one function with the same OccName+ do { complain_no_main dflags main_mod main_occ+ ; return tcg_env } }+ where+ complain_no_main dflags main_mod main_occ+ = unless (interactive && not explicit_mod_hdr) $+ addErrTc (noMainMsg main_mod main_occ) -- #12906 where- ies = fmap unLoc $ unLoc exps- texp = mapMaybe transExportIE ies-- -- Filter all main functions in scope that match the export specs- filterInsMains :: [ModuleName] -> [Name] -> [Name] -- #16453- filterInsMains export_mains inscope_mains =- [mod | mod <- inscope_mains,- (moduleName . nameModule) mod `elem` export_mains]+ interactive = ghcLink dflags == LinkInMemory+ -- Without an explicit module header...+ -- in interactive mode, don't worry about the absence of 'main'.+ -- in other modes, add error message and go on with typechecking. - -- Transform an export_ie to a (ModuleName, OccName) pair.- -- 'IEVar' constructors contain exported values (functions), eg '(Main.main)'- -- 'IEModuleContents' constructors contain fully exported modules, eg '(Main)'- -- All other 'IE...' constructors are not used and transformed to Nothing.- transExportIE :: IE GhcPs -> Maybe (ModuleName, OccName) -- #16453- transExportIE (IEVar _ var) = isQual_maybe $- upqual $ ieWrappedName $ unLoc var- where- -- A module name is always needed, so qualify 'UnQual' rdr names.- upqual (Unqual occ) = Qual main_mod_nm occ- upqual rdr = rdr- transExportIE (IEModuleContents _ mod) = Just (unLoc mod, occ_main_fn)- transExportIE _ = Nothing+ noMainMsg main_mod main_occ+ = text "The" <+> ppMainFn main_occ+ <+> text "is not" <+> text defOrExp <+> text "module"+ <+> quotes (ppr main_mod) - -- Get a main function that is in scope.- -- See Note [Main module without a main function in the export spec]- getSomeMain :: [Name] -> Maybe Name -- #16453- getSomeMain all_mains = case all_mains of- [] -> Nothing -- No main function in scope- [m] -> Just m -- Just one main function in scope- _ -> case mbMainOfMain of- Nothing -> listToMaybe all_mains -- Take the first main function in scope or Nothing- _ -> mbMainOfMain -- Take the Main module's main function or Nothing- where- mbMainOfMain = find (\n -> (moduleName . nameModule) n == main_mod_nm )- all_mains -- the main function of the Main module+ defOrExp | explicit_export_list = "exported by"+ | otherwise = "defined in"+ explicit_export_list = explicit_mod_hdr && isJust export_ies -- | Get the unqualified name of the function to use as the \"main\" for the main module. -- Either returns the default name or the one configured on the command line with -main-is-getMainFun :: DynFlags -> RdrName-getMainFun dflags = case mainFunIs dflags of- Just fn -> mkRdrUnqual (mkVarOccFS (mkFastString fn))- Nothing -> main_RDR_Unqual+getMainOcc :: DynFlags -> OccName+getMainOcc dflags = case mainFunIs dflags of+ Just fn -> mkVarOccFS (mkFastString fn)+ Nothing -> mainOcc -ppMainFn :: RdrName -> SDoc-ppMainFn main_fn- | rdrNameOcc main_fn == mainOcc- = text "IO action" <+> quotes (ppr main_fn)+ppMainFn :: OccName -> SDoc+ppMainFn main_occ+ | main_occ == mainOcc+ = text "IO action" <+> quotes (ppr main_occ) | otherwise- = text "main IO action" <+> quotes (ppr main_fn)+ = text "main IO action" <+> quotes (ppr main_occ) mainOcc :: OccName mainOcc = mkVarOccFS (fsLit "main") -{--Note [Root-main Id]-~~~~~~~~~~~~~~~~~~~-The function that the RTS invokes is always :Main.main, which we call-root_main_id. (Because GHC allows the user to have a module not-called Main as the main module, we can't rely on the main function-being called "Main.main". That's why root_main_id has a fixed module-":Main".)+generateMainBinding :: TcGblEnv -> Name -> TcM TcGblEnv+-- There is a single exported 'main' function, called 'foo' (say),+-- which may be locally defined or imported+-- Define and typecheck the binding+-- :Main.main :: IO res_ty = runMainIO res_ty foo+-- This wraps the user's main function in the top-level stuff+-- defined in runMainIO (eg catching otherwise un-caught exceptions)+-- See Note [Dealing with main]+generateMainBinding tcg_env main_name = do+ { traceTc "checkMain found" (ppr main_name)+ ; (io_ty, res_ty) <- getIOType+ ; let loc = getSrcSpan main_name+ main_expr_rn = L (noAnnSrcSpan loc) (HsVar noExtField (L (noAnnSrcSpan loc) main_name))+ ; (ev_binds, main_expr) <- setMainCtxt main_name io_ty $+ tcCheckMonoExpr main_expr_rn io_ty -This is unusual: it's a LocalId whose Name has a Module from another-module. Tiresomely, we must filter it out again in GHC.Iface.Make, less we-get two defns for 'main' in the interface file!+ -- See Note [Root-main Id]+ -- Construct the binding+ -- :Main.main :: IO res_ty = runMainIO res_ty main+ ; run_main_id <- tcLookupId runMainIOName+ ; let { root_main_name = mkExternalName rootMainKey rOOT_MAIN+ (mkVarOccFS (fsLit "main"))+ (getSrcSpan main_name)+ ; root_main_id = Id.mkExportedVanillaId root_main_name io_ty+ ; co = mkWpTyApps [res_ty]+ -- The ev_binds of the `main` function may contain deferred+ -- type errors when type of `main` is not `IO a`. The `ev_binds`+ -- must be put inside `runMainIO` to ensure the deferred type+ -- error can be emitted correctly. See #13838.+ ; rhs = nlHsApp (mkLHsWrap co (nlHsVar run_main_id)) $+ mkHsDictLet ev_binds main_expr+ ; main_bind = mkVarBind root_main_id rhs } + ; return (tcg_env { tcg_main = Just main_name+ , tcg_binds = tcg_binds tcg_env+ `snocBag` main_bind+ , tcg_dus = tcg_dus tcg_env+ `plusDU` usesOnly (unitFV main_name) })+ -- Record the use of 'main', so that we don't+ -- complain about it being defined but not used+ } -Note [Main module without a main function in the export spec]-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~-Giving accurate error messages for a Main module that does not export a main-function is surprisingly tricky. To see why, consider a module in a file-`Foo.hs` that has no `main` function in the explicit export specs of the module-header:+getIOType :: TcM (TcType, TcType)+-- Return (IO alpha, alpha) for fresh alpha+getIOType = do { ioTyCon <- tcLookupTyCon ioTyConName+ ; res_ty <- newFlexiTyVarTy liftedTypeKind+ ; return (mkTyConApp ioTyCon [res_ty], res_ty) } - module Main () where- foo = return ()+setMainCtxt :: Name -> TcType -> TcM a -> TcM (TcEvBinds, a)+setMainCtxt main_name io_ty thing_inside+ = setSrcSpan (getSrcSpan main_name) $+ addErrCtxt main_ctxt $+ checkConstraints skol_info [] [] $ -- Builds an implication if necessary+ thing_inside -- e.g. with -fdefer-type-errors+ where+ skol_info = SigSkol (FunSigCtxt main_name False) io_ty []+ main_ctxt = text "When checking the type of the"+ <+> ppMainFn (nameOccName main_name) -This does not export a main function and therefore should be rejected, per-chapter 5 of the Haskell Report 2010:+{- Note [Dealing with main]+~~~~~~~~~~~~~~~~~~~~~~~~~~~+Dealing with the 'main' declaration is surprisingly tricky. Here are+the moving parts: - A Haskell program is a collection of modules, one of which, by convention,- must be called Main and must export the value main. The value of the- program is the value of the identifier main in module Main, which must be- a computation of type IO τ for some type τ.+* The flag -main-is=M.foo allows you to set the main module to 'M',+ and the main function to 'foo'. We access them through+ mainModIs :: HscEnv -> Module -- returns M+ getMainOcc :: DynFlags -> OccName -- returns foo+ Of course usually M = Main, and foo = main. -In fact, when you compile the program above using `ghc Foo.hs`, you will-actually get *two* errors:+* checkMainType: when typechecking module M, we add an extra check that+ foo :: IO tau, for some type tau.+ This avoids getting ambiguous-type errors from the monomorphism restriction+ applying to things like+ main = return ()+ Note that checkMainType does not consult the export list because+ we have not yet done rnExports (and can't do it until later). - - The IO action ‘main’ is not defined in module ‘Main’+* rnExports: checks the export list. Very annoyingly, we can only do+ this after running any finalisers, which may add new declarations.+ That's why checkMainType and checkMain have to be separate. - - Ambiguous type variable ‘m0’ arising from a use of ‘return’- prevents the constraint ‘(Monad m0)’ from being solved.+* checkMain: does two things:+ - check that the export list does indeed export something called 'foo'+ - generateMainBinding: generate the root-main binding+ :Main.main = runMainIO M.foo+ See Note [Root-main id] -The first error is self-explanatory, while the second error message occurs-due to the monomorphism restriction.+An annoying consequence of having both checkMainType and checkMain is+that, when (but only when) -fdefer-type-errors is on, we may report an+ill-typed 'main' twice (as warnings): once in checkMainType and once+in checkMain. See test typecheck/should_fail/T13292. -Now consider what would happen if the program above were compiled with-`ghc -main-is foo Foo`. The has the effect of `foo` being designated as the-main function. The program will still be rejected since it does not export-`foo` (and therefore does not export its main function), but there is one-important difference: `foo` will be checked against the type `IO τ`. As a-result, we would *not* expect the monomorphism restriction error message-to occur, since the typechecker should have no trouble figuring out the type-of `foo`. In other words, we should only throw the former error message,-not the latter.+We have the following tests to check this processing:+----------------+----------------------------------------------------------------------------------++ | Module Header: |+ +-------------+-------------+-------------+-------------+-------------+------------++ | module | module Main | <No Header> | module Main |module |module Main |+ | Main(main) | | | (module X)| Main () | (Sub.main)|+----------------+==================================================================================++`main` function | ERROR: | Main.main | ERROR: | Main.main | ERROR: | Sub.main |+in Main module | Ambiguous | | Ambiguous | | `main` not | |+and in imported | | | | | exported | |+module Sub. | T19397E1 | T16453M0 | T19397E2 | T16453M3 | | T16453M1 |+ | | | | X = Main | Remark 2) | |+----------------+-------------+-------------+-------------+-------------+-------------+------------++`main`function | Sub.main | ERROR: | Sub.main | Sub.main | ERROR: | Sub.main |+only in imported| | No `main` in| | | `main` not | |+submodule Sub. | | `Main` | | | exported | |+ | T19397M0 | T16453E1 | T19397M1 | T16453M4 | | T16453M5 |+ | | | | X = Sub | Remark 2) | |+----------------+-------------+-------------+-------------+-------------+-------------+------------++`foo` function | Sub.foo | ERROR: | Sub.foo | Sub.foo | ERROR: | Sub.foo |+in submodule | | No `foo` in | | | `foo` not | |+Sub. | | `Main` | | | exported | |+GHC option: | | | | | | |+ -main-is foo | T19397M2 | T19397E3 | T19397M3 | T19397M4 | T19397E4 | T16453M6 |+ | Remark 1) | | | X = Sub | | Remark 3) |+----------------+-------------+-------------+-------------+-------------+-------------+------------+ -The implementation uses the function `getSomeMain` to find a potential main-function that is defined but not exported. If one is found, it is passed to-`use_as_main` to inform the typechecker that the main function should be of-type `IO τ`. See also the `T414` and `T17171a` test cases for similar examples-of programs whose error messages are influenced by the situation described in-this Note.+Remarks:+* The first line shows the exported `main` function or the error.+* The second line shows the coresponding test case.+* The module `Sub` contains the following functions:+ main :: IO ()+ foo :: IO ()+* Remark 1) Here the header is `Main (foo)`.+* Remark 2) Here we have no extra test case. It would exercise the same code path as `T19397E4`.+* Remark 3) Here the header is `Main (Sub.foo)`. +Note [Root-main Id]+~~~~~~~~~~~~~~~~~~~+The function that the RTS invokes is always :Main.main, which we call+root_main_id. (Because GHC allows the user to have a module not+called Main as the main module, we can't rely on the main function+being called "Main.main". That's why root_main_id has a fixed module+":Main".)++This is unusual: it's a LocalId whose Name has a Module from another+module. Tiresomely, we must filter it out again in GHC.Iface.Make, less we+get two defns for 'main' in the interface file!++ ********************************************************* * * GHCi stuff@@ -1994,7 +2011,7 @@ ********************************************************* -} -runTcInteractive :: HscEnv -> TcRn a -> IO (Messages DecoratedSDoc, Maybe a)+runTcInteractive :: HscEnv -> TcRn a -> IO (Messages DiagnosticMessage, Maybe a) -- Initialise the tcg_inst_env with instances from all home modules. -- This mimics the more selective call to hptInstances in tcRnImports runTcInteractive hsc_env thing_inside@@ -2110,7 +2127,7 @@ -- The returned TypecheckedHsExpr is of type IO [ () ], a list of the bound -- values, coerced to (). tcRnStmt :: HscEnv -> GhciLStmt GhcPs- -> IO (Messages DecoratedSDoc, Maybe ([Id], LHsExpr GhcTc, FixityEnv))+ -> IO (Messages DiagnosticMessage, Maybe ([Id], LHsExpr GhcTc, FixityEnv)) tcRnStmt hsc_env rdr_stmt = runTcInteractive hsc_env $ do { @@ -2211,20 +2228,21 @@ -- Don't try to typecheck if the renamer fails! ; ghciStep <- getGhciStepIO ; uniq <- newUnique+ ; let loc' = noAnnSrcSpan $ locA loc ; interPrintName <- getInteractivePrintName- ; let fresh_it = itName uniq loc- matches = [mkMatch (mkPrefixFunRhs (L loc fresh_it)) [] rn_expr- (noLoc emptyLocalBinds)]+ ; let fresh_it = itName uniq (locA loc)+ matches = [mkMatch (mkPrefixFunRhs (L loc' fresh_it)) [] rn_expr+ emptyLocalBinds] -- [it = expr] the_bind = L loc $ (mkTopFunBind FromSource- (L loc fresh_it) matches)+ (L loc' fresh_it) matches) { fun_ext = fvs } -- Care here! In GHCi the expression might have -- free variables, and they in turn may have free type variables -- (if we are at a breakpoint, say). We must put those free vars -- [let it = expr]- let_stmt = L loc $ LetStmt noExtField $ noLoc $ HsValBinds noExtField+ let_stmt = L loc $ LetStmt noAnn $ HsValBinds noAnn $ XValBindsLR (NValBinds [(NonRecursive,unitBag the_bind)] []) @@ -2234,7 +2252,7 @@ { xbsrn_bindOp = mkRnSyntaxExpr bindIOName , xbsrn_failOp = Nothing })- (L loc (VarPat noExtField (L loc fresh_it)))+ (L loc (VarPat noExtField (L loc' fresh_it))) (nlHsApp ghciStep rn_expr) -- [; print it]@@ -2356,7 +2374,7 @@ tcUserStmt rdr_stmt@(L loc _) = do { (([rn_stmt], fix_env), fvs) <- checkNoErrs $- rnStmts GhciStmtCtxt rnLExpr [rdr_stmt] $ \_ -> do+ rnStmts GhciStmtCtxt rnExpr [rdr_stmt] $ \_ -> do fix_env <- getFixityEnv return (fix_env, emptyFVs) -- Don't try to typecheck if the renamer fails!@@ -2458,17 +2476,17 @@ -- Note [Implementing unsafeCoerce] in base:Unsafe.Coerce ; let ret_expr = nlHsApp (nlHsTyApp ret_id [ret_ty]) $- noLoc $ ExplicitList unitTy $+ noLocA $ ExplicitList unitTy $ map mk_item ids mk_item id = unsafe_coerce_id `nlHsTyApp` [ getRuntimeRep (idType id) , getRuntimeRep unitTy , idType id, unitTy] `nlHsApp` nlHsVar id- stmts = tc_stmts ++ [noLoc (mkLastStmt ret_expr)]+ stmts = tc_stmts ++ [noLocA (mkLastStmt ret_expr)] ; return (ids, mkHsDictLet (EvBinds const_binds) $- noLoc (HsDo io_ret_ty GhciStmtCtxt (noLoc stmts)))+ noLocA (HsDo io_ret_ty GhciStmtCtxt (noLocA stmts))) } -- | Generate a typed ghciStepIO expression (ghciStep :: Ty a -> IO a)@@ -2480,7 +2498,7 @@ ioM = nlHsAppTy (nlHsTyVar ioTyConName) (nlHsTyVar a_tv) step_ty :: LHsSigType GhcRn- step_ty = noLoc $ HsSig+ step_ty = noLocA $ HsSig { sig_bndrs = HsOuterImplicit{hso_ximplicit = [a_tv]} , sig_ext = noExtField , sig_body = nlHsFunTy ghciM ioM }@@ -2488,9 +2506,9 @@ stepTy :: LHsSigWcType GhcRn stepTy = mkEmptyWildCardBndrs step_ty - return (noLoc $ ExprWithTySig noExtField (nlHsVar ghciStepIoMName) stepTy)+ return (noLocA $ ExprWithTySig noExtField (nlHsVar ghciStepIoMName) stepTy) -isGHCiMonad :: HscEnv -> String -> IO (Messages DecoratedSDoc, Maybe Name)+isGHCiMonad :: HscEnv -> String -> IO (Messages DiagnosticMessage, Maybe Name) isGHCiMonad hsc_env ty = runTcInteractive hsc_env $ do rdrEnv <- getGlobalRdrEnv@@ -2517,7 +2535,7 @@ tcRnExpr :: HscEnv -> TcRnExprMode -> LHsExpr GhcPs- -> IO (Messages DecoratedSDoc, Maybe Type)+ -> IO (Messages DiagnosticMessage, Maybe Type) tcRnExpr hsc_env mode rdr_expr = runTcInteractive hsc_env $ do {@@ -2533,7 +2551,7 @@ -- Generalise uniq <- newUnique ;- let { fresh_it = itName uniq (getLoc rdr_expr) } ;+ let { fresh_it = itName uniq (getLocA rdr_expr) } ; ((qtvs, dicts, _, _), residual) <- captureConstraints $ simplifyInfer tclvl infer_mode@@ -2586,7 +2604,7 @@ -------------------------- tcRnImportDecls :: HscEnv -> [LImportDecl GhcPs]- -> IO (Messages DecoratedSDoc, Maybe GlobalRdrEnv)+ -> IO (Messages DiagnosticMessage, Maybe GlobalRdrEnv) -- Find the new chunk of GlobalRdrEnv created by this list of import -- decls. In contract tcRnImports *extends* the TcGblEnv. tcRnImportDecls hsc_env import_decls@@ -2602,7 +2620,7 @@ -> ZonkFlexi -> Bool -- Normalise the returned type -> LHsType GhcPs- -> IO (Messages DecoratedSDoc, Maybe (Type, Kind))+ -> IO (Messages DiagnosticMessage, Maybe (Type, Kind)) tcRnType hsc_env flexi normalise rdr_type = runTcInteractive hsc_env $ setXOptM LangExt.PolyKinds $ -- See Note [Kind-generalise in tcRnType]@@ -2736,10 +2754,10 @@ tcRnDeclsi :: HscEnv -> [LHsDecl GhcPs]- -> IO (Messages DecoratedSDoc, Maybe TcGblEnv)+ -> IO (Messages DiagnosticMessage, Maybe TcGblEnv) tcRnDeclsi hsc_env local_decls = runTcInteractive hsc_env $- tcRnSrcDecls False local_decls Nothing+ tcRnSrcDecls False Nothing local_decls externaliseAndTidyId :: Module -> Id -> TcM Id externaliseAndTidyId this_mod id@@ -2761,17 +2779,17 @@ -- a package module with an interface on disk. If neither of these is -- true, then the result will be an error indicating the interface -- could not be found.-getModuleInterface :: HscEnv -> Module -> IO (Messages DecoratedSDoc, Maybe ModIface)+getModuleInterface :: HscEnv -> Module -> IO (Messages DiagnosticMessage, Maybe ModIface) getModuleInterface hsc_env mod = runTcInteractive hsc_env $ loadModuleInterface (text "getModuleInterface") mod -tcRnLookupRdrName :: HscEnv -> Located RdrName- -> IO (Messages DecoratedSDoc, Maybe [Name])+tcRnLookupRdrName :: HscEnv -> LocatedN RdrName+ -> IO (Messages DiagnosticMessage, Maybe [Name]) -- ^ Find all the Names that this RdrName could mean, in GHCi tcRnLookupRdrName hsc_env (L loc rdr_name) = runTcInteractive hsc_env $- setSrcSpan loc $+ setSrcSpanA loc $ do { -- If the identifier is a constructor (begins with an -- upper-case letter), then we need to consider both -- constructor and type class identifiers.@@ -2781,7 +2799,7 @@ ; when (null names) (addErrTc (text "Not in scope:" <+> quotes (ppr rdr_name))) ; return names } -tcRnLookupName :: HscEnv -> Name -> IO (Messages DecoratedSDoc, Maybe TyThing)+tcRnLookupName :: HscEnv -> Name -> IO (Messages DiagnosticMessage, Maybe TyThing) tcRnLookupName hsc_env name = runTcInteractive hsc_env $ tcRnLookupName' name@@ -2800,7 +2818,7 @@ tcRnGetInfo :: HscEnv -> Name- -> IO ( Messages DecoratedSDoc+ -> IO ( Messages DiagnosticMessage , Maybe (TyThing, Fixity, [ClsInst], [FamInst], SDoc)) -- Used to implement :info in GHCi@@ -2911,7 +2929,7 @@ full_dump = pprLHsBinds (tcg_binds env) -- NB: foreign x-d's have undefined's in their types; -- hence can't show the tc_fords- ast_dump = showAstData NoBlankSrcSpan (tcg_binds env)+ ast_dump = showAstData NoBlankSrcSpan NoBlankEpAnnotations (tcg_binds env) -- It's unpleasant having both pprModGuts and pprModDetails here pprTcGblEnv :: TcGblEnv -> SDoc@@ -3130,5 +3148,5 @@ recordUnsafeInfer pluginUnsafe where unsafeText = "Use of plugins makes the module unsafe"- pluginUnsafe = unitBag ( mkPlainWarnMsg noSrcSpan+ pluginUnsafe = unitBag ( mkPlainMsgEnvelope WarningWithoutFlag noSrcSpan (Outputable.text unsafeText) )
compiler/GHC/Tc/Plugin.hs view
@@ -98,7 +98,11 @@ findImportedModule :: ModuleName -> Maybe FastString -> TcPluginM Finder.FindResult findImportedModule mod_name mb_pkg = do hsc_env <- getTopEnv- tcPluginIO $ Finder.findImportedModule hsc_env mod_name mb_pkg+ let fc = hsc_FC hsc_env+ let home_unit = hsc_home_unit hsc_env+ let units = hsc_units hsc_env+ let dflags = hsc_dflags hsc_env+ tcPluginIO $ Finder.findImportedModule fc units home_unit dflags mod_name mb_pkg lookupOrig :: Module -> OccName -> TcPluginM Name lookupOrig mod = unsafeTcPluginTcM . IfaceEnv.lookupOrig mod
compiler/GHC/Tc/Solver.hs view
@@ -11,7 +11,8 @@ pushLevelAndSolveEqualities, pushLevelAndSolveEqualitiesX, reportUnsolvedEqualities, simplifyWantedsTcM,- tcCheckSatisfiability,+ tcCheckGivens,+ tcCheckWanteds, tcNormalise, captureTopConstraints,@@ -805,11 +806,12 @@ ; return (isEmptyWC unsolved) } -------------------tcCheckSatisfiability :: InertSet -> Bag EvVar -> TcM (Maybe InertSet)--- Return (Just new_inerts) if satisfiable, Nothing if definitely contradictory-tcCheckSatisfiability inerts given_ids = do+tcCheckGivens :: InertSet -> Bag EvVar -> TcM (Maybe InertSet)+-- ^ Return (Just new_inerts) if the Givens are satisfiable, Nothing if definitely+-- contradictory+tcCheckGivens inerts given_ids = do (sat, new_inerts) <- runTcSInerts inerts $ do- traceTcS "checkSatisfiability {" (ppr inerts <+> ppr given_ids)+ traceTcS "checkGivens {" (ppr inerts <+> ppr given_ids) lcl_env <- TcS.getLclEnv let given_loc = mkGivenLoc topTcLevel UnkSkol lcl_env let given_cts = mkGivens given_loc (bagToList given_ids)@@ -817,7 +819,7 @@ solveSimpleGivens given_cts insols <- getInertInsols insols <- try_harder insols- traceTcS "checkSatisfiability }" (ppr insols)+ traceTcS "checkGivens }" (ppr insols) return (isEmptyBag insols) return $ if sat then Just new_inerts else Nothing where@@ -834,6 +836,18 @@ ; solveSimpleGivens new_given ; getInertInsols } +tcCheckWanteds :: InertSet -> ThetaType -> TcM Bool+-- ^ Return True if the Wanteds are soluble, False if not+tcCheckWanteds inerts wanteds = do+ cts <- newWanteds PatCheckOrigin wanteds+ (sat, _new_inerts) <- runTcSInerts inerts $ do+ traceTcS "checkWanteds {" (ppr inerts <+> ppr wanteds)+ -- See Note [Superclasses and satisfiability]+ wcs <- solveWantedsAndDrop (mkSimpleWC cts)+ traceTcS "checkWanteds }" (ppr wcs)+ return (isSolvedWC wcs)+ return sat+ -- | Normalise a type as much as possible using the given constraints. -- See @Note [tcNormalise]@. tcNormalise :: InertSet -> Type -> TcM Type@@ -1332,9 +1346,9 @@ -- Warn about the monomorphism restriction ; warn_mono <- woptM Opt_WarnMonomorphism ; when (case infer_mode of { ApplyMR -> warn_mono; _ -> False}) $- warnTc (Reason Opt_WarnMonomorphism)- (constrained_tvs `intersectsVarSet` tyCoVarsOfTypes taus)- mr_msg+ diagnosticTc (WarningWithFlag Opt_WarnMonomorphism)+ (constrained_tvs `intersectsVarSet` tyCoVarsOfTypes taus)+ mr_msg ; traceTc "decideMonoTyVars" $ vcat [ text "infer_mode =" <+> ppr infer_mode
compiler/GHC/Tc/Solver/Canonical.hs view
@@ -109,9 +109,10 @@ -- e.g. a ~ [a], where [G] a ~ [Int], can decompose canonicalize (CDictCan { cc_ev = ev, cc_class = cls- , cc_tyargs = xis, cc_pend_sc = pend_sc })+ , cc_tyargs = xis, cc_pend_sc = pend_sc+ , cc_fundeps = fds }) = {-# SCC "canClass" #-}- canClass ev cls xis pend_sc+ canClass ev cls xis pend_sc fds canonicalize (CEqCan { cc_ev = ev , cc_lhs = lhs@@ -150,7 +151,7 @@ | isGiven ev -- See Note [Eagerly expand given superclasses] = do { sc_cts <- mkStrictSuperClasses ev [] [] cls tys ; emitWork sc_cts- ; canClass ev cls tys False }+ ; canClass ev cls tys False fds } | isWanted ev , Just ip_name <- isCallStackPred cls tys@@ -174,15 +175,19 @@ ; let ev_cs = EvCsPushCall func (ctLocSpan loc) (ctEvExpr new_ev) ; solveCallStack ev ev_cs - ; canClass new_ev cls tys False }+ ; canClass new_ev cls tys+ False -- No superclasses+ False -- No top level instances for fundeps+ } | otherwise- = canClass ev cls tys (has_scs cls)+ = canClass ev cls tys (has_scs cls) fds where has_scs cls = not (null (classSCTheta cls)) loc = ctEvLoc ev pred = ctEvPred ev+ fds = classHasFds cls solveCallStack :: CtEvidence -> EvCallStack -> TcS () -- Also called from GHC.Tc.Solver when defaulting call stacks@@ -197,10 +202,11 @@ canClass :: CtEvidence -> Class -> [Type] -> Bool -- True <=> un-explored superclasses+ -> Bool -- True <=> unexploited fundep(s) -> TcS (StopOrContinue Ct) -- Precondition: EvVar is class evidence -canClass ev cls tys pend_sc+canClass ev cls tys pend_sc fds = -- all classes do *nominal* matching ASSERT2( ctEvRole ev == Nominal, ppr ev $$ ppr cls $$ ppr tys ) do { (xis, cos) <- rewriteArgsNom ev cls_tc tys@@ -209,7 +215,8 @@ mk_ct new_ev = CDictCan { cc_ev = new_ev , cc_tyargs = xis , cc_class = cls- , cc_pend_sc = pend_sc }+ , cc_pend_sc = pend_sc+ , cc_fundeps = fds } ; mb <- rewriteEvidence ev xi co ; traceTcS "canClass" (vcat [ ppr ev , ppr xi, ppr mb ])@@ -644,7 +651,7 @@ this_ct | null tvs, null theta = CDictCan { cc_ev = ev, cc_class = cls, cc_tyargs = tys- , cc_pend_sc = loop_found }+ , cc_pend_sc = loop_found, cc_fundeps = classHasFds cls } -- NB: If there is a loop, we cut off, so we have not -- added the superclasses, hence cc_pend_sc = True | otherwise
compiler/GHC/Tc/Solver/Interact.hs view
@@ -465,11 +465,12 @@ rare and it doesn't seem worth trying to put them back together again.) -} -solveOneFromTheOther :: CtEvidence -- Inert- -> CtEvidence -- WorkItem+solveOneFromTheOther :: CtEvidence -- Inert (Dict or Irred)+ -> CtEvidence -- WorkItem (same predicate as inert) -> TcS InteractResult -- Precondition: -- * inert and work item represent evidence for the /same/ predicate+-- * Both are CDictCan or CIrredCan -- -- We can always solve one from the other: even if both are wanted, -- although we don't rewrite wanteds with wanteds, we can combine@@ -499,8 +500,8 @@ -- Inert is Given or Wanted = case ev_i of CtWanted { ctev_nosh = WOnly }- | WDeriv <- nosh_w -> return KeepWork- _ -> return KeepInert+ | WDeriv <- nosh_w -> return KeepWork+ _ -> return KeepInert -- Consider work item [WD] C ty1 ty2 -- inert item [W] C ty1 ty2 -- Then we must keep the work item. But if the@@ -511,7 +512,7 @@ -- From here on the work-item is Given | CtWanted { ctev_loc = loc_i } <- ev_i- , prohibitedSuperClassSolve (ctEvLoc ev_w) loc_i+ , prohibitedSuperClassSolve loc_w loc_i = do { traceTcS "prohibitedClassSolve2" (ppr ev_i $$ ppr ev_w) ; return KeepInert } -- Just discard the un-usable Given -- This never actually happens because@@ -1439,49 +1440,107 @@ ********************************************************************** -} -inertsCanDischarge :: InertCans -> CanEqLHS -> TcType -> CtFlavourRole+{- Note [Combining equalities]+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+Suppose we have+ Inert: g1 :: a ~ t+ Work item: g2 :: a ~ t++Then we can simply solve g2 from g1, thus g2 := g1. Easy!+But it's not so simple:++* If t is a type variable, the equalties might be oriented differently:+ e.g. (g1 :: a~b) and (g2 :: b~a)+ So we look both ways round. Hence the SwapFlag result to+ inertsCanDischarge.++* We can only do g2 := g1 if g1 can discharge g2; that depends on+ (a) the role and (b) the flavour. E.g. a representational equality+ cannot discharge a nominal one; a Wanted cannot discharge a Given.+ The predicate is eqCanDischargeFR.++* If the inert is [W] and the work-item is [WD] we don't want to+ forget the [D] part; hence the Bool result of inertsCanDischarge.++* Visibility. Suppose S :: forall k. k -> Type, and consider unifying+ S @Type (a::Type) ~ S @(Type->Type) (b::Type->Type)+ From the first argument we get (Type ~ Type->Type); from the second+ argument we get (a ~ b) which in turn gives (Type ~ Type->Type).+ See typecheck/should_fail/T16204c.++ That first argument is invisible in the source program (aside from+ visible type application), so we'd much prefer to get the error from+ the second. We track visiblity in the uo_visible field of a TypeEqOrigin.+ We use this to prioritise visible errors (see GHC.Tc.Errors.tryReporters,+ the partition on isVisibleOrigin).++ So when combining two otherwise-identical equalites, we want to+ keep the visible one, and discharge the invisible one. Hence the+ call to strictly_more_visible.+-}++inertsCanDischarge :: InertCans -> Ct -> Maybe ( CtEvidence -- The evidence for the inert , SwapFlag -- Whether we need mkSymCo , Bool) -- True <=> keep a [D] version -- of the [WD] constraint-inertsCanDischarge inerts lhs rhs fr+inertsCanDischarge inerts (CEqCan { cc_lhs = lhs_w, cc_rhs = rhs_w+ , cc_ev = ev_w, cc_eq_rel = eq_rel }) | (ev_i : _) <- [ ev_i | CEqCan { cc_ev = ev_i, cc_rhs = rhs_i , cc_eq_rel = eq_rel }- <- findEq inerts lhs- , (ctEvFlavour ev_i, eq_rel) `eqCanDischargeFR` fr- , rhs_i `tcEqType` rhs ]+ <- findEq inerts lhs_w+ , rhs_i `tcEqType` rhs_w+ , inert_beats_wanted ev_i eq_rel ] = -- Inert: a ~ ty -- Work item: a ~ ty Just (ev_i, NotSwapped, keep_deriv ev_i) - | Just rhs_lhs <- canEqLHS_maybe rhs+ | Just rhs_lhs <- canEqLHS_maybe rhs_w , (ev_i : _) <- [ ev_i | CEqCan { cc_ev = ev_i, cc_rhs = rhs_i , cc_eq_rel = eq_rel } <- findEq inerts rhs_lhs- , (ctEvFlavour ev_i, eq_rel) `eqCanDischargeFR` fr- , rhs_i `tcEqType` canEqLHSType lhs ]+ , rhs_i `tcEqType` canEqLHSType lhs_w+ , inert_beats_wanted ev_i eq_rel ] = -- Inert: a ~ b -- Work item: b ~ a Just (ev_i, IsSwapped, keep_deriv ev_i) - | otherwise- = Nothing- where+ loc_w = ctEvLoc ev_w+ flav_w = ctEvFlavour ev_w+ fr_w = (flav_w, eq_rel)++ inert_beats_wanted ev_i eq_rel+ = -- eqCanDischargeFR: see second bullet of Note [Combining equalities]+ -- strictly_more_visible: see last bullet of Note [Combining equalities]+ fr_i`eqCanDischargeFR` fr_w+ && not ((loc_w `strictly_more_visible` ctEvLoc ev_i)+ && (fr_w `eqCanDischargeFR` fr_i))+ where+ fr_i = (ctEvFlavour ev_i, eq_rel)++ -- See Note [Combining equalities], third bullet keep_deriv ev_i | Wanted WOnly <- ctEvFlavour ev_i -- inert is [W]- , (Wanted WDeriv, _) <- fr -- work item is [WD]+ , Wanted WDeriv <- flav_w -- work item is [WD] = True -- Keep a derived version of the work item | otherwise = False -- Work item is fully discharged + -- See Note [Combining equalities], final bullet+ strictly_more_visible loc1 loc2+ = not (isVisibleOrigin (ctLocOrigin loc2)) &&+ isVisibleOrigin (ctLocOrigin loc1)++inertsCanDischarge _ _ = Nothing++ interactEq :: InertCans -> Ct -> TcS (StopOrContinue Ct) interactEq inerts workItem@(CEqCan { cc_lhs = lhs- , cc_rhs = rhs- , cc_ev = ev- , cc_eq_rel = eq_rel })- | Just (ev_i, swapped, keep_deriv)- <- inertsCanDischarge inerts lhs rhs (ctEvFlavour ev, eq_rel)+ , cc_rhs = rhs+ , cc_ev = ev+ , cc_eq_rel = eq_rel })+ | Just (ev_i, swapped, keep_deriv) <- inertsCanDischarge inerts workItem = do { setEvBindIfWanted ev $ evCoercion (maybeTcSymCo swapped $ tcDowngradeRole (eqRelRole eq_rel)@@ -1696,6 +1755,68 @@ It's exactly the same with implicit parameters, except that the "aggressive" approach would be much easier to implement. +Note [Fundeps with instances]+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+doTopFundepImprovement compares the constraint with all the instance+declarations, to see if we can produce any derived equalities. E.g+ class C2 a b | a -> b+ instance C Int Bool+Then the constraint (C Int ty) generates the Derived equality [D] ty ~ Bool.++There is a nasty corner in #19415 which led to the typechecker looping:+ class C s t b | s -> t+ instance ... => C (T kx x) (T ky y) Int+ T :: forall k. k -> Type++ work_item: dwrk :: C (T @ka (a::ka)) (T @kb0 (b0::kb0)) Char+ where kb0, b0 are unification vars+ ==> {fundeps against instance; k0, y0 fresh unification vars}+ [D] T kb0 (b0::kb0) ~ T k0 (y0::k0)+ Add dwrk to inert set+ ==> {solve that Derived kb0 := k0, b0 := y0+ Now kick out dwrk, since it mentions kb0+ But now we are back to the start! Loop!++NB1: this example relies on an instance that does not satisfy+the coverage condition (although it may satisfy the weak coverage+condition), which is known to lead to termination trouble++NB2: if the unification was the other way round, k0:=kb0, all would be+well. It's a very delicate problem.++The ticket #19415 discusses various solutions, but the one we adopted+is very simple:++* There is a flag in CDictCan (cc_fundeps :: Bool)++* cc_fundeps = True means+ a) The class has fundeps+ b) We have not had a successful hit against instances yet++* In doTopFundepImprovement, if we emit some Deriveds we flip the flag+ to False, so that we won't try again with the same CDictCan. In our+ example, dwrk will have its flag set to False.++* Not that if we have no "hits" we must /not/ flip the flag. We might have+ dwrk :: C alpha beta Char+ which does not yet trigger fundeps from the instance, but later we+ get alpha := T ka a. We could be cleverer, and spot that the constraint+ is such that we will /never/ get any hits (no unifiers) but we don't do+ that yet.++Easy! What could go wrong?+* Maybe the class has multiple fundeps, and we get hit with one but not+ the other. Per-fundep flags?+* Maybe we get a hit against one instance with one fundep but, after+ the work-item is instantiated a bit more, we get a second hit+ against a second instance. (This is a pretty strange and+ undesirable thing anyway, and can only happen with overlapping+ instances; one example is in Note [Weird fundeps].)++But both of these seem extremely exotic, and ignoring them threatens+completeness (fixable with some type signature), but not termination+(not fixable). So for now we are just doing the simplest thing.+ Note [Weird fundeps] ~~~~~~~~~~~~~~~~~~~~ Consider class Het a b | a -> b where@@ -1718,6 +1839,39 @@ #7875 is a case in point. -} +doTopFundepImprovement ::Ct -> TcS (StopOrContinue Ct)+-- Try to functional-dependency improvement betweeen the constraint+-- and the top-level instance declarations+-- See Note [Fundeps with instances]+-- See also Note [Weird fundeps]+doTopFundepImprovement work_item@(CDictCan { cc_ev = ev, cc_class = cls+ , cc_tyargs = xis+ , cc_fundeps = has_fds })+ | has_fds, isImprovable ev+ = do { traceTcS "try_fundeps" (ppr work_item)+ ; instEnvs <- getInstEnvs+ ; let fundep_eqns = improveFromInstEnv instEnvs mk_ct_loc cls xis+ ; case fundep_eqns of+ [] -> continueWith work_item -- No improvement+ _ -> do { emitFunDepDeriveds fundep_eqns+ ; continueWith (work_item { cc_fundeps = False }) } }+ | otherwise+ = continueWith work_item++ where+ dict_pred = mkClassPred cls xis+ dict_loc = ctEvLoc ev+ dict_origin = ctLocOrigin dict_loc++ mk_ct_loc :: PredType -- From instance decl+ -> SrcSpan -- also from instance deol+ -> CtLoc+ mk_ct_loc inst_pred inst_loc+ = dict_loc { ctl_origin = FunDepOrigin2 dict_pred dict_origin+ inst_pred inst_loc }++doTopFundepImprovement work_item = pprPanic "doTopFundepImprovement" (ppr work_item)+ emitFunDepDeriveds :: [FunDepEqn CtLoc] -> TcS () -- See Note [FunDep and implicit parameter reactions] emitFunDepDeriveds fd_eqns@@ -1974,8 +2128,7 @@ doTopReactDict inerts work_item@(CDictCan { cc_ev = ev, cc_class = cls , cc_tyargs = xis }) | isGiven ev -- Never use instances for Given constraints- = do { try_fundep_improvement- ; continueWith work_item }+ = doTopFundepImprovement work_item | Just solved_ev <- lookupSolvedDict inerts dict_loc cls xis -- Cached = do { setEvBindIfWanted ev (ctEvTerm solved_ev)@@ -1989,30 +2142,13 @@ -> do { insertSafeOverlapFailureTcS what work_item ; addSolvedDict what ev cls xis ; chooseInstance work_item lkup_res }- _ -> -- NoInstance or NotSure- do { when (isImprovable ev) $- try_fundep_improvement- ; continueWith work_item } }+ _ -> -- NoInstance or NotSure+ -- We didn't solve it; so try functional dependencies with+ -- the instance environment, and return+ doTopFundepImprovement work_item } where- dict_pred = mkClassPred cls xis- dict_loc = ctEvLoc ev- dict_origin = ctLocOrigin dict_loc-- -- We didn't solve it; so try functional dependencies with- -- the instance environment, and return- -- See also Note [Weird fundeps]- try_fundep_improvement- = do { traceTcS "try_fundeps" (ppr work_item)- ; instEnvs <- getInstEnvs- ; emitFunDepDeriveds $- improveFromInstEnv instEnvs mk_ct_loc dict_pred }+ dict_loc = ctEvLoc ev - mk_ct_loc :: PredType -- From instance decl- -> SrcSpan -- also from instance deol- -> CtLoc- mk_ct_loc inst_pred inst_loc- = dict_loc { ctl_origin = FunDepOrigin2 dict_pred dict_origin- inst_pred inst_loc } doTopReactDict _ w = pprPanic "doTopReactDict" (ppr w)
compiler/GHC/Tc/Solver/Monad.hs view
@@ -1,5 +1,10 @@-{-# LANGUAGE CPP, DeriveFunctor, TypeFamilies, ScopedTypeVariables, TypeApplications,- DerivingStrategies, GeneralizedNewtypeDeriving, ScopedTypeVariables #-}+{-# LANGUAGE CPP #-}+{-# LANGUAGE DeriveFunctor #-}+{-# LANGUAGE DerivingStrategies #-}+{-# LANGUAGE GeneralizedNewtypeDeriving #-}+{-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE TypeApplications #-}+{-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -Wno-incomplete-record-updates -Wno-incomplete-uni-patterns #-} @@ -2945,7 +2950,7 @@ warnTcS :: WarningFlag -> SDoc -> TcS () addErrTcS :: SDoc -> TcS () failTcS = wrapTcS . TcM.failWith-warnTcS flag = wrapTcS . TcM.addWarn (Reason flag)+warnTcS flag = wrapTcS . TcM.addDiagnostic (WarningWithFlag flag) addErrTcS = wrapTcS . TcM.addErr panicTcS doc = pprPanic "GHC.Tc.Solver.Canonical" doc
compiler/GHC/Tc/TyCl.hs view
@@ -180,7 +180,7 @@ -- Step 1: Typecheck the standalone kind signatures and type/class declarations ; traceTc "---- tcTyClGroup ---- {" empty ; traceTc "Decls for" (ppr (map (tcdName . unLoc) tyclds))- ; (tyclss, data_deriv_info) <-+ ; (tyclss, data_deriv_info, kindless) <- tcExtendKindEnv (mkPromotionErrorEnv tyclds) $ -- See Note [Type environment evolution] do { kisig_env <- mkNameEnv <$> traverse tcStandaloneKindSig kisigs ; tcTyClDecls tyclds kisig_env role_annots }@@ -214,7 +214,9 @@ tcInstDecls1 instds ; let deriv_info = datafam_deriv_info ++ data_deriv_info- ; return (gbl_env', inst_info, deriv_info) }+ ; let gbl_env'' = gbl_env'+ { tcg_ksigs = tcg_ksigs gbl_env' `unionNameSet` kindless }+ ; return (gbl_env'', inst_info, deriv_info) } -- Gives the kind for every TyCon that has a standalone kind signature type KindSigEnv = NameEnv Kind@@ -223,12 +225,12 @@ :: [LTyClDecl GhcRn] -> KindSigEnv -> RoleAnnotEnv- -> TcM ([TyCon], [DerivInfo])+ -> TcM ([TyCon], [DerivInfo], NameSet) tcTyClDecls tyclds kisig_env role_annots = do { -- Step 1: kind-check this group and returns the final -- (possibly-polymorphic) kind of each TyCon and Class -- See Note [Kind checking for type and class decls]- tc_tycons <- kcTyClGroup kisig_env tyclds+ (tc_tycons, kindless) <- kcTyClGroup kisig_env tyclds ; traceTc "tcTyAndCl generalized kinds" (vcat (map ppr_tc_tycon tc_tycons)) -- Step 2: type-check all groups together, returning@@ -237,7 +239,7 @@ -- NB: We have to be careful here to NOT eagerly unfold -- type synonyms, as we have not tested for type synonym -- loops yet and could fall into a black hole.- ; fixM $ \ ~(rec_tyclss, _) -> do+ ; fixM $ \ ~(rec_tyclss, _, _) -> do { tcg_env <- getGblEnv -- Forced so we don't retain a reference to the TcGblEnv ; let !src = tcg_src tcg_env@@ -258,7 +260,7 @@ -- Kind and type check declarations for this group mapAndUnzipM (tcTyClDecl roles) tyclds- ; return (tycons, concat data_deriv_infos)+ ; return (tycons, concat data_deriv_infos, kindless) } } where ppr_tc_tycon tc = parens (sep [ ppr (tyConName tc) <> comma@@ -631,12 +633,14 @@ -} -kcTyClGroup :: KindSigEnv -> [LTyClDecl GhcRn] -> TcM [TcTyCon]+kcTyClGroup :: KindSigEnv -> [LTyClDecl GhcRn] -> TcM ([TcTyCon], NameSet) -- Kind check this group, kind generalize, and return the resulting local env -- This binds the TyCons and Classes of the group, but not the DataCons -- See Note [Kind checking for type and class decls] -- and Note [Inferring kinds for type declarations]+--+-- The NameSet returned contains kindless tycon names, without CUSK or SAKS. kcTyClGroup kisig_env decls = do { mod <- getModule ; traceTc "---- kcTyClGroup ---- {"@@ -651,9 +655,12 @@ ; cusks_enabled <- xoptM LangExt.CUSKs <&&> xoptM LangExt.PolyKinds -- See Note [CUSKs and PolyKinds] ; let (kindless_decls, kinded_decls) = partitionWith get_kind decls+ kindless_names = mkNameSet $ map get_name kindless_decls + get_name d = tcdName (unLoc d)+ get_kind d- | Just ki <- lookupNameEnv kisig_env (tcdName (unLoc d))+ | Just ki <- lookupNameEnv kisig_env (get_name d) = Right (d, SAKS ki) | cusks_enabled && hsDeclHasCusk (unLoc d)@@ -700,7 +707,7 @@ ; let poly_tcs = checked_tcs ++ generalized_tcs ; traceTc "---- kcTyClGroup end ---- }" (ppr_tc_kinds poly_tcs)- ; return poly_tcs }+ ; return (poly_tcs, kindless_names) } where ppr_tc_kinds tcs = vcat (map pp_tc tcs) pp_tc tc = ppr (tyConName tc) <+> dcolon <+> ppr (tyConKind tc)@@ -945,7 +952,7 @@ * Specified: the argument can be inferred at call sites, but may be instantiated with visible type/kind application - * Inferred: the must be inferred at call sites; it+ * Inferred: the argument must be inferred at call sites; it is unavailable for use with visible type/kind application. Why have Inferred at all? Because we just can't make user-facing@@ -1115,7 +1122,7 @@ All this is very similar at the level of terms: see GHC.Tc.Gen.Bind Note [Quantified variables in partial type signatures] - But there some tricky corners: Note [Tricky scoping in generaliseTcTyCon]+ But there are some tricky corners: Note [Tricky scoping in generaliseTcTyCon] * Step 4. Extend the type environment with a TcTyCon for S and T, now with their utterly-final polymorphic kinds (needed for recursive@@ -1286,7 +1293,7 @@ ; traceTc "inferInitialKinds done }" empty ; return tcs } where- infer_initial_kind = addLocM (getInitialKind InitialKindInfer)+ infer_initial_kind = addLocMA (getInitialKind InitialKindInfer) -- Check type/class declarations against their standalone kind signatures or -- CUSKs, producing a generalized TcTyCon for each.@@ -1298,7 +1305,7 @@ ; return tcs } where check_initial_kind (ldecl, msig) =- addLocM (getInitialKind (InitialKindCheck msig)) ldecl+ addLocMA (getInitialKind (InitialKindCheck msig)) ldecl -- | Get the initial kind of a TyClDecl, either generalized or non-generalized, -- depending on the 'InitialKindStrategy'.@@ -1327,7 +1334,7 @@ -- See Note [Don't process associated types in getInitialKind] ; inner_tcs <- tcExtendNameTyVarEnv parent_tv_prs $- mapM (addLocM (getAssocFamInitialKind cls)) ats+ mapM (addLocMA (getAssocFamInitialKind cls)) ats ; return (cls : inner_tcs) } where getAssocFamInitialKind cls =@@ -1345,7 +1352,7 @@ ; tc <- kcDeclHeader strategy name flav ktvs $ case m_sig of Just ksig -> TheKind <$> tcLHsKindSig ctxt ksig- Nothing -> return $ dataDeclDefaultResultKind new_or_data+ Nothing -> return $ dataDeclDefaultResultKind strategy new_or_data ; return [tc] } getInitialKind InitialKindInfer (FamDecl { tcdFam = decl })@@ -1454,14 +1461,18 @@ -} -- See Note [Data declaration default result kind]-dataDeclDefaultResultKind :: NewOrData -> ContextKind-dataDeclDefaultResultKind NewType = OpenKind- -- See Note [Implementation of UnliftedNewtypes], point <Error Messages>.-dataDeclDefaultResultKind DataType = TheKind liftedTypeKind+dataDeclDefaultResultKind :: InitialKindStrategy -> NewOrData -> ContextKind+dataDeclDefaultResultKind strategy new_or_data+ | NewType <- new_or_data+ = OpenKind -- See Note [Implementation of UnliftedNewtypes], point <Error Messages>.+ | DataType <- new_or_data+ , InitialKindCheck (SAKS _) <- strategy+ = OpenKind -- See Note [Implementation of UnliftedDatatypes]+ | otherwise+ = TheKind liftedTypeKind {- Note [Data declaration default result kind] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~- When the user has not written an inline result kind annotation on a data declaration, we assume it to be 'Type'. That is, the following declarations D1 and D2 are considered equivalent:@@ -1478,14 +1489,25 @@ data D4 :: Type -> Type where MkD4 :: ... -> D4 param -However, there's a twist: for newtypes, we must relax-the assumed result kind to (TYPE r):+However, there are two twists: - newtype D5 where- MkD5 :: Int# -> D5+ * For unlifted newtypes, we must relax the assumed result kind to (TYPE r): -See Note [Implementation of UnliftedNewtypes], STEP 1 and it's sub-note-<Error Messages>.+ newtype D5 where+ MkD5 :: Int# -> D5++ See Note [Implementation of UnliftedNewtypes], STEP 1 and it's sub-note+ <Error Messages>.++ * For unlifted datatypes, we must relax the assumed result kind to+ (TYPE (BoxedRep l)) in the presence of a SAKS:++ type D6 :: Type -> TYPE (BoxedRep Unlifted)+ data D6 a = MkD6 a++ Otherwise, it would be impossible to declare unlifted data types in H98+ syntax (which doesn't allow specification of a result kind).+ -} ---------------------------------@@ -1516,7 +1538,7 @@ -- See Note [Kind checking for type and class decls] -- Called only for declarations without a signature (no CUSKs or SAKs here) kcLTyClDecl (L loc decl)- = setSrcSpan loc $+ = setSrcSpanA loc $ do { tycon <- tcLookupTcTyCon tc_name ; traceTc "kcTyClDecl {" (ppr tc_name) ; addVDQNote tycon $ -- See Note [Inferring visible dependent quantification]@@ -1554,7 +1576,7 @@ , tcdCtxt = ctxt, tcdSigs = sigs }) _tycon = bindTyClTyVars name $ \ _ _ _ -> do { _ <- tcHsContext ctxt- ; mapM_ (wrapLocM_ kc_sig) sigs }+ ; mapM_ (wrapLocMA_ kc_sig) sigs } where kc_sig (ClassOpSig _ _ nms op_ty) = kcClassSigType nms op_ty kc_sig _ = return ()@@ -1602,7 +1624,7 @@ -> TcM () -- See Note [kcConDecls: kind-checking data type decls] kcConDecls new_or_data tc_res_kind cons- = mapM_ (wrapLocM_ (kcConDecl new_or_data tc_res_kind)) cons+ = mapM_ (wrapLocMA_ (kcConDecl new_or_data tc_res_kind)) cons -- Kind check a data constructor. In additional to the data constructor, -- we also need to know about whether or not its corresponding type was@@ -1622,7 +1644,7 @@ = addErrCtxt (dataConCtxt [name]) $ discardResult $ bindExplicitTKBndrs_Tv ex_tvs $- do { _ <- tcHsMbContext ex_ctxt+ do { _ <- tcHsContext ex_ctxt ; kcConH98Args new_or_data tc_res_kind args -- We don't need to check the telescope here, -- because that's done in tcConDecl@@ -1638,7 +1660,7 @@ discardResult $ bindOuterSigTKBndrs_Tv outer_bndrs $ -- Why "_Tv"? See Note [Using TyVarTvs for kind-checking GADTs]- do { _ <- tcHsMbContext cxt+ do { _ <- tcHsContext cxt ; traceTc "kcConDecl:GADT {" (ppr names $$ ppr res_ty) ; con_res_kind <- newOpenTypeKind ; _ <- tcCheckLHsType res_ty (TheKind con_res_kind)@@ -2252,6 +2274,52 @@ example that will notice this lack of inference, so it seems better to improve error messages than be able to infer this instantiation. +Note [Implementation of UnliftedDatatypes]+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+Expected behavior of UnliftedDatatypes:++* Proposal: https://github.com/ghc-proposals/ghc-proposals/blob/master/proposals/0265-unlifted-datatypes.rst+* Discussion: https://github.com/ghc-proposals/ghc-proposals/pull/265++The implementation heavily leans on Note [Implementation of UnliftedNewtypes].++In the frontend, the following tweaks have been made in the typechecker:++* STEP 1: In the inferInitialKinds phase, newExpectedKind gives data type+ constructors a result kind of `TYPE r` with a fresh unification variable+ `r :: RuntimeRep` when there is a SAKS. (Same as for UnliftedNewtypes.)+ Not needed with a CUSK, because it can't specify result kinds.+ If there's a GADTSyntax result kind signature, we keep on using that kind.++ Similarly, for data instances without a kind signature, we use+ `TYPE r` as the result kind, to support the following code:++ data family F a :: UnliftedType+ data instance F Int = TInt++ The ommission of a kind signature for `F` should not mean a result kind+ of `Type` (and thus a kind error) here.++* STEP 2: No change to kcTyClDecl.++* STEP 3: In GHC.Tc.Gen.HsType.checkDataKindSig, we make sure that the result+ kind of the data declaration is actually `Type` or `TYPE (BoxedRep l)`,+ for some `l`. If UnliftedDatatypes is not activated, we emit an error with a+ suggestion in the latter case.++ Why not start out with `TYPE (BoxedRep l)` in the first place? Because then+ we get worse kind error messages in e.g. saks_fail010:++ - Couldn't match expected kind: TYPE ('GHC.Types.BoxedRep t0)+ - with actual kind: * -> *+ + Expected a type, but found something with kind ‘* -> *’+ In the data type declaration for ‘T’++ It seems `TYPE r` already has appropriate pretty-printing support.++The changes to Core, STG and Cmm are of rather cosmetic nature.+The IRs are already well-equipped to handle unlifted types, and unlifted+datatypes are just a new sub-class thereof. -} tcTyClDecl :: RolesInfo -> LTyClDecl GhcRn -> TcM (TyCon, [DerivInfo])@@ -2262,7 +2330,7 @@ _ -> pprPanic "tcTyClDecl" (ppr thing) | otherwise- = setSrcSpan loc $ tcAddDeclCtxt decl $+ = setSrcSpanA loc $ tcAddDeclCtxt decl $ do { traceTc "---- tcTyClDecl ---- {" (ppr decl) ; (tc, deriv_infos) <- tcTyClDecl1 Nothing roles_info decl ; traceTc "---- tcTyClDecl end ---- }" (ppr tc)@@ -2280,7 +2348,7 @@ if isFunTyCon tycon || isPrimTyCon tycon then [] -- no tyConTyVars else mkTyVarNamePairs (tyConTyVars tycon)- , di_clauses = unLoc derivs+ , di_clauses = derivs , di_ctxt = tcMkDeclCtxt decl } ] wiredInDerivInfo _ _ = [] @@ -2325,7 +2393,7 @@ * * ********************************************************************* -} -tcClassDecl1 :: RolesInfo -> Name -> LHsContext GhcRn+tcClassDecl1 :: RolesInfo -> Name -> Maybe (LHsContext GhcRn) -> LHsBinds GhcRn -> [LHsFunDep GhcRn] -> [LSig GhcRn] -> [LFamilyDecl GhcRn] -> [LTyFamDefltDecl GhcRn] -> TcM Class@@ -2343,7 +2411,7 @@ -- The (binderVars binders) is needed bring into scope the -- skolems bound by the class decl header (#17841) do { ctxt <- tcHsContext hs_ctxt- ; fds <- mapM (addLocM tc_fundep) fundeps+ ; fds <- mapM (addLocMA tc_fundep) fundeps ; sig_stuff <- tcClassSigs class_name sigs meths ; at_stuff <- tcClassATs class_name clas ats at_defs ; return (ctxt, fds, sig_stuff, at_stuff) }@@ -2387,9 +2455,11 @@ ; return clas } where skol_info = TyConSkol ClassFlavour class_name- tc_fundep (tvs1, tvs2) = do { tvs1' <- mapM (tcLookupTyVar . unLoc) tvs1 ;+ tc_fundep :: GHC.Hs.FunDep GhcRn -> TcM ([Var],[Var])+ tc_fundep (FunDep _ tvs1 tvs2)+ = do { tvs1' <- mapM (tcLookupTyVar . unLoc) tvs1 ; ; tvs2' <- mapM (tcLookupTyVar . unLoc) tvs2 ;- ; return (tvs1', tvs2') }+ ; return (tvs1',tvs2') } {- Note [Associated type defaults]@@ -2432,7 +2502,7 @@ (at_def_tycon at_def) [at_def]) emptyNameEnv at_defs - tc_at at = do { fam_tc <- addLocM (tcFamDecl1 (Just cls)) at+ tc_at at = do { fam_tc <- addLocMA (tcFamDecl1 (Just cls)) at ; let at_defs = lookupNameEnv at_defs_map (at_fam_name at) `orElse` [] ; atd <- tcDefaultAssocDecl fam_tc at_defs@@ -2457,7 +2527,7 @@ , feqn_pats = hs_pats , feqn_rhs = hs_rhs_ty }})] = -- See Note [Type-checking default assoc decls]- setSrcSpan loc $+ setSrcSpanA loc $ tcAddFamInstCtxt (text "default type instance") tc_name $ do { traceTc "tcDefaultAssocDecl 1" (ppr tc_name) ; let fam_tc_name = tyConName fam_tc@@ -2498,7 +2568,7 @@ -- simply create an empty substitution and let GHC fall -- over later, in GHC.Tc.Validity.checkValidAssocTyFamDeflt. -- See Note [Type-checking default assoc decls].- ; pure $ Just (substTyUnchecked subst rhs_ty, ATVI loc pats)+ ; pure $ Just (substTyUnchecked subst rhs_ty, ATVI (locA loc) pats) -- We perform checks for well-formedness and validity later, in -- GHC.Tc.Validity.checkValidAssocTyFamDeflt. }@@ -2728,7 +2798,7 @@ -- therefore we can always infer the result kind if we know the result type. -- But this does not seem to be useful in any way so we don't do it. (Another -- reason is that the implementation would not be straightforward.)-tcInjectivity tcbs (Just (L loc (InjectivityAnn _ lInjNames)))+tcInjectivity tcbs (Just (L loc (InjectivityAnn _ _ lInjNames))) = setSrcSpan loc $ do { let tvs = binderVars tcbs ; dflags <- getDynFlags@@ -2842,7 +2912,7 @@ gadt_syntax) } ; let deriv_info = DerivInfo { di_rep_tc = tycon , di_scoped_tvs = tcTyConScopedTyVars tctc- , di_clauses = unLoc derivs+ , di_clauses = derivs , di_ctxt = err_ctxt } ; traceTc "tcDataDefn" (ppr tc_name $$ ppr tycon_binders $$ ppr extra_bndrs) ; return (tycon, [deriv_info]) }@@ -2885,7 +2955,7 @@ , feqn_bndrs = outer_bndrs , feqn_pats = hs_pats , feqn_rhs = hs_rhs_ty }))- = setSrcSpan loc $+ = setSrcSpanA loc $ do { traceTc "kcTyFamInstEqn" (vcat [ text "tc_name =" <+> ppr eqn_tc_name , text "fam_tc =" <+> ppr tc_fam_tc <+> dcolon <+> ppr (tyConKind tc_fam_tc)@@ -2928,7 +2998,7 @@ (L loc (FamEqn { feqn_bndrs = outer_bndrs , feqn_pats = hs_pats , feqn_rhs = hs_rhs_ty }))- = setSrcSpan loc $+ = setSrcSpanA loc $ do { traceTc "tcTyFamInstEqn" $ vcat [ ppr loc, ppr fam_tc <+> ppr hs_pats , text "fam tc bndrs" <+> pprTyVars (tyConTyVars fam_tc)@@ -2951,7 +3021,7 @@ -- (tcFamInstEqnGuts zonks to Type) ; return (mkCoAxBranch qtvs [] [] pats rhs_ty (map (const Nominal) qtvs)- loc) }+ (locA loc)) } {- Note [Instantiating a family tycon] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~@@ -3089,7 +3159,7 @@ , (b_first : _) <- bndrs , let b_last = last bndrs skol_info = ForAllSkol (fsep (map ppr bndrs))- = setSrcSpan (combineSrcSpans (getLoc b_first) (getLoc b_last)) $+ = setSrcSpan (combineSrcSpans (getLocA b_first) (getLocA b_last)) $ emitResidualTvConstraint skol_info outer_tvs tclvl emptyWC | otherwise = return ()@@ -3210,11 +3280,12 @@ -} dataDeclChecks :: Name -> NewOrData- -> LHsContext GhcRn -> [LConDecl GhcRn]+ -> Maybe (LHsContext GhcRn) -> [LConDecl GhcRn] -> TcM Bool-dataDeclChecks tc_name new_or_data (L _ stupid_theta) cons- = do { -- Check that we don't use GADT syntax in H98 world- gadtSyntax_ok <- xoptM LangExt.GADTSyntax+dataDeclChecks tc_name new_or_data mctxt cons+ = do { let stupid_theta = fromMaybeContext mctxt+ -- Check that we don't use GADT syntax in H98 world+ ; gadtSyntax_ok <- xoptM LangExt.GADTSyntax ; let gadt_syntax = consUseGadtSyntax cons ; checkTc (gadtSyntax_ok || not gadt_syntax) (badGadtDecl tc_name) @@ -3262,7 +3333,7 @@ -> TcKind -- Result kind -> [LConDecl GhcRn] -> TcM [DataCon] tcConDecls new_or_data dd_info rep_tycon tmpl_bndrs res_kind- = concatMapM $ addLocM $+ = concatMapM $ addLocMA $ tcConDecl new_or_data dd_info rep_tycon tmpl_bndrs res_kind (mkTyConTagMap rep_tycon) -- mkTyConTagMap: it's important that we pay for tag allocation here,@@ -3296,7 +3367,7 @@ ; (tclvl, wanted, (exp_tvbndrs, (ctxt, arg_tys, field_lbls, stricts))) <- pushLevelAndSolveEqualitiesX "tcConDecl:H98" $ tcExplicitTKBndrs explicit_tkv_nms $- do { ctxt <- tcHsMbContext hs_ctxt+ do { ctxt <- tcHsContext hs_ctxt ; let exp_kind = getArgExpKind new_or_data res_kind ; btys <- tcConH98Args exp_kind hs_args ; field_lbls <- lookupConstructorFields name@@ -3382,7 +3453,7 @@ ; (tclvl, wanted, (outer_bndrs, (ctxt, arg_tys, res_ty, field_lbls, stricts))) <- pushLevelAndSolveEqualitiesX "tcConDecl:GADT" $ tcOuterTKBndrs skol_info outer_hs_bndrs $- do { ctxt <- tcHsMbContext cxt+ do { ctxt <- tcHsContext cxt ; (res_ty, res_kind) <- tcInferLHsTypeKind hs_res_ty -- See Note [GADT return kinds] @@ -3602,7 +3673,7 @@ ; return (Scaled w' arg_ty, getBangStrictness bty) } tcRecConDeclFields :: ContextKind- -> Located [LConDeclField GhcRn]+ -> LocatedL [LConDeclField GhcRn] -> TcM [(Scaled TcType, HsSrcBang)] tcRecConDeclFields exp_kind fields = mapM (tcConArg exp_kind) btys@@ -4230,7 +4301,7 @@ checkValidDataCon :: DynFlags -> Bool -> TyCon -> DataCon -> TcM () checkValidDataCon dflags existential_ok tc con = setSrcSpan con_loc $- addErrCtxt (dataConCtxt [L con_loc con_name]) $+ addErrCtxt (dataConCtxt [L (noAnnSrcSpan con_loc) con_name]) $ do { let tc_tvs = tyConTyVars tc res_ty_tmpl = mkFamilyTyConApp tc (mkTyVarTys tc_tvs) orig_res_ty = dataConOrigResTy con@@ -4308,7 +4379,7 @@ | HsSrcBang _ want_unpack strict_mark <- bang , isSrcUnpacked want_unpack, not (is_strict strict_mark)- = addWarnTc NoReason (bad_bang n (text "UNPACK pragma lacks '!'"))+ = addDiagnosticTc WarningWithoutFlag (bad_bang n (text "UNPACK pragma lacks '!'")) | HsSrcBang _ want_unpack _ <- bang , isSrcUnpacked want_unpack@@ -4324,7 +4395,7 @@ -- warn in this case (it gives users the wrong idea about whether -- or not UNPACK on abstract types is supported; it is!) , isHomeUnitDefinite (hsc_home_unit hsc_env)- = addWarnTc NoReason (bad_bang n (text "Ignoring unusable UNPACK pragma"))+ = addDiagnosticTc WarningWithoutFlag (bad_bang n (text "Ignoring unusable UNPACK pragma")) | otherwise = return ()@@ -4829,7 +4900,7 @@ = whenIsJust role_annot_decl_maybe $ \decl@(L loc (RoleAnnotDecl _ _ the_role_annots)) -> addRoleAnnotCtxt name $- setSrcSpan loc $ do+ setSrcSpanA loc $ do { role_annots_ok <- xoptM LangExt.RoleAnnotations ; checkTc role_annots_ok $ needXRoleAnnotations tc ; checkTc (vis_vars `equalLength` the_role_annots)@@ -5025,15 +5096,15 @@ = sep [text "Constructors" <+> ppr con1 <+> text "and" <+> ppr con2, text "give different types for field", quotes (ppr field_name)] -dataConCtxt :: [Located Name] -> SDoc+dataConCtxt :: [LocatedN Name] -> SDoc dataConCtxt cons = text "In the definition of data constructor" <> plural cons <+> ppr_cons cons -dataConResCtxt :: [Located Name] -> SDoc+dataConResCtxt :: [LocatedN Name] -> SDoc dataConResCtxt cons = text "In the result type of data constructor" <> plural cons <+> ppr_cons cons -ppr_cons :: [Located Name] -> SDoc+ppr_cons :: [LocatedN Name] -> SDoc ppr_cons [con] = quotes (ppr con) ppr_cons cons = interpp'SP cons @@ -5155,7 +5226,7 @@ illegalRoleAnnotDecl :: LRoleAnnotDecl GhcRn -> TcM () illegalRoleAnnotDecl (L loc (RoleAnnotDecl _ tycon _)) = setErrCtxt [] $- setSrcSpan loc $+ setSrcSpanA loc $ addErrTc (text "Illegal role annotation for" <+> ppr tycon <> char ';' $$ text "they are allowed only for datatypes and classes.")
compiler/GHC/Tc/TyCl/Class.hs view
@@ -152,12 +152,14 @@ ; traceTc "tcClassSigs 2" (ppr clas) ; return op_info } where- vanilla_sigs = [L loc (nm,ty) | L loc (ClassOpSig _ False nm ty) <- sigs]- gen_sigs = [L loc (nm,ty) | L loc (ClassOpSig _ True nm ty) <- sigs]+ vanilla_sigs :: [Located ([LocatedN Name], LHsSigType GhcRn)] -- AZ temp+ vanilla_sigs = [L (locA loc) (nm,ty) | L loc (ClassOpSig _ False nm ty) <- sigs]+ gen_sigs :: [Located ([LocatedN Name], LHsSigType GhcRn)] -- AZ temp+ gen_sigs = [L (locA loc) (nm,ty) | L loc (ClassOpSig _ True nm ty) <- sigs] dm_bind_names :: [Name] -- These ones have a value binding in the class decl dm_bind_names = [op | L _ (FunBind {fun_id = L _ op}) <- bagToList def_methods] - tc_sig :: NameEnv (SrcSpan, Type) -> ([Located Name], LHsSigType GhcRn)+ tc_sig :: NameEnv (SrcSpan, Type) -> ([LocatedN Name], LHsSigType GhcRn) -> TcM [TcMethInfo] tc_sig gen_dm_env (op_names, op_hs_ty) = do { traceTc "ClsSig 1" (ppr op_names)@@ -171,9 +173,12 @@ | nm `elem` dm_bind_names = Just VanillaDM | otherwise = Nothing + tc_gen_sig :: ([LocatedN Name], LHsSigType GhcRn)+ -> IOEnv (Env TcGblEnv TcLclEnv) [(Name, (SrcSpan, Type))] -- AZ temp tc_gen_sig (op_names, gen_hs_ty) = do { gen_op_ty <- tcClassSigType op_names gen_hs_ty- ; return [ (op_name, (loc, gen_op_ty)) | L loc op_name <- op_names ] }+ ; return [ (op_name, (locA loc, gen_op_ty))+ | L loc op_name <- op_names ] } {- ************************************************************************@@ -188,9 +193,9 @@ tcClassDecl2 (L _ (ClassDecl {tcdLName = class_name, tcdSigs = sigs, tcdMeths = default_binds}))- = recoverM (return emptyLHsBinds) $- setSrcSpan (getLoc class_name) $- do { clas <- tcLookupLocatedClass class_name+ = recoverM (return emptyLHsBinds) $+ setSrcSpan (getLocA class_name) $+ do { clas <- tcLookupLocatedClass (n2l class_name) -- We make a separate binding for each default method. -- At one time I used a single AbsBinds for all of them, thus@@ -227,7 +232,7 @@ tcDefMeth _ _ _ _ _ prag_fn (sel_id, Nothing) = do { -- No default method- mapM_ (addLocM (badDmPrag sel_id))+ mapM_ (addLocMA (badDmPrag sel_id)) (lookupPragEnv prag_fn (idName sel_id)) ; return emptyBag } @@ -253,10 +258,10 @@ ; spec_prags <- discardConstraints $ tcSpecPrags global_dm_id prags- ; warnTc NoReason- (not (null spec_prags))- (text "Ignoring SPECIALISE pragmas on default method"- <+> quotes (ppr sel_name))+ ; diagnosticTc WarningWithoutFlag+ (not (null spec_prags))+ (text "Ignoring SPECIALISE pragmas on default method"+ <+> quotes (ppr sel_name)) ; let hs_ty = hs_sig_fn sel_name `orElse` pprPanic "tc_dm" (ppr sel_name)@@ -272,7 +277,7 @@ local_dm_ty = instantiateMethod clas global_dm_id (mkTyVarTys tyvars) - lm_bind = dm_bind { fun_id = L bind_loc local_dm_name }+ lm_bind = dm_bind { fun_id = L (la2na bind_loc) local_dm_name } -- Substitute the local_meth_name for the binder -- NB: the binding is always a FunBind @@ -288,7 +293,7 @@ ; let local_dm_id = mkLocalId local_dm_name Many local_dm_ty local_dm_sig = CompleteSig { sig_bndr = local_dm_id , sig_ctxt = ctxt- , sig_loc = getLoc hs_ty }+ , sig_loc = getLocA hs_ty } ; (ev_binds, (tc_bind, _)) <- checkConstraints skol_info tyvars [this_dict] $@@ -332,12 +337,12 @@ -- since you can't write a default implementation. when (tcg_src tcg_env /= HsigFile) $ whenIsJust (isUnsatisfied (mindef `impliesAtom`) defMindef) $- (\bf -> addWarnTc NoReason (warningMinimalDefIncomplete bf))+ (\bf -> addDiagnosticTc WarningWithoutFlag (warningMinimalDefIncomplete bf)) return mindef where -- By default require all methods without a default implementation defMindef :: ClassMinimalDef- defMindef = mkAnd [ noLoc (mkVar name)+ defMindef = mkAnd [ noLocA (mkVar name) | (name, _, Nothing) <- op_info ] instantiateMethod :: Class -> TcId -> [TcType] -> TcType@@ -368,7 +373,7 @@ where env = mkHsSigEnv get_classop_sig sigs - get_classop_sig :: LSig GhcRn -> Maybe ([Located Name], LHsSigType GhcRn)+ get_classop_sig :: LSig GhcRn -> Maybe ([LocatedN Name], LHsSigType GhcRn) get_classop_sig (L _ (ClassOpSig _ _ ns hs_ty)) = Just (ns, hs_ty) get_classop_sig _ = Nothing @@ -387,7 +392,7 @@ f bind@(L _ (FunBind { fun_id = L bndr_loc op_name })) | op_name == sel_name- = Just (bind, bndr_loc, prags)+ = Just (bind, locA bndr_loc, prags) f _other = Nothing ---------------------------@@ -517,7 +522,7 @@ (tv', cv') = partition isTyVar tcv' tvs' = scopedSort tv' cvs' = scopedSort cv'- ; rep_tc_name <- newFamInstTyConName (L loc (tyConName fam_tc)) pat_tys'+ ; rep_tc_name <- newFamInstTyConName (L (noAnnSrcSpan loc) (tyConName fam_tc)) pat_tys' ; let axiom = mkSingleCoAxiom Nominal rep_tc_name tvs' [] cvs' fam_tc pat_tys' rhs' -- NB: no validity check. We check validity of default instances@@ -551,7 +556,7 @@ -- hs-boot and signatures never need to provide complete "definitions" -- of any sort, as they aren't really defining anything, but just -- constraining items which are defined elsewhere.- ; warnTc (Reason Opt_WarnMissingMethods) (warn && hsc_src == HsSrcFile)- (text "No explicit" <+> text "associated type"- <+> text "or default declaration for"- <+> quotes (ppr name)) }+ ; diagnosticTc (WarningWithFlag Opt_WarnMissingMethods) (warn && hsc_src == HsSrcFile)+ (text "No explicit" <+> text "associated type"+ <+> text "or default declaration for"+ <+> quotes (ppr name)) }
compiler/GHC/Tc/TyCl/Instance.hs view
@@ -484,7 +484,7 @@ , cid_sigs = uprags, cid_tyfam_insts = ats , cid_overlap_mode = overlap_mode , cid_datafam_insts = adts }))- = setSrcSpan loc $+ = setSrcSpanA loc $ addErrCtxt (instDeclCtxt1 hs_ty) $ do { dfun_ty <- tcHsClsInstType (InstDeclCtxt False) hs_ty ; let (tyvars, theta, clas, inst_tys) = tcSplitDFunTy dfun_ty@@ -517,7 +517,7 @@ -- from their defaults (if available) ; is_boot <- tcIsHsBootOrSig ; let atItems = classATItems clas- ; tf_insts2 <- mapM (tcATDefault loc mini_subst defined_ats)+ ; tf_insts2 <- mapM (tcATDefault (locA loc) mini_subst defined_ats) (if is_boot then [] else atItems) -- Don't default type family instances, but rather omit, in hsig/hs-boot. -- Since hsig/hs-boot files are essentially large binders we want omission@@ -532,7 +532,7 @@ -- Finally, construct the Core representation of the instance. -- (This no longer includes the associated types.)- ; dfun_name <- newDFunName clas inst_tys (getLoc hs_ty)+ ; dfun_name <- newDFunName clas inst_tys (getLocA hs_ty) -- Dfun location is that of instance *header* ; ispec <- newClsInst (fmap unLoc overlap_mode) dfun_name@@ -581,7 +581,7 @@ -- "type instance" -- See Note [Associated type instances] tcTyFamInstDecl mb_clsinfo (L loc decl@(TyFamInstDecl { tfid_eqn = eqn }))- = setSrcSpan loc $+ = setSrcSpanA loc $ tcAddTyFamInstCtxt decl $ do { let fam_lname = feqn_tycon eqn ; fam_tc <- tcLookupLocatedTyCon fam_lname@@ -595,7 +595,7 @@ -- For some reason we don't have a location for the equation -- itself, so we make do with the location of family name ; co_ax_branch <- tcTyFamInstEqn fam_tc mb_clsinfo- (L (getLoc fam_lname) eqn)+ (L (na2la $ getLoc fam_lname) eqn) -- (2) check for validity ; checkConsistentFamInst mb_clsinfo fam_tc co_ax_branch@@ -677,7 +677,7 @@ , dd_cons = hs_cons , dd_kindSig = m_ksig , dd_derivs = derivs } }}))- = setSrcSpan loc $+ = setSrcSpanA loc $ tcAddDataFamInstCtxt decl $ do { fam_tc <- tcLookupLocatedTyCon lfam_name @@ -727,7 +727,7 @@ ; traceTc "tcDataFamInstDecl" $ vcat [ text "Fam tycon:" <+> ppr fam_tc , text "Pats:" <+> ppr pats- , text "visiblities:" <+> ppr (tcbVisibilities fam_tc pats)+ , text "visibilities:" <+> ppr (tcbVisibilities fam_tc pats) , text "all_pats:" <+> ppr all_pats , text "ty_binders" <+> ppr ty_binders , text "fam_tc_binders:" <+> ppr (tyConBinders fam_tc)@@ -781,8 +781,8 @@ ; let scoped_tvs = map mk_deriv_info_scoped_tv_pr (tyConTyVars rep_tc) m_deriv_info = case derivs of- L _ [] -> Nothing- L _ preds ->+ [] -> Nothing+ preds -> Just $ DerivInfo { di_rep_tc = rep_tc , di_scoped_tvs = scoped_tvs , di_clauses = preds@@ -857,7 +857,7 @@ ----------------------- tcDataFamInstHeader :: AssocInstInfo -> TyCon -> HsOuterFamEqnTyVarBndrs GhcRn- -> LexicalFixity -> LHsContext GhcRn+ -> LexicalFixity -> Maybe (LHsContext GhcRn) -> HsTyPats GhcRn -> Maybe (LHsKind GhcRn) -> NewOrData -> TcM ([TyVar], [Type], Kind, ThetaType)@@ -940,12 +940,15 @@ fam_name = tyConName fam_tc data_ctxt = DataKindCtxt fam_name - -- See Note [Implementation of UnliftedNewtypes] in GHC.Tc.TyCl, wrinkle (2).+ -- See Note [Implementation of UnliftedNewtypes] in GHC.Tc.TyCl, families (2),+ -- and Note [Implementation of UnliftedDatatypes]. tc_kind_sig Nothing- = do { unlifted_newtypes <- xoptM LangExt.UnliftedNewtypes- ; if unlifted_newtypes && new_or_data == NewType- then newOpenTypeKind- else pure liftedTypeKind+ = do { unlifted_newtypes <- xoptM LangExt.UnliftedNewtypes+ ; unlifted_datatypes <- xoptM LangExt.UnliftedDatatypes+ ; case new_or_data of+ NewType | unlifted_newtypes -> newOpenTypeKind+ DataType | unlifted_datatypes -> newOpenTypeKind+ _ -> pure liftedTypeKind } -- See Note [Result kind signature for a data family instance]@@ -1234,8 +1237,9 @@ -- Create the result bindings ; self_dict <- newDict clas inst_tys ; let class_tc = classTyCon clas+ loc' = noAnnSrcSpan loc [dict_constr] = tyConDataCons class_tc- dict_bind = mkVarBind self_dict (L loc con_app_args)+ dict_bind = mkVarBind self_dict (L loc' con_app_args) -- We don't produce a binding for the dict_constr; instead we -- rely on the simplifier to unfold this saturated application@@ -1254,8 +1258,8 @@ con_app_args = foldl' app_to_meth con_app_tys sc_meth_ids app_to_meth :: HsExpr GhcTc -> Id -> HsExpr GhcTc- app_to_meth fun meth_id = HsApp noExtField (L loc fun)- (L loc (wrapId arg_wrapper meth_id))+ app_to_meth fun meth_id = HsApp noComments (L loc' fun)+ (L loc' (wrapId arg_wrapper meth_id)) inst_tv_tys = mkTyVarTys inst_tyvars arg_wrapper = mkWpEvVarApps dfun_ev_vars <.> mkWpTyApps inst_tv_tys@@ -1282,7 +1286,8 @@ , abs_binds = unitBag dict_bind , abs_sig = True } - ; return (unitBag (L loc main_bind) `unionBags` sc_meth_binds)+ ; return (unitBag (L loc' main_bind)+ `unionBags` sc_meth_binds) } where dfun_id = instanceDFunId ispec@@ -1321,7 +1326,7 @@ is_newtype = isNewTyCon clas_tc wrapId :: HsWrapper -> Id -> HsExpr GhcTc-wrapId wrapper id = mkHsWrap wrapper (HsVar noExtField (noLoc id))+wrapId wrapper id = mkHsWrap wrapper (HsVar noExtField (noLocA id)) {- Note [Typechecking plan for instance declarations] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~@@ -1433,7 +1438,7 @@ , abs_ev_binds = [dfun_ev_binds, local_ev_binds] , abs_binds = emptyBag , abs_sig = False }- ; return (sc_top_id, L loc bind, sc_implic) }+ ; return (sc_top_id, L (noAnnSrcSpan loc) bind, sc_implic) } ------------------- checkInstConstraints :: TcM result@@ -1652,7 +1657,7 @@ -> [TcTyVar] -> [EvVar] -> [TcType] -> TcEvBinds- -> ([Located TcSpecPrag], TcPragEnv)+ -> ([LTcSpecPrag], TcPragEnv) -> [ClassOpItem] -> InstBindings GhcRn -> TcM ([Id], LHsBinds GhcTc, Bag Implication)@@ -1719,12 +1724,15 @@ mkLHsWrap lam_wrapper (error_rhs dflags) ; return (meth_id, meth_bind, Nothing) } where- error_rhs dflags = L inst_loc $ HsApp noExtField error_fun (error_msg dflags)- error_fun = L inst_loc $+ inst_loc' = noAnnSrcSpan inst_loc+ error_rhs dflags = L inst_loc'+ $ HsApp noComments error_fun (error_msg dflags)+ error_fun = L inst_loc' $ wrapId (mkWpTyApps [ getRuntimeRep meth_tau, meth_tau]) nO_METHOD_BINDING_ERROR_ID- error_msg dflags = L inst_loc (HsLit noExtField (HsStringPrim NoSourceText+ error_msg dflags = L inst_loc'+ (HsLit noComments (HsStringPrim NoSourceText (unsafeMkByteString (error_string dflags)))) meth_tau = classMethodInstTy sel_id inst_tys error_string dflags = showSDoc dflags@@ -1836,7 +1844,8 @@ mkMethIds clas tyvars dfun_ev_vars inst_tys sel_id - ; let lm_bind = meth_bind { fun_id = L bndr_loc (idName local_meth_id) }+ ; let lm_bind = meth_bind { fun_id = L (noAnnSrcSpan bndr_loc)+ (idName local_meth_id) } -- Substitute the local_meth_name for the binder -- NB: the binding is always a FunBind @@ -1881,7 +1890,7 @@ -- There is a signature in the instance -- See Note [Instance method signatures] = do { (sig_ty, hs_wrap)- <- setSrcSpan (getLoc hs_sig_ty) $+ <- setSrcSpan (getLocA hs_sig_ty) $ do { inst_sigs <- xoptM LangExt.InstanceSigs ; checkTc inst_sigs (misplacedInstSig sel_name hs_sig_ty) ; sig_ty <- tcHsSigType (FunSigCtxt sel_name False) hs_sig_ty@@ -1902,7 +1911,7 @@ inner_meth_id = mkLocalId inner_meth_name Many sig_ty inner_meth_sig = CompleteSig { sig_bndr = inner_meth_id , sig_ctxt = ctxt- , sig_loc = getLoc hs_sig_ty }+ , sig_loc = getLocA hs_sig_ty } ; (tc_bind, [inner_id]) <- tcPolyCheck no_prag_fn inner_meth_sig meth_bind@@ -2061,17 +2070,17 @@ ; dm_id <- tcLookupId dm_name ; let inline_prag = idInlinePragma dm_id inline_prags | isAnyInlinePragma inline_prag- = [noLoc (InlineSig noExtField fn inline_prag)]+ = [noLocA (InlineSig noAnn fn inline_prag)] | otherwise = [] -- Copy the inline pragma (if any) from the default method -- to this version. Note [INLINE and default methods] - fn = noLoc (idName sel_id)+ fn = noLocA (idName sel_id) visible_inst_tys = [ ty | (tcb, ty) <- tyConBinders (classTyCon clas) `zip` inst_tys , tyConBinderArgFlag tcb /= Inferred ] rhs = foldl' mk_vta (nlHsVar dm_name) visible_inst_tys- bind = noLoc $ mkTopFunBind Generated fn $+ bind = noLocA $ mkTopFunBind Generated fn $ [mkSimpleMatch (mkPrefixFunRhs fn) [] rhs] ; liftIO (dumpIfSet_dyn logger dflags Opt_D_dump_deriv "Filling in method body"@@ -2084,8 +2093,8 @@ (_, _, _, inst_tys) = tcSplitDFunTy (idType dfun_id) mk_vta :: LHsExpr GhcRn -> Type -> LHsExpr GhcRn- mk_vta fun ty = noLoc (HsAppType noExtField fun (mkEmptyWildCardBndrs $ nlHsParTy- $ noLoc $ XHsType ty))+ mk_vta fun ty = noLocA (HsAppType noExtField fun (mkEmptyWildCardBndrs $ nlHsParTy+ $ noLocA $ XHsType ty)) -- NB: use visible type application -- See Note [Default methods in instances] @@ -2100,7 +2109,7 @@ warnUnsatisfiedMinimalDefinition :: ClassMinimalDef -> TcM () warnUnsatisfiedMinimalDefinition mindef = do { warn <- woptM Opt_WarnMissingMethods- ; warnTc (Reason Opt_WarnMissingMethods) warn message+ ; diagnosticTc (WarningWithFlag Opt_WarnMissingMethods) warn message } where message = vcat [text "No explicit implementation for"@@ -2278,9 +2287,9 @@ -} tcSpecInstPrags :: DFunId -> InstBindings GhcRn- -> TcM ([Located TcSpecPrag], TcPragEnv)+ -> TcM ([LTcSpecPrag], TcPragEnv) tcSpecInstPrags dfun_id (InstBindings { ib_binds = binds, ib_pragmas = uprags })- = do { spec_inst_prags <- mapM (wrapLocM (tcSpecInst dfun_id)) $+ = do { spec_inst_prags <- mapM (wrapLocAM (tcSpecInst dfun_id)) $ filter isSpecInstLSig uprags -- The filter removes the pragmas for methods ; return (spec_inst_prags, mkPragEnv uprags binds) }
compiler/GHC/Tc/TyCl/PatSyn.hs view
@@ -638,9 +638,9 @@ InfixCon name1 name2 -> (map unLoc [name1, name2], True) RecCon names -> (map (unLoc . recordPatSynPatVar) names, False) -addPatSynCtxt :: Located Name -> TcM a -> TcM a+addPatSynCtxt :: LocatedN Name -> TcM a -> TcM a addPatSynCtxt (L loc name) thing_inside- = setSrcSpan loc $+ = setSrcSpanA loc $ addErrCtxt (text "In the declaration for pattern synonym" <+> quotes (ppr name)) $ thing_inside@@ -654,7 +654,7 @@ ------------------------- -- Shared by both tcInferPatSyn and tcCheckPatSyn-tc_patsyn_finish :: Located Name -- ^ PatSyn Name+tc_patsyn_finish :: LocatedN Name -- ^ PatSyn Name -> HsPatSynDir GhcRn -- ^ PatSyn type (Uni/Bidir/ExplicitBidir) -> Bool -- ^ Whether infix -> LPat GhcTc -- ^ Pattern of the PatSyn@@ -737,7 +737,7 @@ ************************************************************************ -} -tcPatSynMatcher :: Located Name+tcPatSynMatcher :: LocatedN Name -> LPat GhcTc -> TcPragEnv -> ([TcTyVar], ThetaType, TcEvBinds, [EvVar])@@ -750,8 +750,9 @@ (univ_tvs, req_theta, req_ev_binds, req_dicts) (ex_tvs, ex_tys, prov_theta, prov_dicts) (args, arg_tys) pat_ty- = do { rr_name <- newNameAt (mkTyVarOcc "rep") loc- ; tv_name <- newNameAt (mkTyVarOcc "r") loc+ = do { let loc' = locA loc+ ; rr_name <- newNameAt (mkTyVarOcc "rep") loc'+ ; tv_name <- newNameAt (mkTyVarOcc "r") loc' ; let rr_tv = mkTyVar rr_name runtimeRepTy rr = mkTyVarTy rr_tv res_tv = mkTyVar tv_name (tYPE rr)@@ -782,7 +783,7 @@ fail' = nlHsApps fail [nlHsVar voidPrimId] args = map nlVarPat [scrutinee, cont, fail]- lwpat = noLoc $ WildPat pat_ty+ lwpat = noLocA $ WildPat pat_ty cases = if isIrrefutableHsPat dflags lpat then [mkHsCaseAlt lpat cont'] else [mkHsCaseAlt lpat cont',@@ -790,23 +791,23 @@ body = mkLHsWrap (mkWpLet req_ev_binds) $ L (getLoc lpat) $ HsCase noExtField (nlHsVar scrutinee) $- MG{ mg_alts = L (getLoc lpat) cases+ MG{ mg_alts = L (l2l $ getLoc lpat) cases , mg_ext = MatchGroupTc [unrestricted pat_ty] res_ty , mg_origin = Generated }- body' = noLoc $+ body' = noLocA $ HsLam noExtField $- MG{ mg_alts = noLoc [mkSimpleMatch LambdaExpr- args body]+ MG{ mg_alts = noLocA [mkSimpleMatch LambdaExpr+ args body] , mg_ext = MatchGroupTc (map unrestricted [pat_ty, cont_ty, fail_ty]) res_ty , mg_origin = Generated } match = mkMatch (mkPrefixFunRhs (L loc name)) [] (mkHsLams (rr_tv:res_tv:univ_tvs) req_dicts body')- (noLoc (EmptyLocalBinds noExtField))+ (EmptyLocalBinds noExtField) mg :: MatchGroup GhcTc (LHsExpr GhcTc)- mg = MG{ mg_alts = L (getLoc match) [match]+ mg = MG{ mg_alts = L (l2l $ getLoc match) [match] , mg_ext = MatchGroupTc [] res_ty , mg_origin = Generated }@@ -818,7 +819,7 @@ , fun_matches = mg , fun_ext = idHsWrapper , fun_tick = [] }- matcher_bind = unitBag (noLoc bind)+ matcher_bind = unitBag (noLocA bind) ; traceTc "tcPatSynMatcher" (ppr name $$ ppr (idType matcher_id)) ; traceTc "tcPatSynMatcher" (ppr matcher_bind) @@ -845,7 +846,7 @@ ************************************************************************ -} -mkPatSynBuilder :: HsPatSynDir a -> Located Name+mkPatSynBuilder :: HsPatSynDir a -> LocatedN Name -> [InvisTVBinder] -> ThetaType -> [InvisTVBinder] -> ThetaType -> [Type] -> Type@@ -879,7 +880,7 @@ = return emptyBag | Left why <- mb_match_group -- Can't invert the pattern- = setSrcSpan (getLoc lpat) $ failWithTc $+ = setSrcSpan (getLocA lpat) $ failWithTc $ vcat [ hang (text "Invalid right-hand side of bidirectional pattern synonym" <+> quotes (ppr ps_name) <> colon) 2 why@@ -919,7 +920,7 @@ vcat [ ppr patsyn , ppr builder_id <+> dcolon <+> ppr (idType builder_id) , ppr prags ]- ; (builder_binds, _) <- tcPolyCheck emptyPragEnv sig (noLoc bind)+ ; (builder_binds, _) <- tcPolyCheck emptyPragEnv sig (noLocA bind) ; traceTc "tcPatSynBuilderBind }" $ ppr builder_binds ; return builder_binds } } } @@ -934,13 +935,13 @@ Unidirectional -> panic "tcPatSynBuilderBind" mk_mg :: LHsExpr GhcRn -> MatchGroup GhcRn (LHsExpr GhcRn)- mk_mg body = mkMatchGroup Generated [builder_match]+ mk_mg body = mkMatchGroup Generated (noLocA [builder_match]) where- builder_args = [L loc (VarPat noExtField (L loc n))+ builder_args = [L (na2la loc) (VarPat noExtField (L loc n)) | L loc n <- args] builder_match = mkMatch (mkPrefixFunRhs ps_lname) builder_args body- (noLoc (EmptyLocalBinds noExtField))+ (EmptyLocalBinds noExtField) args = case details of PrefixCon _ args -> args@@ -974,7 +975,7 @@ | need_dummy_arg = mkVisFunTyMany unboxedUnitTy ty | otherwise = ty -tcPatToExpr :: Name -> [Located Name] -> LPat GhcRn+tcPatToExpr :: Name -> [LocatedN Name] -> LPat GhcRn -> Either SDoc (LHsExpr GhcRn) -- Given a /pattern/, return an /expression/ that builds a value -- that matches the pattern. E.g. if the pattern is (Just [x]),@@ -989,20 +990,23 @@ lhsVars = mkNameSet (map unLoc args) -- Make a prefix con for prefix and infix patterns for simplicity- mkPrefixConExpr :: Located Name -> [LPat GhcRn]+ mkPrefixConExpr :: LocatedN Name -> [LPat GhcRn] -> Either SDoc (HsExpr GhcRn) mkPrefixConExpr lcon@(L loc _) pats = do { exprs <- mapM go pats- ; let con = L loc (HsVar noExtField lcon)+ ; let con = L (l2l loc) (HsVar noExtField lcon) ; return (unLoc $ mkHsApps con exprs) } - mkRecordConExpr :: Located Name -> HsRecFields GhcRn (LPat GhcRn)+ mkRecordConExpr :: LocatedN Name -> HsRecFields GhcRn (LPat GhcRn) -> Either SDoc (HsExpr GhcRn)- mkRecordConExpr con fields- = do { exprFields <- mapM go fields- ; return (RecordCon noExtField con exprFields) }+ mkRecordConExpr con (HsRecFields fields dd)+ = do { exprFields <- mapM go' fields+ ; return (RecordCon noExtField con (HsRecFields exprFields dd)) } + go' :: LHsRecField GhcRn (LPat GhcRn) -> Either SDoc (LHsRecField GhcRn (LHsExpr GhcRn))+ go' (L l rf) = L l <$> traverse go rf+ go :: LPat GhcRn -> Either SDoc (LHsExpr GhcRn) go (L loc p) = L loc <$> go1 p @@ -1021,25 +1025,24 @@ = return $ HsVar noExtField (L l var) | otherwise = Left (quotes (ppr var) <+> text "is not bound by the LHS of the pattern synonym")- go1 (ParPat _ pat) = fmap (HsPar noExtField) $ go pat+ go1 (ParPat _ pat) = fmap (HsPar noAnn) $ go pat go1 p@(ListPat reb pats) | Nothing <- reb = do { exprs <- mapM go pats ; return $ ExplicitList noExtField exprs } | otherwise = notInvertibleListPat p go1 (TuplePat _ pats box) = do { exprs <- mapM go pats ; return $ ExplicitTuple noExtField- (map (noLoc . (Present noExtField)) exprs)- box }+ (map (Present noAnn) exprs) box } go1 (SumPat _ pat alt arity) = do { expr <- go1 (unLoc pat) ; return $ ExplicitSum noExtField alt arity- (noLoc expr)+ (noLocA expr) }- go1 (LitPat _ lit) = return $ HsLit noExtField lit+ go1 (LitPat _ lit) = return $ HsLit noComments lit go1 (NPat _ (L _ n) mb_neg _) | Just (SyntaxExprRn neg) <- mb_neg- = return $ unLoc $ foldl' nlHsApp (noLoc neg)- [noLoc (HsOverLit noExtField n)]- | otherwise = return $ HsOverLit noExtField n+ = return $ unLoc $ foldl' nlHsApp (noLocA neg)+ [noLocA (HsOverLit noAnn n)]+ | otherwise = return $ HsOverLit noAnn n go1 (SplicePat _ (HsSpliced _ _ (HsSplicedPat pat))) = go1 pat go1 (SplicePat _ (HsSpliced{})) = panic "Invalid splice variety"
compiler/GHC/Tc/TyCl/Utils.hs view
@@ -242,7 +242,7 @@ mod = nameModule n ppr_decl tc = case lookupNameEnv lcl_decls n of- Just (L loc decl) -> ppr loc <> colon <+> ppr decl+ Just (L loc decl) -> ppr (locA loc) <> colon <+> ppr decl Nothing -> ppr (getSrcSpan n) <> colon <+> ppr n <+> text "from external module" where@@ -851,7 +851,8 @@ tcValBinds TopLevel binds sigs getGblEnv ; return (tcg_env `addTypecheckedBinds` map snd rec_sel_binds) } where- sigs = [ L loc (IdSig noExtField sel_id) | (sel_id, _) <- sel_bind_prs+ sigs = [ L (noAnnSrcSpan loc) (IdSig noExtField sel_id)+ | (sel_id, _) <- sel_bind_prs , let loc = getSrcSpan sel_id ] binds = [(NonRecursive, unitBag bind) | (_, bind) <- sel_bind_prs] @@ -873,9 +874,11 @@ mkOneRecordSelector :: [ConLike] -> RecSelParent -> FieldLabel -> FieldSelectors -> (Id, LHsBind GhcRn) mkOneRecordSelector all_cons idDetails fl has_sel- = (sel_id, L loc sel_bind)+ = (sel_id, L (noAnnSrcSpan loc) sel_bind) where loc = getSrcSpan sel_name+ loc' = noAnnSrcSpan loc+ locn = noAnnSrcSpan loc lbl = flLabel fl sel_name = flSelector fl @@ -913,18 +916,19 @@ [] unit_rhs] | otherwise = map mk_match cons_w_field ++ deflt mk_match con = mkSimpleMatch (mkPrefixFunRhs sel_lname)- [L loc (mk_sel_pat con)]- (L loc (HsVar noExtField (L loc field_var)))- mk_sel_pat con = ConPat NoExtField (L loc (getName con)) (RecCon rec_fields)+ [L loc' (mk_sel_pat con)]+ (L loc' (HsVar noExtField (L locn field_var)))+ mk_sel_pat con = ConPat NoExtField (L locn (getName con)) (RecCon rec_fields) rec_fields = HsRecFields { rec_flds = [rec_field], rec_dotdot = Nothing }- rec_field = noLoc (HsRecField- { hsRecFieldLbl+ rec_field = noLocA (HsRecField+ { hsRecFieldAnn = noAnn+ , hsRecFieldLbl = L loc (FieldOcc sel_name- (L loc $ mkVarUnqual lbl))+ (L locn $ mkVarUnqual lbl)) , hsRecFieldArg- = L loc (VarPat noExtField (L loc field_var))+ = L loc' (VarPat noExtField (L locn field_var)) , hsRecPun = False })- sel_lname = L loc sel_name+ sel_lname = L locn sel_name field_var = mkInternalName (mkBuiltinUnique 1) (getOccName sel_name) loc -- Add catch-all default case unless the case is exhaustive@@ -932,10 +936,10 @@ -- mentions this particular record selector deflt | all dealt_with all_cons = [] | otherwise = [mkSimpleMatch CaseAlt- [L loc (WildPat noExtField)]- (mkHsApp (L loc (HsVar noExtField- (L loc (getName rEC_SEL_ERROR_ID))))- (L loc (HsLit noExtField msg_lit)))]+ [L loc' (WildPat noExtField)]+ (mkHsApp (L loc' (HsVar noExtField+ (L locn (getName rEC_SEL_ERROR_ID))))+ (L loc' (HsLit noComments msg_lit)))] -- Do not add a default case unless there are unmatched -- constructors. We must take account of GADTs, else we@@ -966,7 +970,7 @@ -- scenarios, eq_subst is an empty substitution. inst_tys = substTyVars eq_subst univ_tvs - unit_rhs = mkLHsTupleExpr []+ unit_rhs = mkLHsTupleExpr [] noExtField msg_lit = HsStringPrim NoSourceText (bytesFS lbl) {-
compiler/GHC/Tc/Types/EvTerm.hs view
@@ -13,6 +13,7 @@ import GHC.Unit import GHC.Builtin.Names+import GHC.Builtin.Types ( liftedRepTy, unitTy ) import GHC.Core.Type import GHC.Core@@ -32,7 +33,11 @@ evDelayedError :: Type -> FastString -> EvTerm evDelayedError ty msg = EvExpr $- Var errorId `mkTyApps` [getRuntimeRep ty, ty] `mkApps` [litMsg]+ let fail_expr = Var errorId `mkTyApps` [liftedRepTy, unitTy] `mkApps` [litMsg]+ in mkWildCase fail_expr (unrestricted unitTy) ty []+ -- See Note [Incompleteness and linearity] in GHC.HsToCore.Utils+ -- c.f. mkFailExpr in GHC.HsToCore.Utils+ where errorId = tYPE_ERROR_ID litMsg = Lit (LitString (bytesFS msg))
compiler/GHC/Tc/Utils/Backpack.hs view
@@ -23,6 +23,7 @@ import GHC.Driver.Ppr import GHC.Types.Basic (TypeOrKind(..))+import GHC.Types.Error ( DiagnosticMessage ) import GHC.Types.Fixity (defaultFixity) import GHC.Types.Fixity.Env import GHC.Types.TypeEnv@@ -185,7 +186,7 @@ -- TODO: maybe we can be a little more -- precise here and use the Located -- info for the *specific* name we matched.- -> getLoc e+ -> getLocA e _ -> nameSrcSpan name addErrAt loc (badReexportedBootThing False name name')@@ -274,10 +275,11 @@ findExtraSigImports' hsc_env HsigFile modname = fmap unionManyUniqDSets (forM reqs $ \(Module iuid mod_name) -> (initIfaceLoad hsc_env- . withException+ . withException dflags $ moduleFreeHolesPrecise (text "findExtraSigImports") (mkModule (VirtUnit iuid) mod_name))) where+ dflags = hsc_dflags hsc_env unit_state = hsc_units hsc_env reqs = requirementMerges unit_state modname @@ -311,12 +313,16 @@ implicitRequirements' hsc_env normal_imports = fmap concat $ forM normal_imports $ \(mb_pkg, L _ imp) -> do- found <- findImportedModule hsc_env imp mb_pkg+ found <- findImportedModule fc units home_unit dflags imp mb_pkg case found of Found _ mod | not (isHomeModule home_unit mod) -> return (uniqDSetToList (moduleFreeHoles mod)) _ -> return []- where home_unit = hsc_home_unit hsc_env+ where+ fc = hsc_FC hsc_env+ home_unit = hsc_home_unit hsc_env+ units = hsc_units hsc_env+ dflags = hsc_dflags hsc_env -- | Like @implicitRequirements'@, but returns either the module name, if it is -- a free hole, or the instantiated unit the imported module is from, so that@@ -328,11 +334,16 @@ -> IO ([ModuleName], [InstantiatedUnit]) implicitRequirementsShallow hsc_env normal_imports = go ([], []) normal_imports where+ fc = hsc_FC hsc_env+ home_unit = hsc_home_unit hsc_env+ units = hsc_units hsc_env+ dflags = hsc_dflags hsc_env+ go acc [] = pure acc go (accL, accR) ((mb_pkg, L _ imp):imports) = do- found <- findImportedModule hsc_env imp mb_pkg+ found <- findImportedModule fc units home_unit dflags imp mb_pkg let acc' = case found of- Found _ mod | not (isHomeModule (hsc_home_unit hsc_env) mod) ->+ Found _ mod | not (isHomeModule home_unit mod) -> case moduleUnit mod of HoleUnit -> (moduleName mod : accL, accR) RealUnit _ -> (accL, accR)@@ -361,7 +372,7 @@ -- an @hsig@ file.) tcRnCheckUnit :: HscEnv -> Unit ->- IO (Messages DecoratedSDoc, Maybe ())+ IO (Messages DiagnosticMessage, Maybe ()) tcRnCheckUnit hsc_env uid = withTiming logger dflags (text "Check unit id" <+> ppr uid)@@ -382,7 +393,7 @@ -- | Top-level driver for signature merging (run after typechecking -- an @hsig@ file). tcRnMergeSignatures :: HscEnv -> HsParsedModule -> TcGblEnv {- from local sig -} -> ModIface- -> IO (Messages DecoratedSDoc, Maybe TcGblEnv)+ -> IO (Messages DiagnosticMessage, Maybe TcGblEnv) tcRnMergeSignatures hsc_env hpm orig_tcg_env iface = withTiming logger dflags (text "Signature merging" <+> brackets (ppr this_mod))@@ -560,10 +571,15 @@ tcg_env <- getGblEnv let outer_mod = tcg_mod tcg_env- inner_mod = tcg_semantic_mod tcg_env- mod_name = moduleName (tcg_mod tcg_env)- unit_state = hsc_units hsc_env- home_unit = hsc_home_unit hsc_env+ let inner_mod = tcg_semantic_mod tcg_env+ let mod_name = moduleName (tcg_mod tcg_env)+ let unit_state = hsc_units hsc_env+ let fc = hsc_FC hsc_env+ let nc = hsc_NC hsc_env+ let home_unit = hsc_home_unit hsc_env+ let dflags = hsc_dflags hsc_env+ let logger = hsc_logger hsc_env+ let hooks = hsc_hooks hsc_env -- STEP 1: Figure out all of the external signature interfaces -- we are going to merge in.@@ -572,12 +588,13 @@ addErrCtxt (pprWithUnitState unit_state $ merge_msg mod_name reqs) $ do -- STEP 2: Read in the RAW forms of all of these interfaces- ireq_ifaces0 <- forM reqs $ \(Module iuid mod_name) ->+ ireq_ifaces0 <- liftIO $ forM reqs $ \(Module iuid mod_name) -> do let m = mkModule (VirtUnit iuid) mod_name im = fst (getModuleInstantiation m)- in fmap fst- . withException- $ findAndReadIface (text "mergeSignatures") im m NotBoot+ fmap fst+ . withException dflags+ $ findAndReadIface logger nc fc hooks unit_state home_unit dflags+ (text "mergeSignatures") im m NotBoot -- STEP 3: Get the unrenamed exports of all these interfaces, -- thin it according to the export list, and do shaping on them.@@ -611,7 +628,7 @@ -- a signature package (i.e., does not expose any -- modules.) If so, we can thin it. | isFromSignaturePackage- -> setSrcSpan loc $ do+ -> setSrcSpanA loc $ do -- Suppress missing errors; they might be used to refer -- to entities from other signatures we are merging in. -- If an identifier truly doesn't exist in any of the@@ -665,7 +682,7 @@ is_mod = mod_name, is_as = mod_name, is_qual = False,- is_dloc = loc+ is_dloc = locA loc } ImpAll rdr_env = mkGlobalRdrEnv (gresFromAvails (Just ispec) as1) setGblEnv tcg_env {@@ -914,7 +931,7 @@ -- an @hsig@ file.) tcRnInstantiateSignature :: HscEnv -> Module -> RealSrcSpan ->- IO (Messages DecoratedSDoc, Maybe TcGblEnv)+ IO (Messages DiagnosticMessage, Maybe TcGblEnv) tcRnInstantiateSignature hsc_env this_mod real_loc = withTiming logger dflags (text "Signature instantiation"<+>brackets (ppr this_mod))@@ -987,7 +1004,17 @@ -- instantiation is correct. let sig_mod = mkModule (VirtUnit uid) mod_name isig_mod = fst (getModuleInstantiation sig_mod)- mb_isig_iface <- findAndReadIface (text "checkImplements 2") isig_mod sig_mod NotBoot+ hsc_env <- getTopEnv+ let nc = hsc_NC hsc_env+ let fc = hsc_FC hsc_env+ let home_unit = hsc_home_unit hsc_env+ let units = hsc_units hsc_env+ let dflags = hsc_dflags hsc_env+ let logger = hsc_logger hsc_env+ let hooks = hsc_hooks hsc_env+ mb_isig_iface <- liftIO $ findAndReadIface logger nc fc hooks units home_unit dflags+ (text "checkImplements 2")+ isig_mod sig_mod NotBoot isig_iface <- case mb_isig_iface of Succeeded (iface, _) -> return iface Failed err -> failWithTc $
compiler/GHC/Tc/Utils/Env.hs view
@@ -229,10 +229,10 @@ -} -tcLookupLocatedGlobal :: Located Name -> TcM TyThing+tcLookupLocatedGlobal :: LocatedA Name -> TcM TyThing -- c.f. GHC.IfaceToCore.tcIfaceGlobal tcLookupLocatedGlobal name- = addLocM tcLookupGlobal name+ = addLocMA tcLookupGlobal name tcLookupGlobal :: Name -> TcM TyThing -- The Name is almost always an ExternalName, but not always@@ -310,14 +310,14 @@ ACoAxiom ax -> return ax _ -> wrongThingErr "axiom" (AGlobal thing) name -tcLookupLocatedGlobalId :: Located Name -> TcM Id-tcLookupLocatedGlobalId = addLocM tcLookupId+tcLookupLocatedGlobalId :: LocatedA Name -> TcM Id+tcLookupLocatedGlobalId = addLocMA tcLookupId -tcLookupLocatedClass :: Located Name -> TcM Class-tcLookupLocatedClass = addLocM tcLookupClass+tcLookupLocatedClass :: LocatedA Name -> TcM Class+tcLookupLocatedClass = addLocMA tcLookupClass -tcLookupLocatedTyCon :: Located Name -> TcM TyCon-tcLookupLocatedTyCon = addLocM tcLookupTyCon+tcLookupLocatedTyCon :: LocatedN Name -> TcM TyCon+tcLookupLocatedTyCon = addLocMA tcLookupTyCon -- Find the instance that exactly matches a type class application. The class arguments must be precisely -- the same as in the instance declaration (modulo renaming & casts).@@ -424,8 +424,8 @@ ************************************************************************ -} -tcLookupLocated :: Located Name -> TcM TcTyThing-tcLookupLocated = addLocM tcLookup+tcLookupLocated :: LocatedA Name -> TcM TcTyThing+tcLookupLocated = addLocMA tcLookup tcLookupLcl_maybe :: Name -> TcM (Maybe TcTyThing) tcLookupLcl_maybe name@@ -437,7 +437,7 @@ local_env <- getLclTypeEnv case lookupNameEnv local_env name of Just thing -> return thing- Nothing -> AGlobal <$> tcLookupGlobal name+ Nothing -> (AGlobal <$> tcLookupGlobal name) tcLookupTyVar :: Name -> TcM TcTyVar tcLookupTyVar name@@ -1056,12 +1056,12 @@ ; dfun_occ <- chooseUniqueOccTc (mkDFunOcc info_string is_boot) ; newGlobalBinder mod dfun_occ loc } -newFamInstTyConName :: Located Name -> [Type] -> TcM Name-newFamInstTyConName (L loc name) tys = mk_fam_inst_name id loc name [tys]+newFamInstTyConName :: LocatedN Name -> [Type] -> TcM Name+newFamInstTyConName (L loc name) tys = mk_fam_inst_name id (locA loc) name [tys] -newFamInstAxiomName :: Located Name -> [[Type]] -> TcM Name+newFamInstAxiomName :: LocatedN Name -> [[Type]] -> TcM Name newFamInstAxiomName (L loc name) branches- = mk_fam_inst_name mkInstTyCoOcc loc name branches+ = mk_fam_inst_name mkInstTyCoOcc (locA loc) name branches mk_fam_inst_name :: (OccName -> OccName) -> SrcSpan -> Name -> [[Type]] -> TcM Name mk_fam_inst_name adaptOcc loc tc_name tyss
compiler/GHC/Tc/Utils/Instantiate.hs view
@@ -127,7 +127,7 @@ ; wrap <- ASSERT( not (isForAllTy ty) && isSingleton theta ) instCall origin ty_args theta - ; return (mkHsWrap wrap (HsVar noExtField (noLoc id))) }+ ; return (mkHsWrap wrap (HsVar noExtField (noLocA id))) } {- ************************************************************************@@ -761,7 +761,7 @@ -- same type as the standard one. -- Tiresome jiggling because tcCheckSigma takes a located expression span <- getSrcSpanM- expr <- tcCheckPolyExpr (L span user_nm_expr) sigma1+ expr <- tcCheckPolyExpr (L (noAnnSrcSpan span) user_nm_expr) sigma1 return (std_nm, unLoc expr) syntaxNameCtxt :: HsExpr GhcRn -> CtOrigin -> Type -> TidyEnv
compiler/GHC/Tc/Utils/Monad.hs view
@@ -28,7 +28,7 @@ whenDOptM, whenGOptM, whenWOptM, whenXOptM, unlessXOptM, getGhcMode,- withDynamicNow, withoutDynamicNow,+ withoutDynamicNow, getEpsVar, getEps, updateEps, updateEps_,@@ -49,7 +49,7 @@ dumpTcRn, getPrintUnqualified, printForUserTcRn,- traceIf, traceHiDiffs, traceOptIf,+ traceIf, traceOptIf, debugTc, -- * Typechecker global environment@@ -61,8 +61,9 @@ addDependentFiles, -- * Error management- getSrcSpanM, setSrcSpan, addLocM, inGeneratedCode,- wrapLocM, wrapLocFstM, wrapLocSndM,wrapLocM_,+ getSrcSpanM, setSrcSpan, setSrcSpanA, addLocM, addLocMA, inGeneratedCode,+ wrapLocM, wrapLocAM, wrapLocFstM, wrapLocFstMA, wrapLocSndM, wrapLocSndMA, wrapLocM_,+ wrapLocMA_,wrapLocMA, getErrsVar, setErrsVar, addErr, failWith, failAt,@@ -75,8 +76,8 @@ tcCollectingUsage, tcScalingUsage, tcEmitBindingUsage, -- * Shared error message stuff: renamer and typechecker- mkLongErrAt, mkDecoratedSDocAt, addLongErrAt, reportErrors, reportError,- reportWarning, recoverM, mapAndRecoverM, mapAndReportM, foldAndRecoverM,+ mkLongErrAt, mkDecoratedSDocAt, addLongErrAt, reportDiagnostic, reportDiagnostics,+ recoverM, mapAndRecoverM, mapAndReportM, foldAndRecoverM, attemptM, tryTc, askNoErrs, discardErrs, tryTcDiscardingErrs, checkNoErrs, whenNoErrs,@@ -92,8 +93,8 @@ failWithTc, failWithTcM, checkTc, checkTcM, failIfTc, failIfTcM,- warnIfFlag, warnIf, warnTc, warnTcM,- addWarnTc, addWarnTcM, addWarn, addWarnAt, add_warn,+ warnIfFlag, warnIf, diagnosticTc, diagnosticTcM,+ addDiagnosticTc, addDiagnosticTcM, addDiagnostic, addDiagnosticAt, add_diagnostic, mkErrInfo, -- * Type constraints@@ -232,7 +233,7 @@ -> Module -> RealSrcSpan -> TcM r- -> IO (Messages DecoratedSDoc, Maybe r)+ -> IO (Messages DiagnosticMessage, Maybe r) -- Nothing => error thrown by the thing inside -- (error messages should have been printed already) @@ -257,9 +258,11 @@ th_coreplugins_var <- newIORef [] ; th_state_var <- newIORef Map.empty ; th_remote_state_var <- newIORef Nothing ;+ th_docs_var <- newIORef Map.empty ; let {- dflags = hsc_dflags hsc_env ;- home_unit = hsc_home_unit hsc_env ;+ -- bangs to avoid leaking the env (#19356)+ !dflags = hsc_dflags hsc_env ;+ !home_unit = hsc_home_unit hsc_env ; maybe_rn_syntax :: forall a. a -> Maybe a ; maybe_rn_syntax empty_val@@ -283,6 +286,7 @@ tcg_th_coreplugins = th_coreplugins_var, tcg_th_state = th_state_var, tcg_th_remote_state = th_remote_state_var,+ tcg_th_docs = th_docs_var, tcg_mod = mod, tcg_semantic_mod = homeModuleInstantiation home_unit mod,@@ -318,6 +322,7 @@ tcg_binds = emptyLHsBinds, tcg_imp_specs = [], tcg_sigs = emptyNameSet,+ tcg_ksigs = emptyNameSet, tcg_ev_binds = emptyBag, tcg_warns = NoWarnings, tcg_anns = [],@@ -354,7 +359,7 @@ -> TcGblEnv -> RealSrcSpan -> TcM r- -> IO (Messages DecoratedSDoc, Maybe r)+ -> IO (Messages DiagnosticMessage, Maybe r) initTcWithGbl hsc_env gbl_env loc do_this = do { lie_var <- newIORef emptyWC ; errs_var <- newIORef emptyMessages@@ -400,7 +405,7 @@ ; return (msgs, final_res) } -initTcInteractive :: HscEnv -> TcM a -> IO (Messages DecoratedSDoc, Maybe a)+initTcInteractive :: HscEnv -> TcM a -> IO (Messages DiagnosticMessage, Maybe a) -- Initialise the type checker monad for use in GHCi initTcInteractive hsc_env thing_inside = initTc hsc_env HsSrcFile False@@ -546,11 +551,6 @@ getGhcMode :: TcRnIf gbl lcl GhcMode getGhcMode = do { env <- getTopEnv; return (ghcMode (hsc_dflags env)) } -withDynamicNow :: TcRnIf gbl lcl a -> TcRnIf gbl lcl a-withDynamicNow =- updTopEnv (\top@(HscEnv { hsc_dflags = dflags }) ->- top { hsc_dflags = setDynamicNow dflags })- withoutDynamicNow :: TcRnIf gbl lcl a -> TcRnIf gbl lcl a withoutDynamicNow = updTopEnv (\top@(HscEnv { hsc_dflags = dflags }) ->@@ -591,10 +591,9 @@ -- | A convenient wrapper for taking a @MaybeErr SDoc a@ and throwing -- an exception if it is an error.-withException :: TcRnIf gbl lcl (MaybeErr SDoc a) -> TcRnIf gbl lcl a-withException do_this = do+withException :: MonadIO m => DynFlags -> m (MaybeErr SDoc a) -> m a+withException dflags do_this = do r <- do_this- dflags <- getDynFlags case r of Failed err -> liftIO $ throwGhcExceptionIO (ProgramError (showSDoc dflags err)) Succeeded result -> return result@@ -789,7 +788,7 @@ if hasPprDebug dflags then do loc <- getSrcSpanM- return (mkLocMessage SevOutput loc doc)+ return (mkLocMessage MCOutput loc doc) else return doc @@ -808,16 +807,14 @@ liftIO (printOutputForUser logger dflags printer doc) {--traceIf and traceHiDiffs work in the TcRnIf monad, where no RdrEnv is+traceIf works in the TcRnIf monad, where no RdrEnv is available. Alas, they behave inconsistently with the other stuff; e.g. are unaffected by -dump-to-file. -} -traceIf, traceHiDiffs :: SDoc -> TcRnIf m n ()-traceIf = traceOptIf Opt_D_dump_if_trace-traceHiDiffs = traceOptIf Opt_D_dump_hi_diffs+traceIf :: SDoc -> TcRnIf m n ()+traceIf = traceOptIf Opt_D_dump_if_trace {-# INLINE traceIf #-}-{-# INLINE traceHiDiffs #-} -- see Note [INLINE conditional tracing utilities] traceOptIf :: DumpFlag -> SDoc -> TcRnIf m n ()@@ -914,34 +911,63 @@ | otherwise = thing_inside +setSrcSpanA :: SrcSpanAnn' ann -> TcRn a -> TcRn a+setSrcSpanA l = setSrcSpan (locA l)+ addLocM :: (a -> TcM b) -> Located a -> TcM b addLocM fn (L loc a) = setSrcSpan loc $ fn a +addLocMA :: (a -> TcM b) -> GenLocated (SrcSpanAnn' ann) a -> TcM b+addLocMA fn (L loc a) = setSrcSpanA loc $ fn a+ wrapLocM :: (a -> TcM b) -> Located a -> TcM (Located b) wrapLocM fn (L loc a) = setSrcSpan loc $ do { b <- fn a ; return (L loc b) } +wrapLocAM :: (a -> TcM b) -> LocatedAn an a -> TcM (Located b)+wrapLocAM fn (L loc a) = setSrcSpanA loc $ do { b <- fn a+ ; return (L (locA loc) b) }++wrapLocMA :: (a -> TcM b) -> GenLocated (SrcSpanAnn' ann) a -> TcRn (GenLocated (SrcSpanAnn' ann) b)+wrapLocMA fn (L loc a) = setSrcSpanA loc $ do { b <- fn a+ ; return (L loc b) }+ wrapLocFstM :: (a -> TcM (b,c)) -> Located a -> TcM (Located b, c) wrapLocFstM fn (L loc a) = setSrcSpan loc $ do (b,c) <- fn a return (L loc b, c) +wrapLocFstMA :: (a -> TcM (b,c)) -> LocatedA a -> TcM (LocatedA b, c)+wrapLocFstMA fn (L loc a) =+ setSrcSpanA loc $ do+ (b,c) <- fn a+ return (L loc b, c)+ wrapLocSndM :: (a -> TcM (b, c)) -> Located a -> TcM (b, Located c) wrapLocSndM fn (L loc a) = setSrcSpan loc $ do (b,c) <- fn a return (b, L loc c) +wrapLocSndMA :: (a -> TcM (b, c)) -> LocatedA a -> TcM (b, LocatedA c)+wrapLocSndMA fn (L loc a) =+ setSrcSpanA loc $ do+ (b,c) <- fn a+ return (b, L loc c)+ wrapLocM_ :: (a -> TcM ()) -> Located a -> TcM () wrapLocM_ fn (L loc a) = setSrcSpan loc (fn a) +wrapLocMA_ :: (a -> TcM ()) -> LocatedA a -> TcM ()+wrapLocMA_ fn (L loc a) = setSrcSpan (locA loc) (fn a)+ -- Reporting errors -getErrsVar :: TcRn (TcRef (Messages DecoratedSDoc))+getErrsVar :: TcRn (TcRef (Messages DiagnosticMessage)) getErrsVar = do { env <- getLclEnv; return (tcl_errs env) } -setErrsVar :: TcRef (Messages DecoratedSDoc) -> TcRn a -> TcRn a+setErrsVar :: TcRef (Messages DiagnosticMessage) -> TcRn a -> TcRn a setErrsVar v = updLclEnv (\ env -> env { tcl_errs = v }) addErr :: SDoc -> TcRn ()@@ -971,7 +997,7 @@ -- Add the error if the bool is False checkErr ok msg = unless ok (addErr msg) -addMessages :: Messages DecoratedSDoc -> TcRn ()+addMessages :: Messages DiagnosticMessage -> TcRn () addMessages msgs1 = do { errs_var <- getErrsVar ; msgs0 <- readTcRef errs_var ;@@ -1000,55 +1026,43 @@ ************************************************************************ -} -mkLongErrAt :: SrcSpan -> SDoc -> SDoc -> TcRn (MsgEnvelope DecoratedSDoc)+mkLongErrAt :: SrcSpan -> SDoc -> SDoc -> TcRn (MsgEnvelope DiagnosticMessage) mkLongErrAt loc msg extra = do { printer <- getPrintUnqualified ; unit_state <- hsc_units <$> getTopEnv ; let msg' = pprWithUnitState unit_state msg in- return $ mkLongMsgEnvelope loc printer msg' extra }+ return $ mkLongMsgEnvelope ErrorWithoutFlag loc printer msg' extra } -mkDecoratedSDocAt :: SrcSpan+mkDecoratedSDocAt :: DiagnosticReason+ -> SrcSpan -> SDoc -- ^ The important part of the message -> SDoc -- ^ The context of the message -> SDoc -- ^ Any supplementary information.- -> TcRn (MsgEnvelope DecoratedSDoc)-mkDecoratedSDocAt loc important context extra+ -> TcRn (MsgEnvelope DiagnosticMessage)+mkDecoratedSDocAt reason loc important context extra = do { printer <- getPrintUnqualified ; unit_state <- hsc_units <$> getTopEnv ; let f = pprWithUnitState unit_state errDoc = [important, context, extra]- errDoc' = mkDecorated $ map f errDoc+ errDoc' = DiagnosticMessage (mkDecorated $ map f errDoc) reason in- return $ mkErr loc printer errDoc' }+ return $ mkMsgEnvelope (defaultReasonSeverity reason) loc printer errDoc' } addLongErrAt :: SrcSpan -> SDoc -> SDoc -> TcRn ()-addLongErrAt loc msg extra = mkLongErrAt loc msg extra >>= reportError+addLongErrAt loc msg extra = mkLongErrAt loc msg extra >>= reportDiagnostic -reportErrors :: [MsgEnvelope DecoratedSDoc] -> TcM ()-reportErrors = mapM_ reportError+reportDiagnostics :: [MsgEnvelope DiagnosticMessage] -> TcM ()+reportDiagnostics = mapM_ reportDiagnostic -reportError :: MsgEnvelope DecoratedSDoc -> TcRn ()-reportError err- = do { traceTc "Adding error:" (pprLocMsgEnvelope err) ;+reportDiagnostic :: MsgEnvelope DiagnosticMessage -> TcRn ()+reportDiagnostic msg+ = do { traceTc "Adding diagnostic:" (pprLocMsgEnvelope msg) ; errs_var <- getErrsVar ; msgs <- readTcRef errs_var ;- writeTcRef errs_var (err `addMessage` msgs) }--reportWarning :: WarnReason -> MsgEnvelope DecoratedSDoc -> TcRn ()-reportWarning reason err- = do { let warn = makeIntoWarning reason err- -- 'err' was built by mkLongMsgEnvelope or something like that,- -- so it's of error severity. For a warning we downgrade- -- its severity to SevWarning-- ; traceTc "Adding warning:" (pprLocMsgEnvelope warn)- ; errs_var <- getErrsVar- ; (warns, errs) <- partitionMessages <$> readTcRef errs_var- ; writeTcRef errs_var (mkMessages $ (warns `snocBag` warn) `unionBags` errs) }-+ writeTcRef errs_var (msg `addMessage` msgs) } ----------------------- checkNoErrs :: TcM r -> TcM r@@ -1221,7 +1235,7 @@ ; lie <- readTcRef lie_var ; return (res, lie) } -capture_messages :: TcM r -> TcM (r, Messages DecoratedSDoc)+capture_messages :: TcM r -> TcM (r, Messages DiagnosticMessage) -- capture_messages simply captures and returns the -- errors arnd warnings generated by thing_inside -- Precondition: thing_inside must not throw an exception!@@ -1391,7 +1405,7 @@ Just acc' -> foldAndRecoverM f acc' xs } ------------------------tryTc :: TcRn a -> TcRn (Maybe a, Messages DecoratedSDoc)+tryTc :: TcRn a -> TcRn (Maybe a, Messages DiagnosticMessage) -- (tryTc m) executes m, and returns -- Just r, if m succeeds (returning r) -- Nothing, if m fails@@ -1490,60 +1504,61 @@ warnIfFlag warn_flag is_bad msg = do { warn_on <- woptM warn_flag ; when (warn_on && is_bad) $- addWarn (Reason warn_flag) msg }+ addDiagnostic (WarningWithFlag warn_flag) msg } -- | Display a warning if a condition is met. warnIf :: Bool -> SDoc -> TcRn () warnIf is_bad msg- = when is_bad (addWarn NoReason msg)+ = when is_bad (addDiagnostic WarningWithoutFlag msg) -- | Display a warning if a condition is met.-warnTc :: WarnReason -> Bool -> SDoc -> TcM ()-warnTc reason warn_if_true warn_msg- | warn_if_true = addWarnTc reason warn_msg- | otherwise = return ()+diagnosticTc :: DiagnosticReason -> Bool -> SDoc -> TcM ()+diagnosticTc reason should_report warn_msg+ | should_report = addDiagnosticTc reason warn_msg+ | otherwise = return () --- | Display a warning if a condition is met.-warnTcM :: WarnReason -> Bool -> (TidyEnv, SDoc) -> TcM ()-warnTcM reason warn_if_true warn_msg- | warn_if_true = addWarnTcM reason warn_msg- | otherwise = return ()+-- | Display a diagnostic if a condition is met.+diagnosticTcM :: DiagnosticReason -> Bool -> (TidyEnv, SDoc) -> TcM ()+diagnosticTcM reason should_report warn_msg+ | should_report = addDiagnosticTcM reason warn_msg+ | otherwise = return () --- | Display a warning in the current context.-addWarnTc :: WarnReason -> SDoc -> TcM ()-addWarnTc reason msg+-- | Display a diagnostic in the current context.+addDiagnosticTc :: DiagnosticReason -> SDoc -> TcM ()+addDiagnosticTc reason msg = do { env0 <- tcInitTidyEnv ;- addWarnTcM reason (env0, msg) }+ addDiagnosticTcM reason (env0, msg) } --- | Display a warning in a given context.-addWarnTcM :: WarnReason -> (TidyEnv, SDoc) -> TcM ()-addWarnTcM reason (env0, msg)+-- | Display a diagnostic in a given context.+addDiagnosticTcM :: DiagnosticReason -> (TidyEnv, SDoc) -> TcM ()+addDiagnosticTcM reason (env0, msg) = do { ctxt <- getErrCtxt ; err_info <- mkErrInfo env0 ctxt ;- add_warn reason msg err_info }+ add_diagnostic reason msg err_info } --- | Display a warning for the current source location.-addWarn :: WarnReason -> SDoc -> TcRn ()-addWarn reason msg = add_warn reason msg Outputable.empty+-- | Display a diagnostic for the current source location.+addDiagnostic :: DiagnosticReason -> SDoc -> TcRn ()+addDiagnostic reason msg = add_diagnostic reason msg Outputable.empty --- | Display a warning for a given source location.-addWarnAt :: WarnReason -> SrcSpan -> SDoc -> TcRn ()-addWarnAt reason loc msg = add_warn_at reason loc msg Outputable.empty+-- | Display a diagnostic for a given source location.+addDiagnosticAt :: DiagnosticReason -> SrcSpan -> SDoc -> TcRn ()+addDiagnosticAt reason loc msg = add_diagnostic_at reason loc msg Outputable.empty --- | Display a warning, with an optional flag, for the current source+-- | Display a diagnostic, with an optional flag, for the current source -- location.-add_warn :: WarnReason -> SDoc -> SDoc -> TcRn ()-add_warn reason msg extra_info+add_diagnostic :: DiagnosticReason -> SDoc -> SDoc -> TcRn ()+add_diagnostic reason msg extra_info = do { loc <- getSrcSpanM- ; add_warn_at reason loc msg extra_info }+ ; add_diagnostic_at reason loc msg extra_info } --- | Display a warning, with an optional flag, for a given location.-add_warn_at :: WarnReason -> SrcSpan -> SDoc -> SDoc -> TcRn ()-add_warn_at reason loc msg extra_info+-- | Display a diagnosticTc, with an optional flag, for a given location.+add_diagnostic_at :: DiagnosticReason -> SrcSpan -> SDoc -> SDoc -> TcRn ()+add_diagnostic_at reason loc msg extra_info = do { printer <- getPrintUnqualified ;- let { warn = mkLongWarnMsg loc printer- msg extra_info } ;- reportWarning reason warn }+ let { dia = mkLongMsgEnvelope reason+ loc printer+ msg extra_info } ;+ reportDiagnostic dia } {-@@ -2021,8 +2036,9 @@ initIfaceTcRn thing_inside = do { tcg_env <- getGblEnv ; hsc_env <- getTopEnv+ -- bangs to avoid leaking the envs (#19356) ; let !mod = tcg_semantic_mod tcg_env- home_unit = hsc_home_unit hsc_env+ !home_unit = hsc_home_unit hsc_env -- When we are instantiating a signature, we DEFINITELY -- do not want to knot tie. is_instantiate = isHomeUnitInstantiating home_unit@@ -2085,7 +2101,7 @@ let full_msg = (if_loc env <> colon) $$ nest 2 msg dflags <- getDynFlags logger <- getLogger- liftIO (putLogMsg logger dflags NoReason SevFatal+ liftIO (putLogMsg logger dflags MCFatal noSrcSpan $ withPprStyle defaultErrStyle full_msg) failM @@ -2120,8 +2136,7 @@ let msg = hang (text "forkM failed:" <+> doc) 2 (text (show exn)) liftIO $ putLogMsg logger dflags- NoReason- SevFatal+ MCFatal noSrcSpan $ withPprStyle defaultErrStyle msg
compiler/GHC/Tc/Utils/TcMType.hs view
@@ -23,6 +23,7 @@ newFlexiTyVarTy, -- Kind -> TcM TcType newFlexiTyVarTys, -- Int -> Kind -> TcM [TcType] newOpenFlexiTyVar, newOpenFlexiTyVarTy, newOpenTypeKind,+ newOpenBoxedTypeKind, newMetaKindVar, newMetaKindVars, newMetaTyVarTyAtLevel, newAnonMetaTyVar, cloneMetaTyVar, newCycleBreakerTyVar,@@ -137,7 +138,6 @@ import Control.Monad import GHC.Data.Maybe-import Control.Arrow ( second ) import qualified Data.Semigroup as Semi {-@@ -1076,6 +1076,12 @@ = do { kind <- newOpenTypeKind ; newFlexiTyVar kind } +newOpenBoxedTypeKind :: TcM TcKind+newOpenBoxedTypeKind+ = do { lev <- newFlexiTyVarTy (mkTyConTy levityTyCon)+ ; let rr = mkTyConApp boxedRepDataConTyCon [lev]+ ; return (tYPE rr) }+ newMetaTyVars :: [TyVar] -> TcM (TCvSubst, [TcTyVar]) -- Instantiate with META type variables -- Note that this works for a sequence of kind, type, and coercion variables@@ -1246,6 +1252,9 @@ This change is inspired by and described in Section 7.2 of "Kind Inference for Datatypes", POPL'20. +NB: this is all rather similar to, but sadly not the same as+ Note [Error on unconstrained meta-variables]+ Wrinkle: We must make absolutely sure that alpha indeed is not@@ -1794,6 +1803,10 @@ = do { traceTc "Defaulting a RuntimeRep var to LiftedRep" (ppr tv) ; writeMetaTyVar tv liftedRepTy ; return True }+ | isLevityVar tv+ = do { traceTc "Defaulting a Levity var to Lifted" (ppr tv)+ ; writeMetaTyVar tv liftedDataConTy+ ; return True } | isMultiplicityVar tv = do { traceTc "Defaulting a Multiplicty var to Many" (ppr tv) ; writeMetaTyVar tv manyDataConTy@@ -1909,6 +1922,9 @@ We choose (D), as described in #17567. Discussion of alternatives is below. +NB: this is all rather similar to, but sadly not the same as+ Note [Naughty quantification candidates]+ (One last example: type instance F Int = Proxy Any, where the unconstrained kind variable is the inferred kind of Any. The four examples here illustrate all cases in which this Note applies.)@@ -1988,6 +2004,7 @@ -> (TidyEnv -> TcM (TidyEnv, SDoc)) -- ^ like "the class context (D a b, E foogle)" -> TcM ()+-- See Note [Error on unconstrained meta-variables] doNotQuantifyTyVars dvs where_found | isEmptyCandidates dvs = traceTc "doNotQuantifyTyVars has nothing to error on" empty@@ -2516,13 +2533,11 @@ ; (env2, exp') <- zonkTidyTcType env1 exp ; return ( env2, orig { uo_actual = act' , uo_expected = exp' }) }-zonkTidyOrigin env (KindEqOrigin ty1 m_ty2 orig t_or_k)- = do { (env1, ty1') <- zonkTidyTcType env ty1- ; (env2, m_ty2') <- case m_ty2 of- Just ty2 -> second Just <$> zonkTidyTcType env1 ty2- Nothing -> return (env1, Nothing)- ; (env3, orig') <- zonkTidyOrigin env2 orig- ; return (env3, KindEqOrigin ty1' m_ty2' orig' t_or_k) }+zonkTidyOrigin env (KindEqOrigin ty1 ty2 orig t_or_k)+ = do { (env1, ty1') <- zonkTidyTcType env ty1+ ; (env2, ty2') <- zonkTidyTcType env1 ty2+ ; (env3, orig') <- zonkTidyOrigin env2 orig+ ; return (env3, KindEqOrigin ty1' ty2' orig' t_or_k) } zonkTidyOrigin env (FunDepOrigin1 p1 o1 l1 p2 o2 l2) = do { (env1, p1') <- zonkTidyTcType env p1 ; (env2, p2') <- zonkTidyTcType env1 p2
compiler/GHC/Tc/Utils/Unify.hs view
@@ -22,7 +22,7 @@ buildImplicationFor, buildTvImplication, emitResidualTvConstraint, -- Various unifications- unifyType, unifyKind,+ unifyType, unifyKind, unifyExpectedType, uType, promoteTcType, swapOverTyVars, canSolveByUnification, @@ -543,11 +543,18 @@ -- It means we don't need to pass in a CtOrigin tcWrapResultMono rn_expr expr act_ty res_ty = ASSERT2( isRhoTy act_ty, ppr act_ty $$ ppr rn_expr )- do { co <- case res_ty of- Infer inf_res -> fillInferResult act_ty inf_res- Check exp_ty -> unifyType (Just (ppr rn_expr)) act_ty exp_ty+ do { co <- unifyExpectedType rn_expr act_ty res_ty ; return (mkHsWrapCo co expr) } +unifyExpectedType :: HsExpr GhcRn+ -> TcRhoType -- Actual -- a rho-type not a sigma-type+ -> ExpRhoType -- Expected+ -> TcM TcCoercionN+unifyExpectedType rn_expr act_ty exp_ty+ = case exp_ty of+ Infer inf_res -> fillInferResult act_ty inf_res+ Check exp_ty -> unifyType (Just (ppr rn_expr)) act_ty exp_ty+ ------------------------ tcSubTypePat :: CtOrigin -> UserTypeCtxt -> ExpSigmaType -> TcSigmaType -> TcM HsWrapper@@ -1249,7 +1256,7 @@ = do { let ty1 = coercionType co1 ty2 = coercionType co2 ; kco <- uType KindLevel- (KindEqOrigin orig_ty1 (Just orig_ty2) origin+ (KindEqOrigin orig_ty1 orig_ty2 origin (Just t_or_k)) ty1 ty2 ; return $ mkProofIrrelCo Nominal kco co1 co2 }@@ -1463,7 +1470,7 @@ ; defer } ty1 = mkTyVarTy tv1- kind_origin = KindEqOrigin ty1 (Just ty2) origin (Just t_or_k)+ kind_origin = KindEqOrigin ty1 ty2 origin (Just t_or_k) defer = unSwap swapped (uType_defer t_or_k origin) ty1 ty2
compiler/GHC/Tc/Utils/Zonk.hs view
@@ -200,11 +200,11 @@ where go_integral int@(IL src neg i) | isIntTy res_ty && platformInIntRange platform i- = Just (HsLit noExtField (HsInt noExtField int))+ = Just (HsLit noAnn (HsInt noExtField int)) | isWordTy res_ty && platformInWordRange platform i = Just (mkLit wordDataCon (HsWordPrim src i)) | isIntegerTy res_ty- = Just (HsLit noExtField (HsInteger src i res_ty))+ = Just (HsLit noAnn (HsInteger src i res_ty)) | otherwise = go_fractional (integralFractionalLit neg i) -- The 'otherwise' case is important@@ -225,11 +225,11 @@ -- is less than 100, which ensures desugaring isn't slow. go_string src s- | isStringTy res_ty = Just (HsLit noExtField (HsString src s))+ | isStringTy res_ty = Just (HsLit noAnn (HsString src s)) | otherwise = Nothing mkLit :: DataCon -> HsLit GhcTc -> HsExpr GhcTc-mkLit con lit = HsApp noExtField (nlHsDataCon con) (nlHsLit lit)+mkLit con lit = HsApp noComments (nlHsDataCon con) (nlHsLit lit) ------------------------------ hsOverLitName :: OverLitVal -> Name@@ -412,7 +412,7 @@ -- It's OK to use nonDetEltsUFM here because we forget the ordering -- immediately by creating a TypeEnv -zonkLIdOcc :: ZonkEnv -> Located TcId -> Located Id+zonkLIdOcc :: ZonkEnv -> LocatedN TcId -> LocatedN Id zonkLIdOcc env = mapLoc (zonkIdOcc env) zonkIdOcc :: ZonkEnv -> TcId -> Id@@ -569,7 +569,7 @@ ; return (env2, (r,b'):bs') } zonkLocalBinds env (HsIPBinds x (IPBinds dict_binds binds )) = do- new_binds <- mapM (wrapLocM zonk_ip_bind) binds+ new_binds <- mapM (wrapLocMA zonk_ip_bind) binds let env1 = extendIdZonkEnvRec env [ n | (L _ (IPBind _ (Right n) _)) <- new_binds]@@ -594,7 +594,7 @@ zonkMonoBinds env binds = mapBagM (zonk_lbind env) binds zonk_lbind :: ZonkEnv -> LHsBind GhcTc -> TcM (LHsBind GhcTc)-zonk_lbind env = wrapLocM (zonk_bind env)+zonk_lbind env = wrapLocMA (zonk_bind env) zonk_bind :: ZonkEnv -> HsBind GhcTc -> TcM (HsBind GhcTc) zonk_bind env bind@(PatBind { pat_lhs = pat, pat_rhs = grhss@@ -733,10 +733,11 @@ ************************************************************************ -} -zonkMatchGroup :: ZonkEnv- -> (ZonkEnv -> Located (body GhcTc) -> TcM (Located (body GhcTc)))- -> MatchGroup GhcTc (Located (body GhcTc))- -> TcM (MatchGroup GhcTc (Located (body GhcTc)))+zonkMatchGroup :: Anno (GRHS GhcTc (LocatedA (body GhcTc))) ~ SrcSpan+ => ZonkEnv+ -> (ZonkEnv -> LocatedA (body GhcTc) -> TcM (LocatedA (body GhcTc)))+ -> MatchGroup GhcTc (LocatedA (body GhcTc))+ -> TcM (MatchGroup GhcTc (LocatedA (body GhcTc))) zonkMatchGroup env zBody (MG { mg_alts = L l ms , mg_ext = MatchGroupTc arg_tys res_ty , mg_origin = origin })@@ -747,10 +748,11 @@ , mg_ext = MatchGroupTc arg_tys' res_ty' , mg_origin = origin }) } -zonkMatch :: ZonkEnv- -> (ZonkEnv -> Located (body GhcTc) -> TcM (Located (body GhcTc)))- -> LMatch GhcTc (Located (body GhcTc))- -> TcM (LMatch GhcTc (Located (body GhcTc)))+zonkMatch :: Anno (GRHS GhcTc (LocatedA (body GhcTc))) ~ SrcSpan+ => ZonkEnv+ -> (ZonkEnv -> LocatedA (body GhcTc) -> TcM (LocatedA (body GhcTc)))+ -> LMatch GhcTc (LocatedA (body GhcTc))+ -> TcM (LMatch GhcTc (LocatedA (body GhcTc))) zonkMatch env zBody (L loc match@(Match { m_pats = pats , m_grhss = grhss })) = do { (env1, new_pats) <- zonkPats env pats@@ -758,12 +760,13 @@ ; return (L loc (match { m_pats = new_pats, m_grhss = new_grhss })) } --------------------------------------------------------------------------zonkGRHSs :: ZonkEnv- -> (ZonkEnv -> Located (body GhcTc) -> TcM (Located (body GhcTc)))- -> GRHSs GhcTc (Located (body GhcTc))- -> TcM (GRHSs GhcTc (Located (body GhcTc)))+zonkGRHSs :: Anno (GRHS GhcTc (LocatedA (body GhcTc))) ~ SrcSpan+ => ZonkEnv+ -> (ZonkEnv -> LocatedA (body GhcTc) -> TcM (LocatedA (body GhcTc)))+ -> GRHSs GhcTc (LocatedA (body GhcTc))+ -> TcM (GRHSs GhcTc (LocatedA (body GhcTc))) -zonkGRHSs env zBody (GRHSs x grhss (L l binds)) = do+zonkGRHSs env zBody (GRHSs x grhss binds) = do (new_env, new_binds) <- zonkLocalBinds env binds let zonk_grhs (GRHS xx guarded rhs)@@ -771,7 +774,7 @@ new_rhs <- zBody env2 rhs return (GRHS xx new_guarded new_rhs) new_grhss <- mapM (wrapLocM zonk_grhs) grhss- return (GRHSs x new_grhss (L l new_binds))+ return (GRHSs x new_grhss new_binds) {- ************************************************************************@@ -786,7 +789,7 @@ zonkExpr :: ZonkEnv -> HsExpr GhcTc -> TcM (HsExpr GhcTc) zonkLExprs env exprs = mapM (zonkLExpr env) exprs-zonkLExpr env expr = wrapLocM (zonkExpr env) expr+zonkLExpr env expr = wrapLocMA (zonkExpr env) expr zonkExpr env (HsVar x (L l id)) = ASSERT2( isNothing (isDataConId_maybe id), ppr id )@@ -894,10 +897,10 @@ = do { new_tup_args <- mapM zonk_tup_arg tup_args ; return (ExplicitTuple x new_tup_args boxed) } where- zonk_tup_arg (L l (Present x e)) = do { e' <- zonkLExpr env e- ; return (L l (Present x e')) }- zonk_tup_arg (L l (Missing t)) = do { t' <- zonkScaledTcTypeToTypeX env t- ; return (L l (Missing t')) }+ zonk_tup_arg (Present x e) = do { e' <- zonkLExpr env e+ ; return (Present x e') }+ zonk_tup_arg (Missing t) = do { t' <- zonkScaledTcTypeToTypeX env t+ ; return (Missing t') } zonkExpr env (ExplicitSum args alt arity expr)@@ -925,10 +928,10 @@ ; expr' <- zonkLExpr env' expr ; return $ GRHS x guard' expr' } -zonkExpr env (HsLet x (L l binds) expr)+zonkExpr env (HsLet x binds expr) = do (new_env, new_binds) <- zonkLocalBinds env binds new_expr <- zonkLExpr new_env expr- return (HsLet x (L l new_binds) new_expr)+ return (HsLet x new_binds new_expr) zonkExpr env (HsDo ty do_or_lc (L l stmts)) = do (_, new_stmts) <- zonkStmts env zonkLExpr stmts@@ -946,21 +949,31 @@ ; return (expr { rcon_ext = new_con_expr , rcon_flds = new_rbinds }) } -zonkExpr env (RecordUpd { rupd_flds = rbinds+-- Record updates via dot syntax are replaced by desugared expressions+-- in the renamer. See Note [Rebindable Syntax and HsExpansion]. This+-- is why we match on 'rupd_flds = Left rbinds' here and panic otherwise.+zonkExpr env (RecordUpd { rupd_flds = Left rbinds , rupd_expr = expr- , rupd_ext = RecordUpdTc- { rupd_cons = cons, rupd_in_tys = in_tys- , rupd_out_tys = out_tys, rupd_wrap = req_wrap }})+ , rupd_ext = RecordUpdTc {+ rupd_cons = cons+ , rupd_in_tys = in_tys+ , rupd_out_tys = out_tys+ , rupd_wrap = req_wrap }}) = do { new_expr <- zonkLExpr env expr ; new_in_tys <- mapM (zonkTcTypeToTypeX env) in_tys ; new_out_tys <- mapM (zonkTcTypeToTypeX env) out_tys ; new_rbinds <- zonkRecUpdFields env rbinds ; (_, new_recwrap) <- zonkCoFn env req_wrap- ; return (RecordUpd { rupd_expr = new_expr, rupd_flds = new_rbinds- , rupd_ext = RecordUpdTc- { rupd_cons = cons, rupd_in_tys = new_in_tys- , rupd_out_tys = new_out_tys- , rupd_wrap = new_recwrap }}) }+ ; return (+ RecordUpd {+ rupd_expr = new_expr+ , rupd_flds = Left new_rbinds+ , rupd_ext = RecordUpdTc {+ rupd_cons = cons+ , rupd_in_tys = new_in_tys+ , rupd_out_tys = new_out_tys+ , rupd_wrap = new_recwrap }}) }+zonkExpr _ (RecordUpd {}) = panic "GHC.Tc.Utils.Zonk: zonkExpr: The impossible happened!" zonkExpr env (ExprWithTySig _ e ty) = do { e' <- zonkLExpr env e@@ -1038,7 +1051,7 @@ zonkLCmd :: ZonkEnv -> LHsCmd GhcTc -> TcM (LHsCmd GhcTc) zonkCmd :: ZonkEnv -> HsCmd GhcTc -> TcM (HsCmd GhcTc) -zonkLCmd env cmd = wrapLocM (zonkCmd env) cmd+zonkLCmd env cmd = wrapLocMA (zonkCmd env) cmd zonkCmd env (XCmd (HsWrap w cmd)) = do { (env1, w') <- zonkCoFn env w@@ -1084,10 +1097,10 @@ ; new_cElse <- zonkLCmd env1 cElse ; return (HsCmdIf x new_eCond new_ePred new_cThen new_cElse) } -zonkCmd env (HsCmdLet x (L l binds) cmd)+zonkCmd env (HsCmdLet x binds cmd) = do (new_env, new_binds) <- zonkLocalBinds env binds new_cmd <- zonkLCmd new_env cmd- return (HsCmdLet x (L l new_binds) new_cmd)+ return (HsCmdLet x new_binds new_cmd) zonkCmd env (HsCmdDo ty (L l stmts)) = do (_, new_stmts) <- zonkStmts env zonkLCmd stmts@@ -1171,19 +1184,21 @@ --------------------------------------------------------------------------zonkStmts :: ZonkEnv- -> (ZonkEnv -> Located (body GhcTc) -> TcM (Located (body GhcTc)))- -> [LStmt GhcTc (Located (body GhcTc))]- -> TcM (ZonkEnv, [LStmt GhcTc (Located (body GhcTc))])+zonkStmts :: Anno (StmtLR GhcTc GhcTc (LocatedA (body GhcTc))) ~ SrcSpanAnnA+ => ZonkEnv+ -> (ZonkEnv -> LocatedA (body GhcTc) -> TcM (LocatedA (body GhcTc)))+ -> [LStmt GhcTc (LocatedA (body GhcTc))]+ -> TcM (ZonkEnv, [LStmt GhcTc (LocatedA (body GhcTc))]) zonkStmts env _ [] = return (env, [])-zonkStmts env zBody (s:ss) = do { (env1, s') <- wrapLocSndM (zonkStmt env zBody) s+zonkStmts env zBody (s:ss) = do { (env1, s') <- wrapLocSndMA (zonkStmt env zBody) s ; (env2, ss') <- zonkStmts env1 zBody ss ; return (env2, s' : ss') } -zonkStmt :: ZonkEnv- -> (ZonkEnv -> Located (body GhcTc) -> TcM (Located (body GhcTc)))- -> Stmt GhcTc (Located (body GhcTc))- -> TcM (ZonkEnv, Stmt GhcTc (Located (body GhcTc)))+zonkStmt :: Anno (StmtLR GhcTc GhcTc (LocatedA (body GhcTc))) ~ SrcSpanAnnA+ => ZonkEnv+ -> (ZonkEnv -> LocatedA (body GhcTc) -> TcM (LocatedA (body GhcTc)))+ -> Stmt GhcTc (LocatedA (body GhcTc))+ -> TcM (ZonkEnv, Stmt GhcTc (LocatedA (body GhcTc))) zonkStmt env _ (ParStmt bind_ty stmts_w_bndrs mzip_op bind_op) = do { (env1, new_bind_op) <- zonkSyntaxExpr env bind_op ; new_bind_ty <- zonkTcTypeToTypeX env1 bind_ty@@ -1203,7 +1218,8 @@ ; return (ParStmtBlock x new_stmts (zonkIdOccs env3 bndrs) new_return) } -zonkStmt env zBody (RecStmt { recS_stmts = segStmts, recS_later_ids = lvs, recS_rec_ids = rvs+zonkStmt env zBody (RecStmt { recS_stmts = L _ segStmts, recS_later_ids = lvs+ , recS_rec_ids = rvs , recS_ret_fn = ret_id, recS_mfix_fn = mfix_id , recS_bind_fn = bind_id , recS_ext =@@ -1225,7 +1241,8 @@ ; new_later_rets <- mapM (zonkExpr env5) later_rets ; new_rec_rets <- mapM (zonkExpr env5) rec_rets ; return (extendIdZonkEnvRec env3 new_lvs, -- Only the lvs are needed- RecStmt { recS_stmts = new_segStmts, recS_later_ids = new_lvs+ RecStmt { recS_stmts = noLocA new_segStmts+ , recS_later_ids = new_lvs , recS_rec_ids = new_rvs, recS_ret_fn = new_ret_id , recS_mfix_fn = new_mfix_id, recS_bind_fn = new_bind_id , recS_ext = RecStmtTc@@ -1273,9 +1290,9 @@ newBinder' <- zonkIdBndr env newBinder return (oldBinder', newBinder') -zonkStmt env _ (LetStmt x (L l binds))+zonkStmt env _ (LetStmt x binds) = do (env1, new_binds) <- zonkLocalBinds env binds- return (env1, LetStmt x (L l new_binds))+ return (env1, LetStmt x new_binds) zonkStmt env zBody (BindStmt xbs pat body) = do { (env1, new_bind) <- zonkSyntaxExpr env (xbstc_bindOp xbs)@@ -1388,7 +1405,7 @@ -- Extend the environment as we go, because it's possible for one -- pattern to bind something that is used in another (inside or -- to the right)-zonkPat env pat = wrapLocSndM (zonk_pat env) pat+zonkPat env pat = wrapLocSndMA (zonk_pat env) pat zonk_pat :: ZonkEnv -> Pat GhcTc -> TcM (ZonkEnv, Pat GhcTc) zonk_pat env (ParPat x p)@@ -1520,7 +1537,7 @@ zonk_pat env (XPat (CoPat co_fn pat ty)) = do { (env', co_fn') <- zonkCoFn env co_fn- ; (env'', pat') <- zonkPat env' (noLoc pat)+ ; (env'', pat') <- zonkPat env' (noLocA pat) ; ty' <- zonkTcTypeToTypeX env'' ty ; return (env'', XPat $ CoPat co_fn' (unLoc pat') ty') }@@ -1564,7 +1581,7 @@ zonkForeignExports :: ZonkEnv -> [LForeignDecl GhcTc] -> TcM [LForeignDecl GhcTc]-zonkForeignExports env ls = mapM (wrapLocM (zonkForeignExport env)) ls+zonkForeignExports env ls = mapM (wrapLocMA (zonkForeignExport env)) ls zonkForeignExport :: ZonkEnv -> ForeignDecl GhcTc -> TcM (ForeignDecl GhcTc) zonkForeignExport env (ForeignExport { fd_name = i, fd_e_ext = co@@ -1576,7 +1593,7 @@ = return for_imp -- Foreign imports don't need zonking zonkRules :: ZonkEnv -> [LRuleDecl GhcTc] -> TcM [LRuleDecl GhcTc]-zonkRules env rs = mapM (wrapLocM (zonkRule env)) rs+zonkRules env rs = mapM (wrapLocMA (zonkRule env)) rs zonkRule :: ZonkEnv -> RuleDecl GhcTc -> TcM (RuleDecl GhcTc) zonkRule env rule@(HsRule { rd_tmvs = tm_bndrs{-::[RuleBndr TcId]-}
compiler/GHC/Tc/Validity.hs view
@@ -1102,9 +1102,9 @@ = return () check_valid_theta env ctxt expand theta = do { dflags <- getDynFlags- ; warnTcM (Reason Opt_WarnDuplicateConstraints)- (wopt Opt_WarnDuplicateConstraints dflags && notNull dups)- (dupPredWarn env dups)+ ; diagnosticTcM (WarningWithFlag Opt_WarnDuplicateConstraints)+ (wopt Opt_WarnDuplicateConstraints dflags && notNull dups)+ (dupPredWarn env dups) ; traceTc "check_valid_theta" (ppr theta) ; mapM_ (check_pred_ty env dflags ctxt expand) theta } where@@ -1297,8 +1297,8 @@ = do { result <- matchGlobalInst dflags False cls tys ; case result of OneInst { cir_what = what }- -> addWarnTc (Reason Opt_WarnSimplifiableClassConstraints)- (simplifiable_constraint_warn what)+ -> addDiagnosticTc (WarningWithFlag Opt_WarnSimplifiableClassConstraints)+ (simplifiable_constraint_warn what) _ -> return () } where pred = mkClassPred cls tys@@ -1864,7 +1864,7 @@ = failWithTc (text "Arity mis-match in instance head") | otherwise- = do { setSrcSpan head_loc $+ = do { setSrcSpanA head_loc $ checkValidInstHead ctxt clas inst_tys ; traceTc "checkValidInstance {" (ppr ty)@@ -2048,7 +2048,7 @@ -- (b) failure of injectivity check_branch_compat prev_branches cur_branch | cur_branch `isDominatedBy` prev_branches- = do { addWarnAt NoReason (coAxBranchSpan cur_branch) $+ = do { addDiagnosticAt WarningWithoutFlag (coAxBranchSpan cur_branch) $ inaccessibleCoAxBranch fam_tc cur_branch ; return prev_branches } | otherwise
compiler/GHC/ThToHs.hs view
@@ -1,12 +1,12 @@-{-# LANGUAGE BangPatterns #-}-{-# LANGUAGE DeriveFunctor #-}-{-# LANGUAGE FlexibleContexts #-}-{-# LANGUAGE FunctionalDependencies #-}-{-# LANGUAGE LambdaCase #-}+{-# LANGUAGE BangPatterns #-} {-# LANGUAGE ConstrainedClassMethods #-}-{-# LANGUAGE ScopedTypeVariables #-}-{-# LANGUAGE TypeFamilies #-}-{-# LANGUAGE ViewPatterns #-}+{-# LANGUAGE DeriveFunctor #-}+{-# LANGUAGE FlexibleContexts #-}+{-# LANGUAGE FunctionalDependencies #-}+{-# LANGUAGE LambdaCase #-}+{-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE TypeFamilies #-}+{-# LANGUAGE ViewPatterns #-} {-# OPTIONS_GHC -Wno-incomplete-record-updates #-} {-# OPTIONS_GHC -Wno-incomplete-uni-patterns #-}@@ -53,7 +53,6 @@ import GHC.Data.FastString import GHC.Utils.Outputable as Outputable import GHC.Utils.Panic-import GHC.Parser.Annotation import qualified Data.ByteString as BS import Control.Monad( unless, ap )@@ -131,12 +130,19 @@ returnL :: a -> CvtM (Located a) returnL x = CvtM (\_ loc -> Right (loc, L loc x)) -returnJustL :: a -> CvtM (Maybe (Located a))-returnJustL = fmap Just . returnL+-- returnLA :: a -> CvtM (LocatedA a)+returnLA :: e -> CvtM (GenLocated (SrcSpanAnn' (EpAnn' ann)) e)+returnLA x = CvtM (\_ loc -> Right (loc, L (noAnnSrcSpan loc) x)) -wrapParL :: (Located a -> a) -> a -> CvtM a-wrapParL add_par x = CvtM (\_ loc -> Right (loc, add_par (L loc x)))+returnJustLA :: a -> CvtM (Maybe (LocatedA a))+returnJustLA = fmap Just . returnLA +-- wrapParL :: (Located a -> a) -> a -> CvtM a+-- wrapParL add_par x = CvtM (\_ loc -> Right (loc, add_par (L loc x)))++wrapParLA :: (LocatedA a -> a) -> a -> CvtM a+wrapParLA add_par x = CvtM (\_ loc -> Right (loc, add_par (L (noAnnSrcSpan loc) x)))+ wrapMsg :: (Show a, TH.Ppr a) => String -> a -> CvtM b -> CvtM b -- E.g wrapMsg "declaration" dec thing wrapMsg what item (CvtM m)@@ -156,6 +162,16 @@ Left err -> Left err Right (loc', v) -> Right (loc', L loc v) +wrapLN :: CvtM a -> CvtM (LocatedN a)+wrapLN (CvtM m) = CvtM $ \origin loc -> case m origin loc of+ Left err -> Left err+ Right (loc', v) -> Right (loc', L (noAnnSrcSpan loc) v)++wrapLA :: CvtM a -> CvtM (LocatedA a)+wrapLA (CvtM m) = CvtM $ \origin loc -> case m origin loc of+ Left err -> Left err+ Right (loc', v) -> Right (loc', L (noAnnSrcSpan loc) v)+ ------------------------------------------------------------------- cvtDecs :: [TH.Dec] -> CvtM [LHsDecl GhcPs] cvtDecs = fmap catMaybes . mapM cvtDec@@ -163,19 +179,19 @@ cvtDec :: TH.Dec -> CvtM (Maybe (LHsDecl GhcPs)) cvtDec (TH.ValD pat body ds) | TH.VarP s <- pat- = do { s' <- vNameL s+ = do { s' <- vNameN s ; cl' <- cvtClause (mkPrefixFunRhs s') (Clause [] body ds) ; th_origin <- getOrigin- ; returnJustL $ Hs.ValD noExtField $ mkFunBind th_origin s' [cl'] }+ ; returnJustLA $ Hs.ValD noExtField $ mkFunBind th_origin s' [cl'] } | otherwise = do { pat' <- cvtPat pat ; body' <- cvtGuard body ; ds' <- cvtLocalDecs (text "a where clause") ds- ; returnJustL $ Hs.ValD noExtField $+ ; returnJustLA $ Hs.ValD noExtField $ PatBind { pat_lhs = pat'- , pat_rhs = GRHSs noExtField body' (noLoc ds')- , pat_ext = noExtField+ , pat_rhs = GRHSs noExtField body' ds'+ , pat_ext = noAnn , pat_ticks = ([],[]) } } cvtDec (TH.FunD nm cls)@@ -184,30 +200,30 @@ <+> quotes (text (TH.pprint nm)) <+> text "has no equations") | otherwise- = do { nm' <- vNameL nm+ = do { nm' <- vNameN nm ; cls' <- mapM (cvtClause (mkPrefixFunRhs nm')) cls ; th_origin <- getOrigin- ; returnJustL $ Hs.ValD noExtField $ mkFunBind th_origin nm' cls' }+ ; returnJustLA $ Hs.ValD noExtField $ mkFunBind th_origin nm' cls' } cvtDec (TH.SigD nm typ)- = do { nm' <- vNameL nm+ = do { nm' <- vNameN nm ; ty' <- cvtSigType typ- ; returnJustL $ Hs.SigD noExtField- (TypeSig noExtField [nm'] (mkHsWildCardBndrs ty')) }+ ; returnJustLA $ Hs.SigD noExtField+ (TypeSig noAnn [nm'] (mkHsWildCardBndrs ty')) } cvtDec (TH.KiSigD nm ki)- = do { nm' <- tconNameL nm+ = do { nm' <- tconNameN nm ; ki' <- cvtSigKind ki- ; let sig' = StandaloneKindSig noExtField nm' ki'- ; returnJustL $ Hs.KindSigD noExtField sig' }+ ; let sig' = StandaloneKindSig noAnn nm' ki'+ ; returnJustLA $ Hs.KindSigD noExtField sig' } cvtDec (TH.InfixD fx nm) -- Fixity signatures are allowed for variables, constructors, and types -- the renamer automatically looks for types during renaming, even when -- the RdrName says it's a variable or a constructor. So, just assume -- it's a variable or constructor and proceed.- = do { nm' <- vcNameL nm- ; returnJustL (Hs.SigD noExtField (FixSig noExtField+ = do { nm' <- vcNameN nm+ ; returnJustLA (Hs.SigD noExtField (FixSig noAnn (FixitySig noExtField [nm'] (cvtFixity fx)))) } cvtDec (PragmaD prag)@@ -216,8 +232,8 @@ cvtDec (TySynD tc tvs rhs) = do { (_, tc', tvs') <- cvt_tycl_hdr [] tc tvs ; rhs' <- cvtType rhs- ; returnJustL $ TyClD noExtField $- SynDecl { tcdSExt = noExtField, tcdLName = tc', tcdTyVars = tvs'+ ; returnJustLA $ TyClD noExtField $+ SynDecl { tcdSExt = noAnn, tcdLName = tc', tcdTyVars = tvs' , tcdFixity = Prefix , tcdRhs = rhs' } } @@ -237,13 +253,13 @@ ; ksig' <- cvtKind `traverse` ksig ; cons' <- mapM cvtConstr constrs ; derivs' <- cvtDerivs derivs- ; let defn = HsDataDefn { dd_ext = noExtField+ ; let defn = HsDataDefn { dd_ext = noAnn , dd_ND = DataType, dd_cType = Nothing- , dd_ctxt = ctxt'+ , dd_ctxt = Just ctxt' , dd_kindSig = ksig' , dd_cons = cons', dd_derivs = derivs' }- ; returnJustL $ TyClD noExtField $- DataDecl { tcdDExt = noExtField+ ; returnJustLA $ TyClD noExtField $+ DataDecl { tcdDExt = noAnn , tcdLName = tc', tcdTyVars = tvs' , tcdFixity = Prefix , tcdDataDefn = defn } }@@ -253,14 +269,14 @@ ; ksig' <- cvtKind `traverse` ksig ; con' <- cvtConstr constr ; derivs' <- cvtDerivs derivs- ; let defn = HsDataDefn { dd_ext = noExtField+ ; let defn = HsDataDefn { dd_ext = noAnn , dd_ND = NewType, dd_cType = Nothing- , dd_ctxt = ctxt'+ , dd_ctxt = Just ctxt' , dd_kindSig = ksig' , dd_cons = [con'] , dd_derivs = derivs' }- ; returnJustL $ TyClD noExtField $- DataDecl { tcdDExt = noExtField+ ; returnJustLA $ TyClD noExtField $+ DataDecl { tcdDExt = noAnn , tcdLName = tc', tcdTyVars = tvs' , tcdFixity = Prefix , tcdDataDefn = defn } }@@ -273,9 +289,9 @@ (failWith $ (text "Default data instance declarations" <+> text "are not allowed:") $$ (Outputable.ppr adts'))- ; returnJustL $ TyClD noExtField $- ClassDecl { tcdCExt = NoLayoutInfo- , tcdCtxt = cxt', tcdLName = tc', tcdTyVars = tvs'+ ; returnJustLA $ TyClD noExtField $+ ClassDecl { tcdCExt = (noAnn, NoAnnSortKey, NoLayoutInfo)+ , tcdCtxt = Just cxt', tcdLName = tc', tcdTyVars = tvs' , tcdFixity = Prefix , tcdFDs = fds', tcdSigs = Hs.mkClassOpSigs sigs' , tcdMeths = binds'@@ -291,12 +307,13 @@ ; (L loc ty') <- cvtType ty ; let inst_ty' = L loc $ mkHsImplicitSigType $ mkHsQualTy ctxt loc ctxt' $ L loc ty'- ; returnJustL $ InstD noExtField $ ClsInstD noExtField $- ClsInstDecl { cid_ext = noExtField, cid_poly_ty = inst_ty'+ ; returnJustLA $ InstD noExtField $ ClsInstD noExtField $+ ClsInstDecl { cid_ext = (noAnn, NoAnnSortKey), cid_poly_ty = inst_ty' , cid_binds = binds' , cid_sigs = Hs.mkClassOpSigs sigs' , cid_tyfam_insts = ats', cid_datafam_insts = adts'- , cid_overlap_mode = fmap (L loc . overlap) o } }+ , cid_overlap_mode+ = fmap (L (l2l loc) . overlap) o } } where overlap pragma = case pragma of@@ -310,29 +327,29 @@ cvtDec (ForeignD ford) = do { ford' <- cvtForD ford- ; returnJustL $ ForD noExtField ford' }+ ; returnJustLA $ ForD noExtField ford' } cvtDec (DataFamilyD tc tvs kind) = do { (_, tc', tvs') <- cvt_tycl_hdr [] tc tvs ; result <- cvtMaybeKindToFamilyResultSig kind- ; returnJustL $ TyClD noExtField $ FamDecl noExtField $- FamilyDecl noExtField DataFamily tc' tvs' Prefix result Nothing }+ ; returnJustLA $ TyClD noExtField $ FamDecl noExtField $+ FamilyDecl noAnn DataFamily TopLevel tc' tvs' Prefix result Nothing } cvtDec (DataInstD ctxt bndrs tys ksig constrs derivs) = do { (ctxt', tc', bndrs', typats') <- cvt_datainst_hdr ctxt bndrs tys ; ksig' <- cvtKind `traverse` ksig ; cons' <- mapM cvtConstr constrs ; derivs' <- cvtDerivs derivs- ; let defn = HsDataDefn { dd_ext = noExtField+ ; let defn = HsDataDefn { dd_ext = noAnn , dd_ND = DataType, dd_cType = Nothing- , dd_ctxt = ctxt'+ , dd_ctxt = Just ctxt' , dd_kindSig = ksig' , dd_cons = cons', dd_derivs = derivs' } - ; returnJustL $ InstD noExtField $ DataFamInstD- { dfid_ext = noExtField+ ; returnJustLA $ InstD noExtField $ DataFamInstD+ { dfid_ext = noAnn , dfid_inst = DataFamInstDecl { dfid_eqn =- FamEqn { feqn_ext = noExtField+ FamEqn { feqn_ext = noAnn , feqn_tycon = tc' , feqn_bndrs = bndrs' , feqn_pats = typats'@@ -344,15 +361,15 @@ ; ksig' <- cvtKind `traverse` ksig ; con' <- cvtConstr constr ; derivs' <- cvtDerivs derivs- ; let defn = HsDataDefn { dd_ext = noExtField+ ; let defn = HsDataDefn { dd_ext = noAnn , dd_ND = NewType, dd_cType = Nothing- , dd_ctxt = ctxt'+ , dd_ctxt = Just ctxt' , dd_kindSig = ksig' , dd_cons = [con'], dd_derivs = derivs' }- ; returnJustL $ InstD noExtField $ DataFamInstD- { dfid_ext = noExtField+ ; returnJustLA $ InstD noExtField $ DataFamInstD+ { dfid_ext = noAnn , dfid_inst = DataFamInstDecl { dfid_eqn =- FamEqn { feqn_ext = noExtField+ FamEqn { feqn_ext = noAnn , feqn_tycon = tc' , feqn_bndrs = bndrs' , feqn_pats = typats'@@ -361,27 +378,28 @@ cvtDec (TySynInstD eqn) = do { (L _ eqn') <- cvtTySynEqn eqn- ; returnJustL $ InstD noExtField $ TyFamInstD+ ; returnJustLA $ InstD noExtField $ TyFamInstD { tfid_ext = noExtField- , tfid_inst = TyFamInstDecl { tfid_eqn = eqn' } } }+ , tfid_inst = TyFamInstDecl { tfid_xtn = noAnn, tfid_eqn = eqn' } }} cvtDec (OpenTypeFamilyD head) = do { (tc', tyvars', result', injectivity') <- cvt_tyfam_head head- ; returnJustL $ TyClD noExtField $ FamDecl noExtField $- FamilyDecl noExtField OpenTypeFamily tc' tyvars' Prefix result' injectivity'+ ; returnJustLA $ TyClD noExtField $ FamDecl noExtField $+ FamilyDecl noAnn OpenTypeFamily TopLevel tc' tyvars' Prefix result' injectivity' } cvtDec (ClosedTypeFamilyD head eqns) = do { (tc', tyvars', result', injectivity') <- cvt_tyfam_head head ; eqns' <- mapM cvtTySynEqn eqns- ; returnJustL $ TyClD noExtField $ FamDecl noExtField $- FamilyDecl noExtField (ClosedTypeFamily (Just eqns')) tc' tyvars' Prefix+ ; returnJustLA $ TyClD noExtField $ FamDecl noExtField $+ FamilyDecl noAnn (ClosedTypeFamily (Just eqns')) TopLevel tc' tyvars' Prefix result' injectivity' } cvtDec (TH.RoleAnnotD tc roles)- = do { tc' <- tconNameL tc+ = do { tc' <- tconNameN tc ; let roles' = map (noLoc . cvtRole) roles- ; returnJustL $ Hs.RoleAnnotD noExtField (RoleAnnotDecl noExtField tc' roles') }+ ; returnJustLA+ $ Hs.RoleAnnotD noExtField (RoleAnnotDecl noAnn tc' roles') } cvtDec (TH.StandaloneDerivD ds cxt ty) = do { cxt' <- cvtContext funPrec cxt@@ -389,44 +407,45 @@ ; (L loc ty') <- cvtType ty ; let inst_ty' = L loc $ mkHsImplicitSigType $ mkHsQualTy cxt loc cxt' $ L loc ty'- ; returnJustL $ DerivD noExtField $- DerivDecl { deriv_ext =noExtField+ ; returnJustLA $ DerivD noExtField $+ DerivDecl { deriv_ext = noAnn , deriv_strategy = ds' , deriv_type = mkHsWildCardBndrs inst_ty' , deriv_overlap_mode = Nothing } } cvtDec (TH.DefaultSigD nm typ)- = do { nm' <- vNameL nm+ = do { nm' <- vNameN nm ; ty' <- cvtSigType typ- ; returnJustL $ Hs.SigD noExtField- $ ClassOpSig noExtField True [nm'] ty'}+ ; returnJustLA $ Hs.SigD noExtField+ $ ClassOpSig noAnn True [nm'] ty'} cvtDec (TH.PatSynD nm args dir pat)- = do { nm' <- cNameL nm+ = do { nm' <- cNameN nm ; args' <- cvtArgs args ; dir' <- cvtDir nm' dir ; pat' <- cvtPat pat- ; returnJustL $ Hs.ValD noExtField $ PatSynBind noExtField $- PSB noExtField nm' args' pat' dir' }+ ; returnJustLA $ Hs.ValD noExtField $ PatSynBind noExtField $+ PSB noAnn nm' args' pat' dir' } where- cvtArgs (TH.PrefixPatSyn args) = Hs.PrefixCon noTypeArgs <$> mapM vNameL args- cvtArgs (TH.InfixPatSyn a1 a2) = Hs.InfixCon <$> vNameL a1 <*> vNameL a2+ cvtArgs (TH.PrefixPatSyn args) = Hs.PrefixCon noTypeArgs <$> mapM vNameN args+ cvtArgs (TH.InfixPatSyn a1 a2) = Hs.InfixCon <$> vNameN a1 <*> vNameN a2 cvtArgs (TH.RecordPatSyn sels)- = do { sels' <- mapM (fmap (\ (L li i) -> FieldOcc noExtField (L li i)) . vNameL) sels- ; vars' <- mapM (vNameL . mkNameS . nameBase) sels+ = do { sels' <- mapM (fmap (\ (L li i) -> FieldOcc noExtField (L li i)) . vNameN) sels+ ; vars' <- mapM (vNameN . mkNameS . nameBase) sels ; return $ Hs.RecCon $ zipWith RecordPatSynField sels' vars' } + -- cvtDir :: LocatedN RdrName -> (PatSynDir -> CvtM (HsPatSynDir RdrName)) cvtDir _ Unidir = return Unidirectional cvtDir _ ImplBidir = return ImplicitBidirectional cvtDir n (ExplBidir cls) = do { ms <- mapM (cvtClause (mkPrefixFunRhs n)) cls ; th_origin <- getOrigin- ; return $ ExplicitBidirectional $ mkMatchGroup th_origin ms }+ ; return $ ExplicitBidirectional $ mkMatchGroup th_origin (noLocA ms) } cvtDec (TH.PatSynSigD nm ty)- = do { nm' <- cNameL nm+ = do { nm' <- cNameN nm ; ty' <- cvtPatSynSigTy ty- ; returnJustL $ Hs.SigD noExtField $ PatSynSig noExtField [nm'] ty'}+ ; returnJustLA $ Hs.SigD noExtField $ PatSynSig noAnn [nm'] ty'} -- Implicit parameter bindings are handled in cvtLocalDecs and -- cvtImplicitParamBind. They are not allowed in any other scope, so@@ -441,21 +460,21 @@ ; let outer_bndrs = mkHsOuterFamEqnTyVarBndrs mb_bndrs' ; (head_ty, args) <- split_ty_app lhs ; case head_ty of- ConT nm -> do { nm' <- tconNameL nm+ ConT nm -> do { nm' <- tconNameN nm ; rhs' <- cvtType rhs ; let args' = map wrap_tyarg args- ; returnL- $ FamEqn { feqn_ext = noExtField+ ; returnLA+ $ FamEqn { feqn_ext = noAnn , feqn_tycon = nm' , feqn_bndrs = outer_bndrs , feqn_pats = args' , feqn_fixity = Prefix , feqn_rhs = rhs' } }- InfixT t1 nm t2 -> do { nm' <- tconNameL nm+ InfixT t1 nm t2 -> do { nm' <- tconNameN nm ; args' <- mapM cvtType [t1,t2] ; rhs' <- cvtType rhs- ; returnL- $ FamEqn { feqn_ext = noExtField+ ; returnLA+ $ FamEqn { feqn_ext = noAnn , feqn_tycon = nm' , feqn_bndrs = outer_bndrs , feqn_pats =@@ -488,18 +507,18 @@ ---------------- cvt_tycl_hdr :: TH.Cxt -> TH.Name -> [TH.TyVarBndr ()] -> CvtM ( LHsContext GhcPs- , Located RdrName+ , LocatedN RdrName , LHsQTyVars GhcPs) cvt_tycl_hdr cxt tc tvs = do { cxt' <- cvtContext funPrec cxt- ; tc' <- tconNameL tc+ ; tc' <- tconNameN tc ; tvs' <- cvtTvs tvs ; return (cxt', tc', mkHsQTvs tvs') } cvt_datainst_hdr :: TH.Cxt -> Maybe [TH.TyVarBndr ()] -> TH.Type -> CvtM ( LHsContext GhcPs- , Located RdrName+ , LocatedN RdrName , HsOuterFamEqnTyVarBndrs GhcPs , HsTyPats GhcPs) cvt_datainst_hdr cxt bndrs tys@@ -508,10 +527,10 @@ ; let outer_bndrs = mkHsOuterFamEqnTyVarBndrs bndrs' ; (head_ty, args) <- split_ty_app tys ; case head_ty of- ConT nm -> do { nm' <- tconNameL nm+ ConT nm -> do { nm' <- tconNameN nm ; let args' = map wrap_tyarg args ; return (cxt', nm', outer_bndrs, args') }- InfixT t1 nm t2 -> do { nm' <- tconNameL nm+ InfixT t1 nm t2 -> do { nm' <- tconNameN nm ; args' <- mapM cvtType [t1,t2] ; return (cxt', nm', outer_bndrs, ((map HsValArg args') ++ args)) }@@ -520,7 +539,7 @@ ---------------- cvt_tyfam_head :: TypeFamilyHead- -> CvtM ( Located RdrName+ -> CvtM ( LocatedN RdrName , LHsQTyVars GhcPs , Hs.LFamilyResultSig GhcPs , Maybe (Hs.LInjectivityAnn GhcPs))@@ -576,28 +595,28 @@ cvtConstr :: TH.Con -> CvtM (LConDecl GhcPs) cvtConstr (NormalC c strtys)- = do { c' <- cNameL c+ = do { c' <- cNameN c ; tys' <- mapM cvt_arg strtys- ; returnL $ mkConDeclH98 c' Nothing Nothing (PrefixCon noTypeArgs (map hsLinear tys')) }+ ; returnLA $ mkConDeclH98 noAnn c' Nothing Nothing (PrefixCon noTypeArgs (map hsLinear tys')) } cvtConstr (RecC c varstrtys)- = do { c' <- cNameL c+ = do { c' <- cNameN c ; args' <- mapM cvt_id_arg varstrtys- ; returnL $ mkConDeclH98 c' Nothing Nothing- (RecCon (noLoc args')) }+ ; returnLA $ mkConDeclH98 noAnn c' Nothing Nothing+ (RecCon (noLocA args')) } cvtConstr (InfixC st1 c st2)- = do { c' <- cNameL c+ = do { c' <- cNameN c ; st1' <- cvt_arg st1 ; st2' <- cvt_arg st2- ; returnL $ mkConDeclH98 c' Nothing Nothing (InfixCon (hsLinear st1')- (hsLinear st2')) }+ ; returnLA $ mkConDeclH98 noAnn c' Nothing Nothing+ (InfixCon (hsLinear st1') (hsLinear st2')) } cvtConstr (ForallC tvs ctxt con) = do { tvs' <- cvtTvs tvs ; ctxt' <- cvtContext funPrec ctxt ; L _ con' <- cvtConstr con- ; returnL $ add_forall tvs' ctxt' con' }+ ; returnLA $ add_forall tvs' ctxt' con' } where add_cxt lcxt Nothing = Just lcxt add_cxt (L loc cxt1) (Just (L _ cxt2))@@ -611,14 +630,14 @@ where outer_bndrs' | null all_tvs = mkHsOuterImplicit- | otherwise = mkHsOuterExplicit all_tvs+ | otherwise = mkHsOuterExplicit noAnn all_tvs all_tvs = tvs' ++ outer_exp_tvs outer_exp_tvs = hsOuterExplicitBndrs outer_bndrs add_forall tvs' cxt' con@(ConDeclH98 { con_ex_tvs = ex_tvs, con_mb_cxt = cxt })- = con { con_forall = noLoc $ not (null all_tvs)+ = con { con_forall = not (null all_tvs) , con_ex_tvs = all_tvs , con_mb_cxt = add_cxt cxt' cxt } where@@ -628,26 +647,26 @@ = failWith (text "GadtC must have at least one constructor name") cvtConstr (GadtC c strtys ty)- = do { c' <- mapM cNameL c+ = do { c' <- mapM cNameN c ; args <- mapM cvt_arg strtys ; ty' <- cvtType ty- ; returnL $ mk_gadt_decl c' (PrefixConGADT $ map hsLinear args) ty'}+ ; returnLA $ mk_gadt_decl c' (PrefixConGADT $ map hsLinear args) ty'} cvtConstr (RecGadtC [] _varstrtys _ty) = failWith (text "RecGadtC must have at least one constructor name") cvtConstr (RecGadtC c varstrtys ty)- = do { c' <- mapM cNameL c+ = do { c' <- mapM cNameN c ; ty' <- cvtType ty ; rec_flds <- mapM cvt_id_arg varstrtys- ; returnL $ mk_gadt_decl c' (RecConGADT $ noLoc rec_flds) ty' }+ ; returnLA $ mk_gadt_decl c' (RecConGADT $ noLocA rec_flds) ty' } -mk_gadt_decl :: [Located RdrName] -> HsConDeclGADTDetails GhcPs -> LHsType GhcPs+mk_gadt_decl :: [LocatedN RdrName] -> HsConDeclGADTDetails GhcPs -> LHsType GhcPs -> ConDecl GhcPs mk_gadt_decl names args res_ty- = ConDeclGADT { con_g_ext = noExtField+ = ConDeclGADT { con_g_ext = noAnn , con_names = names- , con_bndrs = noLoc mkHsOuterImplicit+ , con_bndrs = noLocA mkHsOuterImplicit , con_mb_cxt = Nothing , con_g_args = args , con_res_ty = res_ty@@ -669,27 +688,26 @@ ; let ty' = parenthesizeHsType appPrec ty'' su' = cvtSrcUnpackedness su ss' = cvtSrcStrictness ss- ; returnL $ HsBangTy noExtField (HsSrcBang NoSourceText su' ss') ty' }+ ; returnLA $ HsBangTy noAnn (HsSrcBang NoSourceText su' ss') ty' } cvt_id_arg :: (TH.Name, TH.Bang, TH.Type) -> CvtM (LConDeclField GhcPs) cvt_id_arg (i, str, ty)- = do { L li i' <- vNameL i+ = do { L li i' <- vNameN i ; ty' <- cvt_arg (str,ty)- ; return $ noLoc (ConDeclField- { cd_fld_ext = noExtField+ ; return $ noLocA (ConDeclField+ { cd_fld_ext = noAnn , cd_fld_names- = [L li $ FieldOcc noExtField (L li i')]+ = [L (locA li) $ FieldOcc noExtField (L li i')] , cd_fld_type = ty' , cd_fld_doc = Nothing}) } cvtDerivs :: [TH.DerivClause] -> CvtM (HsDeriving GhcPs)-cvtDerivs cs = do { cs' <- mapM cvtDerivClause cs- ; returnL cs' }+cvtDerivs cs = do { mapM cvtDerivClause cs } -cvt_fundep :: FunDep -> CvtM (LHsFunDep GhcPs)-cvt_fundep (FunDep xs ys) = do { xs' <- mapM tNameL xs- ; ys' <- mapM tNameL ys- ; returnL (xs', ys') }+cvt_fundep :: TH.FunDep -> CvtM (LHsFunDep GhcPs)+cvt_fundep (TH.FunDep xs ys) = do { xs' <- mapM tNameN xs+ ; ys' <- mapM tNameN ys+ ; returnLA (Hs.FunDep noAnn xs' ys') } ------------------------------------------@@ -714,9 +732,9 @@ = failWith $ text (show from) <+> text "is not a valid ccall impent" where mk_imp impspec- = do { nm' <- vNameL nm+ = do { nm' <- vNameN nm ; ty' <- cvtSigType ty- ; return (ForeignImport { fd_i_ext = noExtField+ ; return (ForeignImport { fd_i_ext = noAnn , fd_name = nm' , fd_sig_ty = ty' , fd_fi = impspec })@@ -727,13 +745,13 @@ Interruptible -> PlayInterruptible cvtForD (ExportF callconv as nm ty)- = do { nm' <- vNameL nm+ = do { nm' <- vNameN nm ; ty' <- cvtSigType ty ; let e = CExport (noLoc (CExportStatic (SourceText as) (mkFastString as) (cvt_conv callconv))) (noLoc (SourceText as))- ; return $ ForeignExport { fd_e_ext = noExtField+ ; return $ ForeignExport { fd_e_ext = noAnn , fd_name = nm' , fd_sig_ty = ty' , fd_fe = e } }@@ -751,7 +769,7 @@ cvtPragmaD :: Pragma -> CvtM (Maybe (LHsDecl GhcPs)) cvtPragmaD (InlineP nm inline rm phases)- = do { nm' <- vNameL nm+ = do { nm' <- vNameN nm ; let dflt = dfltActivation inline ; let src TH.NoInline = "{-# NOINLINE" src TH.Inline = "{-# INLINE"@@ -761,10 +779,10 @@ , inl_rule = cvtRuleMatch rm , inl_act = cvtPhases phases dflt , inl_sat = Nothing }- ; returnJustL $ Hs.SigD noExtField $ InlineSig noExtField nm' ip }+ ; returnJustLA $ Hs.SigD noExtField $ InlineSig noAnn nm' ip } cvtPragmaD (SpecialiseP nm ty inline phases)- = do { nm' <- vNameL nm+ = do { nm' <- vNameN nm ; ty' <- cvtSigType ty ; let src TH.NoInline = "{-# SPECIALISE NOINLINE" src TH.Inline = "{-# SPECIALISE INLINE"@@ -779,12 +797,12 @@ , inl_rule = Hs.FunLike , inl_act = cvtPhases phases dflt , inl_sat = Nothing }- ; returnJustL $ Hs.SigD noExtField $ SpecSig noExtField nm' [ty'] ip }+ ; returnJustLA $ Hs.SigD noExtField $ SpecSig noAnn nm' [ty'] ip } cvtPragmaD (SpecialiseInstP ty) = do { ty' <- cvtSigType ty- ; returnJustL $ Hs.SigD noExtField $- SpecInstSig noExtField (SourceText "{-# SPECIALISE") ty' }+ ; returnJustLA $ Hs.SigD noExtField $+ SpecInstSig noAnn (SourceText "{-# SPECIALISE") ty' } cvtPragmaD (RuleP nm ty_bndrs tm_bndrs lhs rhs phases) = do { let nm' = mkFastString nm@@ -793,11 +811,11 @@ ; tm_bndrs' <- mapM cvtRuleBndr tm_bndrs ; lhs' <- cvtl lhs ; rhs' <- cvtl rhs- ; returnJustL $ Hs.RuleD noExtField- $ HsRules { rds_ext = noExtField+ ; returnJustLA $ Hs.RuleD noExtField+ $ HsRules { rds_ext = noAnn , rds_src = SourceText "{-# RULES"- , rds_rules = [noLoc $- HsRule { rd_ext = noExtField+ , rds_rules = [noLocA $+ HsRule { rd_ext = noAnn , rd_name = (noLoc (quotedSourceText nm,nm')) , rd_act = act , rd_tyvs = ty_bndrs'@@ -813,12 +831,12 @@ ModuleAnnotation -> return ModuleAnnProvenance TypeAnnotation n -> do n' <- tconName n- return (TypeAnnProvenance (noLoc n'))+ return (TypeAnnProvenance (noLocA n')) ValueAnnotation n -> do n' <- vcName n- return (ValueAnnProvenance (noLoc n'))- ; returnJustL $ Hs.AnnD noExtField- $ HsAnnotation noExtField (SourceText "{-# ANN") target' exp'+ return (ValueAnnProvenance (noLocA n'))+ ; returnJustLA $ Hs.AnnD noExtField+ $ HsAnnotation noAnn (SourceText "{-# ANN") target' exp' } cvtPragmaD (LineP line file)@@ -826,10 +844,10 @@ ; return Nothing } cvtPragmaD (CompleteP cls mty)- = do { cls' <- noLoc <$> mapM cNameL cls- ; mty' <- traverse tconNameL mty- ; returnJustL $ Hs.SigD noExtField- $ CompleteMatchSig noExtField NoSourceText cls' mty' }+ = do { cls' <- noLoc <$> mapM cNameN cls+ ; mty' <- traverse tconNameN mty+ ; returnJustLA $ Hs.SigD noExtField+ $ CompleteMatchSig noAnn NoSourceText cls' mty' } dfltActivation :: TH.Inline -> Activation dfltActivation TH.NoInline = NeverActive@@ -851,12 +869,12 @@ cvtRuleBndr :: TH.RuleBndr -> CvtM (Hs.LRuleBndr GhcPs) cvtRuleBndr (RuleVar n)- = do { n' <- vNameL n- ; return $ noLoc $ Hs.RuleBndr noExtField n' }+ = do { n' <- vNameN n+ ; return $ noLoc $ Hs.RuleBndr noAnn n' } cvtRuleBndr (TypedRuleVar n ty)- = do { n' <- vNameL n+ = do { n' <- vNameN n ; ty' <- cvtType ty- ; return $ noLoc $ Hs.RuleBndrSig noExtField n' $ mkHsPatSigType ty' }+ ; return $ noLoc $ Hs.RuleBndrSig noAnn n' $ mkHsPatSigType ty' } --------------------------------------------------- -- Declarations@@ -871,10 +889,10 @@ let (binds, prob_sigs) = partitionWith is_bind ds' let (sigs, bads) = partitionWith is_sig prob_sigs unless (null bads) (failWith (mkBadDecMsg doc bads))- return (HsValBinds noExtField (ValBinds noExtField (listToBag binds) sigs))+ return (HsValBinds noAnn (ValBinds NoAnnSortKey (listToBag binds) sigs)) (ip_binds, []) -> do binds <- mapM (uncurry cvtImplicitParamBind) ip_binds- return (HsIPBinds noExtField (IPBinds noExtField binds))+ return (HsIPBinds noAnn (IPBinds noExtField binds)) ((_:_), (_:_)) -> failWith (text "Implicit parameters mixed with other bindings") @@ -885,27 +903,27 @@ ; let pps = map (parenthesizePat appPrec) ps' ; g' <- cvtGuard body ; ds' <- cvtLocalDecs (text "a where clause") wheres- ; returnL $ Hs.Match noExtField ctxt pps (GRHSs noExtField g' (noLoc ds')) }+ ; returnLA $ Hs.Match noAnn ctxt pps (GRHSs noExtField g' ds') } cvtImplicitParamBind :: String -> TH.Exp -> CvtM (LIPBind GhcPs) cvtImplicitParamBind n e = do n' <- wrapL (ipName n) e' <- cvtl e- returnL (IPBind noExtField (Left n') e')+ returnLA (IPBind noAnn (Left n') e') ------------------------------------------------------------------- -- Expressions ------------------------------------------------------------------- cvtl :: TH.Exp -> CvtM (LHsExpr GhcPs)-cvtl e = wrapL (cvt e)+cvtl e = wrapLA (cvt e) where- cvt (VarE s) = do { s' <- vName s; return $ HsVar noExtField (noLoc s') }- cvt (ConE s) = do { s' <- cName s; return $ HsVar noExtField (noLoc s') }+ cvt (VarE s) = do { s' <- vName s; return $ HsVar noExtField (noLocA s') }+ cvt (ConE s) = do { s' <- cName s; return $ HsVar noExtField (noLocA s') } cvt (LitE l)- | overloadedLit l = go cvtOverLit (HsOverLit noExtField)+ | overloadedLit l = go cvtOverLit (HsOverLit noComments) (hsOverLitNeedsParens appPrec)- | otherwise = go cvtLit (HsLit noExtField)+ | otherwise = go cvtLit (HsLit noComments) (hsLitNeedsParens appPrec) where go :: (Lit -> CvtM (l GhcPs))@@ -915,17 +933,17 @@ go cvt_lit mk_expr is_compound_lit = do l' <- cvt_lit l let e' = mk_expr l'- return $ if is_compound_lit l' then HsPar noExtField (noLoc e') else e'+ return $ if is_compound_lit l' then HsPar noAnn (noLocA e') else e' cvt (AppE x@(LamE _ _) y) = do { x' <- cvtl x; y' <- cvtl y- ; return $ HsApp noExtField (mkLHsPar x')+ ; return $ HsApp noComments (mkLHsPar x') (mkLHsPar y')} cvt (AppE x y) = do { x' <- cvtl x; y' <- cvtl y- ; return $ HsApp noExtField (mkLHsPar x')+ ; return $ HsApp noComments (mkLHsPar x') (mkLHsPar y')} cvt (AppTypeE e t) = do { e' <- cvtl e ; t' <- cvtType t ; let tp = parenthesizeHsType appPrec t'- ; return $ HsAppType noExtField e'+ ; return $ HsAppType noSrcSpan e' $ mkHsWildCardBndrs tp } cvt (LamE [] e) = cvt e -- Degenerate case. We convert the body as its -- own expression to avoid pretty-printing@@ -935,42 +953,42 @@ ; let pats = map (parenthesizePat appPrec) ps' ; th_origin <- getOrigin ; return $ HsLam noExtField (mkMatchGroup th_origin- [mkSimpleMatch LambdaExpr- pats e'])}+ (noLocA [mkSimpleMatch LambdaExpr+ pats e']))} cvt (LamCaseE ms) = do { ms' <- mapM (cvtMatch CaseAlt) ms ; th_origin <- getOrigin- ; return $ HsLamCase noExtField- (mkMatchGroup th_origin ms')+ ; return $ HsLamCase noAnn+ (mkMatchGroup th_origin (noLocA ms')) } cvt (TupE es) = cvt_tup es Boxed cvt (UnboxedTupE es) = cvt_tup es Unboxed cvt (UnboxedSumE e alt arity) = do { e' <- cvtl e ; unboxedSumChecks alt arity- ; return $ ExplicitSum noExtField+ ; return $ ExplicitSum noAnn alt arity e'} cvt (CondE x y z) = do { x' <- cvtl x; y' <- cvtl y; z' <- cvtl z;- ; return $ mkHsIf x' y' z' }+ ; return $ mkHsIf x' y' z' noAnn } cvt (MultiIfE alts) | null alts = failWith (text "Multi-way if-expression with no alternatives") | otherwise = do { alts' <- mapM cvtpair alts- ; return $ HsMultiIf noExtField alts' }+ ; return $ HsMultiIf noAnn alts' } cvt (LetE ds e) = do { ds' <- cvtLocalDecs (text "a let expression") ds- ; e' <- cvtl e; return $ HsLet noExtField (noLoc ds') e'}+ ; e' <- cvtl e; return $ HsLet noAnn ds' e'} cvt (CaseE e ms) = do { e' <- cvtl e; ms' <- mapM (cvtMatch CaseAlt) ms ; th_origin <- getOrigin- ; return $ HsCase noExtField e'- (mkMatchGroup th_origin ms') }+ ; return $ HsCase noAnn e'+ (mkMatchGroup th_origin (noLocA ms')) } cvt (DoE m ss) = cvtHsDo (DoExpr (mk_mod <$> m)) ss cvt (MDoE m ss) = cvtHsDo (MDoExpr (mk_mod <$> m)) ss cvt (CompE ss) = cvtHsDo ListComp ss cvt (ArithSeqE dd) = do { dd' <- cvtDD dd- ; return $ ArithSeq noExtField Nothing dd' }+ ; return $ ArithSeq noAnn Nothing dd' } cvt (ListE xs) | Just s <- allCharLs xs = do { l' <- cvtLit (StringL s)- ; return (HsLit noExtField l') }+ ; return (HsLit noComments l') } -- Note [Converting strings] | otherwise = do { xs' <- mapM cvtl xs- ; return $ ExplicitList noExtField xs'+ ; return $ ExplicitList noAnn xs' } -- Infix expressions@@ -980,25 +998,25 @@ ; y' <- cvtl y ; let px = parenthesizeHsExpr opPrec x' py = parenthesizeHsExpr opPrec y'- ; wrapParL (HsPar noExtField)- $ OpApp noExtField px s' py }+ ; wrapParLA (HsPar noAnn)+ $ OpApp noAnn px s' py } -- Parenthesise both arguments and result, -- to ensure this operator application does -- does not get re-associated -- See Note [Operator association] cvt (InfixE Nothing s (Just y)) = ensureValidOpExp s $ do { s' <- cvtl s; y' <- cvtl y- ; wrapParL (HsPar noExtField) $- SectionR noExtField s' y' }+ ; wrapParLA (HsPar noAnn) $+ SectionR noComments s' y' } -- See Note [Sections in HsSyn] in GHC.Hs.Expr cvt (InfixE (Just x) s Nothing ) = ensureValidOpExp s $ do { x' <- cvtl x; s' <- cvtl s- ; wrapParL (HsPar noExtField) $- SectionL noExtField x' s' }+ ; wrapParLA (HsPar noAnn) $+ SectionL noComments x' s' } cvt (InfixE Nothing s Nothing ) = ensureValidOpExp s $ do { s' <- cvtl s- ; return $ HsPar noExtField s' }+ ; return $ HsPar noAnn s' } -- Can I indicate this is an infix thing? -- Note [Dropping constructors] @@ -1009,26 +1027,26 @@ _ -> mkLHsPar x' ; cvtOpApp x'' s y } -- Note [Converting UInfix] - cvt (ParensE e) = do { e' <- cvtl e; return $ HsPar noExtField e' }+ cvt (ParensE e) = do { e' <- cvtl e; return $ HsPar noAnn e' } cvt (SigE e t) = do { e' <- cvtl e; t' <- cvtSigType t ; let pe = parenthesizeHsExpr sigPrec e'- ; return $ ExprWithTySig noExtField pe (mkHsWildCardBndrs t') }- cvt (RecConE c flds) = do { c' <- cNameL c- ; flds' <- mapM (cvtFld (mkFieldOcc . noLoc)) flds- ; return $ mkRdrRecordCon c' (HsRecFields flds' Nothing) }+ ; return $ ExprWithTySig noAnn pe (mkHsWildCardBndrs t') }+ cvt (RecConE c flds) = do { c' <- cNameN c+ ; flds' <- mapM (cvtFld (mkFieldOcc . noLocA)) flds+ ; return $ mkRdrRecordCon c' (HsRecFields flds' Nothing) noAnn } cvt (RecUpdE e flds) = do { e' <- cvtl e ; flds'- <- mapM (cvtFld (mkAmbiguousFieldOcc . noLoc))+ <- mapM (cvtFld (mkAmbiguousFieldOcc . noLocA)) flds- ; return $ mkRdrRecordUpd e' flds' }- cvt (StaticE e) = fmap (HsStatic noExtField) $ cvtl e+ ; return $ RecordUpd noAnn e' (Left flds') }+ cvt (StaticE e) = fmap (HsStatic noAnn) $ cvtl e cvt (UnboundVarE s) = do -- Use of 'vcName' here instead of 'vName' is -- important, because UnboundVarE may contain -- constructor names - see #14627. { s' <- vcName s- ; return $ HsVar noExtField (noLoc s') }- cvt (LabelE s) = return $ HsOverLabel noExtField (fsLit s)- cvt (ImplicitParamVarE n) = do { n' <- ipName n; return $ HsIPVar noExtField n' }+ ; return $ HsVar noExtField (noLocA s') }+ cvt (LabelE s) = return $ HsOverLabel noComments (fsLit s)+ cvt (ImplicitParamVarE n) = do { n' <- ipName n; return $ HsIPVar noComments n' } {- | #16895 Ensure an infix expression's operator is a variable/constructor. Consider this example:@@ -1064,12 +1082,13 @@ -} cvtFld :: (RdrName -> t) -> (TH.Name, TH.Exp)- -> CvtM (LHsRecField' t (LHsExpr GhcPs))+ -> CvtM (LHsRecField' GhcPs t (LHsExpr GhcPs)) cvtFld f (v,e) = do { v' <- vNameL v; e' <- cvtl e- ; return (noLoc $ HsRecField { hsRecFieldLbl = fmap f v'- , hsRecFieldArg = e'- , hsRecPun = False}) }+ ; return (noLocA $ HsRecField { hsRecFieldAnn = noAnn+ , hsRecFieldLbl = reLoc $ fmap f v'+ , hsRecFieldArg = e'+ , hsRecPun = False}) } cvtDD :: Range -> CvtM (ArithSeqInfo GhcPs) cvtDD (FromR x) = do { x' <- cvtl x; return $ From x' }@@ -1078,12 +1097,12 @@ cvtDD (FromThenToR x y z) = do { x' <- cvtl x; y' <- cvtl y; z' <- cvtl z; return $ FromThenTo x' y' z' } cvt_tup :: [Maybe Exp] -> Boxity -> CvtM (HsExpr GhcPs)-cvt_tup es boxity = do { let cvtl_maybe Nothing = return missingTupArg- cvtl_maybe (Just e) = fmap (Present noExtField) (cvtl e)+cvt_tup es boxity = do { let cvtl_maybe Nothing = return (missingTupArg noAnn)+ cvtl_maybe (Just e) = fmap (Present noAnn) (cvtl e) ; es' <- mapM cvtl_maybe es ; return $ ExplicitTuple- noExtField- (map noLoc es')+ noAnn+ es' boxity } {- Note [Operator association]@@ -1140,12 +1159,12 @@ -} cvtOpApp :: LHsExpr GhcPs -> TH.Exp -> TH.Exp -> CvtM (HsExpr GhcPs) cvtOpApp x op1 (UInfixE y op2 z)- = do { l <- wrapL $ cvtOpApp x op1 y+ = do { l <- wrapLA $ cvtOpApp x op1 y ; cvtOpApp l op2 z } cvtOpApp x op y = do { op' <- cvtl op ; y' <- cvtl y- ; return (OpApp noExtField x op' y') }+ ; return (OpApp noAnn x op' y') } ------------------------------------- -- Do notation and statements@@ -1163,7 +1182,7 @@ -> return (L loc (mkLastStmt body)) _ -> failWith (bad_last last') - ; return $ HsDo noExtField do_or_lc (noLoc (stmts'' ++ [last''])) }+ ; return $ HsDo noAnn do_or_lc (noLocA (stmts'' ++ [last''])) } where bad_last stmt = vcat [ text "Illegal last statement of" <+> pprAStmtContext do_or_lc <> colon , nest 2 $ Outputable.ppr stmt@@ -1173,39 +1192,39 @@ cvtStmts = mapM cvtStmt cvtStmt :: TH.Stmt -> CvtM (Hs.LStmt GhcPs (LHsExpr GhcPs))-cvtStmt (NoBindS e) = do { e' <- cvtl e; returnL $ mkBodyStmt e' }-cvtStmt (TH.BindS p e) = do { p' <- cvtPat p; e' <- cvtl e; returnL $ mkPsBindStmt p' e' }+cvtStmt (NoBindS e) = do { e' <- cvtl e; returnLA $ mkBodyStmt e' }+cvtStmt (TH.BindS p e) = do { p' <- cvtPat p; e' <- cvtl e; returnLA $ mkPsBindStmt noAnn p' e' } cvtStmt (TH.LetS ds) = do { ds' <- cvtLocalDecs (text "a let binding") ds- ; returnL $ LetStmt noExtField (noLoc ds') }+ ; returnLA $ LetStmt noAnn ds' } cvtStmt (TH.ParS dss) = do { dss' <- mapM cvt_one dss- ; returnL $ ParStmt noExtField dss' noExpr noSyntaxExpr }+ ; returnLA $ ParStmt noExtField dss' noExpr noSyntaxExpr } where cvt_one ds = do { ds' <- cvtStmts ds ; return (ParStmtBlock noExtField ds' undefined noSyntaxExpr) }-cvtStmt (TH.RecS ss) = do { ss' <- mapM cvtStmt ss; returnL (mkRecStmt ss') }+cvtStmt (TH.RecS ss) = do { ss' <- mapM cvtStmt ss; returnLA (mkRecStmt noAnn (noLocA ss')) } cvtMatch :: HsMatchContext GhcPs -> TH.Match -> CvtM (Hs.LMatch GhcPs (LHsExpr GhcPs)) cvtMatch ctxt (TH.Match p body decs) = do { p' <- cvtPat p ; let lp = case p' of- (L loc SigPat{}) -> L loc (ParPat noExtField p') -- #14875+ (L loc SigPat{}) -> L loc (ParPat noAnn p') -- #14875 _ -> p' ; g' <- cvtGuard body ; decs' <- cvtLocalDecs (text "a where clause") decs- ; returnL $ Hs.Match noExtField ctxt [lp] (GRHSs noExtField g' (noLoc decs')) }+ ; returnLA $ Hs.Match noAnn ctxt [lp] (GRHSs noExtField g' decs') } cvtGuard :: TH.Body -> CvtM [LGRHS GhcPs (LHsExpr GhcPs)] cvtGuard (GuardedB pairs) = mapM cvtpair pairs cvtGuard (NormalB e) = do { e' <- cvtl e- ; g' <- returnL $ GRHS noExtField [] e'; return [g'] }+ ; g' <- returnL $ GRHS noAnn [] e'; return [g'] } cvtpair :: (TH.Guard, TH.Exp) -> CvtM (LGRHS GhcPs (LHsExpr GhcPs)) cvtpair (NormalG ge,rhs) = do { ge' <- cvtl ge; rhs' <- cvtl rhs- ; g' <- returnL $ mkBodyStmt ge'- ; returnL $ GRHS noExtField [g'] rhs' }+ ; g' <- returnLA $ mkBodyStmt ge'+ ; returnL $ GRHS noAnn [g'] rhs' } cvtpair (PatG gs,rhs) = do { gs' <- cvtStmts gs; rhs' <- cvtl rhs- ; returnL $ GRHS noExtField gs' rhs' }+ ; returnL $ GRHS noAnn gs' rhs' } cvtOverLit :: Lit -> CvtM (HsOverLit GhcPs) cvtOverLit (IntegerL i)@@ -1273,39 +1292,39 @@ cvtPats pats = mapM cvtPat pats cvtPat :: TH.Pat -> CvtM (Hs.LPat GhcPs)-cvtPat pat = wrapL (cvtp pat)+cvtPat pat = wrapLA (cvtp pat) cvtp :: TH.Pat -> CvtM (Hs.Pat GhcPs) cvtp (TH.LitP l) | overloadedLit l = do { l' <- cvtOverLit l- ; return (mkNPat (noLoc l') Nothing) }+ ; return (mkNPat (noLoc l') Nothing noAnn) } -- Not right for negative patterns; -- need to think about that! | otherwise = do { l' <- cvtLit l; return $ Hs.LitPat noExtField l' } cvtp (TH.VarP s) = do { s' <- vName s- ; return $ Hs.VarPat noExtField (noLoc s') }+ ; return $ Hs.VarPat noExtField (noLocA s') } cvtp (TupP ps) = do { ps' <- cvtPats ps- ; return $ TuplePat noExtField ps' Boxed }+ ; return $ TuplePat noAnn ps' Boxed } cvtp (UnboxedTupP ps) = do { ps' <- cvtPats ps- ; return $ TuplePat noExtField ps' Unboxed }+ ; return $ TuplePat noAnn ps' Unboxed } cvtp (UnboxedSumP p alt arity) = do { p' <- cvtPat p ; unboxedSumChecks alt arity- ; return $ SumPat noExtField p' alt arity }-cvtp (ConP s ts ps) = do { s' <- cNameL s+ ; return $ SumPat noAnn p' alt arity }+cvtp (ConP s ts ps) = do { s' <- cNameN s ; ps' <- cvtPats ps ; ts' <- mapM cvtType ts ; let pps = map (parenthesizePat appPrec) ps' ; return $ ConPat- { pat_con_ext = noExtField+ { pat_con_ext = noAnn , pat_con = s' , pat_args = PrefixCon (map mkHsPatSigType ts') pps } }-cvtp (InfixP p1 s p2) = do { s' <- cNameL s; p1' <- cvtPat p1; p2' <- cvtPat p2- ; wrapParL (ParPat noExtField) $+cvtp (InfixP p1 s p2) = do { s' <- cNameN s; p1' <- cvtPat p1; p2' <- cvtPat p2+ ; wrapParLA (ParPat noAnn) $ ConPat- { pat_con_ext = NoExtField+ { pat_con_ext = noAnn , pat_con = s' , pat_args = InfixCon (parenthesizePat opPrec p1')@@ -1317,35 +1336,36 @@ cvtp (ParensP p) = do { p' <- cvtPat p; ; case unLoc p' of -- may be wrapped ConPatIn ParPat {} -> return $ unLoc p'- _ -> return $ ParPat noExtField p' }-cvtp (TildeP p) = do { p' <- cvtPat p; return $ LazyPat noExtField p' }-cvtp (BangP p) = do { p' <- cvtPat p; return $ BangPat noExtField p' }-cvtp (TH.AsP s p) = do { s' <- vNameL s; p' <- cvtPat p- ; return $ AsPat noExtField s' p' }+ _ -> return $ ParPat noAnn p' }+cvtp (TildeP p) = do { p' <- cvtPat p; return $ LazyPat noAnn p' }+cvtp (BangP p) = do { p' <- cvtPat p; return $ BangPat noAnn p' }+cvtp (TH.AsP s p) = do { s' <- vNameN s; p' <- cvtPat p+ ; return $ AsPat noAnn s' p' } cvtp TH.WildP = return $ WildPat noExtField-cvtp (RecP c fs) = do { c' <- cNameL c; fs' <- mapM cvtPatFld fs+cvtp (RecP c fs) = do { c' <- cNameN c; fs' <- mapM cvtPatFld fs ; return $ ConPat- { pat_con_ext = noExtField+ { pat_con_ext = noAnn , pat_con = c' , pat_args = Hs.RecCon $ HsRecFields fs' Nothing } } cvtp (ListP ps) = do { ps' <- cvtPats ps ; return- $ ListPat noExtField ps'}+ $ ListPat noAnn ps'} cvtp (SigP p t) = do { p' <- cvtPat p; t' <- cvtType t- ; return $ SigPat noExtField p' (mkHsPatSigType t') }+ ; return $ SigPat noAnn p' (mkHsPatSigType t') } cvtp (ViewP e p) = do { e' <- cvtl e; p' <- cvtPat p- ; return $ ViewPat noExtField e' p'}+ ; return $ ViewPat noAnn e' p'} cvtPatFld :: (TH.Name, TH.Pat) -> CvtM (LHsRecField GhcPs (LPat GhcPs)) cvtPatFld (s,p)- = do { L ls s' <- vNameL s+ = do { L ls s' <- vNameN s ; p' <- cvtPat p- ; return (noLoc $ HsRecField { hsRecFieldLbl- = L ls $ mkFieldOcc (L ls s')- , hsRecFieldArg = p'- , hsRecPun = False}) }+ ; return (noLocA $ HsRecField { hsRecFieldAnn = noAnn+ , hsRecFieldLbl+ = L (locA ls) $ mkFieldOcc (L ls s')+ , hsRecFieldArg = p'+ , hsRecPun = False}) } {- | @cvtOpAppP x op y@ converts @op@ and @y@ and produces the operator application @x `op` y@. The produced tree of infix patterns will be left-biased, provided @x@ is.@@ -1354,13 +1374,13 @@ -} cvtOpAppP :: Hs.LPat GhcPs -> TH.Name -> TH.Pat -> CvtM (Hs.Pat GhcPs) cvtOpAppP x op1 (UInfixP y op2 z)- = do { l <- wrapL $ cvtOpAppP x op1 y+ = do { l <- wrapLA $ cvtOpAppP x op1 y ; cvtOpAppP l op2 z } cvtOpAppP x op y- = do { op' <- cNameL op+ = do { op' <- cNameN op ; y' <- cvtPat y ; return $ ConPat- { pat_con_ext = noExtField+ { pat_con_ext = noAnn , pat_con = op' , pat_args = InfixCon x y' }@@ -1384,14 +1404,14 @@ cvt_tv :: CvtFlag flag flag' => (TH.TyVarBndr flag) -> CvtM (LHsTyVarBndr flag' GhcPs) cvt_tv (TH.PlainTV nm fl)- = do { nm' <- tNameL nm+ = do { nm' <- tNameN nm ; let fl' = cvtFlag fl- ; returnL $ UserTyVar noExtField fl' nm' }+ ; returnLA $ UserTyVar noAnn fl' nm' } cvt_tv (TH.KindedTV nm fl ki)- = do { nm' <- tNameL nm+ = do { nm' <- tNameN nm ; let fl' = cvtFlag fl ; ki' <- cvtKind ki- ; returnL $ KindedTyVar noExtField fl' nm' ki' }+ ; returnLA $ KindedTyVar noAnn fl' nm' ki' } cvtRole :: TH.Role -> Maybe Coercion.Role cvtRole TH.NominalR = Just Coercion.Nominal@@ -1401,7 +1421,7 @@ cvtContext :: PprPrec -> TH.Cxt -> CvtM (LHsContext GhcPs) cvtContext p tys = do { preds' <- mapM cvtPred tys- ; parenthesizeHsContext p <$> returnL preds' }+ ; parenthesizeHsContext p <$> returnLA preds' } cvtPred :: TH.Pred -> CvtM (LHsType GhcPs) cvtPred = cvtType@@ -1417,23 +1437,23 @@ ; case tys' of [ty'@(L l (HsSig { sig_bndrs = HsOuterImplicit{} , sig_body = L _ (HsTyVar _ NotPromoted _) }))]- -> return $ L l $ DctSingle noExtField ty'- _ -> returnL $ DctMulti noExtField tys' }+ -> return $ L (l2l l) $ DctSingle noExtField ty'+ _ -> returnLA $ DctMulti noExtField tys' } cvtDerivClause :: TH.DerivClause -> CvtM (LHsDerivingClause GhcPs) cvtDerivClause (TH.DerivClause ds tys) = do { tys' <- cvtDerivClauseTys tys ; ds' <- traverse cvtDerivStrategy ds- ; returnL $ HsDerivingClause noExtField ds' tys' }+ ; returnL $ HsDerivingClause noAnn ds' tys' } cvtDerivStrategy :: TH.DerivStrategy -> CvtM (Hs.LDerivStrategy GhcPs)-cvtDerivStrategy TH.StockStrategy = returnL Hs.StockStrategy-cvtDerivStrategy TH.AnyclassStrategy = returnL Hs.AnyclassStrategy-cvtDerivStrategy TH.NewtypeStrategy = returnL Hs.NewtypeStrategy+cvtDerivStrategy TH.StockStrategy = returnL (Hs.StockStrategy noAnn)+cvtDerivStrategy TH.AnyclassStrategy = returnL (Hs.AnyclassStrategy noAnn)+cvtDerivStrategy TH.NewtypeStrategy = returnL (Hs.NewtypeStrategy noAnn) cvtDerivStrategy (TH.ViaStrategy ty) = do ty' <- cvtSigType ty- returnL $ Hs.ViaStrategy ty'+ returnL $ Hs.ViaStrategy (XViaStrategyPs noAnn ty') cvtType :: TH.Type -> CvtM (LHsType GhcPs) cvtType = cvtTypeKind "type"@@ -1460,18 +1480,20 @@ TupleT n | Just normals <- m_normals , normals `lengthIs` n -- Saturated- -> returnL (HsTupleTy noExtField HsBoxedOrConstraintTuple normals)+ -> returnLA (HsTupleTy noAnn HsBoxedOrConstraintTuple normals) | otherwise -> mk_apps- (HsTyVar noExtField NotPromoted (noLoc (getRdrName (tupleTyCon Boxed n))))+ (HsTyVar noAnn NotPromoted+ (noLocA (getRdrName (tupleTyCon Boxed n)))) tys' UnboxedTupleT n | Just normals <- m_normals , normals `lengthIs` n -- Saturated- -> returnL (HsTupleTy noExtField HsUnboxedTuple normals)+ -> returnLA (HsTupleTy noAnn HsUnboxedTuple normals) | otherwise -> mk_apps- (HsTyVar noExtField NotPromoted (noLoc (getRdrName (tupleTyCon Unboxed n))))+ (HsTyVar noAnn NotPromoted+ (noLocA (getRdrName (tupleTyCon Unboxed n)))) tys' UnboxedSumT n | n < 2@@ -1481,56 +1503,56 @@ text "Sums must have an arity of at least 2" ] | Just normals <- m_normals , normals `lengthIs` n -- Saturated- -> returnL (HsSumTy noExtField normals)+ -> returnLA (HsSumTy noAnn normals) | otherwise -> mk_apps- (HsTyVar noExtField NotPromoted (noLoc (getRdrName (sumTyCon n))))+ (HsTyVar noAnn NotPromoted (noLocA (getRdrName (sumTyCon n)))) tys' ArrowT | Just normals <- m_normals , [x',y'] <- normals -> do x'' <- case unLoc x' of- HsFunTy{} -> returnL (HsParTy noExtField x')- HsForAllTy{} -> returnL (HsParTy noExtField x') -- #14646- HsQualTy{} -> returnL (HsParTy noExtField x') -- #15324+ HsFunTy{} -> returnLA (HsParTy noAnn x')+ HsForAllTy{} -> returnLA (HsParTy noAnn x') -- #14646+ HsQualTy{} -> returnLA (HsParTy noAnn x') -- #15324 _ -> return $ parenthesizeHsType sigPrec x' let y'' = parenthesizeHsType sigPrec y'- returnL (HsFunTy noExtField (HsUnrestrictedArrow NormalSyntax) x'' y'')+ returnLA (HsFunTy noAnn (HsUnrestrictedArrow NormalSyntax) x'' y'') | otherwise -> mk_apps- (HsTyVar noExtField NotPromoted (noLoc (getRdrName unrestrictedFunTyCon)))+ (HsTyVar noAnn NotPromoted (noLocA (getRdrName unrestrictedFunTyCon))) tys' MulArrowT | Just normals <- m_normals , [w',x',y'] <- normals -> do x'' <- case unLoc x' of- HsFunTy{} -> returnL (HsParTy noExtField x')- HsForAllTy{} -> returnL (HsParTy noExtField x') -- #14646- HsQualTy{} -> returnL (HsParTy noExtField x') -- #15324+ HsFunTy{} -> returnLA (HsParTy noAnn x')+ HsForAllTy{} -> returnLA (HsParTy noAnn x') -- #14646+ HsQualTy{} -> returnLA (HsParTy noAnn x') -- #15324 _ -> return $ parenthesizeHsType sigPrec x' let y'' = parenthesizeHsType sigPrec y' w'' = hsTypeToArrow w'- returnL (HsFunTy noExtField w'' x'' y'')+ returnLA (HsFunTy noAnn w'' x'' y'') | otherwise -> mk_apps- (HsTyVar noExtField NotPromoted (noLoc (getRdrName funTyCon)))+ (HsTyVar noAnn NotPromoted (noLocA (getRdrName funTyCon))) tys' ListT | Just normals <- m_normals , [x'] <- normals ->- returnL (HsListTy noExtField x')+ returnLA (HsListTy noAnn x') | otherwise -> mk_apps- (HsTyVar noExtField NotPromoted (noLoc (getRdrName listTyCon)))+ (HsTyVar noAnn NotPromoted (noLocA (getRdrName listTyCon))) tys' - VarT nm -> do { nm' <- tNameL nm- ; mk_apps (HsTyVar noExtField NotPromoted nm') tys' }+ VarT nm -> do { nm' <- tNameN nm+ ; mk_apps (HsTyVar noAnn NotPromoted nm') tys' } ConT nm -> do { nm' <- tconName nm ; let prom = name_promotedness nm'- ; mk_apps (HsTyVar noExtField prom (noLoc nm')) tys'}+ ; mk_apps (HsTyVar noAnn prom (noLocA nm')) tys'} ForallT tvs cxt ty | null tys'@@ -1538,9 +1560,10 @@ ; cxt' <- cvtContext funPrec cxt ; ty' <- cvtType ty ; loc <- getL- ; let tele = mkHsForAllInvisTele tvs'- hs_ty = mkHsForAllTy loc tele rho_ty- rho_ty = mkHsQualTy cxt loc cxt' ty'+ ; let loc' = noAnnSrcSpan loc+ ; let tele = mkHsForAllInvisTele noAnn tvs'+ hs_ty = mkHsForAllTy loc' tele rho_ty+ rho_ty = mkHsQualTy cxt loc' cxt' ty' ; return hs_ty } @@ -1549,13 +1572,14 @@ -> do { tvs' <- cvtTvs tvs ; ty' <- cvtType ty ; loc <- getL- ; let tele = mkHsForAllVisTele tvs'- ; pure $ mkHsForAllTy loc tele ty' }+ ; let loc' = noAnnSrcSpan loc+ ; let tele = mkHsForAllVisTele noAnn tvs'+ ; pure $ mkHsForAllTy loc' tele ty' } SigT ty ki -> do { ty' <- cvtType ty ; ki' <- cvtKind ki- ; mk_apps (HsKindSig noExtField ty' ki') tys'+ ; mk_apps (HsKindSig noAnn ty' ki') tys' } LitT lit@@ -1570,7 +1594,7 @@ ; t2' <- cvtType t2 ; let prom = name_promotedness s' ; mk_apps- (HsTyVar noExtField prom (noLoc s'))+ (HsTyVar noAnn prom (noLocA s')) ([HsValArg t1', HsValArg t2'] ++ tys') } @@ -1582,44 +1606,48 @@ ParensT t -> do { t' <- cvtType t- ; mk_apps (HsParTy noExtField t') tys'+ ; mk_apps (HsParTy noAnn t') tys' } PromotedT nm -> do { nm' <- cName nm- ; mk_apps (HsTyVar noExtField IsPromoted (noLoc nm'))+ ; mk_apps (HsTyVar noAnn IsPromoted+ (noLocA nm')) tys' } -- Promoted data constructor; hence cName PromotedTupleT n | Just normals <- m_normals , normals `lengthIs` n -- Saturated- -> returnL (HsExplicitTupleTy noExtField normals)+ -> returnLA (HsExplicitTupleTy noAnn normals) | otherwise -> mk_apps- (HsTyVar noExtField IsPromoted (noLoc (getRdrName (tupleDataCon Boxed n))))+ (HsTyVar noAnn IsPromoted+ (noLocA (getRdrName (tupleDataCon Boxed n)))) tys' PromotedNilT- -> mk_apps (HsExplicitListTy noExtField IsPromoted []) tys'+ -> mk_apps (HsExplicitListTy noAnn IsPromoted []) tys' PromotedConsT -- See Note [Representing concrete syntax in types] -- in Language.Haskell.TH.Syntax | Just normals <- m_normals , [ty1, L _ (HsExplicitListTy _ ip tys2)] <- normals- -> returnL (HsExplicitListTy noExtField ip (ty1:tys2))+ -> returnLA (HsExplicitListTy noAnn ip (ty1:tys2)) | otherwise -> mk_apps- (HsTyVar noExtField IsPromoted (noLoc (getRdrName consDataCon)))+ (HsTyVar noAnn IsPromoted (noLocA (getRdrName consDataCon))) tys' StarT -> mk_apps- (HsTyVar noExtField NotPromoted (noLoc (getRdrName liftedTypeKindTyCon)))+ (HsTyVar noAnn NotPromoted+ (noLocA (getRdrName liftedTypeKindTyCon))) tys' ConstraintT -> mk_apps- (HsTyVar noExtField NotPromoted (noLoc (getRdrName constraintKindTyCon)))+ (HsTyVar noAnn NotPromoted+ (noLocA (getRdrName constraintKindTyCon))) tys' EqualityT@@ -1627,18 +1655,18 @@ , [x',y'] <- normals -> let px = parenthesizeHsType opPrec x' py = parenthesizeHsType opPrec y'- in returnL (HsOpTy noExtField px (noLoc eqTyCon_RDR) py)+ in returnLA (HsOpTy noExtField px (noLocA eqTyCon_RDR) py) -- The long-term goal is to remove the above case entirely and -- subsume it under the case for InfixT. See #15815, comment:6, -- for more details. | otherwise ->- mk_apps (HsTyVar noExtField NotPromoted- (noLoc eqTyCon_RDR)) tys'+ mk_apps (HsTyVar noAnn NotPromoted+ (noLocA eqTyCon_RDR)) tys' ImplicitParamT n t -> do { n' <- wrapL $ ipName n ; t' <- cvtType t- ; returnL (HsIParamTy noExtField n' t')+ ; returnLA (HsIParamTy noAnn n' t') } _ -> failWith (ptext (sLit ("Malformed " ++ ty_str)) <+> text (show ty))@@ -1647,9 +1675,9 @@ hsTypeToArrow :: LHsType GhcPs -> HsArrow GhcPs hsTypeToArrow w = case unLoc w of HsTyVar _ _ (L _ (isExact_maybe -> Just n))- | n == oneDataConName -> HsLinearArrow NormalSyntax+ | n == oneDataConName -> HsLinearArrow NormalSyntax Nothing | n == manyDataConName -> HsUnrestrictedArrow NormalSyntax- _ -> HsExplicitMult NormalSyntax w+ _ -> HsExplicitMult NormalSyntax Nothing w -- ConT/InfixT can contain both data constructor (i.e., promoted) names and -- other (i.e, unpromoted) names, as opposed to PromotedT, which can only@@ -1664,7 +1692,7 @@ -- | Constructs an application of a type to arguments passed in a list. mk_apps :: HsType GhcPs -> [LHsTypeArg GhcPs] -> CvtM (LHsType GhcPs) mk_apps head_ty type_args = do- head_ty' <- returnL head_ty+ head_ty' <- returnLA head_ty -- We must parenthesize the function type in case of an explicit -- signature. For instance, in `(Maybe :: Type -> Type) Int`, there -- _must_ be parentheses around `Maybe :: Type -> Type`.@@ -1679,13 +1707,13 @@ mk_apps (HsAppTy noExtField phead_ty p_ty) args HsTypeArg l ki -> do p_ki <- add_parens ki mk_apps (HsAppKindTy l phead_ty p_ki) args- HsArgPar _ -> mk_apps (HsParTy noExtField phead_ty) args+ HsArgPar _ -> mk_apps (HsParTy noAnn phead_ty) args go type_args where -- See Note [Adding parens for splices] add_parens lt@(L _ t)- | hsTypeNeedsParens appPrec t = returnL (HsParTy noExtField lt)+ | hsTypeNeedsParens appPrec t = returnLA (HsParTy noAnn lt) | otherwise = return lt wrap_tyarg :: LHsTypeArg GhcPs -> LHsTypeArg GhcPs@@ -1742,9 +1770,9 @@ = do { l <- cvtOpAppT y op1 z ; cvtOpAppT x op2 l } cvtOpAppT x op y- = do { op' <- tconNameL op+ = do { op' <- tconNameN op ; x' <- cvtType x- ; returnL (mkHsOpTy x' op' y) }+ ; returnLA (mkHsOpTy x' op' y) } cvtKind :: TH.Kind -> CvtM (LHsKind GhcPs) cvtKind = cvtTypeKind "kind"@@ -1774,9 +1802,9 @@ cvtInjectivityAnnotation :: TH.InjectivityAnn -> CvtM (Hs.LInjectivityAnn GhcPs) cvtInjectivityAnnotation (TH.InjectivityAnn annLHS annRHS)- = do { annLHS' <- tNameL annLHS- ; annRHS' <- mapM tNameL annRHS- ; returnL (Hs.InjectivityAnn annLHS' annRHS') }+ = do { annLHS' <- tNameN annLHS+ ; annRHS' <- mapM tNameN annRHS+ ; returnL (Hs.InjectivityAnn noAnn annLHS' annRHS') } cvtPatSynSigTy :: TH.Type -> CvtM (LHsSigType GhcPs) -- pattern synonym types are of peculiar shapes, which is why we treat@@ -1784,20 +1812,22 @@ -- see Note [Pattern synonym type signatures and Template Haskell] cvtPatSynSigTy (ForallT univs reqs (ForallT exis provs ty)) | null exis, null provs = cvtSigType (ForallT univs reqs ty)- | null univs, null reqs = do { l <- getL+ | null univs, null reqs = do { l' <- getL+ ; let l = noAnnSrcSpan l' ; ty' <- cvtType (ForallT exis provs ty) ; return $ L l $ mkHsImplicitSigType- $ L l (HsQualTy { hst_ctxt = L l []+ $ L l (HsQualTy { hst_ctxt = Nothing , hst_xqual = noExtField , hst_body = ty' }) }- | null reqs = do { l <- getL+ | null reqs = do { l' <- getL+ ; let l'' = noAnnSrcSpan l' ; univs' <- cvtTvs univs ; ty' <- cvtType (ForallT exis provs ty)- ; let forTy = mkHsExplicitSigType univs' $ L l cxtTy- cxtTy = HsQualTy { hst_ctxt = L l []+ ; let forTy = mkHsExplicitSigType noAnn univs' $ L l'' cxtTy+ cxtTy = HsQualTy { hst_ctxt = Nothing , hst_xqual = noExtField , hst_body = ty' }- ; return $ L l forTy }+ ; return $ L (noAnnSrcSpan l') forTy } | otherwise = cvtSigType (ForallT univs reqs (ForallT exis provs ty)) cvtPatSynSigTy ty = cvtSigType ty @@ -1840,7 +1870,7 @@ -- | If passed an empty list of 'LHsTyVarBndr's, this simply returns the -- third argument (an 'LHsType'). Otherwise, return an 'HsForAllTy' -- using the provided 'LHsQTyVars' and 'LHsType'.-mkHsForAllTy :: SrcSpan+mkHsForAllTy :: SrcSpanAnnA -- ^ The location of the returned 'LHsType' if it needs an -- explicit forall -> HsForAllTelescope GhcPs@@ -1868,7 +1898,7 @@ -- they're empty. See #13183. mkHsQualTy :: TH.Cxt -- ^ The original Template Haskell context- -> SrcSpan+ -> SrcSpanAnnA -- ^ The location of the returned 'LHsType' if it needs an -- explicit context -> LHsContext GhcPs@@ -1880,38 +1910,40 @@ mkHsQualTy ctxt loc ctxt' ty | null ctxt = ty | otherwise = L loc $ HsQualTy { hst_xqual = noExtField- , hst_ctxt = ctxt'+ , hst_ctxt = Just ctxt' , hst_body = ty } mkHsOuterFamEqnTyVarBndrs :: Maybe [LHsTyVarBndr () GhcPs] -> HsOuterFamEqnTyVarBndrs GhcPs-mkHsOuterFamEqnTyVarBndrs = maybe mkHsOuterImplicit mkHsOuterExplicit+mkHsOuterFamEqnTyVarBndrs = maybe mkHsOuterImplicit (mkHsOuterExplicit noAnn) -------------------------------------------------------------------- -- Turning Name back into RdrName -------------------------------------------------------------------- -- variable names-vNameL, cNameL, vcNameL, tNameL, tconNameL :: TH.Name -> CvtM (Located RdrName)+vNameN, cNameN, vcNameN, tNameN, tconNameN :: TH.Name -> CvtM (LocatedN RdrName)+vNameL :: TH.Name -> CvtM (LocatedA RdrName) vName, cName, vcName, tName, tconName :: TH.Name -> CvtM RdrName -- Variable names-vNameL n = wrapL (vName n)+vNameN n = wrapLN (vName n)+vNameL n = wrapLA (vName n) vName n = cvtName OccName.varName n -- Constructor function names; this is Haskell source, hence srcDataName-cNameL n = wrapL (cName n)+cNameN n = wrapLN (cName n) cName n = cvtName OccName.dataName n -- Variable *or* constructor names; check by looking at the first char-vcNameL n = wrapL (vcName n)+vcNameN n = wrapLN (vcName n) vcName n = if isVarName n then vName n else cName n -- Type variable names-tNameL n = wrapL (tName n)+tNameN n = wrapLN (tName n) tName n = cvtName OccName.tvName n -- Type Constructor names-tconNameL n = wrapL (tconName n)+tconNameN n = wrapLN (tconName n) tconName n = cvtName OccName.tcClsName n ipName :: String -> CvtM HsIPName
compiler/GHC/Types/Unique/SDFM.hs view
@@ -88,8 +88,8 @@ case (lu x, lu y) of ((x', _) , (y', _)) | getUnique x' == getUnique y' -> (Nothing, usdfm) -- nothing to do- ((x', _) , (_ , Nothing)) -> (Nothing, set_indirect y x')- ((_ , mb_ex), (y', _)) -> (mb_ex, set_indirect x y')+ ((x', _) , (y', Nothing)) -> (Nothing, set_indirect y' x')+ ((x', mb_ex), (y', _)) -> (mb_ex, set_indirect x' y') where lu = lookupReprAndEntryUSDFM usdfm set_indirect a b = USDFM $ addToUDFM env a (Indirect b)
compiler/GHC/Unit/Finder.hs view
@@ -11,6 +11,7 @@ FindResult(..), InstalledFindResult(..), FinderCache,+ initFinderCache, flushFinderCaches, findImportedModule, findPluginModule,@@ -35,7 +36,6 @@ import GHC.Prelude -import GHC.Driver.Env import GHC.Driver.Session import GHC.Platform.Ways@@ -58,7 +58,7 @@ import GHC.Linker.Types -import Data.IORef ( IORef, readIORef, atomicModifyIORef' )+import Data.IORef import System.Directory import System.FilePath import Control.Monad@@ -81,26 +81,28 @@ -- ----------------------------------------------------------------------------- -- The finder's cache ++initFinderCache :: IO FinderCache+initFinderCache = FinderCache <$> newIORef emptyInstalledModuleEnv+ -- remove all the home modules from the cache; package modules are -- assumed to not move around during a session.-flushFinderCaches :: HscEnv -> IO ()-flushFinderCaches hsc_env =- atomicModifyIORef' fc_ref $ \fm -> (filterInstalledModuleEnv is_ext fm, ())+flushFinderCaches :: FinderCache -> HomeUnit -> IO ()+flushFinderCaches (FinderCache ref) home_unit =+ atomicModifyIORef' ref $ \fm -> (filterInstalledModuleEnv is_ext fm, ()) where- fc_ref = hsc_FC hsc_env- home_unit = hsc_home_unit hsc_env- is_ext mod _ = not (isHomeInstalledModule home_unit mod)+ is_ext mod _ = not (isHomeInstalledModule home_unit mod) -addToFinderCache :: IORef FinderCache -> InstalledModule -> InstalledFindResult -> IO ()-addToFinderCache ref key val =+addToFinderCache :: FinderCache -> InstalledModule -> InstalledFindResult -> IO ()+addToFinderCache (FinderCache ref) key val = atomicModifyIORef' ref $ \c -> (extendInstalledModuleEnv c key val, ()) -removeFromFinderCache :: IORef FinderCache -> InstalledModule -> IO ()-removeFromFinderCache ref key =+removeFromFinderCache :: FinderCache -> InstalledModule -> IO ()+removeFromFinderCache (FinderCache ref) key = atomicModifyIORef' ref $ \c -> (delInstalledModuleEnv c key, ()) -lookupFinderCache :: IORef FinderCache -> InstalledModule -> IO (Maybe InstalledFindResult)-lookupFinderCache ref key = do+lookupFinderCache :: FinderCache -> InstalledModule -> IO (Maybe InstalledFindResult)+lookupFinderCache (FinderCache ref) key = do c <- readIORef ref return $! lookupInstalledModuleEnv c key @@ -113,30 +115,37 @@ -- packages to find the module, if a package is specified then only -- that package is searched for the module. -findImportedModule :: HscEnv -> ModuleName -> Maybe FastString -> IO FindResult-findImportedModule hsc_env mod_name mb_pkg =+findImportedModule+ :: FinderCache+ -> UnitState+ -> HomeUnit+ -> DynFlags+ -> ModuleName+ -> Maybe FastString+ -> IO FindResult+findImportedModule fc units home_unit dflags mod_name mb_pkg = case mb_pkg of Nothing -> unqual_import Just pkg | pkg == fsLit "this" -> home_import -- "this" is special | otherwise -> pkg_import where- home_import = findHomeModule hsc_env mod_name+ home_import = findHomeModule fc home_unit dflags mod_name - pkg_import = findExposedPackageModule hsc_env mod_name mb_pkg+ pkg_import = findExposedPackageModule fc units dflags mod_name mb_pkg unqual_import = home_import `orIfNotFound`- findExposedPackageModule hsc_env mod_name Nothing+ findExposedPackageModule fc units dflags mod_name Nothing -- | Locate a plugin module requested by the user, for a compiler -- plugin. This consults the same set of exposed packages as -- 'findImportedModule', unless @-hide-all-plugin-packages@ or -- @-plugin-package@ are specified.-findPluginModule :: HscEnv -> ModuleName -> IO FindResult-findPluginModule hsc_env mod_name =- findHomeModule hsc_env mod_name+findPluginModule :: FinderCache -> UnitState -> HomeUnit -> DynFlags -> ModuleName -> IO FindResult+findPluginModule fc units home_unit dflags mod_name =+ findHomeModule fc home_unit dflags mod_name `orIfNotFound`- findExposedPluginPackageModule hsc_env mod_name+ findExposedPluginPackageModule fc units dflags mod_name -- | Locate a specific 'Module'. The purpose of this function is to -- create a 'ModLocation' for a given 'Module', that is to find out@@ -144,12 +153,11 @@ -- reading the interface for a module mentioned by another interface, -- for example (a "system import"). -findExactModule :: HscEnv -> InstalledModule -> IO InstalledFindResult-findExactModule hsc_env mod =- let home_unit = hsc_home_unit hsc_env- in if isHomeInstalledModule home_unit mod- then findInstalledHomeModule hsc_env (moduleName mod)- else findPackageModule hsc_env mod+findExactModule :: FinderCache -> DynFlags -> UnitState -> HomeUnit -> InstalledModule -> IO InstalledFindResult+findExactModule fc dflags unit_state home_unit mod = do+ if isHomeInstalledModule home_unit mod+ then findInstalledHomeModule fc dflags home_unit (moduleName mod)+ else findPackageModule fc unit_state dflags mod -- ----------------------------------------------------------------------------- -- Helpers@@ -184,31 +192,26 @@ -- been done. Otherwise, do the lookup (with the IO action) and save -- the result in the finder cache and the module location cache (if it -- was successful.)-homeSearchCache :: HscEnv -> ModuleName -> IO InstalledFindResult -> IO InstalledFindResult-homeSearchCache hsc_env mod_name do_this = do- let home_unit = hsc_home_unit hsc_env- mod = mkHomeInstalledModule home_unit mod_name- modLocationCache hsc_env mod do_this+homeSearchCache :: FinderCache -> HomeUnit -> ModuleName -> IO InstalledFindResult -> IO InstalledFindResult+homeSearchCache fc home_unit mod_name do_this = do+ let mod = mkHomeInstalledModule home_unit mod_name+ modLocationCache fc mod do_this -findExposedPackageModule :: HscEnv -> ModuleName -> Maybe FastString- -> IO FindResult-findExposedPackageModule hsc_env mod_name mb_pkg- = findLookupResult hsc_env- $ lookupModuleWithSuggestions- (hsc_units hsc_env) mod_name mb_pkg+findExposedPackageModule :: FinderCache -> UnitState -> DynFlags -> ModuleName -> Maybe FastString -> IO FindResult+findExposedPackageModule fc units dflags mod_name mb_pkg =+ findLookupResult fc dflags+ $ lookupModuleWithSuggestions units mod_name mb_pkg -findExposedPluginPackageModule :: HscEnv -> ModuleName- -> IO FindResult-findExposedPluginPackageModule hsc_env mod_name- = findLookupResult hsc_env- $ lookupPluginModuleWithSuggestions- (hsc_units hsc_env) mod_name Nothing+findExposedPluginPackageModule :: FinderCache -> UnitState -> DynFlags -> ModuleName -> IO FindResult+findExposedPluginPackageModule fc units dflags mod_name =+ findLookupResult fc dflags+ $ lookupPluginModuleWithSuggestions units mod_name Nothing -findLookupResult :: HscEnv -> LookupResult -> IO FindResult-findLookupResult hsc_env r = case r of+findLookupResult :: FinderCache -> DynFlags -> LookupResult -> IO FindResult+findLookupResult fc dflags r = case r of LookupFound m pkg_conf -> do let im = fst (getModuleInstantiation m)- r' <- findPackageModule_ hsc_env im pkg_conf+ r' <- findPackageModule_ fc dflags im pkg_conf case r' of -- TODO: ghc -M is unlikely to do the right thing -- with just the location of the thing that was@@ -241,7 +244,7 @@ , fr_suggestions = [] }) LookupNotFound suggest -> do let suggest'- | gopt Opt_HelpfulErrors (hsc_dflags hsc_env) = suggest+ | gopt Opt_HelpfulErrors dflags = suggest | otherwise = [] return (NotFound{ fr_paths = [], fr_pkg = Nothing , fr_pkgs_hidden = []@@ -249,36 +252,35 @@ , fr_unusables = [] , fr_suggestions = suggest' }) -modLocationCache :: HscEnv -> InstalledModule -> IO InstalledFindResult -> IO InstalledFindResult-modLocationCache hsc_env mod do_this = do- m <- lookupFinderCache (hsc_FC hsc_env) mod+modLocationCache :: FinderCache -> InstalledModule -> IO InstalledFindResult -> IO InstalledFindResult+modLocationCache fc mod do_this = do+ m <- lookupFinderCache fc mod case m of Just result -> return result Nothing -> do result <- do_this- addToFinderCache (hsc_FC hsc_env) mod result+ addToFinderCache fc mod result return result -- This returns a module because it's more convenient for users-addHomeModuleToFinder :: HscEnv -> ModuleName -> ModLocation -> IO Module-addHomeModuleToFinder hsc_env mod_name loc = do- let home_unit = hsc_home_unit hsc_env- mod = mkHomeInstalledModule home_unit mod_name- addToFinderCache (hsc_FC hsc_env) mod (InstalledFound loc mod)+addHomeModuleToFinder :: FinderCache -> HomeUnit -> ModuleName -> ModLocation -> IO Module+addHomeModuleToFinder fc home_unit mod_name loc = do+ let mod = mkHomeInstalledModule home_unit mod_name+ addToFinderCache fc mod (InstalledFound loc mod) return (mkHomeModule home_unit mod_name) -uncacheModule :: HscEnv -> ModuleName -> IO ()-uncacheModule hsc_env mod_name = do- let home_unit = hsc_home_unit hsc_env- mod = mkHomeInstalledModule home_unit mod_name- removeFromFinderCache (hsc_FC hsc_env) mod+uncacheModule :: FinderCache -> HomeUnit -> ModuleName -> IO ()+uncacheModule fc home_unit mod_name = do+ let mod = mkHomeInstalledModule home_unit mod_name+ removeFromFinderCache fc mod -- ----------------------------------------------------------------------------- -- The internal workers -findHomeModule :: HscEnv -> ModuleName -> IO FindResult-findHomeModule hsc_env mod_name = do- r <- findInstalledHomeModule hsc_env mod_name+findHomeModule :: FinderCache -> HomeUnit -> DynFlags -> ModuleName -> IO FindResult+findHomeModule fc home_unit dflags mod_name = do+ let uid = homeUnitAsUnit home_unit+ r <- findInstalledHomeModule fc dflags home_unit mod_name return $ case r of InstalledFound loc _ -> Found loc (mkHomeModule home_unit mod_name) InstalledNoPackage _ -> NoPackage uid -- impossible@@ -290,9 +292,6 @@ fr_unusables = [], fr_suggestions = [] }- where- home_unit = hsc_home_unit hsc_env- uid = homeUnitAsUnit home_unit -- | Implements the search for a module name in the home package only. Calling -- this function directly is usually *not* what you want; currently, it's used@@ -310,12 +309,10 @@ -- -- 4. Some special-case code in GHCi (ToDo: Figure out why that needs to -- call this.)-findInstalledHomeModule :: HscEnv -> ModuleName -> IO InstalledFindResult-findInstalledHomeModule hsc_env mod_name =- homeSearchCache hsc_env mod_name $+findInstalledHomeModule :: FinderCache -> DynFlags -> HomeUnit -> ModuleName -> IO InstalledFindResult+findInstalledHomeModule fc dflags home_unit mod_name = do+ homeSearchCache fc home_unit mod_name $ let- dflags = hsc_dflags hsc_env- home_unit = hsc_home_unit hsc_env home_path = importPaths dflags hisuf = hiSuf dflags mod = mkHomeInstalledModule home_unit mod_name@@ -340,21 +337,21 @@ | otherwise = source_exts in - -- special case for GHC.Prim; we won't find it in the filesystem.- -- This is important only when compiling the base package (where GHC.Prim- -- is a home module).- if mod `installedModuleEq` gHC_PRIM- then return (InstalledFound (error "GHC.Prim ModLocation") mod)- else searchPathExts home_path mod exts+ -- special case for GHC.Prim; we won't find it in the filesystem.+ -- This is important only when compiling the base package (where GHC.Prim+ -- is a home module).+ if mod `installedModuleEq` gHC_PRIM+ then return (InstalledFound (error "GHC.Prim ModLocation") mod)+ else searchPathExts home_path mod exts -- | Search for a module in external packages only.-findPackageModule :: HscEnv -> InstalledModule -> IO InstalledFindResult-findPackageModule hsc_env mod = do+findPackageModule :: FinderCache -> UnitState -> DynFlags -> InstalledModule -> IO InstalledFindResult+findPackageModule fc unit_state dflags mod = do let pkg_id = moduleUnit mod- case lookupUnitId (hsc_units hsc_env) pkg_id of+ case lookupUnitId unit_state pkg_id of Nothing -> return (InstalledNoPackage pkg_id)- Just u -> findPackageModule_ hsc_env mod u+ Just u -> findPackageModule_ fc dflags mod u -- | Look up the interface file associated with module @mod@. This function -- requires a few invariants to be upheld: (1) the 'Module' in question must@@ -363,39 +360,38 @@ -- the 'UnitInfo' must be consistent with the unit id in the 'Module'. -- The redundancy is to avoid an extra lookup in the package state -- for the appropriate config.-findPackageModule_ :: HscEnv -> InstalledModule -> UnitInfo -> IO InstalledFindResult-findPackageModule_ hsc_env mod pkg_conf =- ASSERT2( moduleUnit mod == unitId pkg_conf, ppr (moduleUnit mod) <+> ppr (unitId pkg_conf) )- modLocationCache hsc_env mod $+findPackageModule_ :: FinderCache -> DynFlags -> InstalledModule -> UnitInfo -> IO InstalledFindResult+findPackageModule_ fc dflags mod pkg_conf = do+ MASSERT2( moduleUnit mod == unitId pkg_conf, ppr (moduleUnit mod) <+> ppr (unitId pkg_conf) )+ modLocationCache fc mod $ - -- special case for GHC.Prim; we won't find it in the filesystem.- if mod `installedModuleEq` gHC_PRIM- then return (InstalledFound (error "GHC.Prim ModLocation") mod)- else+ -- special case for GHC.Prim; we won't find it in the filesystem.+ if mod `installedModuleEq` gHC_PRIM+ then return (InstalledFound (error "GHC.Prim ModLocation") mod)+ else - let- dflags = hsc_dflags hsc_env- tag = waysBuildTag (ways dflags)+ let+ tag = waysBuildTag (ways dflags) - -- hi-suffix for packages depends on the build tag.- package_hisuf | null tag = "hi"- | otherwise = tag ++ "_hi"+ -- hi-suffix for packages depends on the build tag.+ package_hisuf | null tag = "hi"+ | otherwise = tag ++ "_hi" - mk_hi_loc = mkHiOnlyModLocation dflags package_hisuf+ mk_hi_loc = mkHiOnlyModLocation dflags package_hisuf - import_dirs = map ST.unpack $ unitImportDirs pkg_conf- -- we never look for a .hi-boot file in an external package;- -- .hi-boot files only make sense for the home package.- in- case import_dirs of- [one] | MkDepend <- ghcMode dflags -> do- -- there's only one place that this .hi file can be, so- -- don't bother looking for it.- let basename = moduleNameSlashes (moduleName mod)- loc <- mk_hi_loc one basename- return (InstalledFound loc mod)- _otherwise ->- searchPathExts import_dirs mod [(package_hisuf, mk_hi_loc)]+ import_dirs = map ST.unpack $ unitImportDirs pkg_conf+ -- we never look for a .hi-boot file in an external package;+ -- .hi-boot files only make sense for the home package.+ in+ case import_dirs of+ [one] | MkDepend <- ghcMode dflags -> do+ -- there's only one place that this .hi file can be, so+ -- don't bother looking for it.+ let basename = moduleNameSlashes (moduleName mod)+ loc <- mk_hi_loc one basename+ return (InstalledFound loc mod)+ _otherwise ->+ searchPathExts import_dirs mod [(package_hisuf, mk_hi_loc)] -- ----------------------------------------------------------------------------- -- General path searching
ghc-lib.cabal view
@@ -1,7 +1,7 @@ cabal-version: >=1.22 build-type: Simple name: ghc-lib-version: 0.20210228+version: 0.20210331 license: BSD3 license-file: LICENSE category: Development@@ -64,7 +64,7 @@ build-depends: Win32 build-depends: ghc-prim > 0.2 && < 0.8,- base >= 4.12 && < 4.16,+ base >= 4.14 && < 4.17, containers >= 0.5 && < 0.7, bytestring >= 0.9 && < 0.11, binary == 0.8.*,@@ -79,7 +79,7 @@ hpc == 0.6.*, exceptions == 0.10.*, parsec,- ghc-lib-parser == 0.20210228+ ghc-lib-parser == 0.20210331 build-tools: alex >= 3.1, happy >= 1.19.4 other-extensions: BangPatterns@@ -280,6 +280,7 @@ GHC.Platform.NoRegs, GHC.Platform.PPC, GHC.Platform.Profile,+ GHC.Platform.RISCV64, GHC.Platform.Reg, GHC.Platform.Reg.Class, GHC.Platform.Regs,@@ -300,7 +301,6 @@ GHC.Stg.Syntax, GHC.StgToCmm.Types, GHC.SysTools.BaseDir,- GHC.SysTools.FileCleanup, GHC.SysTools.Terminal, GHC.Tc.Errors.Hole.FitTypes, GHC.Tc.Types,@@ -323,6 +323,7 @@ GHC.Types.ForeignCall, GHC.Types.ForeignStubs, GHC.Types.HpcInfo,+ GHC.Types.IPE, GHC.Types.Id, GHC.Types.Id.Info, GHC.Types.Id.Make,@@ -342,12 +343,14 @@ GHC.Types.SourceText, GHC.Types.SrcLoc, GHC.Types.Target,+ GHC.Types.Tickish, GHC.Types.TyThing, GHC.Types.TypeEnv, GHC.Types.Unique, GHC.Types.Unique.DFM, GHC.Types.Unique.DSet, GHC.Types.Unique.FM,+ GHC.Types.Unique.Map, GHC.Types.Unique.Set, GHC.Types.Unique.Supply, GHC.Types.Var,@@ -400,6 +403,7 @@ GHC.Utils.Panic.Plain, GHC.Utils.Ppr, GHC.Utils.Ppr.Colour,+ GHC.Utils.TmpFs, GHC.Version, GHCi.BreakArray, GHCi.FFI,@@ -557,7 +561,6 @@ GHC.Core.Rules GHC.Core.Tidy GHC.Core.TyCon.Set- GHC.CoreToByteCode GHC.CoreToStg GHC.CoreToStg.Prep GHC.Data.Bitmap@@ -651,6 +654,7 @@ GHC.Settings.IO GHC.Settings.Utils GHC.Stg.CSE+ GHC.Stg.Debug GHC.Stg.DepAnal GHC.Stg.FVs GHC.Stg.Lift@@ -661,6 +665,7 @@ GHC.Stg.Stats GHC.Stg.Subst GHC.Stg.Unarise+ GHC.StgToByteCode GHC.StgToCmm GHC.StgToCmm.ArgRep GHC.StgToCmm.Bind@@ -674,6 +679,7 @@ GHC.StgToCmm.Heap GHC.StgToCmm.Hpc GHC.StgToCmm.Layout+ GHC.StgToCmm.Lit GHC.StgToCmm.Monad GHC.StgToCmm.Prim GHC.StgToCmm.Prof
ghc-lib/stage0/compiler/build/primop-data-decl.hs-incl view
@@ -327,6 +327,7 @@ | MutableByteArrayIsPinnedOp | ByteArrayIsPinnedOp | ByteArrayContents_Char+ | MutableByteArrayContents_Char | SameMutableByteArrayOp | ShrinkMutableByteArrayOp_Char | ResizeMutableByteArrayOp_Char@@ -618,6 +619,7 @@ | GetCCSOfOp | GetCurrentCCSOp | ClearCCSOp+ | WhereFromOp | TraceEventOp | TraceEventBinaryOp | TraceMarkerOp
ghc-lib/stage0/compiler/build/primop-docs.hs-incl view
@@ -103,6 +103,7 @@ , ("isMutableByteArrayPinned#","Determine whether a @MutableByteArray\\#@ is guaranteed not to move\n during GC.") , ("isByteArrayPinned#","Determine whether a @ByteArray\\#@ is guaranteed not to move during GC.") , ("byteArrayContents#","Intended for use with pinned arrays; otherwise very unsafe!")+ , ("mutableByteArrayContents#","Intended for use with pinned arrays; otherwise very unsafe!") , ("shrinkMutableByteArray#","Shrink mutable byte array to new specified size (in bytes), in\n the specified state thread. The new size argument must be less than or\n equal to the current size as reported by @getSizeofMutableByteArray\\#@.") , ("resizeMutableByteArray#","Resize (unpinned) mutable byte array to new specified size (in bytes).\n The returned @MutableByteArray\\#@ is either the original\n @MutableByteArray\\#@ resized in-place or, if not possible, a newly\n allocated (unpinned) @MutableByteArray\\#@ (with the original content\n copied over).\n\n To avoid undefined behaviour, the original @MutableByteArray\\#@ shall\n not be accessed anymore after a @resizeMutableByteArray\\#@ has been\n performed. Moreover, no reference to the old one should be kept in order\n to allow garbage collection of the original @MutableByteArray\\#@ in\n case a new @MutableByteArray\\#@ had to be allocated.") , ("unsafeFreezeByteArray#","Make a mutable byte array immutable, without copying.")@@ -298,6 +299,7 @@ , ("closureSize#"," @closureSize\\# closure@ returns the size of the given closure in\n machine words. ") , ("getCurrentCCS#"," Returns the current @CostCentreStack@ (value is @NULL@ if\n not profiling). Takes a dummy argument which can be used to\n avoid the call to @getCurrentCCS\\#@ being floated out by the\n simplifier, which would result in an uninformative stack\n (\"CAF\"). ") , ("clearCCS#"," Run the supplied IO action with an empty CCS. For example, this\n is used by the interpreter to run an interpreted computation\n without the call stack showing that it was invoked from GHC. ")+ , ("whereFrom#"," Returns the @InfoProvEnt @ for the info table of the given object\n (value is @NULL@ if the table does not exist or there is no information\n about the closure).") , ("FUN","The builtin function type, written in infix form as @a # m -> b@.\n Values of this type are functions taking inputs of type @a@ and\n producing outputs of type @b@. The multiplicity of the input is\n @m@.\n\n Note that @FUN m a b@ permits levity-polymorphism in both @a@ and\n @b@, so that types like @Int\\# -> Int\\#@ can still be well-kinded.\n ") , ("realWorld#"," The token used in the implementation of the IO monad as a state monad.\n It does not pass any information at runtime.\n See also @GHC.Magic.runRW\\#@. ") , ("void#"," This is an alias for the unboxed unit tuple constructor.\n In earlier versions of GHC, @void\\#@ was a value\n of the primitive type @Void\\#@, which is now defined to be @(\\# \\#)@.\n ")
ghc-lib/stage0/compiler/build/primop-list.hs-incl view
@@ -326,6 +326,7 @@ , MutableByteArrayIsPinnedOp , ByteArrayIsPinnedOp , ByteArrayContents_Char+ , MutableByteArrayContents_Char , SameMutableByteArrayOp , ShrinkMutableByteArrayOp_Char , ResizeMutableByteArrayOp_Char@@ -617,6 +618,7 @@ , GetCCSOfOp , GetCurrentCCSOp , ClearCCSOp+ , WhereFromOp , TraceEventOp , TraceEventBinaryOp , TraceMarkerOp
ghc-lib/stage0/compiler/build/primop-out-of-line.hs-incl view
@@ -98,6 +98,7 @@ primOpOutOfLine ClosureSizeOp = True primOpOutOfLine GetApStackValOp = True primOpOutOfLine ClearCCSOp = True+primOpOutOfLine WhereFromOp = True primOpOutOfLine TraceEventOp = True primOpOutOfLine TraceEventBinaryOp = True primOpOutOfLine TraceMarkerOp = True
ghc-lib/stage0/compiler/build/primop-primop-info.hs-incl view
@@ -5,8 +5,8 @@ primOpInfo CharLtOp = mkCompare (fsLit "ltChar#") charPrimTy primOpInfo CharLeOp = mkCompare (fsLit "leChar#") charPrimTy primOpInfo OrdOp = mkGenPrimOp (fsLit "ord#") [] [charPrimTy] (intPrimTy)-primOpInfo Int8ToIntOp = mkGenPrimOp (fsLit "extendInt8#") [] [int8PrimTy] (intPrimTy)-primOpInfo IntToInt8Op = mkGenPrimOp (fsLit "narrowInt8#") [] [intPrimTy] (int8PrimTy)+primOpInfo Int8ToIntOp = mkGenPrimOp (fsLit "int8ToInt#") [] [int8PrimTy] (intPrimTy)+primOpInfo IntToInt8Op = mkGenPrimOp (fsLit "intToInt8#") [] [intPrimTy] (int8PrimTy) primOpInfo Int8NegOp = mkGenPrimOp (fsLit "negateInt8#") [] [int8PrimTy] (int8PrimTy) primOpInfo Int8AddOp = mkGenPrimOp (fsLit "plusInt8#") [] [int8PrimTy, int8PrimTy] (int8PrimTy) primOpInfo Int8SubOp = mkGenPrimOp (fsLit "subInt8#") [] [int8PrimTy, int8PrimTy] (int8PrimTy)@@ -24,8 +24,8 @@ primOpInfo Int8LeOp = mkCompare (fsLit "leInt8#") int8PrimTy primOpInfo Int8LtOp = mkCompare (fsLit "ltInt8#") int8PrimTy primOpInfo Int8NeOp = mkCompare (fsLit "neInt8#") int8PrimTy-primOpInfo Word8ToWordOp = mkGenPrimOp (fsLit "extendWord8#") [] [word8PrimTy] (wordPrimTy)-primOpInfo WordToWord8Op = mkGenPrimOp (fsLit "narrowWord8#") [] [wordPrimTy] (word8PrimTy)+primOpInfo Word8ToWordOp = mkGenPrimOp (fsLit "word8ToWord#") [] [word8PrimTy] (wordPrimTy)+primOpInfo WordToWord8Op = mkGenPrimOp (fsLit "wordToWord8#") [] [wordPrimTy] (word8PrimTy) primOpInfo Word8AddOp = mkGenPrimOp (fsLit "plusWord8#") [] [word8PrimTy, word8PrimTy] (word8PrimTy) primOpInfo Word8SubOp = mkGenPrimOp (fsLit "subWord8#") [] [word8PrimTy, word8PrimTy] (word8PrimTy) primOpInfo Word8MulOp = mkGenPrimOp (fsLit "timesWord8#") [] [word8PrimTy, word8PrimTy] (word8PrimTy)@@ -45,8 +45,8 @@ primOpInfo Word8LeOp = mkCompare (fsLit "leWord8#") word8PrimTy primOpInfo Word8LtOp = mkCompare (fsLit "ltWord8#") word8PrimTy primOpInfo Word8NeOp = mkCompare (fsLit "neWord8#") word8PrimTy-primOpInfo Int16ToIntOp = mkGenPrimOp (fsLit "extendInt16#") [] [int16PrimTy] (intPrimTy)-primOpInfo IntToInt16Op = mkGenPrimOp (fsLit "narrowInt16#") [] [intPrimTy] (int16PrimTy)+primOpInfo Int16ToIntOp = mkGenPrimOp (fsLit "int16ToInt#") [] [int16PrimTy] (intPrimTy)+primOpInfo IntToInt16Op = mkGenPrimOp (fsLit "intToInt16#") [] [intPrimTy] (int16PrimTy) primOpInfo Int16NegOp = mkGenPrimOp (fsLit "negateInt16#") [] [int16PrimTy] (int16PrimTy) primOpInfo Int16AddOp = mkGenPrimOp (fsLit "plusInt16#") [] [int16PrimTy, int16PrimTy] (int16PrimTy) primOpInfo Int16SubOp = mkGenPrimOp (fsLit "subInt16#") [] [int16PrimTy, int16PrimTy] (int16PrimTy)@@ -64,8 +64,8 @@ primOpInfo Int16LeOp = mkCompare (fsLit "leInt16#") int16PrimTy primOpInfo Int16LtOp = mkCompare (fsLit "ltInt16#") int16PrimTy primOpInfo Int16NeOp = mkCompare (fsLit "neInt16#") int16PrimTy-primOpInfo Word16ToWordOp = mkGenPrimOp (fsLit "extendWord16#") [] [word16PrimTy] (wordPrimTy)-primOpInfo WordToWord16Op = mkGenPrimOp (fsLit "narrowWord16#") [] [wordPrimTy] (word16PrimTy)+primOpInfo Word16ToWordOp = mkGenPrimOp (fsLit "word16ToWord#") [] [word16PrimTy] (wordPrimTy)+primOpInfo WordToWord16Op = mkGenPrimOp (fsLit "wordToWord16#") [] [wordPrimTy] (word16PrimTy) primOpInfo Word16AddOp = mkGenPrimOp (fsLit "plusWord16#") [] [word16PrimTy, word16PrimTy] (word16PrimTy) primOpInfo Word16SubOp = mkGenPrimOp (fsLit "subWord16#") [] [word16PrimTy, word16PrimTy] (word16PrimTy) primOpInfo Word16MulOp = mkGenPrimOp (fsLit "timesWord16#") [] [word16PrimTy, word16PrimTy] (word16PrimTy)@@ -85,8 +85,8 @@ primOpInfo Word16LeOp = mkCompare (fsLit "leWord16#") word16PrimTy primOpInfo Word16LtOp = mkCompare (fsLit "ltWord16#") word16PrimTy primOpInfo Word16NeOp = mkCompare (fsLit "neWord16#") word16PrimTy-primOpInfo Int32ToIntOp = mkGenPrimOp (fsLit "extendInt32#") [] [int32PrimTy] (intPrimTy)-primOpInfo IntToInt32Op = mkGenPrimOp (fsLit "narrowInt32#") [] [intPrimTy] (int32PrimTy)+primOpInfo Int32ToIntOp = mkGenPrimOp (fsLit "int32ToInt#") [] [int32PrimTy] (intPrimTy)+primOpInfo IntToInt32Op = mkGenPrimOp (fsLit "intToInt32#") [] [intPrimTy] (int32PrimTy) primOpInfo Int32NegOp = mkGenPrimOp (fsLit "negateInt32#") [] [int32PrimTy] (int32PrimTy) primOpInfo Int32AddOp = mkGenPrimOp (fsLit "plusInt32#") [] [int32PrimTy, int32PrimTy] (int32PrimTy) primOpInfo Int32SubOp = mkGenPrimOp (fsLit "subInt32#") [] [int32PrimTy, int32PrimTy] (int32PrimTy)@@ -104,8 +104,8 @@ primOpInfo Int32LeOp = mkCompare (fsLit "leInt32#") int32PrimTy primOpInfo Int32LtOp = mkCompare (fsLit "ltInt32#") int32PrimTy primOpInfo Int32NeOp = mkCompare (fsLit "neInt32#") int32PrimTy-primOpInfo Word32ToWordOp = mkGenPrimOp (fsLit "extendWord32#") [] [word32PrimTy] (wordPrimTy)-primOpInfo WordToWord32Op = mkGenPrimOp (fsLit "narrowWord32#") [] [wordPrimTy] (word32PrimTy)+primOpInfo Word32ToWordOp = mkGenPrimOp (fsLit "word32ToWord#") [] [word32PrimTy] (wordPrimTy)+primOpInfo WordToWord32Op = mkGenPrimOp (fsLit "wordToWord32#") [] [wordPrimTy] (word32PrimTy) primOpInfo Word32AddOp = mkGenPrimOp (fsLit "plusWord32#") [] [word32PrimTy, word32PrimTy] (word32PrimTy) primOpInfo Word32SubOp = mkGenPrimOp (fsLit "subWord32#") [] [word32PrimTy, word32PrimTy] (word32PrimTy) primOpInfo Word32MulOp = mkGenPrimOp (fsLit "timesWord32#") [] [word32PrimTy, word32PrimTy] (word32PrimTy)@@ -326,6 +326,7 @@ primOpInfo MutableByteArrayIsPinnedOp = mkGenPrimOp (fsLit "isMutableByteArrayPinned#") [deltaTyVar] [mkMutableByteArrayPrimTy deltaTy] (intPrimTy) primOpInfo ByteArrayIsPinnedOp = mkGenPrimOp (fsLit "isByteArrayPinned#") [] [byteArrayPrimTy] (intPrimTy) primOpInfo ByteArrayContents_Char = mkGenPrimOp (fsLit "byteArrayContents#") [] [byteArrayPrimTy] (addrPrimTy)+primOpInfo MutableByteArrayContents_Char = mkGenPrimOp (fsLit "mutableByteArrayContents#") [deltaTyVar] [mkMutableByteArrayPrimTy deltaTy] (addrPrimTy) primOpInfo SameMutableByteArrayOp = mkGenPrimOp (fsLit "sameMutableByteArray#") [deltaTyVar] [mkMutableByteArrayPrimTy deltaTy, mkMutableByteArrayPrimTy deltaTy] (intPrimTy) primOpInfo ShrinkMutableByteArrayOp_Char = mkGenPrimOp (fsLit "shrinkMutableByteArray#") [deltaTyVar] [mkMutableByteArrayPrimTy deltaTy, intPrimTy, mkStatePrimTy deltaTy] (mkStatePrimTy deltaTy) primOpInfo ResizeMutableByteArrayOp_Char = mkGenPrimOp (fsLit "resizeMutableByteArray#") [deltaTyVar] [mkMutableByteArrayPrimTy deltaTy, intPrimTy, mkStatePrimTy deltaTy] ((mkTupleTy Unboxed [mkStatePrimTy deltaTy, mkMutableByteArrayPrimTy deltaTy]))@@ -341,13 +342,13 @@ primOpInfo IndexByteArrayOp_Float = mkGenPrimOp (fsLit "indexFloatArray#") [] [byteArrayPrimTy, intPrimTy] (floatPrimTy) primOpInfo IndexByteArrayOp_Double = mkGenPrimOp (fsLit "indexDoubleArray#") [] [byteArrayPrimTy, intPrimTy] (doublePrimTy) primOpInfo IndexByteArrayOp_StablePtr = mkGenPrimOp (fsLit "indexStablePtrArray#") [alphaTyVar] [byteArrayPrimTy, intPrimTy] (mkStablePtrPrimTy alphaTy)-primOpInfo IndexByteArrayOp_Int8 = mkGenPrimOp (fsLit "indexInt8Array#") [] [byteArrayPrimTy, intPrimTy] (intPrimTy)-primOpInfo IndexByteArrayOp_Int16 = mkGenPrimOp (fsLit "indexInt16Array#") [] [byteArrayPrimTy, intPrimTy] (intPrimTy)-primOpInfo IndexByteArrayOp_Int32 = mkGenPrimOp (fsLit "indexInt32Array#") [] [byteArrayPrimTy, intPrimTy] (intPrimTy)+primOpInfo IndexByteArrayOp_Int8 = mkGenPrimOp (fsLit "indexInt8Array#") [] [byteArrayPrimTy, intPrimTy] (int8PrimTy)+primOpInfo IndexByteArrayOp_Int16 = mkGenPrimOp (fsLit "indexInt16Array#") [] [byteArrayPrimTy, intPrimTy] (int16PrimTy)+primOpInfo IndexByteArrayOp_Int32 = mkGenPrimOp (fsLit "indexInt32Array#") [] [byteArrayPrimTy, intPrimTy] (int32PrimTy) primOpInfo IndexByteArrayOp_Int64 = mkGenPrimOp (fsLit "indexInt64Array#") [] [byteArrayPrimTy, intPrimTy] (intPrimTy)-primOpInfo IndexByteArrayOp_Word8 = mkGenPrimOp (fsLit "indexWord8Array#") [] [byteArrayPrimTy, intPrimTy] (wordPrimTy)-primOpInfo IndexByteArrayOp_Word16 = mkGenPrimOp (fsLit "indexWord16Array#") [] [byteArrayPrimTy, intPrimTy] (wordPrimTy)-primOpInfo IndexByteArrayOp_Word32 = mkGenPrimOp (fsLit "indexWord32Array#") [] [byteArrayPrimTy, intPrimTy] (wordPrimTy)+primOpInfo IndexByteArrayOp_Word8 = mkGenPrimOp (fsLit "indexWord8Array#") [] [byteArrayPrimTy, intPrimTy] (word8PrimTy)+primOpInfo IndexByteArrayOp_Word16 = mkGenPrimOp (fsLit "indexWord16Array#") [] [byteArrayPrimTy, intPrimTy] (word16PrimTy)+primOpInfo IndexByteArrayOp_Word32 = mkGenPrimOp (fsLit "indexWord32Array#") [] [byteArrayPrimTy, intPrimTy] (word32PrimTy) primOpInfo IndexByteArrayOp_Word64 = mkGenPrimOp (fsLit "indexWord64Array#") [] [byteArrayPrimTy, intPrimTy] (wordPrimTy) primOpInfo IndexByteArrayOp_Word8AsChar = mkGenPrimOp (fsLit "indexWord8ArrayAsChar#") [] [byteArrayPrimTy, intPrimTy] (charPrimTy) primOpInfo IndexByteArrayOp_Word8AsWideChar = mkGenPrimOp (fsLit "indexWord8ArrayAsWideChar#") [] [byteArrayPrimTy, intPrimTy] (charPrimTy)@@ -357,11 +358,11 @@ primOpInfo IndexByteArrayOp_Word8AsFloat = mkGenPrimOp (fsLit "indexWord8ArrayAsFloat#") [] [byteArrayPrimTy, intPrimTy] (floatPrimTy) primOpInfo IndexByteArrayOp_Word8AsDouble = mkGenPrimOp (fsLit "indexWord8ArrayAsDouble#") [] [byteArrayPrimTy, intPrimTy] (doublePrimTy) primOpInfo IndexByteArrayOp_Word8AsStablePtr = mkGenPrimOp (fsLit "indexWord8ArrayAsStablePtr#") [alphaTyVar] [byteArrayPrimTy, intPrimTy] (mkStablePtrPrimTy alphaTy)-primOpInfo IndexByteArrayOp_Word8AsInt16 = mkGenPrimOp (fsLit "indexWord8ArrayAsInt16#") [] [byteArrayPrimTy, intPrimTy] (intPrimTy)-primOpInfo IndexByteArrayOp_Word8AsInt32 = mkGenPrimOp (fsLit "indexWord8ArrayAsInt32#") [] [byteArrayPrimTy, intPrimTy] (intPrimTy)+primOpInfo IndexByteArrayOp_Word8AsInt16 = mkGenPrimOp (fsLit "indexWord8ArrayAsInt16#") [] [byteArrayPrimTy, intPrimTy] (int16PrimTy)+primOpInfo IndexByteArrayOp_Word8AsInt32 = mkGenPrimOp (fsLit "indexWord8ArrayAsInt32#") [] [byteArrayPrimTy, intPrimTy] (int32PrimTy) primOpInfo IndexByteArrayOp_Word8AsInt64 = mkGenPrimOp (fsLit "indexWord8ArrayAsInt64#") [] [byteArrayPrimTy, intPrimTy] (intPrimTy)-primOpInfo IndexByteArrayOp_Word8AsWord16 = mkGenPrimOp (fsLit "indexWord8ArrayAsWord16#") [] [byteArrayPrimTy, intPrimTy] (wordPrimTy)-primOpInfo IndexByteArrayOp_Word8AsWord32 = mkGenPrimOp (fsLit "indexWord8ArrayAsWord32#") [] [byteArrayPrimTy, intPrimTy] (wordPrimTy)+primOpInfo IndexByteArrayOp_Word8AsWord16 = mkGenPrimOp (fsLit "indexWord8ArrayAsWord16#") [] [byteArrayPrimTy, intPrimTy] (word16PrimTy)+primOpInfo IndexByteArrayOp_Word8AsWord32 = mkGenPrimOp (fsLit "indexWord8ArrayAsWord32#") [] [byteArrayPrimTy, intPrimTy] (word32PrimTy) primOpInfo IndexByteArrayOp_Word8AsWord64 = mkGenPrimOp (fsLit "indexWord8ArrayAsWord64#") [] [byteArrayPrimTy, intPrimTy] (wordPrimTy) primOpInfo ReadByteArrayOp_Char = mkGenPrimOp (fsLit "readCharArray#") [deltaTyVar] [mkMutableByteArrayPrimTy deltaTy, intPrimTy, mkStatePrimTy deltaTy] ((mkTupleTy Unboxed [mkStatePrimTy deltaTy, charPrimTy])) primOpInfo ReadByteArrayOp_WideChar = mkGenPrimOp (fsLit "readWideCharArray#") [deltaTyVar] [mkMutableByteArrayPrimTy deltaTy, intPrimTy, mkStatePrimTy deltaTy] ((mkTupleTy Unboxed [mkStatePrimTy deltaTy, charPrimTy]))@@ -371,13 +372,13 @@ primOpInfo ReadByteArrayOp_Float = mkGenPrimOp (fsLit "readFloatArray#") [deltaTyVar] [mkMutableByteArrayPrimTy deltaTy, intPrimTy, mkStatePrimTy deltaTy] ((mkTupleTy Unboxed [mkStatePrimTy deltaTy, floatPrimTy])) primOpInfo ReadByteArrayOp_Double = mkGenPrimOp (fsLit "readDoubleArray#") [deltaTyVar] [mkMutableByteArrayPrimTy deltaTy, intPrimTy, mkStatePrimTy deltaTy] ((mkTupleTy Unboxed [mkStatePrimTy deltaTy, doublePrimTy])) primOpInfo ReadByteArrayOp_StablePtr = mkGenPrimOp (fsLit "readStablePtrArray#") [deltaTyVar, alphaTyVar] [mkMutableByteArrayPrimTy deltaTy, intPrimTy, mkStatePrimTy deltaTy] ((mkTupleTy Unboxed [mkStatePrimTy deltaTy, mkStablePtrPrimTy alphaTy]))-primOpInfo ReadByteArrayOp_Int8 = mkGenPrimOp (fsLit "readInt8Array#") [deltaTyVar] [mkMutableByteArrayPrimTy deltaTy, intPrimTy, mkStatePrimTy deltaTy] ((mkTupleTy Unboxed [mkStatePrimTy deltaTy, intPrimTy]))-primOpInfo ReadByteArrayOp_Int16 = mkGenPrimOp (fsLit "readInt16Array#") [deltaTyVar] [mkMutableByteArrayPrimTy deltaTy, intPrimTy, mkStatePrimTy deltaTy] ((mkTupleTy Unboxed [mkStatePrimTy deltaTy, intPrimTy]))-primOpInfo ReadByteArrayOp_Int32 = mkGenPrimOp (fsLit "readInt32Array#") [deltaTyVar] [mkMutableByteArrayPrimTy deltaTy, intPrimTy, mkStatePrimTy deltaTy] ((mkTupleTy Unboxed [mkStatePrimTy deltaTy, intPrimTy]))+primOpInfo ReadByteArrayOp_Int8 = mkGenPrimOp (fsLit "readInt8Array#") [deltaTyVar] [mkMutableByteArrayPrimTy deltaTy, intPrimTy, mkStatePrimTy deltaTy] ((mkTupleTy Unboxed [mkStatePrimTy deltaTy, int8PrimTy]))+primOpInfo ReadByteArrayOp_Int16 = mkGenPrimOp (fsLit "readInt16Array#") [deltaTyVar] [mkMutableByteArrayPrimTy deltaTy, intPrimTy, mkStatePrimTy deltaTy] ((mkTupleTy Unboxed [mkStatePrimTy deltaTy, int16PrimTy]))+primOpInfo ReadByteArrayOp_Int32 = mkGenPrimOp (fsLit "readInt32Array#") [deltaTyVar] [mkMutableByteArrayPrimTy deltaTy, intPrimTy, mkStatePrimTy deltaTy] ((mkTupleTy Unboxed [mkStatePrimTy deltaTy, int32PrimTy])) primOpInfo ReadByteArrayOp_Int64 = mkGenPrimOp (fsLit "readInt64Array#") [deltaTyVar] [mkMutableByteArrayPrimTy deltaTy, intPrimTy, mkStatePrimTy deltaTy] ((mkTupleTy Unboxed [mkStatePrimTy deltaTy, intPrimTy]))-primOpInfo ReadByteArrayOp_Word8 = mkGenPrimOp (fsLit "readWord8Array#") [deltaTyVar] [mkMutableByteArrayPrimTy deltaTy, intPrimTy, mkStatePrimTy deltaTy] ((mkTupleTy Unboxed [mkStatePrimTy deltaTy, wordPrimTy]))-primOpInfo ReadByteArrayOp_Word16 = mkGenPrimOp (fsLit "readWord16Array#") [deltaTyVar] [mkMutableByteArrayPrimTy deltaTy, intPrimTy, mkStatePrimTy deltaTy] ((mkTupleTy Unboxed [mkStatePrimTy deltaTy, wordPrimTy]))-primOpInfo ReadByteArrayOp_Word32 = mkGenPrimOp (fsLit "readWord32Array#") [deltaTyVar] [mkMutableByteArrayPrimTy deltaTy, intPrimTy, mkStatePrimTy deltaTy] ((mkTupleTy Unboxed [mkStatePrimTy deltaTy, wordPrimTy]))+primOpInfo ReadByteArrayOp_Word8 = mkGenPrimOp (fsLit "readWord8Array#") [deltaTyVar] [mkMutableByteArrayPrimTy deltaTy, intPrimTy, mkStatePrimTy deltaTy] ((mkTupleTy Unboxed [mkStatePrimTy deltaTy, word8PrimTy]))+primOpInfo ReadByteArrayOp_Word16 = mkGenPrimOp (fsLit "readWord16Array#") [deltaTyVar] [mkMutableByteArrayPrimTy deltaTy, intPrimTy, mkStatePrimTy deltaTy] ((mkTupleTy Unboxed [mkStatePrimTy deltaTy, word16PrimTy]))+primOpInfo ReadByteArrayOp_Word32 = mkGenPrimOp (fsLit "readWord32Array#") [deltaTyVar] [mkMutableByteArrayPrimTy deltaTy, intPrimTy, mkStatePrimTy deltaTy] ((mkTupleTy Unboxed [mkStatePrimTy deltaTy, word32PrimTy])) primOpInfo ReadByteArrayOp_Word64 = mkGenPrimOp (fsLit "readWord64Array#") [deltaTyVar] [mkMutableByteArrayPrimTy deltaTy, intPrimTy, mkStatePrimTy deltaTy] ((mkTupleTy Unboxed [mkStatePrimTy deltaTy, wordPrimTy])) primOpInfo ReadByteArrayOp_Word8AsChar = mkGenPrimOp (fsLit "readWord8ArrayAsChar#") [deltaTyVar] [mkMutableByteArrayPrimTy deltaTy, intPrimTy, mkStatePrimTy deltaTy] ((mkTupleTy Unboxed [mkStatePrimTy deltaTy, charPrimTy])) primOpInfo ReadByteArrayOp_Word8AsWideChar = mkGenPrimOp (fsLit "readWord8ArrayAsWideChar#") [deltaTyVar] [mkMutableByteArrayPrimTy deltaTy, intPrimTy, mkStatePrimTy deltaTy] ((mkTupleTy Unboxed [mkStatePrimTy deltaTy, charPrimTy]))@@ -387,11 +388,11 @@ primOpInfo ReadByteArrayOp_Word8AsFloat = mkGenPrimOp (fsLit "readWord8ArrayAsFloat#") [deltaTyVar] [mkMutableByteArrayPrimTy deltaTy, intPrimTy, mkStatePrimTy deltaTy] ((mkTupleTy Unboxed [mkStatePrimTy deltaTy, floatPrimTy])) primOpInfo ReadByteArrayOp_Word8AsDouble = mkGenPrimOp (fsLit "readWord8ArrayAsDouble#") [deltaTyVar] [mkMutableByteArrayPrimTy deltaTy, intPrimTy, mkStatePrimTy deltaTy] ((mkTupleTy Unboxed [mkStatePrimTy deltaTy, doublePrimTy])) primOpInfo ReadByteArrayOp_Word8AsStablePtr = mkGenPrimOp (fsLit "readWord8ArrayAsStablePtr#") [deltaTyVar, alphaTyVar] [mkMutableByteArrayPrimTy deltaTy, intPrimTy, mkStatePrimTy deltaTy] ((mkTupleTy Unboxed [mkStatePrimTy deltaTy, mkStablePtrPrimTy alphaTy]))-primOpInfo ReadByteArrayOp_Word8AsInt16 = mkGenPrimOp (fsLit "readWord8ArrayAsInt16#") [deltaTyVar] [mkMutableByteArrayPrimTy deltaTy, intPrimTy, mkStatePrimTy deltaTy] ((mkTupleTy Unboxed [mkStatePrimTy deltaTy, intPrimTy]))-primOpInfo ReadByteArrayOp_Word8AsInt32 = mkGenPrimOp (fsLit "readWord8ArrayAsInt32#") [deltaTyVar] [mkMutableByteArrayPrimTy deltaTy, intPrimTy, mkStatePrimTy deltaTy] ((mkTupleTy Unboxed [mkStatePrimTy deltaTy, intPrimTy]))+primOpInfo ReadByteArrayOp_Word8AsInt16 = mkGenPrimOp (fsLit "readWord8ArrayAsInt16#") [deltaTyVar] [mkMutableByteArrayPrimTy deltaTy, intPrimTy, mkStatePrimTy deltaTy] ((mkTupleTy Unboxed [mkStatePrimTy deltaTy, int16PrimTy]))+primOpInfo ReadByteArrayOp_Word8AsInt32 = mkGenPrimOp (fsLit "readWord8ArrayAsInt32#") [deltaTyVar] [mkMutableByteArrayPrimTy deltaTy, intPrimTy, mkStatePrimTy deltaTy] ((mkTupleTy Unboxed [mkStatePrimTy deltaTy, int32PrimTy])) primOpInfo ReadByteArrayOp_Word8AsInt64 = mkGenPrimOp (fsLit "readWord8ArrayAsInt64#") [deltaTyVar] [mkMutableByteArrayPrimTy deltaTy, intPrimTy, mkStatePrimTy deltaTy] ((mkTupleTy Unboxed [mkStatePrimTy deltaTy, intPrimTy]))-primOpInfo ReadByteArrayOp_Word8AsWord16 = mkGenPrimOp (fsLit "readWord8ArrayAsWord16#") [deltaTyVar] [mkMutableByteArrayPrimTy deltaTy, intPrimTy, mkStatePrimTy deltaTy] ((mkTupleTy Unboxed [mkStatePrimTy deltaTy, wordPrimTy]))-primOpInfo ReadByteArrayOp_Word8AsWord32 = mkGenPrimOp (fsLit "readWord8ArrayAsWord32#") [deltaTyVar] [mkMutableByteArrayPrimTy deltaTy, intPrimTy, mkStatePrimTy deltaTy] ((mkTupleTy Unboxed [mkStatePrimTy deltaTy, wordPrimTy]))+primOpInfo ReadByteArrayOp_Word8AsWord16 = mkGenPrimOp (fsLit "readWord8ArrayAsWord16#") [deltaTyVar] [mkMutableByteArrayPrimTy deltaTy, intPrimTy, mkStatePrimTy deltaTy] ((mkTupleTy Unboxed [mkStatePrimTy deltaTy, word16PrimTy]))+primOpInfo ReadByteArrayOp_Word8AsWord32 = mkGenPrimOp (fsLit "readWord8ArrayAsWord32#") [deltaTyVar] [mkMutableByteArrayPrimTy deltaTy, intPrimTy, mkStatePrimTy deltaTy] ((mkTupleTy Unboxed [mkStatePrimTy deltaTy, word32PrimTy])) primOpInfo ReadByteArrayOp_Word8AsWord64 = mkGenPrimOp (fsLit "readWord8ArrayAsWord64#") [deltaTyVar] [mkMutableByteArrayPrimTy deltaTy, intPrimTy, mkStatePrimTy deltaTy] ((mkTupleTy Unboxed [mkStatePrimTy deltaTy, wordPrimTy])) primOpInfo WriteByteArrayOp_Char = mkGenPrimOp (fsLit "writeCharArray#") [deltaTyVar] [mkMutableByteArrayPrimTy deltaTy, intPrimTy, charPrimTy, mkStatePrimTy deltaTy] (mkStatePrimTy deltaTy) primOpInfo WriteByteArrayOp_WideChar = mkGenPrimOp (fsLit "writeWideCharArray#") [deltaTyVar] [mkMutableByteArrayPrimTy deltaTy, intPrimTy, charPrimTy, mkStatePrimTy deltaTy] (mkStatePrimTy deltaTy)@@ -401,13 +402,13 @@ primOpInfo WriteByteArrayOp_Float = mkGenPrimOp (fsLit "writeFloatArray#") [deltaTyVar] [mkMutableByteArrayPrimTy deltaTy, intPrimTy, floatPrimTy, mkStatePrimTy deltaTy] (mkStatePrimTy deltaTy) primOpInfo WriteByteArrayOp_Double = mkGenPrimOp (fsLit "writeDoubleArray#") [deltaTyVar] [mkMutableByteArrayPrimTy deltaTy, intPrimTy, doublePrimTy, mkStatePrimTy deltaTy] (mkStatePrimTy deltaTy) primOpInfo WriteByteArrayOp_StablePtr = mkGenPrimOp (fsLit "writeStablePtrArray#") [deltaTyVar, alphaTyVar] [mkMutableByteArrayPrimTy deltaTy, intPrimTy, mkStablePtrPrimTy alphaTy, mkStatePrimTy deltaTy] (mkStatePrimTy deltaTy)-primOpInfo WriteByteArrayOp_Int8 = mkGenPrimOp (fsLit "writeInt8Array#") [deltaTyVar] [mkMutableByteArrayPrimTy deltaTy, intPrimTy, intPrimTy, mkStatePrimTy deltaTy] (mkStatePrimTy deltaTy)-primOpInfo WriteByteArrayOp_Int16 = mkGenPrimOp (fsLit "writeInt16Array#") [deltaTyVar] [mkMutableByteArrayPrimTy deltaTy, intPrimTy, intPrimTy, mkStatePrimTy deltaTy] (mkStatePrimTy deltaTy)-primOpInfo WriteByteArrayOp_Int32 = mkGenPrimOp (fsLit "writeInt32Array#") [deltaTyVar] [mkMutableByteArrayPrimTy deltaTy, intPrimTy, intPrimTy, mkStatePrimTy deltaTy] (mkStatePrimTy deltaTy)+primOpInfo WriteByteArrayOp_Int8 = mkGenPrimOp (fsLit "writeInt8Array#") [deltaTyVar] [mkMutableByteArrayPrimTy deltaTy, intPrimTy, int8PrimTy, mkStatePrimTy deltaTy] (mkStatePrimTy deltaTy)+primOpInfo WriteByteArrayOp_Int16 = mkGenPrimOp (fsLit "writeInt16Array#") [deltaTyVar] [mkMutableByteArrayPrimTy deltaTy, intPrimTy, int16PrimTy, mkStatePrimTy deltaTy] (mkStatePrimTy deltaTy)+primOpInfo WriteByteArrayOp_Int32 = mkGenPrimOp (fsLit "writeInt32Array#") [deltaTyVar] [mkMutableByteArrayPrimTy deltaTy, intPrimTy, int32PrimTy, mkStatePrimTy deltaTy] (mkStatePrimTy deltaTy) primOpInfo WriteByteArrayOp_Int64 = mkGenPrimOp (fsLit "writeInt64Array#") [deltaTyVar] [mkMutableByteArrayPrimTy deltaTy, intPrimTy, intPrimTy, mkStatePrimTy deltaTy] (mkStatePrimTy deltaTy)-primOpInfo WriteByteArrayOp_Word8 = mkGenPrimOp (fsLit "writeWord8Array#") [deltaTyVar] [mkMutableByteArrayPrimTy deltaTy, intPrimTy, wordPrimTy, mkStatePrimTy deltaTy] (mkStatePrimTy deltaTy)-primOpInfo WriteByteArrayOp_Word16 = mkGenPrimOp (fsLit "writeWord16Array#") [deltaTyVar] [mkMutableByteArrayPrimTy deltaTy, intPrimTy, wordPrimTy, mkStatePrimTy deltaTy] (mkStatePrimTy deltaTy)-primOpInfo WriteByteArrayOp_Word32 = mkGenPrimOp (fsLit "writeWord32Array#") [deltaTyVar] [mkMutableByteArrayPrimTy deltaTy, intPrimTy, wordPrimTy, mkStatePrimTy deltaTy] (mkStatePrimTy deltaTy)+primOpInfo WriteByteArrayOp_Word8 = mkGenPrimOp (fsLit "writeWord8Array#") [deltaTyVar] [mkMutableByteArrayPrimTy deltaTy, intPrimTy, word8PrimTy, mkStatePrimTy deltaTy] (mkStatePrimTy deltaTy)+primOpInfo WriteByteArrayOp_Word16 = mkGenPrimOp (fsLit "writeWord16Array#") [deltaTyVar] [mkMutableByteArrayPrimTy deltaTy, intPrimTy, word16PrimTy, mkStatePrimTy deltaTy] (mkStatePrimTy deltaTy)+primOpInfo WriteByteArrayOp_Word32 = mkGenPrimOp (fsLit "writeWord32Array#") [deltaTyVar] [mkMutableByteArrayPrimTy deltaTy, intPrimTy, word32PrimTy, mkStatePrimTy deltaTy] (mkStatePrimTy deltaTy) primOpInfo WriteByteArrayOp_Word64 = mkGenPrimOp (fsLit "writeWord64Array#") [deltaTyVar] [mkMutableByteArrayPrimTy deltaTy, intPrimTy, wordPrimTy, mkStatePrimTy deltaTy] (mkStatePrimTy deltaTy) primOpInfo WriteByteArrayOp_Word8AsChar = mkGenPrimOp (fsLit "writeWord8ArrayAsChar#") [deltaTyVar] [mkMutableByteArrayPrimTy deltaTy, intPrimTy, charPrimTy, mkStatePrimTy deltaTy] (mkStatePrimTy deltaTy) primOpInfo WriteByteArrayOp_Word8AsWideChar = mkGenPrimOp (fsLit "writeWord8ArrayAsWideChar#") [deltaTyVar] [mkMutableByteArrayPrimTy deltaTy, intPrimTy, charPrimTy, mkStatePrimTy deltaTy] (mkStatePrimTy deltaTy)@@ -417,11 +418,11 @@ primOpInfo WriteByteArrayOp_Word8AsFloat = mkGenPrimOp (fsLit "writeWord8ArrayAsFloat#") [deltaTyVar] [mkMutableByteArrayPrimTy deltaTy, intPrimTy, floatPrimTy, mkStatePrimTy deltaTy] (mkStatePrimTy deltaTy) primOpInfo WriteByteArrayOp_Word8AsDouble = mkGenPrimOp (fsLit "writeWord8ArrayAsDouble#") [deltaTyVar] [mkMutableByteArrayPrimTy deltaTy, intPrimTy, doublePrimTy, mkStatePrimTy deltaTy] (mkStatePrimTy deltaTy) primOpInfo WriteByteArrayOp_Word8AsStablePtr = mkGenPrimOp (fsLit "writeWord8ArrayAsStablePtr#") [deltaTyVar, alphaTyVar] [mkMutableByteArrayPrimTy deltaTy, intPrimTy, mkStablePtrPrimTy alphaTy, mkStatePrimTy deltaTy] (mkStatePrimTy deltaTy)-primOpInfo WriteByteArrayOp_Word8AsInt16 = mkGenPrimOp (fsLit "writeWord8ArrayAsInt16#") [deltaTyVar] [mkMutableByteArrayPrimTy deltaTy, intPrimTy, intPrimTy, mkStatePrimTy deltaTy] (mkStatePrimTy deltaTy)-primOpInfo WriteByteArrayOp_Word8AsInt32 = mkGenPrimOp (fsLit "writeWord8ArrayAsInt32#") [deltaTyVar] [mkMutableByteArrayPrimTy deltaTy, intPrimTy, intPrimTy, mkStatePrimTy deltaTy] (mkStatePrimTy deltaTy)+primOpInfo WriteByteArrayOp_Word8AsInt16 = mkGenPrimOp (fsLit "writeWord8ArrayAsInt16#") [deltaTyVar] [mkMutableByteArrayPrimTy deltaTy, intPrimTy, int16PrimTy, mkStatePrimTy deltaTy] (mkStatePrimTy deltaTy)+primOpInfo WriteByteArrayOp_Word8AsInt32 = mkGenPrimOp (fsLit "writeWord8ArrayAsInt32#") [deltaTyVar] [mkMutableByteArrayPrimTy deltaTy, intPrimTy, int32PrimTy, mkStatePrimTy deltaTy] (mkStatePrimTy deltaTy) primOpInfo WriteByteArrayOp_Word8AsInt64 = mkGenPrimOp (fsLit "writeWord8ArrayAsInt64#") [deltaTyVar] [mkMutableByteArrayPrimTy deltaTy, intPrimTy, intPrimTy, mkStatePrimTy deltaTy] (mkStatePrimTy deltaTy)-primOpInfo WriteByteArrayOp_Word8AsWord16 = mkGenPrimOp (fsLit "writeWord8ArrayAsWord16#") [deltaTyVar] [mkMutableByteArrayPrimTy deltaTy, intPrimTy, wordPrimTy, mkStatePrimTy deltaTy] (mkStatePrimTy deltaTy)-primOpInfo WriteByteArrayOp_Word8AsWord32 = mkGenPrimOp (fsLit "writeWord8ArrayAsWord32#") [deltaTyVar] [mkMutableByteArrayPrimTy deltaTy, intPrimTy, wordPrimTy, mkStatePrimTy deltaTy] (mkStatePrimTy deltaTy)+primOpInfo WriteByteArrayOp_Word8AsWord16 = mkGenPrimOp (fsLit "writeWord8ArrayAsWord16#") [deltaTyVar] [mkMutableByteArrayPrimTy deltaTy, intPrimTy, word16PrimTy, mkStatePrimTy deltaTy] (mkStatePrimTy deltaTy)+primOpInfo WriteByteArrayOp_Word8AsWord32 = mkGenPrimOp (fsLit "writeWord8ArrayAsWord32#") [deltaTyVar] [mkMutableByteArrayPrimTy deltaTy, intPrimTy, word32PrimTy, mkStatePrimTy deltaTy] (mkStatePrimTy deltaTy) primOpInfo WriteByteArrayOp_Word8AsWord64 = mkGenPrimOp (fsLit "writeWord8ArrayAsWord64#") [deltaTyVar] [mkMutableByteArrayPrimTy deltaTy, intPrimTy, wordPrimTy, mkStatePrimTy deltaTy] (mkStatePrimTy deltaTy) primOpInfo CompareByteArraysOp = mkGenPrimOp (fsLit "compareByteArrays#") [] [byteArrayPrimTy, intPrimTy, byteArrayPrimTy, intPrimTy, intPrimTy] (intPrimTy) primOpInfo CopyByteArrayOp = mkGenPrimOp (fsLit "copyByteArray#") [deltaTyVar] [byteArrayPrimTy, intPrimTy, mkMutableByteArrayPrimTy deltaTy, intPrimTy, intPrimTy, mkStatePrimTy deltaTy] (mkStatePrimTy deltaTy)@@ -475,13 +476,13 @@ primOpInfo IndexOffAddrOp_Float = mkGenPrimOp (fsLit "indexFloatOffAddr#") [] [addrPrimTy, intPrimTy] (floatPrimTy) primOpInfo IndexOffAddrOp_Double = mkGenPrimOp (fsLit "indexDoubleOffAddr#") [] [addrPrimTy, intPrimTy] (doublePrimTy) primOpInfo IndexOffAddrOp_StablePtr = mkGenPrimOp (fsLit "indexStablePtrOffAddr#") [alphaTyVar] [addrPrimTy, intPrimTy] (mkStablePtrPrimTy alphaTy)-primOpInfo IndexOffAddrOp_Int8 = mkGenPrimOp (fsLit "indexInt8OffAddr#") [] [addrPrimTy, intPrimTy] (intPrimTy)-primOpInfo IndexOffAddrOp_Int16 = mkGenPrimOp (fsLit "indexInt16OffAddr#") [] [addrPrimTy, intPrimTy] (intPrimTy)-primOpInfo IndexOffAddrOp_Int32 = mkGenPrimOp (fsLit "indexInt32OffAddr#") [] [addrPrimTy, intPrimTy] (intPrimTy)+primOpInfo IndexOffAddrOp_Int8 = mkGenPrimOp (fsLit "indexInt8OffAddr#") [] [addrPrimTy, intPrimTy] (int8PrimTy)+primOpInfo IndexOffAddrOp_Int16 = mkGenPrimOp (fsLit "indexInt16OffAddr#") [] [addrPrimTy, intPrimTy] (int16PrimTy)+primOpInfo IndexOffAddrOp_Int32 = mkGenPrimOp (fsLit "indexInt32OffAddr#") [] [addrPrimTy, intPrimTy] (int32PrimTy) primOpInfo IndexOffAddrOp_Int64 = mkGenPrimOp (fsLit "indexInt64OffAddr#") [] [addrPrimTy, intPrimTy] (intPrimTy)-primOpInfo IndexOffAddrOp_Word8 = mkGenPrimOp (fsLit "indexWord8OffAddr#") [] [addrPrimTy, intPrimTy] (wordPrimTy)-primOpInfo IndexOffAddrOp_Word16 = mkGenPrimOp (fsLit "indexWord16OffAddr#") [] [addrPrimTy, intPrimTy] (wordPrimTy)-primOpInfo IndexOffAddrOp_Word32 = mkGenPrimOp (fsLit "indexWord32OffAddr#") [] [addrPrimTy, intPrimTy] (wordPrimTy)+primOpInfo IndexOffAddrOp_Word8 = mkGenPrimOp (fsLit "indexWord8OffAddr#") [] [addrPrimTy, intPrimTy] (word8PrimTy)+primOpInfo IndexOffAddrOp_Word16 = mkGenPrimOp (fsLit "indexWord16OffAddr#") [] [addrPrimTy, intPrimTy] (word16PrimTy)+primOpInfo IndexOffAddrOp_Word32 = mkGenPrimOp (fsLit "indexWord32OffAddr#") [] [addrPrimTy, intPrimTy] (word32PrimTy) primOpInfo IndexOffAddrOp_Word64 = mkGenPrimOp (fsLit "indexWord64OffAddr#") [] [addrPrimTy, intPrimTy] (wordPrimTy) primOpInfo ReadOffAddrOp_Char = mkGenPrimOp (fsLit "readCharOffAddr#") [deltaTyVar] [addrPrimTy, intPrimTy, mkStatePrimTy deltaTy] ((mkTupleTy Unboxed [mkStatePrimTy deltaTy, charPrimTy])) primOpInfo ReadOffAddrOp_WideChar = mkGenPrimOp (fsLit "readWideCharOffAddr#") [deltaTyVar] [addrPrimTy, intPrimTy, mkStatePrimTy deltaTy] ((mkTupleTy Unboxed [mkStatePrimTy deltaTy, charPrimTy]))@@ -491,13 +492,13 @@ primOpInfo ReadOffAddrOp_Float = mkGenPrimOp (fsLit "readFloatOffAddr#") [deltaTyVar] [addrPrimTy, intPrimTy, mkStatePrimTy deltaTy] ((mkTupleTy Unboxed [mkStatePrimTy deltaTy, floatPrimTy])) primOpInfo ReadOffAddrOp_Double = mkGenPrimOp (fsLit "readDoubleOffAddr#") [deltaTyVar] [addrPrimTy, intPrimTy, mkStatePrimTy deltaTy] ((mkTupleTy Unboxed [mkStatePrimTy deltaTy, doublePrimTy])) primOpInfo ReadOffAddrOp_StablePtr = mkGenPrimOp (fsLit "readStablePtrOffAddr#") [deltaTyVar, alphaTyVar] [addrPrimTy, intPrimTy, mkStatePrimTy deltaTy] ((mkTupleTy Unboxed [mkStatePrimTy deltaTy, mkStablePtrPrimTy alphaTy]))-primOpInfo ReadOffAddrOp_Int8 = mkGenPrimOp (fsLit "readInt8OffAddr#") [deltaTyVar] [addrPrimTy, intPrimTy, mkStatePrimTy deltaTy] ((mkTupleTy Unboxed [mkStatePrimTy deltaTy, intPrimTy]))-primOpInfo ReadOffAddrOp_Int16 = mkGenPrimOp (fsLit "readInt16OffAddr#") [deltaTyVar] [addrPrimTy, intPrimTy, mkStatePrimTy deltaTy] ((mkTupleTy Unboxed [mkStatePrimTy deltaTy, intPrimTy]))-primOpInfo ReadOffAddrOp_Int32 = mkGenPrimOp (fsLit "readInt32OffAddr#") [deltaTyVar] [addrPrimTy, intPrimTy, mkStatePrimTy deltaTy] ((mkTupleTy Unboxed [mkStatePrimTy deltaTy, intPrimTy]))+primOpInfo ReadOffAddrOp_Int8 = mkGenPrimOp (fsLit "readInt8OffAddr#") [deltaTyVar] [addrPrimTy, intPrimTy, mkStatePrimTy deltaTy] ((mkTupleTy Unboxed [mkStatePrimTy deltaTy, int8PrimTy]))+primOpInfo ReadOffAddrOp_Int16 = mkGenPrimOp (fsLit "readInt16OffAddr#") [deltaTyVar] [addrPrimTy, intPrimTy, mkStatePrimTy deltaTy] ((mkTupleTy Unboxed [mkStatePrimTy deltaTy, int16PrimTy]))+primOpInfo ReadOffAddrOp_Int32 = mkGenPrimOp (fsLit "readInt32OffAddr#") [deltaTyVar] [addrPrimTy, intPrimTy, mkStatePrimTy deltaTy] ((mkTupleTy Unboxed [mkStatePrimTy deltaTy, int32PrimTy])) primOpInfo ReadOffAddrOp_Int64 = mkGenPrimOp (fsLit "readInt64OffAddr#") [deltaTyVar] [addrPrimTy, intPrimTy, mkStatePrimTy deltaTy] ((mkTupleTy Unboxed [mkStatePrimTy deltaTy, intPrimTy]))-primOpInfo ReadOffAddrOp_Word8 = mkGenPrimOp (fsLit "readWord8OffAddr#") [deltaTyVar] [addrPrimTy, intPrimTy, mkStatePrimTy deltaTy] ((mkTupleTy Unboxed [mkStatePrimTy deltaTy, wordPrimTy]))-primOpInfo ReadOffAddrOp_Word16 = mkGenPrimOp (fsLit "readWord16OffAddr#") [deltaTyVar] [addrPrimTy, intPrimTy, mkStatePrimTy deltaTy] ((mkTupleTy Unboxed [mkStatePrimTy deltaTy, wordPrimTy]))-primOpInfo ReadOffAddrOp_Word32 = mkGenPrimOp (fsLit "readWord32OffAddr#") [deltaTyVar] [addrPrimTy, intPrimTy, mkStatePrimTy deltaTy] ((mkTupleTy Unboxed [mkStatePrimTy deltaTy, wordPrimTy]))+primOpInfo ReadOffAddrOp_Word8 = mkGenPrimOp (fsLit "readWord8OffAddr#") [deltaTyVar] [addrPrimTy, intPrimTy, mkStatePrimTy deltaTy] ((mkTupleTy Unboxed [mkStatePrimTy deltaTy, word8PrimTy]))+primOpInfo ReadOffAddrOp_Word16 = mkGenPrimOp (fsLit "readWord16OffAddr#") [deltaTyVar] [addrPrimTy, intPrimTy, mkStatePrimTy deltaTy] ((mkTupleTy Unboxed [mkStatePrimTy deltaTy, word16PrimTy]))+primOpInfo ReadOffAddrOp_Word32 = mkGenPrimOp (fsLit "readWord32OffAddr#") [deltaTyVar] [addrPrimTy, intPrimTy, mkStatePrimTy deltaTy] ((mkTupleTy Unboxed [mkStatePrimTy deltaTy, word32PrimTy])) primOpInfo ReadOffAddrOp_Word64 = mkGenPrimOp (fsLit "readWord64OffAddr#") [deltaTyVar] [addrPrimTy, intPrimTy, mkStatePrimTy deltaTy] ((mkTupleTy Unboxed [mkStatePrimTy deltaTy, wordPrimTy])) primOpInfo WriteOffAddrOp_Char = mkGenPrimOp (fsLit "writeCharOffAddr#") [deltaTyVar] [addrPrimTy, intPrimTy, charPrimTy, mkStatePrimTy deltaTy] (mkStatePrimTy deltaTy) primOpInfo WriteOffAddrOp_WideChar = mkGenPrimOp (fsLit "writeWideCharOffAddr#") [deltaTyVar] [addrPrimTy, intPrimTy, charPrimTy, mkStatePrimTy deltaTy] (mkStatePrimTy deltaTy)@@ -507,13 +508,13 @@ primOpInfo WriteOffAddrOp_Float = mkGenPrimOp (fsLit "writeFloatOffAddr#") [deltaTyVar] [addrPrimTy, intPrimTy, floatPrimTy, mkStatePrimTy deltaTy] (mkStatePrimTy deltaTy) primOpInfo WriteOffAddrOp_Double = mkGenPrimOp (fsLit "writeDoubleOffAddr#") [deltaTyVar] [addrPrimTy, intPrimTy, doublePrimTy, mkStatePrimTy deltaTy] (mkStatePrimTy deltaTy) primOpInfo WriteOffAddrOp_StablePtr = mkGenPrimOp (fsLit "writeStablePtrOffAddr#") [alphaTyVar, deltaTyVar] [addrPrimTy, intPrimTy, mkStablePtrPrimTy alphaTy, mkStatePrimTy deltaTy] (mkStatePrimTy deltaTy)-primOpInfo WriteOffAddrOp_Int8 = mkGenPrimOp (fsLit "writeInt8OffAddr#") [deltaTyVar] [addrPrimTy, intPrimTy, intPrimTy, mkStatePrimTy deltaTy] (mkStatePrimTy deltaTy)-primOpInfo WriteOffAddrOp_Int16 = mkGenPrimOp (fsLit "writeInt16OffAddr#") [deltaTyVar] [addrPrimTy, intPrimTy, intPrimTy, mkStatePrimTy deltaTy] (mkStatePrimTy deltaTy)-primOpInfo WriteOffAddrOp_Int32 = mkGenPrimOp (fsLit "writeInt32OffAddr#") [deltaTyVar] [addrPrimTy, intPrimTy, intPrimTy, mkStatePrimTy deltaTy] (mkStatePrimTy deltaTy)+primOpInfo WriteOffAddrOp_Int8 = mkGenPrimOp (fsLit "writeInt8OffAddr#") [deltaTyVar] [addrPrimTy, intPrimTy, int8PrimTy, mkStatePrimTy deltaTy] (mkStatePrimTy deltaTy)+primOpInfo WriteOffAddrOp_Int16 = mkGenPrimOp (fsLit "writeInt16OffAddr#") [deltaTyVar] [addrPrimTy, intPrimTy, int16PrimTy, mkStatePrimTy deltaTy] (mkStatePrimTy deltaTy)+primOpInfo WriteOffAddrOp_Int32 = mkGenPrimOp (fsLit "writeInt32OffAddr#") [deltaTyVar] [addrPrimTy, intPrimTy, int32PrimTy, mkStatePrimTy deltaTy] (mkStatePrimTy deltaTy) primOpInfo WriteOffAddrOp_Int64 = mkGenPrimOp (fsLit "writeInt64OffAddr#") [deltaTyVar] [addrPrimTy, intPrimTy, intPrimTy, mkStatePrimTy deltaTy] (mkStatePrimTy deltaTy)-primOpInfo WriteOffAddrOp_Word8 = mkGenPrimOp (fsLit "writeWord8OffAddr#") [deltaTyVar] [addrPrimTy, intPrimTy, wordPrimTy, mkStatePrimTy deltaTy] (mkStatePrimTy deltaTy)-primOpInfo WriteOffAddrOp_Word16 = mkGenPrimOp (fsLit "writeWord16OffAddr#") [deltaTyVar] [addrPrimTy, intPrimTy, wordPrimTy, mkStatePrimTy deltaTy] (mkStatePrimTy deltaTy)-primOpInfo WriteOffAddrOp_Word32 = mkGenPrimOp (fsLit "writeWord32OffAddr#") [deltaTyVar] [addrPrimTy, intPrimTy, wordPrimTy, mkStatePrimTy deltaTy] (mkStatePrimTy deltaTy)+primOpInfo WriteOffAddrOp_Word8 = mkGenPrimOp (fsLit "writeWord8OffAddr#") [deltaTyVar] [addrPrimTy, intPrimTy, word8PrimTy, mkStatePrimTy deltaTy] (mkStatePrimTy deltaTy)+primOpInfo WriteOffAddrOp_Word16 = mkGenPrimOp (fsLit "writeWord16OffAddr#") [deltaTyVar] [addrPrimTy, intPrimTy, word16PrimTy, mkStatePrimTy deltaTy] (mkStatePrimTy deltaTy)+primOpInfo WriteOffAddrOp_Word32 = mkGenPrimOp (fsLit "writeWord32OffAddr#") [deltaTyVar] [addrPrimTy, intPrimTy, word32PrimTy, mkStatePrimTy deltaTy] (mkStatePrimTy deltaTy) primOpInfo WriteOffAddrOp_Word64 = mkGenPrimOp (fsLit "writeWord64OffAddr#") [deltaTyVar] [addrPrimTy, intPrimTy, wordPrimTy, mkStatePrimTy deltaTy] (mkStatePrimTy deltaTy) primOpInfo InterlockedExchange_Addr = mkGenPrimOp (fsLit "atomicExchangeAddrAddr#") [deltaTyVar] [addrPrimTy, addrPrimTy, mkStatePrimTy deltaTy] ((mkTupleTy Unboxed [mkStatePrimTy deltaTy, addrPrimTy])) primOpInfo InterlockedExchange_Word = mkGenPrimOp (fsLit "atomicExchangeWordAddr#") [deltaTyVar] [addrPrimTy, wordPrimTy, mkStatePrimTy deltaTy] ((mkTupleTy Unboxed [mkStatePrimTy deltaTy, wordPrimTy]))@@ -617,33 +618,34 @@ primOpInfo GetCCSOfOp = mkGenPrimOp (fsLit "getCCSOf#") [alphaTyVar, deltaTyVar] [alphaTy, mkStatePrimTy deltaTy] ((mkTupleTy Unboxed [mkStatePrimTy deltaTy, addrPrimTy])) primOpInfo GetCurrentCCSOp = mkGenPrimOp (fsLit "getCurrentCCS#") [alphaTyVar, deltaTyVar] [alphaTy, mkStatePrimTy deltaTy] ((mkTupleTy Unboxed [mkStatePrimTy deltaTy, addrPrimTy])) primOpInfo ClearCCSOp = mkGenPrimOp (fsLit "clearCCS#") [deltaTyVar, alphaTyVar] [(mkVisFunTyMany (mkStatePrimTy deltaTy) ((mkTupleTy Unboxed [mkStatePrimTy deltaTy, alphaTy]))), mkStatePrimTy deltaTy] ((mkTupleTy Unboxed [mkStatePrimTy deltaTy, alphaTy]))+primOpInfo WhereFromOp = mkGenPrimOp (fsLit "whereFrom#") [alphaTyVar, deltaTyVar] [alphaTy, mkStatePrimTy deltaTy] ((mkTupleTy Unboxed [mkStatePrimTy deltaTy, addrPrimTy])) primOpInfo TraceEventOp = mkGenPrimOp (fsLit "traceEvent#") [deltaTyVar] [addrPrimTy, mkStatePrimTy deltaTy] (mkStatePrimTy deltaTy) primOpInfo TraceEventBinaryOp = mkGenPrimOp (fsLit "traceBinaryEvent#") [deltaTyVar] [addrPrimTy, intPrimTy, mkStatePrimTy deltaTy] (mkStatePrimTy deltaTy) primOpInfo TraceMarkerOp = mkGenPrimOp (fsLit "traceMarker#") [deltaTyVar] [addrPrimTy, mkStatePrimTy deltaTy] (mkStatePrimTy deltaTy) primOpInfo SetThreadAllocationCounter = mkGenPrimOp (fsLit "setThreadAllocationCounter#") [] [intPrimTy, mkStatePrimTy realWorldTy] (mkStatePrimTy realWorldTy)-primOpInfo (VecBroadcastOp IntVec 16 W8) = mkGenPrimOp (fsLit "broadcastInt8X16#") [] [intPrimTy] (int8X16PrimTy)-primOpInfo (VecBroadcastOp IntVec 8 W16) = mkGenPrimOp (fsLit "broadcastInt16X8#") [] [intPrimTy] (int16X8PrimTy)-primOpInfo (VecBroadcastOp IntVec 4 W32) = mkGenPrimOp (fsLit "broadcastInt32X4#") [] [intPrimTy] (int32X4PrimTy)+primOpInfo (VecBroadcastOp IntVec 16 W8) = mkGenPrimOp (fsLit "broadcastInt8X16#") [] [int8PrimTy] (int8X16PrimTy)+primOpInfo (VecBroadcastOp IntVec 8 W16) = mkGenPrimOp (fsLit "broadcastInt16X8#") [] [int16PrimTy] (int16X8PrimTy)+primOpInfo (VecBroadcastOp IntVec 4 W32) = mkGenPrimOp (fsLit "broadcastInt32X4#") [] [int32PrimTy] (int32X4PrimTy) primOpInfo (VecBroadcastOp IntVec 2 W64) = mkGenPrimOp (fsLit "broadcastInt64X2#") [] [intPrimTy] (int64X2PrimTy)-primOpInfo (VecBroadcastOp IntVec 32 W8) = mkGenPrimOp (fsLit "broadcastInt8X32#") [] [intPrimTy] (int8X32PrimTy)-primOpInfo (VecBroadcastOp IntVec 16 W16) = mkGenPrimOp (fsLit "broadcastInt16X16#") [] [intPrimTy] (int16X16PrimTy)-primOpInfo (VecBroadcastOp IntVec 8 W32) = mkGenPrimOp (fsLit "broadcastInt32X8#") [] [intPrimTy] (int32X8PrimTy)+primOpInfo (VecBroadcastOp IntVec 32 W8) = mkGenPrimOp (fsLit "broadcastInt8X32#") [] [int8PrimTy] (int8X32PrimTy)+primOpInfo (VecBroadcastOp IntVec 16 W16) = mkGenPrimOp (fsLit "broadcastInt16X16#") [] [int16PrimTy] (int16X16PrimTy)+primOpInfo (VecBroadcastOp IntVec 8 W32) = mkGenPrimOp (fsLit "broadcastInt32X8#") [] [int32PrimTy] (int32X8PrimTy) primOpInfo (VecBroadcastOp IntVec 4 W64) = mkGenPrimOp (fsLit "broadcastInt64X4#") [] [intPrimTy] (int64X4PrimTy)-primOpInfo (VecBroadcastOp IntVec 64 W8) = mkGenPrimOp (fsLit "broadcastInt8X64#") [] [intPrimTy] (int8X64PrimTy)-primOpInfo (VecBroadcastOp IntVec 32 W16) = mkGenPrimOp (fsLit "broadcastInt16X32#") [] [intPrimTy] (int16X32PrimTy)-primOpInfo (VecBroadcastOp IntVec 16 W32) = mkGenPrimOp (fsLit "broadcastInt32X16#") [] [intPrimTy] (int32X16PrimTy)+primOpInfo (VecBroadcastOp IntVec 64 W8) = mkGenPrimOp (fsLit "broadcastInt8X64#") [] [int8PrimTy] (int8X64PrimTy)+primOpInfo (VecBroadcastOp IntVec 32 W16) = mkGenPrimOp (fsLit "broadcastInt16X32#") [] [int16PrimTy] (int16X32PrimTy)+primOpInfo (VecBroadcastOp IntVec 16 W32) = mkGenPrimOp (fsLit "broadcastInt32X16#") [] [int32PrimTy] (int32X16PrimTy) primOpInfo (VecBroadcastOp IntVec 8 W64) = mkGenPrimOp (fsLit "broadcastInt64X8#") [] [intPrimTy] (int64X8PrimTy) primOpInfo (VecBroadcastOp WordVec 16 W8) = mkGenPrimOp (fsLit "broadcastWord8X16#") [] [wordPrimTy] (word8X16PrimTy) primOpInfo (VecBroadcastOp WordVec 8 W16) = mkGenPrimOp (fsLit "broadcastWord16X8#") [] [wordPrimTy] (word16X8PrimTy)-primOpInfo (VecBroadcastOp WordVec 4 W32) = mkGenPrimOp (fsLit "broadcastWord32X4#") [] [wordPrimTy] (word32X4PrimTy)+primOpInfo (VecBroadcastOp WordVec 4 W32) = mkGenPrimOp (fsLit "broadcastWord32X4#") [] [word32PrimTy] (word32X4PrimTy) primOpInfo (VecBroadcastOp WordVec 2 W64) = mkGenPrimOp (fsLit "broadcastWord64X2#") [] [wordPrimTy] (word64X2PrimTy) primOpInfo (VecBroadcastOp WordVec 32 W8) = mkGenPrimOp (fsLit "broadcastWord8X32#") [] [wordPrimTy] (word8X32PrimTy) primOpInfo (VecBroadcastOp WordVec 16 W16) = mkGenPrimOp (fsLit "broadcastWord16X16#") [] [wordPrimTy] (word16X16PrimTy)-primOpInfo (VecBroadcastOp WordVec 8 W32) = mkGenPrimOp (fsLit "broadcastWord32X8#") [] [wordPrimTy] (word32X8PrimTy)+primOpInfo (VecBroadcastOp WordVec 8 W32) = mkGenPrimOp (fsLit "broadcastWord32X8#") [] [word32PrimTy] (word32X8PrimTy) primOpInfo (VecBroadcastOp WordVec 4 W64) = mkGenPrimOp (fsLit "broadcastWord64X4#") [] [wordPrimTy] (word64X4PrimTy) primOpInfo (VecBroadcastOp WordVec 64 W8) = mkGenPrimOp (fsLit "broadcastWord8X64#") [] [wordPrimTy] (word8X64PrimTy) primOpInfo (VecBroadcastOp WordVec 32 W16) = mkGenPrimOp (fsLit "broadcastWord16X32#") [] [wordPrimTy] (word16X32PrimTy)-primOpInfo (VecBroadcastOp WordVec 16 W32) = mkGenPrimOp (fsLit "broadcastWord32X16#") [] [wordPrimTy] (word32X16PrimTy)+primOpInfo (VecBroadcastOp WordVec 16 W32) = mkGenPrimOp (fsLit "broadcastWord32X16#") [] [word32PrimTy] (word32X16PrimTy) primOpInfo (VecBroadcastOp WordVec 8 W64) = mkGenPrimOp (fsLit "broadcastWord64X8#") [] [wordPrimTy] (word64X8PrimTy) primOpInfo (VecBroadcastOp FloatVec 4 W32) = mkGenPrimOp (fsLit "broadcastFloatX4#") [] [floatPrimTy] (floatX4PrimTy) primOpInfo (VecBroadcastOp FloatVec 2 W64) = mkGenPrimOp (fsLit "broadcastDoubleX2#") [] [doublePrimTy] (doubleX2PrimTy)@@ -651,29 +653,29 @@ primOpInfo (VecBroadcastOp FloatVec 4 W64) = mkGenPrimOp (fsLit "broadcastDoubleX4#") [] [doublePrimTy] (doubleX4PrimTy) primOpInfo (VecBroadcastOp FloatVec 16 W32) = mkGenPrimOp (fsLit "broadcastFloatX16#") [] [floatPrimTy] (floatX16PrimTy) primOpInfo (VecBroadcastOp FloatVec 8 W64) = mkGenPrimOp (fsLit "broadcastDoubleX8#") [] [doublePrimTy] (doubleX8PrimTy)-primOpInfo (VecPackOp IntVec 16 W8) = mkGenPrimOp (fsLit "packInt8X16#") [] [(mkTupleTy Unboxed [intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy])] (int8X16PrimTy)-primOpInfo (VecPackOp IntVec 8 W16) = mkGenPrimOp (fsLit "packInt16X8#") [] [(mkTupleTy Unboxed [intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy])] (int16X8PrimTy)-primOpInfo (VecPackOp IntVec 4 W32) = mkGenPrimOp (fsLit "packInt32X4#") [] [(mkTupleTy Unboxed [intPrimTy, intPrimTy, intPrimTy, intPrimTy])] (int32X4PrimTy)+primOpInfo (VecPackOp IntVec 16 W8) = mkGenPrimOp (fsLit "packInt8X16#") [] [(mkTupleTy Unboxed [int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy])] (int8X16PrimTy)+primOpInfo (VecPackOp IntVec 8 W16) = mkGenPrimOp (fsLit "packInt16X8#") [] [(mkTupleTy Unboxed [int16PrimTy, int16PrimTy, int16PrimTy, int16PrimTy, int16PrimTy, int16PrimTy, int16PrimTy, int16PrimTy])] (int16X8PrimTy)+primOpInfo (VecPackOp IntVec 4 W32) = mkGenPrimOp (fsLit "packInt32X4#") [] [(mkTupleTy Unboxed [int32PrimTy, int32PrimTy, int32PrimTy, int32PrimTy])] (int32X4PrimTy) primOpInfo (VecPackOp IntVec 2 W64) = mkGenPrimOp (fsLit "packInt64X2#") [] [(mkTupleTy Unboxed [intPrimTy, intPrimTy])] (int64X2PrimTy)-primOpInfo (VecPackOp IntVec 32 W8) = mkGenPrimOp (fsLit "packInt8X32#") [] [(mkTupleTy Unboxed [intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy])] (int8X32PrimTy)-primOpInfo (VecPackOp IntVec 16 W16) = mkGenPrimOp (fsLit "packInt16X16#") [] [(mkTupleTy Unboxed [intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy])] (int16X16PrimTy)-primOpInfo (VecPackOp IntVec 8 W32) = mkGenPrimOp (fsLit "packInt32X8#") [] [(mkTupleTy Unboxed [intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy])] (int32X8PrimTy)+primOpInfo (VecPackOp IntVec 32 W8) = mkGenPrimOp (fsLit "packInt8X32#") [] [(mkTupleTy Unboxed [int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy])] (int8X32PrimTy)+primOpInfo (VecPackOp IntVec 16 W16) = mkGenPrimOp (fsLit "packInt16X16#") [] [(mkTupleTy Unboxed [int16PrimTy, int16PrimTy, int16PrimTy, int16PrimTy, int16PrimTy, int16PrimTy, int16PrimTy, int16PrimTy, int16PrimTy, int16PrimTy, int16PrimTy, int16PrimTy, int16PrimTy, int16PrimTy, int16PrimTy, int16PrimTy])] (int16X16PrimTy)+primOpInfo (VecPackOp IntVec 8 W32) = mkGenPrimOp (fsLit "packInt32X8#") [] [(mkTupleTy Unboxed [int32PrimTy, int32PrimTy, int32PrimTy, int32PrimTy, int32PrimTy, int32PrimTy, int32PrimTy, int32PrimTy])] (int32X8PrimTy) primOpInfo (VecPackOp IntVec 4 W64) = mkGenPrimOp (fsLit "packInt64X4#") [] [(mkTupleTy Unboxed [intPrimTy, intPrimTy, intPrimTy, intPrimTy])] (int64X4PrimTy)-primOpInfo (VecPackOp IntVec 64 W8) = mkGenPrimOp (fsLit "packInt8X64#") [] [(mkTupleTy Unboxed [intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy])] (int8X64PrimTy)-primOpInfo (VecPackOp IntVec 32 W16) = mkGenPrimOp (fsLit "packInt16X32#") [] [(mkTupleTy Unboxed [intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy])] (int16X32PrimTy)-primOpInfo (VecPackOp IntVec 16 W32) = mkGenPrimOp (fsLit "packInt32X16#") [] [(mkTupleTy Unboxed [intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy])] (int32X16PrimTy)+primOpInfo (VecPackOp IntVec 64 W8) = mkGenPrimOp (fsLit "packInt8X64#") [] [(mkTupleTy Unboxed [int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy])] (int8X64PrimTy)+primOpInfo (VecPackOp IntVec 32 W16) = mkGenPrimOp (fsLit "packInt16X32#") [] [(mkTupleTy Unboxed [int16PrimTy, int16PrimTy, int16PrimTy, int16PrimTy, int16PrimTy, int16PrimTy, int16PrimTy, int16PrimTy, int16PrimTy, int16PrimTy, int16PrimTy, int16PrimTy, int16PrimTy, int16PrimTy, int16PrimTy, int16PrimTy, int16PrimTy, int16PrimTy, int16PrimTy, int16PrimTy, int16PrimTy, int16PrimTy, int16PrimTy, int16PrimTy, int16PrimTy, int16PrimTy, int16PrimTy, int16PrimTy, int16PrimTy, int16PrimTy, int16PrimTy, int16PrimTy])] (int16X32PrimTy)+primOpInfo (VecPackOp IntVec 16 W32) = mkGenPrimOp (fsLit "packInt32X16#") [] [(mkTupleTy Unboxed [int32PrimTy, int32PrimTy, int32PrimTy, int32PrimTy, int32PrimTy, int32PrimTy, int32PrimTy, int32PrimTy, int32PrimTy, int32PrimTy, int32PrimTy, int32PrimTy, int32PrimTy, int32PrimTy, int32PrimTy, int32PrimTy])] (int32X16PrimTy) primOpInfo (VecPackOp IntVec 8 W64) = mkGenPrimOp (fsLit "packInt64X8#") [] [(mkTupleTy Unboxed [intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy])] (int64X8PrimTy) primOpInfo (VecPackOp WordVec 16 W8) = mkGenPrimOp (fsLit "packWord8X16#") [] [(mkTupleTy Unboxed [wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy])] (word8X16PrimTy) primOpInfo (VecPackOp WordVec 8 W16) = mkGenPrimOp (fsLit "packWord16X8#") [] [(mkTupleTy Unboxed [wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy])] (word16X8PrimTy)-primOpInfo (VecPackOp WordVec 4 W32) = mkGenPrimOp (fsLit "packWord32X4#") [] [(mkTupleTy Unboxed [wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy])] (word32X4PrimTy)+primOpInfo (VecPackOp WordVec 4 W32) = mkGenPrimOp (fsLit "packWord32X4#") [] [(mkTupleTy Unboxed [word32PrimTy, word32PrimTy, word32PrimTy, word32PrimTy])] (word32X4PrimTy) primOpInfo (VecPackOp WordVec 2 W64) = mkGenPrimOp (fsLit "packWord64X2#") [] [(mkTupleTy Unboxed [wordPrimTy, wordPrimTy])] (word64X2PrimTy) primOpInfo (VecPackOp WordVec 32 W8) = mkGenPrimOp (fsLit "packWord8X32#") [] [(mkTupleTy Unboxed [wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy])] (word8X32PrimTy) primOpInfo (VecPackOp WordVec 16 W16) = mkGenPrimOp (fsLit "packWord16X16#") [] [(mkTupleTy Unboxed [wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy])] (word16X16PrimTy)-primOpInfo (VecPackOp WordVec 8 W32) = mkGenPrimOp (fsLit "packWord32X8#") [] [(mkTupleTy Unboxed [wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy])] (word32X8PrimTy)+primOpInfo (VecPackOp WordVec 8 W32) = mkGenPrimOp (fsLit "packWord32X8#") [] [(mkTupleTy Unboxed [word32PrimTy, word32PrimTy, word32PrimTy, word32PrimTy, word32PrimTy, word32PrimTy, word32PrimTy, word32PrimTy])] (word32X8PrimTy) primOpInfo (VecPackOp WordVec 4 W64) = mkGenPrimOp (fsLit "packWord64X4#") [] [(mkTupleTy Unboxed [wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy])] (word64X4PrimTy) primOpInfo (VecPackOp WordVec 64 W8) = mkGenPrimOp (fsLit "packWord8X64#") [] [(mkTupleTy Unboxed [wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy])] (word8X64PrimTy) primOpInfo (VecPackOp WordVec 32 W16) = mkGenPrimOp (fsLit "packWord16X32#") [] [(mkTupleTy Unboxed [wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy])] (word16X32PrimTy)-primOpInfo (VecPackOp WordVec 16 W32) = mkGenPrimOp (fsLit "packWord32X16#") [] [(mkTupleTy Unboxed [wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy])] (word32X16PrimTy)+primOpInfo (VecPackOp WordVec 16 W32) = mkGenPrimOp (fsLit "packWord32X16#") [] [(mkTupleTy Unboxed [word32PrimTy, word32PrimTy, word32PrimTy, word32PrimTy, word32PrimTy, word32PrimTy, word32PrimTy, word32PrimTy, word32PrimTy, word32PrimTy, word32PrimTy, word32PrimTy, word32PrimTy, word32PrimTy, word32PrimTy, word32PrimTy])] (word32X16PrimTy) primOpInfo (VecPackOp WordVec 8 W64) = mkGenPrimOp (fsLit "packWord64X8#") [] [(mkTupleTy Unboxed [wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy])] (word64X8PrimTy) primOpInfo (VecPackOp FloatVec 4 W32) = mkGenPrimOp (fsLit "packFloatX4#") [] [(mkTupleTy Unboxed [floatPrimTy, floatPrimTy, floatPrimTy, floatPrimTy])] (floatX4PrimTy) primOpInfo (VecPackOp FloatVec 2 W64) = mkGenPrimOp (fsLit "packDoubleX2#") [] [(mkTupleTy Unboxed [doublePrimTy, doublePrimTy])] (doubleX2PrimTy)@@ -681,29 +683,29 @@ primOpInfo (VecPackOp FloatVec 4 W64) = mkGenPrimOp (fsLit "packDoubleX4#") [] [(mkTupleTy Unboxed [doublePrimTy, doublePrimTy, doublePrimTy, doublePrimTy])] (doubleX4PrimTy) primOpInfo (VecPackOp FloatVec 16 W32) = mkGenPrimOp (fsLit "packFloatX16#") [] [(mkTupleTy Unboxed [floatPrimTy, floatPrimTy, floatPrimTy, floatPrimTy, floatPrimTy, floatPrimTy, floatPrimTy, floatPrimTy, floatPrimTy, floatPrimTy, floatPrimTy, floatPrimTy, floatPrimTy, floatPrimTy, floatPrimTy, floatPrimTy])] (floatX16PrimTy) primOpInfo (VecPackOp FloatVec 8 W64) = mkGenPrimOp (fsLit "packDoubleX8#") [] [(mkTupleTy Unboxed [doublePrimTy, doublePrimTy, doublePrimTy, doublePrimTy, doublePrimTy, doublePrimTy, doublePrimTy, doublePrimTy])] (doubleX8PrimTy)-primOpInfo (VecUnpackOp IntVec 16 W8) = mkGenPrimOp (fsLit "unpackInt8X16#") [] [int8X16PrimTy] ((mkTupleTy Unboxed [intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy]))-primOpInfo (VecUnpackOp IntVec 8 W16) = mkGenPrimOp (fsLit "unpackInt16X8#") [] [int16X8PrimTy] ((mkTupleTy Unboxed [intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy]))-primOpInfo (VecUnpackOp IntVec 4 W32) = mkGenPrimOp (fsLit "unpackInt32X4#") [] [int32X4PrimTy] ((mkTupleTy Unboxed [intPrimTy, intPrimTy, intPrimTy, intPrimTy]))+primOpInfo (VecUnpackOp IntVec 16 W8) = mkGenPrimOp (fsLit "unpackInt8X16#") [] [int8X16PrimTy] ((mkTupleTy Unboxed [int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy]))+primOpInfo (VecUnpackOp IntVec 8 W16) = mkGenPrimOp (fsLit "unpackInt16X8#") [] [int16X8PrimTy] ((mkTupleTy Unboxed [int16PrimTy, int16PrimTy, int16PrimTy, int16PrimTy, int16PrimTy, int16PrimTy, int16PrimTy, int16PrimTy]))+primOpInfo (VecUnpackOp IntVec 4 W32) = mkGenPrimOp (fsLit "unpackInt32X4#") [] [int32X4PrimTy] ((mkTupleTy Unboxed [int32PrimTy, int32PrimTy, int32PrimTy, int32PrimTy])) primOpInfo (VecUnpackOp IntVec 2 W64) = mkGenPrimOp (fsLit "unpackInt64X2#") [] [int64X2PrimTy] ((mkTupleTy Unboxed [intPrimTy, intPrimTy]))-primOpInfo (VecUnpackOp IntVec 32 W8) = mkGenPrimOp (fsLit "unpackInt8X32#") [] [int8X32PrimTy] ((mkTupleTy Unboxed [intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy]))-primOpInfo (VecUnpackOp IntVec 16 W16) = mkGenPrimOp (fsLit "unpackInt16X16#") [] [int16X16PrimTy] ((mkTupleTy Unboxed [intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy]))-primOpInfo (VecUnpackOp IntVec 8 W32) = mkGenPrimOp (fsLit "unpackInt32X8#") [] [int32X8PrimTy] ((mkTupleTy Unboxed [intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy]))+primOpInfo (VecUnpackOp IntVec 32 W8) = mkGenPrimOp (fsLit "unpackInt8X32#") [] [int8X32PrimTy] ((mkTupleTy Unboxed [int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy]))+primOpInfo (VecUnpackOp IntVec 16 W16) = mkGenPrimOp (fsLit "unpackInt16X16#") [] [int16X16PrimTy] ((mkTupleTy Unboxed [int16PrimTy, int16PrimTy, int16PrimTy, int16PrimTy, int16PrimTy, int16PrimTy, int16PrimTy, int16PrimTy, int16PrimTy, int16PrimTy, int16PrimTy, int16PrimTy, int16PrimTy, int16PrimTy, int16PrimTy, int16PrimTy]))+primOpInfo (VecUnpackOp IntVec 8 W32) = mkGenPrimOp (fsLit "unpackInt32X8#") [] [int32X8PrimTy] ((mkTupleTy Unboxed [int32PrimTy, int32PrimTy, int32PrimTy, int32PrimTy, int32PrimTy, int32PrimTy, int32PrimTy, int32PrimTy])) primOpInfo (VecUnpackOp IntVec 4 W64) = mkGenPrimOp (fsLit "unpackInt64X4#") [] [int64X4PrimTy] ((mkTupleTy Unboxed [intPrimTy, intPrimTy, intPrimTy, intPrimTy]))-primOpInfo (VecUnpackOp IntVec 64 W8) = mkGenPrimOp (fsLit "unpackInt8X64#") [] [int8X64PrimTy] ((mkTupleTy Unboxed [intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy]))-primOpInfo (VecUnpackOp IntVec 32 W16) = mkGenPrimOp (fsLit "unpackInt16X32#") [] [int16X32PrimTy] ((mkTupleTy Unboxed [intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy]))-primOpInfo (VecUnpackOp IntVec 16 W32) = mkGenPrimOp (fsLit "unpackInt32X16#") [] [int32X16PrimTy] ((mkTupleTy Unboxed [intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy]))+primOpInfo (VecUnpackOp IntVec 64 W8) = mkGenPrimOp (fsLit "unpackInt8X64#") [] [int8X64PrimTy] ((mkTupleTy Unboxed [int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy, int8PrimTy]))+primOpInfo (VecUnpackOp IntVec 32 W16) = mkGenPrimOp (fsLit "unpackInt16X32#") [] [int16X32PrimTy] ((mkTupleTy Unboxed [int16PrimTy, int16PrimTy, int16PrimTy, int16PrimTy, int16PrimTy, int16PrimTy, int16PrimTy, int16PrimTy, int16PrimTy, int16PrimTy, int16PrimTy, int16PrimTy, int16PrimTy, int16PrimTy, int16PrimTy, int16PrimTy, int16PrimTy, int16PrimTy, int16PrimTy, int16PrimTy, int16PrimTy, int16PrimTy, int16PrimTy, int16PrimTy, int16PrimTy, int16PrimTy, int16PrimTy, int16PrimTy, int16PrimTy, int16PrimTy, int16PrimTy, int16PrimTy]))+primOpInfo (VecUnpackOp IntVec 16 W32) = mkGenPrimOp (fsLit "unpackInt32X16#") [] [int32X16PrimTy] ((mkTupleTy Unboxed [int32PrimTy, int32PrimTy, int32PrimTy, int32PrimTy, int32PrimTy, int32PrimTy, int32PrimTy, int32PrimTy, int32PrimTy, int32PrimTy, int32PrimTy, int32PrimTy, int32PrimTy, int32PrimTy, int32PrimTy, int32PrimTy])) primOpInfo (VecUnpackOp IntVec 8 W64) = mkGenPrimOp (fsLit "unpackInt64X8#") [] [int64X8PrimTy] ((mkTupleTy Unboxed [intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy, intPrimTy])) primOpInfo (VecUnpackOp WordVec 16 W8) = mkGenPrimOp (fsLit "unpackWord8X16#") [] [word8X16PrimTy] ((mkTupleTy Unboxed [wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy])) primOpInfo (VecUnpackOp WordVec 8 W16) = mkGenPrimOp (fsLit "unpackWord16X8#") [] [word16X8PrimTy] ((mkTupleTy Unboxed [wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy]))-primOpInfo (VecUnpackOp WordVec 4 W32) = mkGenPrimOp (fsLit "unpackWord32X4#") [] [word32X4PrimTy] ((mkTupleTy Unboxed [wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy]))+primOpInfo (VecUnpackOp WordVec 4 W32) = mkGenPrimOp (fsLit "unpackWord32X4#") [] [word32X4PrimTy] ((mkTupleTy Unboxed [word32PrimTy, word32PrimTy, word32PrimTy, word32PrimTy])) primOpInfo (VecUnpackOp WordVec 2 W64) = mkGenPrimOp (fsLit "unpackWord64X2#") [] [word64X2PrimTy] ((mkTupleTy Unboxed [wordPrimTy, wordPrimTy])) primOpInfo (VecUnpackOp WordVec 32 W8) = mkGenPrimOp (fsLit "unpackWord8X32#") [] [word8X32PrimTy] ((mkTupleTy Unboxed [wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy])) primOpInfo (VecUnpackOp WordVec 16 W16) = mkGenPrimOp (fsLit "unpackWord16X16#") [] [word16X16PrimTy] ((mkTupleTy Unboxed [wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy]))-primOpInfo (VecUnpackOp WordVec 8 W32) = mkGenPrimOp (fsLit "unpackWord32X8#") [] [word32X8PrimTy] ((mkTupleTy Unboxed [wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy]))+primOpInfo (VecUnpackOp WordVec 8 W32) = mkGenPrimOp (fsLit "unpackWord32X8#") [] [word32X8PrimTy] ((mkTupleTy Unboxed [word32PrimTy, word32PrimTy, word32PrimTy, word32PrimTy, word32PrimTy, word32PrimTy, word32PrimTy, word32PrimTy])) primOpInfo (VecUnpackOp WordVec 4 W64) = mkGenPrimOp (fsLit "unpackWord64X4#") [] [word64X4PrimTy] ((mkTupleTy Unboxed [wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy])) primOpInfo (VecUnpackOp WordVec 64 W8) = mkGenPrimOp (fsLit "unpackWord8X64#") [] [word8X64PrimTy] ((mkTupleTy Unboxed [wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy])) primOpInfo (VecUnpackOp WordVec 32 W16) = mkGenPrimOp (fsLit "unpackWord16X32#") [] [word16X32PrimTy] ((mkTupleTy Unboxed [wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy]))-primOpInfo (VecUnpackOp WordVec 16 W32) = mkGenPrimOp (fsLit "unpackWord32X16#") [] [word32X16PrimTy] ((mkTupleTy Unboxed [wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy]))+primOpInfo (VecUnpackOp WordVec 16 W32) = mkGenPrimOp (fsLit "unpackWord32X16#") [] [word32X16PrimTy] ((mkTupleTy Unboxed [word32PrimTy, word32PrimTy, word32PrimTy, word32PrimTy, word32PrimTy, word32PrimTy, word32PrimTy, word32PrimTy, word32PrimTy, word32PrimTy, word32PrimTy, word32PrimTy, word32PrimTy, word32PrimTy, word32PrimTy, word32PrimTy])) primOpInfo (VecUnpackOp WordVec 8 W64) = mkGenPrimOp (fsLit "unpackWord64X8#") [] [word64X8PrimTy] ((mkTupleTy Unboxed [wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy, wordPrimTy])) primOpInfo (VecUnpackOp FloatVec 4 W32) = mkGenPrimOp (fsLit "unpackFloatX4#") [] [floatX4PrimTy] ((mkTupleTy Unboxed [floatPrimTy, floatPrimTy, floatPrimTy, floatPrimTy])) primOpInfo (VecUnpackOp FloatVec 2 W64) = mkGenPrimOp (fsLit "unpackDoubleX2#") [] [doubleX2PrimTy] ((mkTupleTy Unboxed [doublePrimTy, doublePrimTy]))@@ -711,29 +713,29 @@ primOpInfo (VecUnpackOp FloatVec 4 W64) = mkGenPrimOp (fsLit "unpackDoubleX4#") [] [doubleX4PrimTy] ((mkTupleTy Unboxed [doublePrimTy, doublePrimTy, doublePrimTy, doublePrimTy])) primOpInfo (VecUnpackOp FloatVec 16 W32) = mkGenPrimOp (fsLit "unpackFloatX16#") [] [floatX16PrimTy] ((mkTupleTy Unboxed [floatPrimTy, floatPrimTy, floatPrimTy, floatPrimTy, floatPrimTy, floatPrimTy, floatPrimTy, floatPrimTy, floatPrimTy, floatPrimTy, floatPrimTy, floatPrimTy, floatPrimTy, floatPrimTy, floatPrimTy, floatPrimTy])) primOpInfo (VecUnpackOp FloatVec 8 W64) = mkGenPrimOp (fsLit "unpackDoubleX8#") [] [doubleX8PrimTy] ((mkTupleTy Unboxed [doublePrimTy, doublePrimTy, doublePrimTy, doublePrimTy, doublePrimTy, doublePrimTy, doublePrimTy, doublePrimTy]))-primOpInfo (VecInsertOp IntVec 16 W8) = mkGenPrimOp (fsLit "insertInt8X16#") [] [int8X16PrimTy, intPrimTy, intPrimTy] (int8X16PrimTy)-primOpInfo (VecInsertOp IntVec 8 W16) = mkGenPrimOp (fsLit "insertInt16X8#") [] [int16X8PrimTy, intPrimTy, intPrimTy] (int16X8PrimTy)-primOpInfo (VecInsertOp IntVec 4 W32) = mkGenPrimOp (fsLit "insertInt32X4#") [] [int32X4PrimTy, intPrimTy, intPrimTy] (int32X4PrimTy)+primOpInfo (VecInsertOp IntVec 16 W8) = mkGenPrimOp (fsLit "insertInt8X16#") [] [int8X16PrimTy, int8PrimTy, intPrimTy] (int8X16PrimTy)+primOpInfo (VecInsertOp IntVec 8 W16) = mkGenPrimOp (fsLit "insertInt16X8#") [] [int16X8PrimTy, int16PrimTy, intPrimTy] (int16X8PrimTy)+primOpInfo (VecInsertOp IntVec 4 W32) = mkGenPrimOp (fsLit "insertInt32X4#") [] [int32X4PrimTy, int32PrimTy, intPrimTy] (int32X4PrimTy) primOpInfo (VecInsertOp IntVec 2 W64) = mkGenPrimOp (fsLit "insertInt64X2#") [] [int64X2PrimTy, intPrimTy, intPrimTy] (int64X2PrimTy)-primOpInfo (VecInsertOp IntVec 32 W8) = mkGenPrimOp (fsLit "insertInt8X32#") [] [int8X32PrimTy, intPrimTy, intPrimTy] (int8X32PrimTy)-primOpInfo (VecInsertOp IntVec 16 W16) = mkGenPrimOp (fsLit "insertInt16X16#") [] [int16X16PrimTy, intPrimTy, intPrimTy] (int16X16PrimTy)-primOpInfo (VecInsertOp IntVec 8 W32) = mkGenPrimOp (fsLit "insertInt32X8#") [] [int32X8PrimTy, intPrimTy, intPrimTy] (int32X8PrimTy)+primOpInfo (VecInsertOp IntVec 32 W8) = mkGenPrimOp (fsLit "insertInt8X32#") [] [int8X32PrimTy, int8PrimTy, intPrimTy] (int8X32PrimTy)+primOpInfo (VecInsertOp IntVec 16 W16) = mkGenPrimOp (fsLit "insertInt16X16#") [] [int16X16PrimTy, int16PrimTy, intPrimTy] (int16X16PrimTy)+primOpInfo (VecInsertOp IntVec 8 W32) = mkGenPrimOp (fsLit "insertInt32X8#") [] [int32X8PrimTy, int32PrimTy, intPrimTy] (int32X8PrimTy) primOpInfo (VecInsertOp IntVec 4 W64) = mkGenPrimOp (fsLit "insertInt64X4#") [] [int64X4PrimTy, intPrimTy, intPrimTy] (int64X4PrimTy)-primOpInfo (VecInsertOp IntVec 64 W8) = mkGenPrimOp (fsLit "insertInt8X64#") [] [int8X64PrimTy, intPrimTy, intPrimTy] (int8X64PrimTy)-primOpInfo (VecInsertOp IntVec 32 W16) = mkGenPrimOp (fsLit "insertInt16X32#") [] [int16X32PrimTy, intPrimTy, intPrimTy] (int16X32PrimTy)-primOpInfo (VecInsertOp IntVec 16 W32) = mkGenPrimOp (fsLit "insertInt32X16#") [] [int32X16PrimTy, intPrimTy, intPrimTy] (int32X16PrimTy)+primOpInfo (VecInsertOp IntVec 64 W8) = mkGenPrimOp (fsLit "insertInt8X64#") [] [int8X64PrimTy, int8PrimTy, intPrimTy] (int8X64PrimTy)+primOpInfo (VecInsertOp IntVec 32 W16) = mkGenPrimOp (fsLit "insertInt16X32#") [] [int16X32PrimTy, int16PrimTy, intPrimTy] (int16X32PrimTy)+primOpInfo (VecInsertOp IntVec 16 W32) = mkGenPrimOp (fsLit "insertInt32X16#") [] [int32X16PrimTy, int32PrimTy, intPrimTy] (int32X16PrimTy) primOpInfo (VecInsertOp IntVec 8 W64) = mkGenPrimOp (fsLit "insertInt64X8#") [] [int64X8PrimTy, intPrimTy, intPrimTy] (int64X8PrimTy) primOpInfo (VecInsertOp WordVec 16 W8) = mkGenPrimOp (fsLit "insertWord8X16#") [] [word8X16PrimTy, wordPrimTy, intPrimTy] (word8X16PrimTy) primOpInfo (VecInsertOp WordVec 8 W16) = mkGenPrimOp (fsLit "insertWord16X8#") [] [word16X8PrimTy, wordPrimTy, intPrimTy] (word16X8PrimTy)-primOpInfo (VecInsertOp WordVec 4 W32) = mkGenPrimOp (fsLit "insertWord32X4#") [] [word32X4PrimTy, wordPrimTy, intPrimTy] (word32X4PrimTy)+primOpInfo (VecInsertOp WordVec 4 W32) = mkGenPrimOp (fsLit "insertWord32X4#") [] [word32X4PrimTy, word32PrimTy, intPrimTy] (word32X4PrimTy) primOpInfo (VecInsertOp WordVec 2 W64) = mkGenPrimOp (fsLit "insertWord64X2#") [] [word64X2PrimTy, wordPrimTy, intPrimTy] (word64X2PrimTy) primOpInfo (VecInsertOp WordVec 32 W8) = mkGenPrimOp (fsLit "insertWord8X32#") [] [word8X32PrimTy, wordPrimTy, intPrimTy] (word8X32PrimTy) primOpInfo (VecInsertOp WordVec 16 W16) = mkGenPrimOp (fsLit "insertWord16X16#") [] [word16X16PrimTy, wordPrimTy, intPrimTy] (word16X16PrimTy)-primOpInfo (VecInsertOp WordVec 8 W32) = mkGenPrimOp (fsLit "insertWord32X8#") [] [word32X8PrimTy, wordPrimTy, intPrimTy] (word32X8PrimTy)+primOpInfo (VecInsertOp WordVec 8 W32) = mkGenPrimOp (fsLit "insertWord32X8#") [] [word32X8PrimTy, word32PrimTy, intPrimTy] (word32X8PrimTy) primOpInfo (VecInsertOp WordVec 4 W64) = mkGenPrimOp (fsLit "insertWord64X4#") [] [word64X4PrimTy, wordPrimTy, intPrimTy] (word64X4PrimTy) primOpInfo (VecInsertOp WordVec 64 W8) = mkGenPrimOp (fsLit "insertWord8X64#") [] [word8X64PrimTy, wordPrimTy, intPrimTy] (word8X64PrimTy) primOpInfo (VecInsertOp WordVec 32 W16) = mkGenPrimOp (fsLit "insertWord16X32#") [] [word16X32PrimTy, wordPrimTy, intPrimTy] (word16X32PrimTy)-primOpInfo (VecInsertOp WordVec 16 W32) = mkGenPrimOp (fsLit "insertWord32X16#") [] [word32X16PrimTy, wordPrimTy, intPrimTy] (word32X16PrimTy)+primOpInfo (VecInsertOp WordVec 16 W32) = mkGenPrimOp (fsLit "insertWord32X16#") [] [word32X16PrimTy, word32PrimTy, intPrimTy] (word32X16PrimTy) primOpInfo (VecInsertOp WordVec 8 W64) = mkGenPrimOp (fsLit "insertWord64X8#") [] [word64X8PrimTy, wordPrimTy, intPrimTy] (word64X8PrimTy) primOpInfo (VecInsertOp FloatVec 4 W32) = mkGenPrimOp (fsLit "insertFloatX4#") [] [floatX4PrimTy, floatPrimTy, intPrimTy] (floatX4PrimTy) primOpInfo (VecInsertOp FloatVec 2 W64) = mkGenPrimOp (fsLit "insertDoubleX2#") [] [doubleX2PrimTy, doublePrimTy, intPrimTy] (doubleX2PrimTy)
ghc-lib/stage0/compiler/build/primop-strictness.hs-incl view
@@ -1,19 +1,19 @@-primOpStrictness CatchOp = \ _arity -> mkClosedStrictSig [ lazyApply1Dmd+primOpStrictness CatchOp = \ _arity -> mkClosedDmdSig [ lazyApply1Dmd , lazyApply2Dmd , topDmd] topDiv -primOpStrictness RaiseOp = \ _arity -> mkClosedStrictSig [topDmd] botDiv -primOpStrictness RaiseIOOp = \ _arity -> mkClosedStrictSig [topDmd, topDmd] exnDiv -primOpStrictness MaskAsyncExceptionsOp = \ _arity -> mkClosedStrictSig [strictOnceApply1Dmd,topDmd] topDiv -primOpStrictness MaskUninterruptibleOp = \ _arity -> mkClosedStrictSig [strictOnceApply1Dmd,topDmd] topDiv -primOpStrictness UnmaskAsyncExceptionsOp = \ _arity -> mkClosedStrictSig [strictOnceApply1Dmd,topDmd] topDiv -primOpStrictness AtomicallyOp = \ _arity -> mkClosedStrictSig [strictManyApply1Dmd,topDmd] topDiv -primOpStrictness RetryOp = \ _arity -> mkClosedStrictSig [topDmd] botDiv -primOpStrictness CatchRetryOp = \ _arity -> mkClosedStrictSig [ lazyApply1Dmd+primOpStrictness RaiseOp = \ _arity -> mkClosedDmdSig [topDmd] botDiv +primOpStrictness RaiseIOOp = \ _arity -> mkClosedDmdSig [topDmd, topDmd] exnDiv +primOpStrictness MaskAsyncExceptionsOp = \ _arity -> mkClosedDmdSig [strictOnceApply1Dmd,topDmd] topDiv +primOpStrictness MaskUninterruptibleOp = \ _arity -> mkClosedDmdSig [strictOnceApply1Dmd,topDmd] topDiv +primOpStrictness UnmaskAsyncExceptionsOp = \ _arity -> mkClosedDmdSig [strictOnceApply1Dmd,topDmd] topDiv +primOpStrictness AtomicallyOp = \ _arity -> mkClosedDmdSig [strictManyApply1Dmd,topDmd] topDiv +primOpStrictness RetryOp = \ _arity -> mkClosedDmdSig [topDmd] botDiv +primOpStrictness CatchRetryOp = \ _arity -> mkClosedDmdSig [ lazyApply1Dmd , lazyApply1Dmd , topDmd ] topDiv -primOpStrictness CatchSTMOp = \ _arity -> mkClosedStrictSig [ lazyApply1Dmd+primOpStrictness CatchSTMOp = \ _arity -> mkClosedDmdSig [ lazyApply1Dmd , lazyApply2Dmd , topDmd ] topDiv -primOpStrictness KeepAliveOp = \ _arity -> mkClosedStrictSig [topDmd, topDmd, strictOnceApply1Dmd] topDiv -primOpStrictness DataToTagOp = \ _arity -> mkClosedStrictSig [evalDmd] topDiv -primOpStrictness _ = \ arity -> mkClosedStrictSig (replicate arity topDmd) topDiv +primOpStrictness KeepAliveOp = \ _arity -> mkClosedDmdSig [topDmd, topDmd, strictOnceApply1Dmd] topDiv +primOpStrictness DataToTagOp = \ _arity -> mkClosedDmdSig [evalDmd] topDiv +primOpStrictness _ = \ arity -> mkClosedDmdSig (replicate arity topDmd) topDiv
ghc-lib/stage0/compiler/build/primop-tag.hs-incl view
@@ -1,1284 +1,1286 @@ maxPrimOpTag :: Int-maxPrimOpTag = 1281-primOpTag :: PrimOp -> Int-primOpTag CharGtOp = 1-primOpTag CharGeOp = 2-primOpTag CharEqOp = 3-primOpTag CharNeOp = 4-primOpTag CharLtOp = 5-primOpTag CharLeOp = 6-primOpTag OrdOp = 7-primOpTag Int8ToIntOp = 8-primOpTag IntToInt8Op = 9-primOpTag Int8NegOp = 10-primOpTag Int8AddOp = 11-primOpTag Int8SubOp = 12-primOpTag Int8MulOp = 13-primOpTag Int8QuotOp = 14-primOpTag Int8RemOp = 15-primOpTag Int8QuotRemOp = 16-primOpTag Int8SllOp = 17-primOpTag Int8SraOp = 18-primOpTag Int8SrlOp = 19-primOpTag Int8ToWord8Op = 20-primOpTag Int8EqOp = 21-primOpTag Int8GeOp = 22-primOpTag Int8GtOp = 23-primOpTag Int8LeOp = 24-primOpTag Int8LtOp = 25-primOpTag Int8NeOp = 26-primOpTag Word8ToWordOp = 27-primOpTag WordToWord8Op = 28-primOpTag Word8AddOp = 29-primOpTag Word8SubOp = 30-primOpTag Word8MulOp = 31-primOpTag Word8QuotOp = 32-primOpTag Word8RemOp = 33-primOpTag Word8QuotRemOp = 34-primOpTag Word8AndOp = 35-primOpTag Word8OrOp = 36-primOpTag Word8XorOp = 37-primOpTag Word8NotOp = 38-primOpTag Word8SllOp = 39-primOpTag Word8SrlOp = 40-primOpTag Word8ToInt8Op = 41-primOpTag Word8EqOp = 42-primOpTag Word8GeOp = 43-primOpTag Word8GtOp = 44-primOpTag Word8LeOp = 45-primOpTag Word8LtOp = 46-primOpTag Word8NeOp = 47-primOpTag Int16ToIntOp = 48-primOpTag IntToInt16Op = 49-primOpTag Int16NegOp = 50-primOpTag Int16AddOp = 51-primOpTag Int16SubOp = 52-primOpTag Int16MulOp = 53-primOpTag Int16QuotOp = 54-primOpTag Int16RemOp = 55-primOpTag Int16QuotRemOp = 56-primOpTag Int16SllOp = 57-primOpTag Int16SraOp = 58-primOpTag Int16SrlOp = 59-primOpTag Int16ToWord16Op = 60-primOpTag Int16EqOp = 61-primOpTag Int16GeOp = 62-primOpTag Int16GtOp = 63-primOpTag Int16LeOp = 64-primOpTag Int16LtOp = 65-primOpTag Int16NeOp = 66-primOpTag Word16ToWordOp = 67-primOpTag WordToWord16Op = 68-primOpTag Word16AddOp = 69-primOpTag Word16SubOp = 70-primOpTag Word16MulOp = 71-primOpTag Word16QuotOp = 72-primOpTag Word16RemOp = 73-primOpTag Word16QuotRemOp = 74-primOpTag Word16AndOp = 75-primOpTag Word16OrOp = 76-primOpTag Word16XorOp = 77-primOpTag Word16NotOp = 78-primOpTag Word16SllOp = 79-primOpTag Word16SrlOp = 80-primOpTag Word16ToInt16Op = 81-primOpTag Word16EqOp = 82-primOpTag Word16GeOp = 83-primOpTag Word16GtOp = 84-primOpTag Word16LeOp = 85-primOpTag Word16LtOp = 86-primOpTag Word16NeOp = 87-primOpTag Int32ToIntOp = 88-primOpTag IntToInt32Op = 89-primOpTag Int32NegOp = 90-primOpTag Int32AddOp = 91-primOpTag Int32SubOp = 92-primOpTag Int32MulOp = 93-primOpTag Int32QuotOp = 94-primOpTag Int32RemOp = 95-primOpTag Int32QuotRemOp = 96-primOpTag Int32SllOp = 97-primOpTag Int32SraOp = 98-primOpTag Int32SrlOp = 99-primOpTag Int32ToWord32Op = 100-primOpTag Int32EqOp = 101-primOpTag Int32GeOp = 102-primOpTag Int32GtOp = 103-primOpTag Int32LeOp = 104-primOpTag Int32LtOp = 105-primOpTag Int32NeOp = 106-primOpTag Word32ToWordOp = 107-primOpTag WordToWord32Op = 108-primOpTag Word32AddOp = 109-primOpTag Word32SubOp = 110-primOpTag Word32MulOp = 111-primOpTag Word32QuotOp = 112-primOpTag Word32RemOp = 113-primOpTag Word32QuotRemOp = 114-primOpTag Word32AndOp = 115-primOpTag Word32OrOp = 116-primOpTag Word32XorOp = 117-primOpTag Word32NotOp = 118-primOpTag Word32SllOp = 119-primOpTag Word32SrlOp = 120-primOpTag Word32ToInt32Op = 121-primOpTag Word32EqOp = 122-primOpTag Word32GeOp = 123-primOpTag Word32GtOp = 124-primOpTag Word32LeOp = 125-primOpTag Word32LtOp = 126-primOpTag Word32NeOp = 127-primOpTag IntAddOp = 128-primOpTag IntSubOp = 129-primOpTag IntMulOp = 130-primOpTag IntMul2Op = 131-primOpTag IntMulMayOfloOp = 132-primOpTag IntQuotOp = 133-primOpTag IntRemOp = 134-primOpTag IntQuotRemOp = 135-primOpTag IntAndOp = 136-primOpTag IntOrOp = 137-primOpTag IntXorOp = 138-primOpTag IntNotOp = 139-primOpTag IntNegOp = 140-primOpTag IntAddCOp = 141-primOpTag IntSubCOp = 142-primOpTag IntGtOp = 143-primOpTag IntGeOp = 144-primOpTag IntEqOp = 145-primOpTag IntNeOp = 146-primOpTag IntLtOp = 147-primOpTag IntLeOp = 148-primOpTag ChrOp = 149-primOpTag IntToWordOp = 150-primOpTag IntToFloatOp = 151-primOpTag IntToDoubleOp = 152-primOpTag WordToFloatOp = 153-primOpTag WordToDoubleOp = 154-primOpTag IntSllOp = 155-primOpTag IntSraOp = 156-primOpTag IntSrlOp = 157-primOpTag WordAddOp = 158-primOpTag WordAddCOp = 159-primOpTag WordSubCOp = 160-primOpTag WordAdd2Op = 161-primOpTag WordSubOp = 162-primOpTag WordMulOp = 163-primOpTag WordMul2Op = 164-primOpTag WordQuotOp = 165-primOpTag WordRemOp = 166-primOpTag WordQuotRemOp = 167-primOpTag WordQuotRem2Op = 168-primOpTag WordAndOp = 169-primOpTag WordOrOp = 170-primOpTag WordXorOp = 171-primOpTag WordNotOp = 172-primOpTag WordSllOp = 173-primOpTag WordSrlOp = 174-primOpTag WordToIntOp = 175-primOpTag WordGtOp = 176-primOpTag WordGeOp = 177-primOpTag WordEqOp = 178-primOpTag WordNeOp = 179-primOpTag WordLtOp = 180-primOpTag WordLeOp = 181-primOpTag PopCnt8Op = 182-primOpTag PopCnt16Op = 183-primOpTag PopCnt32Op = 184-primOpTag PopCnt64Op = 185-primOpTag PopCntOp = 186-primOpTag Pdep8Op = 187-primOpTag Pdep16Op = 188-primOpTag Pdep32Op = 189-primOpTag Pdep64Op = 190-primOpTag PdepOp = 191-primOpTag Pext8Op = 192-primOpTag Pext16Op = 193-primOpTag Pext32Op = 194-primOpTag Pext64Op = 195-primOpTag PextOp = 196-primOpTag Clz8Op = 197-primOpTag Clz16Op = 198-primOpTag Clz32Op = 199-primOpTag Clz64Op = 200-primOpTag ClzOp = 201-primOpTag Ctz8Op = 202-primOpTag Ctz16Op = 203-primOpTag Ctz32Op = 204-primOpTag Ctz64Op = 205-primOpTag CtzOp = 206-primOpTag BSwap16Op = 207-primOpTag BSwap32Op = 208-primOpTag BSwap64Op = 209-primOpTag BSwapOp = 210-primOpTag BRev8Op = 211-primOpTag BRev16Op = 212-primOpTag BRev32Op = 213-primOpTag BRev64Op = 214-primOpTag BRevOp = 215-primOpTag Narrow8IntOp = 216-primOpTag Narrow16IntOp = 217-primOpTag Narrow32IntOp = 218-primOpTag Narrow8WordOp = 219-primOpTag Narrow16WordOp = 220-primOpTag Narrow32WordOp = 221-primOpTag DoubleGtOp = 222-primOpTag DoubleGeOp = 223-primOpTag DoubleEqOp = 224-primOpTag DoubleNeOp = 225-primOpTag DoubleLtOp = 226-primOpTag DoubleLeOp = 227-primOpTag DoubleAddOp = 228-primOpTag DoubleSubOp = 229-primOpTag DoubleMulOp = 230-primOpTag DoubleDivOp = 231-primOpTag DoubleNegOp = 232-primOpTag DoubleFabsOp = 233-primOpTag DoubleToIntOp = 234-primOpTag DoubleToFloatOp = 235-primOpTag DoubleExpOp = 236-primOpTag DoubleExpM1Op = 237-primOpTag DoubleLogOp = 238-primOpTag DoubleLog1POp = 239-primOpTag DoubleSqrtOp = 240-primOpTag DoubleSinOp = 241-primOpTag DoubleCosOp = 242-primOpTag DoubleTanOp = 243-primOpTag DoubleAsinOp = 244-primOpTag DoubleAcosOp = 245-primOpTag DoubleAtanOp = 246-primOpTag DoubleSinhOp = 247-primOpTag DoubleCoshOp = 248-primOpTag DoubleTanhOp = 249-primOpTag DoubleAsinhOp = 250-primOpTag DoubleAcoshOp = 251-primOpTag DoubleAtanhOp = 252-primOpTag DoublePowerOp = 253-primOpTag DoubleDecode_2IntOp = 254-primOpTag DoubleDecode_Int64Op = 255-primOpTag FloatGtOp = 256-primOpTag FloatGeOp = 257-primOpTag FloatEqOp = 258-primOpTag FloatNeOp = 259-primOpTag FloatLtOp = 260-primOpTag FloatLeOp = 261-primOpTag FloatAddOp = 262-primOpTag FloatSubOp = 263-primOpTag FloatMulOp = 264-primOpTag FloatDivOp = 265-primOpTag FloatNegOp = 266-primOpTag FloatFabsOp = 267-primOpTag FloatToIntOp = 268-primOpTag FloatExpOp = 269-primOpTag FloatExpM1Op = 270-primOpTag FloatLogOp = 271-primOpTag FloatLog1POp = 272-primOpTag FloatSqrtOp = 273-primOpTag FloatSinOp = 274-primOpTag FloatCosOp = 275-primOpTag FloatTanOp = 276-primOpTag FloatAsinOp = 277-primOpTag FloatAcosOp = 278-primOpTag FloatAtanOp = 279-primOpTag FloatSinhOp = 280-primOpTag FloatCoshOp = 281-primOpTag FloatTanhOp = 282-primOpTag FloatAsinhOp = 283-primOpTag FloatAcoshOp = 284-primOpTag FloatAtanhOp = 285-primOpTag FloatPowerOp = 286-primOpTag FloatToDoubleOp = 287-primOpTag FloatDecode_IntOp = 288-primOpTag NewArrayOp = 289-primOpTag SameMutableArrayOp = 290-primOpTag ReadArrayOp = 291-primOpTag WriteArrayOp = 292-primOpTag SizeofArrayOp = 293-primOpTag SizeofMutableArrayOp = 294-primOpTag IndexArrayOp = 295-primOpTag UnsafeFreezeArrayOp = 296-primOpTag UnsafeThawArrayOp = 297-primOpTag CopyArrayOp = 298-primOpTag CopyMutableArrayOp = 299-primOpTag CloneArrayOp = 300-primOpTag CloneMutableArrayOp = 301-primOpTag FreezeArrayOp = 302-primOpTag ThawArrayOp = 303-primOpTag CasArrayOp = 304-primOpTag NewSmallArrayOp = 305-primOpTag SameSmallMutableArrayOp = 306-primOpTag ShrinkSmallMutableArrayOp_Char = 307-primOpTag ReadSmallArrayOp = 308-primOpTag WriteSmallArrayOp = 309-primOpTag SizeofSmallArrayOp = 310-primOpTag SizeofSmallMutableArrayOp = 311-primOpTag GetSizeofSmallMutableArrayOp = 312-primOpTag IndexSmallArrayOp = 313-primOpTag UnsafeFreezeSmallArrayOp = 314-primOpTag UnsafeThawSmallArrayOp = 315-primOpTag CopySmallArrayOp = 316-primOpTag CopySmallMutableArrayOp = 317-primOpTag CloneSmallArrayOp = 318-primOpTag CloneSmallMutableArrayOp = 319-primOpTag FreezeSmallArrayOp = 320-primOpTag ThawSmallArrayOp = 321-primOpTag CasSmallArrayOp = 322-primOpTag NewByteArrayOp_Char = 323-primOpTag NewPinnedByteArrayOp_Char = 324-primOpTag NewAlignedPinnedByteArrayOp_Char = 325-primOpTag MutableByteArrayIsPinnedOp = 326-primOpTag ByteArrayIsPinnedOp = 327-primOpTag ByteArrayContents_Char = 328-primOpTag SameMutableByteArrayOp = 329-primOpTag ShrinkMutableByteArrayOp_Char = 330-primOpTag ResizeMutableByteArrayOp_Char = 331-primOpTag UnsafeFreezeByteArrayOp = 332-primOpTag SizeofByteArrayOp = 333-primOpTag SizeofMutableByteArrayOp = 334-primOpTag GetSizeofMutableByteArrayOp = 335-primOpTag IndexByteArrayOp_Char = 336-primOpTag IndexByteArrayOp_WideChar = 337-primOpTag IndexByteArrayOp_Int = 338-primOpTag IndexByteArrayOp_Word = 339-primOpTag IndexByteArrayOp_Addr = 340-primOpTag IndexByteArrayOp_Float = 341-primOpTag IndexByteArrayOp_Double = 342-primOpTag IndexByteArrayOp_StablePtr = 343-primOpTag IndexByteArrayOp_Int8 = 344-primOpTag IndexByteArrayOp_Int16 = 345-primOpTag IndexByteArrayOp_Int32 = 346-primOpTag IndexByteArrayOp_Int64 = 347-primOpTag IndexByteArrayOp_Word8 = 348-primOpTag IndexByteArrayOp_Word16 = 349-primOpTag IndexByteArrayOp_Word32 = 350-primOpTag IndexByteArrayOp_Word64 = 351-primOpTag IndexByteArrayOp_Word8AsChar = 352-primOpTag IndexByteArrayOp_Word8AsWideChar = 353-primOpTag IndexByteArrayOp_Word8AsInt = 354-primOpTag IndexByteArrayOp_Word8AsWord = 355-primOpTag IndexByteArrayOp_Word8AsAddr = 356-primOpTag IndexByteArrayOp_Word8AsFloat = 357-primOpTag IndexByteArrayOp_Word8AsDouble = 358-primOpTag IndexByteArrayOp_Word8AsStablePtr = 359-primOpTag IndexByteArrayOp_Word8AsInt16 = 360-primOpTag IndexByteArrayOp_Word8AsInt32 = 361-primOpTag IndexByteArrayOp_Word8AsInt64 = 362-primOpTag IndexByteArrayOp_Word8AsWord16 = 363-primOpTag IndexByteArrayOp_Word8AsWord32 = 364-primOpTag IndexByteArrayOp_Word8AsWord64 = 365-primOpTag ReadByteArrayOp_Char = 366-primOpTag ReadByteArrayOp_WideChar = 367-primOpTag ReadByteArrayOp_Int = 368-primOpTag ReadByteArrayOp_Word = 369-primOpTag ReadByteArrayOp_Addr = 370-primOpTag ReadByteArrayOp_Float = 371-primOpTag ReadByteArrayOp_Double = 372-primOpTag ReadByteArrayOp_StablePtr = 373-primOpTag ReadByteArrayOp_Int8 = 374-primOpTag ReadByteArrayOp_Int16 = 375-primOpTag ReadByteArrayOp_Int32 = 376-primOpTag ReadByteArrayOp_Int64 = 377-primOpTag ReadByteArrayOp_Word8 = 378-primOpTag ReadByteArrayOp_Word16 = 379-primOpTag ReadByteArrayOp_Word32 = 380-primOpTag ReadByteArrayOp_Word64 = 381-primOpTag ReadByteArrayOp_Word8AsChar = 382-primOpTag ReadByteArrayOp_Word8AsWideChar = 383-primOpTag ReadByteArrayOp_Word8AsInt = 384-primOpTag ReadByteArrayOp_Word8AsWord = 385-primOpTag ReadByteArrayOp_Word8AsAddr = 386-primOpTag ReadByteArrayOp_Word8AsFloat = 387-primOpTag ReadByteArrayOp_Word8AsDouble = 388-primOpTag ReadByteArrayOp_Word8AsStablePtr = 389-primOpTag ReadByteArrayOp_Word8AsInt16 = 390-primOpTag ReadByteArrayOp_Word8AsInt32 = 391-primOpTag ReadByteArrayOp_Word8AsInt64 = 392-primOpTag ReadByteArrayOp_Word8AsWord16 = 393-primOpTag ReadByteArrayOp_Word8AsWord32 = 394-primOpTag ReadByteArrayOp_Word8AsWord64 = 395-primOpTag WriteByteArrayOp_Char = 396-primOpTag WriteByteArrayOp_WideChar = 397-primOpTag WriteByteArrayOp_Int = 398-primOpTag WriteByteArrayOp_Word = 399-primOpTag WriteByteArrayOp_Addr = 400-primOpTag WriteByteArrayOp_Float = 401-primOpTag WriteByteArrayOp_Double = 402-primOpTag WriteByteArrayOp_StablePtr = 403-primOpTag WriteByteArrayOp_Int8 = 404-primOpTag WriteByteArrayOp_Int16 = 405-primOpTag WriteByteArrayOp_Int32 = 406-primOpTag WriteByteArrayOp_Int64 = 407-primOpTag WriteByteArrayOp_Word8 = 408-primOpTag WriteByteArrayOp_Word16 = 409-primOpTag WriteByteArrayOp_Word32 = 410-primOpTag WriteByteArrayOp_Word64 = 411-primOpTag WriteByteArrayOp_Word8AsChar = 412-primOpTag WriteByteArrayOp_Word8AsWideChar = 413-primOpTag WriteByteArrayOp_Word8AsInt = 414-primOpTag WriteByteArrayOp_Word8AsWord = 415-primOpTag WriteByteArrayOp_Word8AsAddr = 416-primOpTag WriteByteArrayOp_Word8AsFloat = 417-primOpTag WriteByteArrayOp_Word8AsDouble = 418-primOpTag WriteByteArrayOp_Word8AsStablePtr = 419-primOpTag WriteByteArrayOp_Word8AsInt16 = 420-primOpTag WriteByteArrayOp_Word8AsInt32 = 421-primOpTag WriteByteArrayOp_Word8AsInt64 = 422-primOpTag WriteByteArrayOp_Word8AsWord16 = 423-primOpTag WriteByteArrayOp_Word8AsWord32 = 424-primOpTag WriteByteArrayOp_Word8AsWord64 = 425-primOpTag CompareByteArraysOp = 426-primOpTag CopyByteArrayOp = 427-primOpTag CopyMutableByteArrayOp = 428-primOpTag CopyByteArrayToAddrOp = 429-primOpTag CopyMutableByteArrayToAddrOp = 430-primOpTag CopyAddrToByteArrayOp = 431-primOpTag SetByteArrayOp = 432-primOpTag AtomicReadByteArrayOp_Int = 433-primOpTag AtomicWriteByteArrayOp_Int = 434-primOpTag CasByteArrayOp_Int = 435-primOpTag FetchAddByteArrayOp_Int = 436-primOpTag FetchSubByteArrayOp_Int = 437-primOpTag FetchAndByteArrayOp_Int = 438-primOpTag FetchNandByteArrayOp_Int = 439-primOpTag FetchOrByteArrayOp_Int = 440-primOpTag FetchXorByteArrayOp_Int = 441-primOpTag NewArrayArrayOp = 442-primOpTag SameMutableArrayArrayOp = 443-primOpTag UnsafeFreezeArrayArrayOp = 444-primOpTag SizeofArrayArrayOp = 445-primOpTag SizeofMutableArrayArrayOp = 446-primOpTag IndexArrayArrayOp_ByteArray = 447-primOpTag IndexArrayArrayOp_ArrayArray = 448-primOpTag ReadArrayArrayOp_ByteArray = 449-primOpTag ReadArrayArrayOp_MutableByteArray = 450-primOpTag ReadArrayArrayOp_ArrayArray = 451-primOpTag ReadArrayArrayOp_MutableArrayArray = 452-primOpTag WriteArrayArrayOp_ByteArray = 453-primOpTag WriteArrayArrayOp_MutableByteArray = 454-primOpTag WriteArrayArrayOp_ArrayArray = 455-primOpTag WriteArrayArrayOp_MutableArrayArray = 456-primOpTag CopyArrayArrayOp = 457-primOpTag CopyMutableArrayArrayOp = 458-primOpTag AddrAddOp = 459-primOpTag AddrSubOp = 460-primOpTag AddrRemOp = 461-primOpTag AddrToIntOp = 462-primOpTag IntToAddrOp = 463-primOpTag AddrGtOp = 464-primOpTag AddrGeOp = 465-primOpTag AddrEqOp = 466-primOpTag AddrNeOp = 467-primOpTag AddrLtOp = 468-primOpTag AddrLeOp = 469-primOpTag IndexOffAddrOp_Char = 470-primOpTag IndexOffAddrOp_WideChar = 471-primOpTag IndexOffAddrOp_Int = 472-primOpTag IndexOffAddrOp_Word = 473-primOpTag IndexOffAddrOp_Addr = 474-primOpTag IndexOffAddrOp_Float = 475-primOpTag IndexOffAddrOp_Double = 476-primOpTag IndexOffAddrOp_StablePtr = 477-primOpTag IndexOffAddrOp_Int8 = 478-primOpTag IndexOffAddrOp_Int16 = 479-primOpTag IndexOffAddrOp_Int32 = 480-primOpTag IndexOffAddrOp_Int64 = 481-primOpTag IndexOffAddrOp_Word8 = 482-primOpTag IndexOffAddrOp_Word16 = 483-primOpTag IndexOffAddrOp_Word32 = 484-primOpTag IndexOffAddrOp_Word64 = 485-primOpTag ReadOffAddrOp_Char = 486-primOpTag ReadOffAddrOp_WideChar = 487-primOpTag ReadOffAddrOp_Int = 488-primOpTag ReadOffAddrOp_Word = 489-primOpTag ReadOffAddrOp_Addr = 490-primOpTag ReadOffAddrOp_Float = 491-primOpTag ReadOffAddrOp_Double = 492-primOpTag ReadOffAddrOp_StablePtr = 493-primOpTag ReadOffAddrOp_Int8 = 494-primOpTag ReadOffAddrOp_Int16 = 495-primOpTag ReadOffAddrOp_Int32 = 496-primOpTag ReadOffAddrOp_Int64 = 497-primOpTag ReadOffAddrOp_Word8 = 498-primOpTag ReadOffAddrOp_Word16 = 499-primOpTag ReadOffAddrOp_Word32 = 500-primOpTag ReadOffAddrOp_Word64 = 501-primOpTag WriteOffAddrOp_Char = 502-primOpTag WriteOffAddrOp_WideChar = 503-primOpTag WriteOffAddrOp_Int = 504-primOpTag WriteOffAddrOp_Word = 505-primOpTag WriteOffAddrOp_Addr = 506-primOpTag WriteOffAddrOp_Float = 507-primOpTag WriteOffAddrOp_Double = 508-primOpTag WriteOffAddrOp_StablePtr = 509-primOpTag WriteOffAddrOp_Int8 = 510-primOpTag WriteOffAddrOp_Int16 = 511-primOpTag WriteOffAddrOp_Int32 = 512-primOpTag WriteOffAddrOp_Int64 = 513-primOpTag WriteOffAddrOp_Word8 = 514-primOpTag WriteOffAddrOp_Word16 = 515-primOpTag WriteOffAddrOp_Word32 = 516-primOpTag WriteOffAddrOp_Word64 = 517-primOpTag InterlockedExchange_Addr = 518-primOpTag InterlockedExchange_Word = 519-primOpTag CasAddrOp_Addr = 520-primOpTag CasAddrOp_Word = 521-primOpTag FetchAddAddrOp_Word = 522-primOpTag FetchSubAddrOp_Word = 523-primOpTag FetchAndAddrOp_Word = 524-primOpTag FetchNandAddrOp_Word = 525-primOpTag FetchOrAddrOp_Word = 526-primOpTag FetchXorAddrOp_Word = 527-primOpTag AtomicReadAddrOp_Word = 528-primOpTag AtomicWriteAddrOp_Word = 529-primOpTag NewMutVarOp = 530-primOpTag ReadMutVarOp = 531-primOpTag WriteMutVarOp = 532-primOpTag SameMutVarOp = 533-primOpTag AtomicModifyMutVar2Op = 534-primOpTag AtomicModifyMutVar_Op = 535-primOpTag CasMutVarOp = 536-primOpTag CatchOp = 537-primOpTag RaiseOp = 538-primOpTag RaiseIOOp = 539-primOpTag MaskAsyncExceptionsOp = 540-primOpTag MaskUninterruptibleOp = 541-primOpTag UnmaskAsyncExceptionsOp = 542-primOpTag MaskStatus = 543-primOpTag AtomicallyOp = 544-primOpTag RetryOp = 545-primOpTag CatchRetryOp = 546-primOpTag CatchSTMOp = 547-primOpTag NewTVarOp = 548-primOpTag ReadTVarOp = 549-primOpTag ReadTVarIOOp = 550-primOpTag WriteTVarOp = 551-primOpTag SameTVarOp = 552-primOpTag NewMVarOp = 553-primOpTag TakeMVarOp = 554-primOpTag TryTakeMVarOp = 555-primOpTag PutMVarOp = 556-primOpTag TryPutMVarOp = 557-primOpTag ReadMVarOp = 558-primOpTag TryReadMVarOp = 559-primOpTag SameMVarOp = 560-primOpTag IsEmptyMVarOp = 561-primOpTag NewIOPortrOp = 562-primOpTag ReadIOPortOp = 563-primOpTag WriteIOPortOp = 564-primOpTag SameIOPortOp = 565-primOpTag DelayOp = 566-primOpTag WaitReadOp = 567-primOpTag WaitWriteOp = 568-primOpTag ForkOp = 569-primOpTag ForkOnOp = 570-primOpTag KillThreadOp = 571-primOpTag YieldOp = 572-primOpTag MyThreadIdOp = 573-primOpTag LabelThreadOp = 574-primOpTag IsCurrentThreadBoundOp = 575-primOpTag NoDuplicateOp = 576-primOpTag ThreadStatusOp = 577-primOpTag MkWeakOp = 578-primOpTag MkWeakNoFinalizerOp = 579-primOpTag AddCFinalizerToWeakOp = 580-primOpTag DeRefWeakOp = 581-primOpTag FinalizeWeakOp = 582-primOpTag TouchOp = 583-primOpTag MakeStablePtrOp = 584-primOpTag DeRefStablePtrOp = 585-primOpTag EqStablePtrOp = 586-primOpTag MakeStableNameOp = 587-primOpTag EqStableNameOp = 588-primOpTag StableNameToIntOp = 589-primOpTag CompactNewOp = 590-primOpTag CompactResizeOp = 591-primOpTag CompactContainsOp = 592-primOpTag CompactContainsAnyOp = 593-primOpTag CompactGetFirstBlockOp = 594-primOpTag CompactGetNextBlockOp = 595-primOpTag CompactAllocateBlockOp = 596-primOpTag CompactFixupPointersOp = 597-primOpTag CompactAdd = 598-primOpTag CompactAddWithSharing = 599-primOpTag CompactSize = 600-primOpTag ReallyUnsafePtrEqualityOp = 601-primOpTag ParOp = 602-primOpTag SparkOp = 603-primOpTag SeqOp = 604-primOpTag GetSparkOp = 605-primOpTag NumSparks = 606-primOpTag KeepAliveOp = 607-primOpTag DataToTagOp = 608-primOpTag TagToEnumOp = 609-primOpTag AddrToAnyOp = 610-primOpTag AnyToAddrOp = 611-primOpTag MkApUpd0_Op = 612-primOpTag NewBCOOp = 613-primOpTag UnpackClosureOp = 614-primOpTag ClosureSizeOp = 615-primOpTag GetApStackValOp = 616-primOpTag GetCCSOfOp = 617-primOpTag GetCurrentCCSOp = 618-primOpTag ClearCCSOp = 619-primOpTag TraceEventOp = 620-primOpTag TraceEventBinaryOp = 621-primOpTag TraceMarkerOp = 622-primOpTag SetThreadAllocationCounter = 623-primOpTag (VecBroadcastOp IntVec 16 W8) = 624-primOpTag (VecBroadcastOp IntVec 8 W16) = 625-primOpTag (VecBroadcastOp IntVec 4 W32) = 626-primOpTag (VecBroadcastOp IntVec 2 W64) = 627-primOpTag (VecBroadcastOp IntVec 32 W8) = 628-primOpTag (VecBroadcastOp IntVec 16 W16) = 629-primOpTag (VecBroadcastOp IntVec 8 W32) = 630-primOpTag (VecBroadcastOp IntVec 4 W64) = 631-primOpTag (VecBroadcastOp IntVec 64 W8) = 632-primOpTag (VecBroadcastOp IntVec 32 W16) = 633-primOpTag (VecBroadcastOp IntVec 16 W32) = 634-primOpTag (VecBroadcastOp IntVec 8 W64) = 635-primOpTag (VecBroadcastOp WordVec 16 W8) = 636-primOpTag (VecBroadcastOp WordVec 8 W16) = 637-primOpTag (VecBroadcastOp WordVec 4 W32) = 638-primOpTag (VecBroadcastOp WordVec 2 W64) = 639-primOpTag (VecBroadcastOp WordVec 32 W8) = 640-primOpTag (VecBroadcastOp WordVec 16 W16) = 641-primOpTag (VecBroadcastOp WordVec 8 W32) = 642-primOpTag (VecBroadcastOp WordVec 4 W64) = 643-primOpTag (VecBroadcastOp WordVec 64 W8) = 644-primOpTag (VecBroadcastOp WordVec 32 W16) = 645-primOpTag (VecBroadcastOp WordVec 16 W32) = 646-primOpTag (VecBroadcastOp WordVec 8 W64) = 647-primOpTag (VecBroadcastOp FloatVec 4 W32) = 648-primOpTag (VecBroadcastOp FloatVec 2 W64) = 649-primOpTag (VecBroadcastOp FloatVec 8 W32) = 650-primOpTag (VecBroadcastOp FloatVec 4 W64) = 651-primOpTag (VecBroadcastOp FloatVec 16 W32) = 652-primOpTag (VecBroadcastOp FloatVec 8 W64) = 653-primOpTag (VecPackOp IntVec 16 W8) = 654-primOpTag (VecPackOp IntVec 8 W16) = 655-primOpTag (VecPackOp IntVec 4 W32) = 656-primOpTag (VecPackOp IntVec 2 W64) = 657-primOpTag (VecPackOp IntVec 32 W8) = 658-primOpTag (VecPackOp IntVec 16 W16) = 659-primOpTag (VecPackOp IntVec 8 W32) = 660-primOpTag (VecPackOp IntVec 4 W64) = 661-primOpTag (VecPackOp IntVec 64 W8) = 662-primOpTag (VecPackOp IntVec 32 W16) = 663-primOpTag (VecPackOp IntVec 16 W32) = 664-primOpTag (VecPackOp IntVec 8 W64) = 665-primOpTag (VecPackOp WordVec 16 W8) = 666-primOpTag (VecPackOp WordVec 8 W16) = 667-primOpTag (VecPackOp WordVec 4 W32) = 668-primOpTag (VecPackOp WordVec 2 W64) = 669-primOpTag (VecPackOp WordVec 32 W8) = 670-primOpTag (VecPackOp WordVec 16 W16) = 671-primOpTag (VecPackOp WordVec 8 W32) = 672-primOpTag (VecPackOp WordVec 4 W64) = 673-primOpTag (VecPackOp WordVec 64 W8) = 674-primOpTag (VecPackOp WordVec 32 W16) = 675-primOpTag (VecPackOp WordVec 16 W32) = 676-primOpTag (VecPackOp WordVec 8 W64) = 677-primOpTag (VecPackOp FloatVec 4 W32) = 678-primOpTag (VecPackOp FloatVec 2 W64) = 679-primOpTag (VecPackOp FloatVec 8 W32) = 680-primOpTag (VecPackOp FloatVec 4 W64) = 681-primOpTag (VecPackOp FloatVec 16 W32) = 682-primOpTag (VecPackOp FloatVec 8 W64) = 683-primOpTag (VecUnpackOp IntVec 16 W8) = 684-primOpTag (VecUnpackOp IntVec 8 W16) = 685-primOpTag (VecUnpackOp IntVec 4 W32) = 686-primOpTag (VecUnpackOp IntVec 2 W64) = 687-primOpTag (VecUnpackOp IntVec 32 W8) = 688-primOpTag (VecUnpackOp IntVec 16 W16) = 689-primOpTag (VecUnpackOp IntVec 8 W32) = 690-primOpTag (VecUnpackOp IntVec 4 W64) = 691-primOpTag (VecUnpackOp IntVec 64 W8) = 692-primOpTag (VecUnpackOp IntVec 32 W16) = 693-primOpTag (VecUnpackOp IntVec 16 W32) = 694-primOpTag (VecUnpackOp IntVec 8 W64) = 695-primOpTag (VecUnpackOp WordVec 16 W8) = 696-primOpTag (VecUnpackOp WordVec 8 W16) = 697-primOpTag (VecUnpackOp WordVec 4 W32) = 698-primOpTag (VecUnpackOp WordVec 2 W64) = 699-primOpTag (VecUnpackOp WordVec 32 W8) = 700-primOpTag (VecUnpackOp WordVec 16 W16) = 701-primOpTag (VecUnpackOp WordVec 8 W32) = 702-primOpTag (VecUnpackOp WordVec 4 W64) = 703-primOpTag (VecUnpackOp WordVec 64 W8) = 704-primOpTag (VecUnpackOp WordVec 32 W16) = 705-primOpTag (VecUnpackOp WordVec 16 W32) = 706-primOpTag (VecUnpackOp WordVec 8 W64) = 707-primOpTag (VecUnpackOp FloatVec 4 W32) = 708-primOpTag (VecUnpackOp FloatVec 2 W64) = 709-primOpTag (VecUnpackOp FloatVec 8 W32) = 710-primOpTag (VecUnpackOp FloatVec 4 W64) = 711-primOpTag (VecUnpackOp FloatVec 16 W32) = 712-primOpTag (VecUnpackOp FloatVec 8 W64) = 713-primOpTag (VecInsertOp IntVec 16 W8) = 714-primOpTag (VecInsertOp IntVec 8 W16) = 715-primOpTag (VecInsertOp IntVec 4 W32) = 716-primOpTag (VecInsertOp IntVec 2 W64) = 717-primOpTag (VecInsertOp IntVec 32 W8) = 718-primOpTag (VecInsertOp IntVec 16 W16) = 719-primOpTag (VecInsertOp IntVec 8 W32) = 720-primOpTag (VecInsertOp IntVec 4 W64) = 721-primOpTag (VecInsertOp IntVec 64 W8) = 722-primOpTag (VecInsertOp IntVec 32 W16) = 723-primOpTag (VecInsertOp IntVec 16 W32) = 724-primOpTag (VecInsertOp IntVec 8 W64) = 725-primOpTag (VecInsertOp WordVec 16 W8) = 726-primOpTag (VecInsertOp WordVec 8 W16) = 727-primOpTag (VecInsertOp WordVec 4 W32) = 728-primOpTag (VecInsertOp WordVec 2 W64) = 729-primOpTag (VecInsertOp WordVec 32 W8) = 730-primOpTag (VecInsertOp WordVec 16 W16) = 731-primOpTag (VecInsertOp WordVec 8 W32) = 732-primOpTag (VecInsertOp WordVec 4 W64) = 733-primOpTag (VecInsertOp WordVec 64 W8) = 734-primOpTag (VecInsertOp WordVec 32 W16) = 735-primOpTag (VecInsertOp WordVec 16 W32) = 736-primOpTag (VecInsertOp WordVec 8 W64) = 737-primOpTag (VecInsertOp FloatVec 4 W32) = 738-primOpTag (VecInsertOp FloatVec 2 W64) = 739-primOpTag (VecInsertOp FloatVec 8 W32) = 740-primOpTag (VecInsertOp FloatVec 4 W64) = 741-primOpTag (VecInsertOp FloatVec 16 W32) = 742-primOpTag (VecInsertOp FloatVec 8 W64) = 743-primOpTag (VecAddOp IntVec 16 W8) = 744-primOpTag (VecAddOp IntVec 8 W16) = 745-primOpTag (VecAddOp IntVec 4 W32) = 746-primOpTag (VecAddOp IntVec 2 W64) = 747-primOpTag (VecAddOp IntVec 32 W8) = 748-primOpTag (VecAddOp IntVec 16 W16) = 749-primOpTag (VecAddOp IntVec 8 W32) = 750-primOpTag (VecAddOp IntVec 4 W64) = 751-primOpTag (VecAddOp IntVec 64 W8) = 752-primOpTag (VecAddOp IntVec 32 W16) = 753-primOpTag (VecAddOp IntVec 16 W32) = 754-primOpTag (VecAddOp IntVec 8 W64) = 755-primOpTag (VecAddOp WordVec 16 W8) = 756-primOpTag (VecAddOp WordVec 8 W16) = 757-primOpTag (VecAddOp WordVec 4 W32) = 758-primOpTag (VecAddOp WordVec 2 W64) = 759-primOpTag (VecAddOp WordVec 32 W8) = 760-primOpTag (VecAddOp WordVec 16 W16) = 761-primOpTag (VecAddOp WordVec 8 W32) = 762-primOpTag (VecAddOp WordVec 4 W64) = 763-primOpTag (VecAddOp WordVec 64 W8) = 764-primOpTag (VecAddOp WordVec 32 W16) = 765-primOpTag (VecAddOp WordVec 16 W32) = 766-primOpTag (VecAddOp WordVec 8 W64) = 767-primOpTag (VecAddOp FloatVec 4 W32) = 768-primOpTag (VecAddOp FloatVec 2 W64) = 769-primOpTag (VecAddOp FloatVec 8 W32) = 770-primOpTag (VecAddOp FloatVec 4 W64) = 771-primOpTag (VecAddOp FloatVec 16 W32) = 772-primOpTag (VecAddOp FloatVec 8 W64) = 773-primOpTag (VecSubOp IntVec 16 W8) = 774-primOpTag (VecSubOp IntVec 8 W16) = 775-primOpTag (VecSubOp IntVec 4 W32) = 776-primOpTag (VecSubOp IntVec 2 W64) = 777-primOpTag (VecSubOp IntVec 32 W8) = 778-primOpTag (VecSubOp IntVec 16 W16) = 779-primOpTag (VecSubOp IntVec 8 W32) = 780-primOpTag (VecSubOp IntVec 4 W64) = 781-primOpTag (VecSubOp IntVec 64 W8) = 782-primOpTag (VecSubOp IntVec 32 W16) = 783-primOpTag (VecSubOp IntVec 16 W32) = 784-primOpTag (VecSubOp IntVec 8 W64) = 785-primOpTag (VecSubOp WordVec 16 W8) = 786-primOpTag (VecSubOp WordVec 8 W16) = 787-primOpTag (VecSubOp WordVec 4 W32) = 788-primOpTag (VecSubOp WordVec 2 W64) = 789-primOpTag (VecSubOp WordVec 32 W8) = 790-primOpTag (VecSubOp WordVec 16 W16) = 791-primOpTag (VecSubOp WordVec 8 W32) = 792-primOpTag (VecSubOp WordVec 4 W64) = 793-primOpTag (VecSubOp WordVec 64 W8) = 794-primOpTag (VecSubOp WordVec 32 W16) = 795-primOpTag (VecSubOp WordVec 16 W32) = 796-primOpTag (VecSubOp WordVec 8 W64) = 797-primOpTag (VecSubOp FloatVec 4 W32) = 798-primOpTag (VecSubOp FloatVec 2 W64) = 799-primOpTag (VecSubOp FloatVec 8 W32) = 800-primOpTag (VecSubOp FloatVec 4 W64) = 801-primOpTag (VecSubOp FloatVec 16 W32) = 802-primOpTag (VecSubOp FloatVec 8 W64) = 803-primOpTag (VecMulOp IntVec 16 W8) = 804-primOpTag (VecMulOp IntVec 8 W16) = 805-primOpTag (VecMulOp IntVec 4 W32) = 806-primOpTag (VecMulOp IntVec 2 W64) = 807-primOpTag (VecMulOp IntVec 32 W8) = 808-primOpTag (VecMulOp IntVec 16 W16) = 809-primOpTag (VecMulOp IntVec 8 W32) = 810-primOpTag (VecMulOp IntVec 4 W64) = 811-primOpTag (VecMulOp IntVec 64 W8) = 812-primOpTag (VecMulOp IntVec 32 W16) = 813-primOpTag (VecMulOp IntVec 16 W32) = 814-primOpTag (VecMulOp IntVec 8 W64) = 815-primOpTag (VecMulOp WordVec 16 W8) = 816-primOpTag (VecMulOp WordVec 8 W16) = 817-primOpTag (VecMulOp WordVec 4 W32) = 818-primOpTag (VecMulOp WordVec 2 W64) = 819-primOpTag (VecMulOp WordVec 32 W8) = 820-primOpTag (VecMulOp WordVec 16 W16) = 821-primOpTag (VecMulOp WordVec 8 W32) = 822-primOpTag (VecMulOp WordVec 4 W64) = 823-primOpTag (VecMulOp WordVec 64 W8) = 824-primOpTag (VecMulOp WordVec 32 W16) = 825-primOpTag (VecMulOp WordVec 16 W32) = 826-primOpTag (VecMulOp WordVec 8 W64) = 827-primOpTag (VecMulOp FloatVec 4 W32) = 828-primOpTag (VecMulOp FloatVec 2 W64) = 829-primOpTag (VecMulOp FloatVec 8 W32) = 830-primOpTag (VecMulOp FloatVec 4 W64) = 831-primOpTag (VecMulOp FloatVec 16 W32) = 832-primOpTag (VecMulOp FloatVec 8 W64) = 833-primOpTag (VecDivOp FloatVec 4 W32) = 834-primOpTag (VecDivOp FloatVec 2 W64) = 835-primOpTag (VecDivOp FloatVec 8 W32) = 836-primOpTag (VecDivOp FloatVec 4 W64) = 837-primOpTag (VecDivOp FloatVec 16 W32) = 838-primOpTag (VecDivOp FloatVec 8 W64) = 839-primOpTag (VecQuotOp IntVec 16 W8) = 840-primOpTag (VecQuotOp IntVec 8 W16) = 841-primOpTag (VecQuotOp IntVec 4 W32) = 842-primOpTag (VecQuotOp IntVec 2 W64) = 843-primOpTag (VecQuotOp IntVec 32 W8) = 844-primOpTag (VecQuotOp IntVec 16 W16) = 845-primOpTag (VecQuotOp IntVec 8 W32) = 846-primOpTag (VecQuotOp IntVec 4 W64) = 847-primOpTag (VecQuotOp IntVec 64 W8) = 848-primOpTag (VecQuotOp IntVec 32 W16) = 849-primOpTag (VecQuotOp IntVec 16 W32) = 850-primOpTag (VecQuotOp IntVec 8 W64) = 851-primOpTag (VecQuotOp WordVec 16 W8) = 852-primOpTag (VecQuotOp WordVec 8 W16) = 853-primOpTag (VecQuotOp WordVec 4 W32) = 854-primOpTag (VecQuotOp WordVec 2 W64) = 855-primOpTag (VecQuotOp WordVec 32 W8) = 856-primOpTag (VecQuotOp WordVec 16 W16) = 857-primOpTag (VecQuotOp WordVec 8 W32) = 858-primOpTag (VecQuotOp WordVec 4 W64) = 859-primOpTag (VecQuotOp WordVec 64 W8) = 860-primOpTag (VecQuotOp WordVec 32 W16) = 861-primOpTag (VecQuotOp WordVec 16 W32) = 862-primOpTag (VecQuotOp WordVec 8 W64) = 863-primOpTag (VecRemOp IntVec 16 W8) = 864-primOpTag (VecRemOp IntVec 8 W16) = 865-primOpTag (VecRemOp IntVec 4 W32) = 866-primOpTag (VecRemOp IntVec 2 W64) = 867-primOpTag (VecRemOp IntVec 32 W8) = 868-primOpTag (VecRemOp IntVec 16 W16) = 869-primOpTag (VecRemOp IntVec 8 W32) = 870-primOpTag (VecRemOp IntVec 4 W64) = 871-primOpTag (VecRemOp IntVec 64 W8) = 872-primOpTag (VecRemOp IntVec 32 W16) = 873-primOpTag (VecRemOp IntVec 16 W32) = 874-primOpTag (VecRemOp IntVec 8 W64) = 875-primOpTag (VecRemOp WordVec 16 W8) = 876-primOpTag (VecRemOp WordVec 8 W16) = 877-primOpTag (VecRemOp WordVec 4 W32) = 878-primOpTag (VecRemOp WordVec 2 W64) = 879-primOpTag (VecRemOp WordVec 32 W8) = 880-primOpTag (VecRemOp WordVec 16 W16) = 881-primOpTag (VecRemOp WordVec 8 W32) = 882-primOpTag (VecRemOp WordVec 4 W64) = 883-primOpTag (VecRemOp WordVec 64 W8) = 884-primOpTag (VecRemOp WordVec 32 W16) = 885-primOpTag (VecRemOp WordVec 16 W32) = 886-primOpTag (VecRemOp WordVec 8 W64) = 887-primOpTag (VecNegOp IntVec 16 W8) = 888-primOpTag (VecNegOp IntVec 8 W16) = 889-primOpTag (VecNegOp IntVec 4 W32) = 890-primOpTag (VecNegOp IntVec 2 W64) = 891-primOpTag (VecNegOp IntVec 32 W8) = 892-primOpTag (VecNegOp IntVec 16 W16) = 893-primOpTag (VecNegOp IntVec 8 W32) = 894-primOpTag (VecNegOp IntVec 4 W64) = 895-primOpTag (VecNegOp IntVec 64 W8) = 896-primOpTag (VecNegOp IntVec 32 W16) = 897-primOpTag (VecNegOp IntVec 16 W32) = 898-primOpTag (VecNegOp IntVec 8 W64) = 899-primOpTag (VecNegOp FloatVec 4 W32) = 900-primOpTag (VecNegOp FloatVec 2 W64) = 901-primOpTag (VecNegOp FloatVec 8 W32) = 902-primOpTag (VecNegOp FloatVec 4 W64) = 903-primOpTag (VecNegOp FloatVec 16 W32) = 904-primOpTag (VecNegOp FloatVec 8 W64) = 905-primOpTag (VecIndexByteArrayOp IntVec 16 W8) = 906-primOpTag (VecIndexByteArrayOp IntVec 8 W16) = 907-primOpTag (VecIndexByteArrayOp IntVec 4 W32) = 908-primOpTag (VecIndexByteArrayOp IntVec 2 W64) = 909-primOpTag (VecIndexByteArrayOp IntVec 32 W8) = 910-primOpTag (VecIndexByteArrayOp IntVec 16 W16) = 911-primOpTag (VecIndexByteArrayOp IntVec 8 W32) = 912-primOpTag (VecIndexByteArrayOp IntVec 4 W64) = 913-primOpTag (VecIndexByteArrayOp IntVec 64 W8) = 914-primOpTag (VecIndexByteArrayOp IntVec 32 W16) = 915-primOpTag (VecIndexByteArrayOp IntVec 16 W32) = 916-primOpTag (VecIndexByteArrayOp IntVec 8 W64) = 917-primOpTag (VecIndexByteArrayOp WordVec 16 W8) = 918-primOpTag (VecIndexByteArrayOp WordVec 8 W16) = 919-primOpTag (VecIndexByteArrayOp WordVec 4 W32) = 920-primOpTag (VecIndexByteArrayOp WordVec 2 W64) = 921-primOpTag (VecIndexByteArrayOp WordVec 32 W8) = 922-primOpTag (VecIndexByteArrayOp WordVec 16 W16) = 923-primOpTag (VecIndexByteArrayOp WordVec 8 W32) = 924-primOpTag (VecIndexByteArrayOp WordVec 4 W64) = 925-primOpTag (VecIndexByteArrayOp WordVec 64 W8) = 926-primOpTag (VecIndexByteArrayOp WordVec 32 W16) = 927-primOpTag (VecIndexByteArrayOp WordVec 16 W32) = 928-primOpTag (VecIndexByteArrayOp WordVec 8 W64) = 929-primOpTag (VecIndexByteArrayOp FloatVec 4 W32) = 930-primOpTag (VecIndexByteArrayOp FloatVec 2 W64) = 931-primOpTag (VecIndexByteArrayOp FloatVec 8 W32) = 932-primOpTag (VecIndexByteArrayOp FloatVec 4 W64) = 933-primOpTag (VecIndexByteArrayOp FloatVec 16 W32) = 934-primOpTag (VecIndexByteArrayOp FloatVec 8 W64) = 935-primOpTag (VecReadByteArrayOp IntVec 16 W8) = 936-primOpTag (VecReadByteArrayOp IntVec 8 W16) = 937-primOpTag (VecReadByteArrayOp IntVec 4 W32) = 938-primOpTag (VecReadByteArrayOp IntVec 2 W64) = 939-primOpTag (VecReadByteArrayOp IntVec 32 W8) = 940-primOpTag (VecReadByteArrayOp IntVec 16 W16) = 941-primOpTag (VecReadByteArrayOp IntVec 8 W32) = 942-primOpTag (VecReadByteArrayOp IntVec 4 W64) = 943-primOpTag (VecReadByteArrayOp IntVec 64 W8) = 944-primOpTag (VecReadByteArrayOp IntVec 32 W16) = 945-primOpTag (VecReadByteArrayOp IntVec 16 W32) = 946-primOpTag (VecReadByteArrayOp IntVec 8 W64) = 947-primOpTag (VecReadByteArrayOp WordVec 16 W8) = 948-primOpTag (VecReadByteArrayOp WordVec 8 W16) = 949-primOpTag (VecReadByteArrayOp WordVec 4 W32) = 950-primOpTag (VecReadByteArrayOp WordVec 2 W64) = 951-primOpTag (VecReadByteArrayOp WordVec 32 W8) = 952-primOpTag (VecReadByteArrayOp WordVec 16 W16) = 953-primOpTag (VecReadByteArrayOp WordVec 8 W32) = 954-primOpTag (VecReadByteArrayOp WordVec 4 W64) = 955-primOpTag (VecReadByteArrayOp WordVec 64 W8) = 956-primOpTag (VecReadByteArrayOp WordVec 32 W16) = 957-primOpTag (VecReadByteArrayOp WordVec 16 W32) = 958-primOpTag (VecReadByteArrayOp WordVec 8 W64) = 959-primOpTag (VecReadByteArrayOp FloatVec 4 W32) = 960-primOpTag (VecReadByteArrayOp FloatVec 2 W64) = 961-primOpTag (VecReadByteArrayOp FloatVec 8 W32) = 962-primOpTag (VecReadByteArrayOp FloatVec 4 W64) = 963-primOpTag (VecReadByteArrayOp FloatVec 16 W32) = 964-primOpTag (VecReadByteArrayOp FloatVec 8 W64) = 965-primOpTag (VecWriteByteArrayOp IntVec 16 W8) = 966-primOpTag (VecWriteByteArrayOp IntVec 8 W16) = 967-primOpTag (VecWriteByteArrayOp IntVec 4 W32) = 968-primOpTag (VecWriteByteArrayOp IntVec 2 W64) = 969-primOpTag (VecWriteByteArrayOp IntVec 32 W8) = 970-primOpTag (VecWriteByteArrayOp IntVec 16 W16) = 971-primOpTag (VecWriteByteArrayOp IntVec 8 W32) = 972-primOpTag (VecWriteByteArrayOp IntVec 4 W64) = 973-primOpTag (VecWriteByteArrayOp IntVec 64 W8) = 974-primOpTag (VecWriteByteArrayOp IntVec 32 W16) = 975-primOpTag (VecWriteByteArrayOp IntVec 16 W32) = 976-primOpTag (VecWriteByteArrayOp IntVec 8 W64) = 977-primOpTag (VecWriteByteArrayOp WordVec 16 W8) = 978-primOpTag (VecWriteByteArrayOp WordVec 8 W16) = 979-primOpTag (VecWriteByteArrayOp WordVec 4 W32) = 980-primOpTag (VecWriteByteArrayOp WordVec 2 W64) = 981-primOpTag (VecWriteByteArrayOp WordVec 32 W8) = 982-primOpTag (VecWriteByteArrayOp WordVec 16 W16) = 983-primOpTag (VecWriteByteArrayOp WordVec 8 W32) = 984-primOpTag (VecWriteByteArrayOp WordVec 4 W64) = 985-primOpTag (VecWriteByteArrayOp WordVec 64 W8) = 986-primOpTag (VecWriteByteArrayOp WordVec 32 W16) = 987-primOpTag (VecWriteByteArrayOp WordVec 16 W32) = 988-primOpTag (VecWriteByteArrayOp WordVec 8 W64) = 989-primOpTag (VecWriteByteArrayOp FloatVec 4 W32) = 990-primOpTag (VecWriteByteArrayOp FloatVec 2 W64) = 991-primOpTag (VecWriteByteArrayOp FloatVec 8 W32) = 992-primOpTag (VecWriteByteArrayOp FloatVec 4 W64) = 993-primOpTag (VecWriteByteArrayOp FloatVec 16 W32) = 994-primOpTag (VecWriteByteArrayOp FloatVec 8 W64) = 995-primOpTag (VecIndexOffAddrOp IntVec 16 W8) = 996-primOpTag (VecIndexOffAddrOp IntVec 8 W16) = 997-primOpTag (VecIndexOffAddrOp IntVec 4 W32) = 998-primOpTag (VecIndexOffAddrOp IntVec 2 W64) = 999-primOpTag (VecIndexOffAddrOp IntVec 32 W8) = 1000-primOpTag (VecIndexOffAddrOp IntVec 16 W16) = 1001-primOpTag (VecIndexOffAddrOp IntVec 8 W32) = 1002-primOpTag (VecIndexOffAddrOp IntVec 4 W64) = 1003-primOpTag (VecIndexOffAddrOp IntVec 64 W8) = 1004-primOpTag (VecIndexOffAddrOp IntVec 32 W16) = 1005-primOpTag (VecIndexOffAddrOp IntVec 16 W32) = 1006-primOpTag (VecIndexOffAddrOp IntVec 8 W64) = 1007-primOpTag (VecIndexOffAddrOp WordVec 16 W8) = 1008-primOpTag (VecIndexOffAddrOp WordVec 8 W16) = 1009-primOpTag (VecIndexOffAddrOp WordVec 4 W32) = 1010-primOpTag (VecIndexOffAddrOp WordVec 2 W64) = 1011-primOpTag (VecIndexOffAddrOp WordVec 32 W8) = 1012-primOpTag (VecIndexOffAddrOp WordVec 16 W16) = 1013-primOpTag (VecIndexOffAddrOp WordVec 8 W32) = 1014-primOpTag (VecIndexOffAddrOp WordVec 4 W64) = 1015-primOpTag (VecIndexOffAddrOp WordVec 64 W8) = 1016-primOpTag (VecIndexOffAddrOp WordVec 32 W16) = 1017-primOpTag (VecIndexOffAddrOp WordVec 16 W32) = 1018-primOpTag (VecIndexOffAddrOp WordVec 8 W64) = 1019-primOpTag (VecIndexOffAddrOp FloatVec 4 W32) = 1020-primOpTag (VecIndexOffAddrOp FloatVec 2 W64) = 1021-primOpTag (VecIndexOffAddrOp FloatVec 8 W32) = 1022-primOpTag (VecIndexOffAddrOp FloatVec 4 W64) = 1023-primOpTag (VecIndexOffAddrOp FloatVec 16 W32) = 1024-primOpTag (VecIndexOffAddrOp FloatVec 8 W64) = 1025-primOpTag (VecReadOffAddrOp IntVec 16 W8) = 1026-primOpTag (VecReadOffAddrOp IntVec 8 W16) = 1027-primOpTag (VecReadOffAddrOp IntVec 4 W32) = 1028-primOpTag (VecReadOffAddrOp IntVec 2 W64) = 1029-primOpTag (VecReadOffAddrOp IntVec 32 W8) = 1030-primOpTag (VecReadOffAddrOp IntVec 16 W16) = 1031-primOpTag (VecReadOffAddrOp IntVec 8 W32) = 1032-primOpTag (VecReadOffAddrOp IntVec 4 W64) = 1033-primOpTag (VecReadOffAddrOp IntVec 64 W8) = 1034-primOpTag (VecReadOffAddrOp IntVec 32 W16) = 1035-primOpTag (VecReadOffAddrOp IntVec 16 W32) = 1036-primOpTag (VecReadOffAddrOp IntVec 8 W64) = 1037-primOpTag (VecReadOffAddrOp WordVec 16 W8) = 1038-primOpTag (VecReadOffAddrOp WordVec 8 W16) = 1039-primOpTag (VecReadOffAddrOp WordVec 4 W32) = 1040-primOpTag (VecReadOffAddrOp WordVec 2 W64) = 1041-primOpTag (VecReadOffAddrOp WordVec 32 W8) = 1042-primOpTag (VecReadOffAddrOp WordVec 16 W16) = 1043-primOpTag (VecReadOffAddrOp WordVec 8 W32) = 1044-primOpTag (VecReadOffAddrOp WordVec 4 W64) = 1045-primOpTag (VecReadOffAddrOp WordVec 64 W8) = 1046-primOpTag (VecReadOffAddrOp WordVec 32 W16) = 1047-primOpTag (VecReadOffAddrOp WordVec 16 W32) = 1048-primOpTag (VecReadOffAddrOp WordVec 8 W64) = 1049-primOpTag (VecReadOffAddrOp FloatVec 4 W32) = 1050-primOpTag (VecReadOffAddrOp FloatVec 2 W64) = 1051-primOpTag (VecReadOffAddrOp FloatVec 8 W32) = 1052-primOpTag (VecReadOffAddrOp FloatVec 4 W64) = 1053-primOpTag (VecReadOffAddrOp FloatVec 16 W32) = 1054-primOpTag (VecReadOffAddrOp FloatVec 8 W64) = 1055-primOpTag (VecWriteOffAddrOp IntVec 16 W8) = 1056-primOpTag (VecWriteOffAddrOp IntVec 8 W16) = 1057-primOpTag (VecWriteOffAddrOp IntVec 4 W32) = 1058-primOpTag (VecWriteOffAddrOp IntVec 2 W64) = 1059-primOpTag (VecWriteOffAddrOp IntVec 32 W8) = 1060-primOpTag (VecWriteOffAddrOp IntVec 16 W16) = 1061-primOpTag (VecWriteOffAddrOp IntVec 8 W32) = 1062-primOpTag (VecWriteOffAddrOp IntVec 4 W64) = 1063-primOpTag (VecWriteOffAddrOp IntVec 64 W8) = 1064-primOpTag (VecWriteOffAddrOp IntVec 32 W16) = 1065-primOpTag (VecWriteOffAddrOp IntVec 16 W32) = 1066-primOpTag (VecWriteOffAddrOp IntVec 8 W64) = 1067-primOpTag (VecWriteOffAddrOp WordVec 16 W8) = 1068-primOpTag (VecWriteOffAddrOp WordVec 8 W16) = 1069-primOpTag (VecWriteOffAddrOp WordVec 4 W32) = 1070-primOpTag (VecWriteOffAddrOp WordVec 2 W64) = 1071-primOpTag (VecWriteOffAddrOp WordVec 32 W8) = 1072-primOpTag (VecWriteOffAddrOp WordVec 16 W16) = 1073-primOpTag (VecWriteOffAddrOp WordVec 8 W32) = 1074-primOpTag (VecWriteOffAddrOp WordVec 4 W64) = 1075-primOpTag (VecWriteOffAddrOp WordVec 64 W8) = 1076-primOpTag (VecWriteOffAddrOp WordVec 32 W16) = 1077-primOpTag (VecWriteOffAddrOp WordVec 16 W32) = 1078-primOpTag (VecWriteOffAddrOp WordVec 8 W64) = 1079-primOpTag (VecWriteOffAddrOp FloatVec 4 W32) = 1080-primOpTag (VecWriteOffAddrOp FloatVec 2 W64) = 1081-primOpTag (VecWriteOffAddrOp FloatVec 8 W32) = 1082-primOpTag (VecWriteOffAddrOp FloatVec 4 W64) = 1083-primOpTag (VecWriteOffAddrOp FloatVec 16 W32) = 1084-primOpTag (VecWriteOffAddrOp FloatVec 8 W64) = 1085-primOpTag (VecIndexScalarByteArrayOp IntVec 16 W8) = 1086-primOpTag (VecIndexScalarByteArrayOp IntVec 8 W16) = 1087-primOpTag (VecIndexScalarByteArrayOp IntVec 4 W32) = 1088-primOpTag (VecIndexScalarByteArrayOp IntVec 2 W64) = 1089-primOpTag (VecIndexScalarByteArrayOp IntVec 32 W8) = 1090-primOpTag (VecIndexScalarByteArrayOp IntVec 16 W16) = 1091-primOpTag (VecIndexScalarByteArrayOp IntVec 8 W32) = 1092-primOpTag (VecIndexScalarByteArrayOp IntVec 4 W64) = 1093-primOpTag (VecIndexScalarByteArrayOp IntVec 64 W8) = 1094-primOpTag (VecIndexScalarByteArrayOp IntVec 32 W16) = 1095-primOpTag (VecIndexScalarByteArrayOp IntVec 16 W32) = 1096-primOpTag (VecIndexScalarByteArrayOp IntVec 8 W64) = 1097-primOpTag (VecIndexScalarByteArrayOp WordVec 16 W8) = 1098-primOpTag (VecIndexScalarByteArrayOp WordVec 8 W16) = 1099-primOpTag (VecIndexScalarByteArrayOp WordVec 4 W32) = 1100-primOpTag (VecIndexScalarByteArrayOp WordVec 2 W64) = 1101-primOpTag (VecIndexScalarByteArrayOp WordVec 32 W8) = 1102-primOpTag (VecIndexScalarByteArrayOp WordVec 16 W16) = 1103-primOpTag (VecIndexScalarByteArrayOp WordVec 8 W32) = 1104-primOpTag (VecIndexScalarByteArrayOp WordVec 4 W64) = 1105-primOpTag (VecIndexScalarByteArrayOp WordVec 64 W8) = 1106-primOpTag (VecIndexScalarByteArrayOp WordVec 32 W16) = 1107-primOpTag (VecIndexScalarByteArrayOp WordVec 16 W32) = 1108-primOpTag (VecIndexScalarByteArrayOp WordVec 8 W64) = 1109-primOpTag (VecIndexScalarByteArrayOp FloatVec 4 W32) = 1110-primOpTag (VecIndexScalarByteArrayOp FloatVec 2 W64) = 1111-primOpTag (VecIndexScalarByteArrayOp FloatVec 8 W32) = 1112-primOpTag (VecIndexScalarByteArrayOp FloatVec 4 W64) = 1113-primOpTag (VecIndexScalarByteArrayOp FloatVec 16 W32) = 1114-primOpTag (VecIndexScalarByteArrayOp FloatVec 8 W64) = 1115-primOpTag (VecReadScalarByteArrayOp IntVec 16 W8) = 1116-primOpTag (VecReadScalarByteArrayOp IntVec 8 W16) = 1117-primOpTag (VecReadScalarByteArrayOp IntVec 4 W32) = 1118-primOpTag (VecReadScalarByteArrayOp IntVec 2 W64) = 1119-primOpTag (VecReadScalarByteArrayOp IntVec 32 W8) = 1120-primOpTag (VecReadScalarByteArrayOp IntVec 16 W16) = 1121-primOpTag (VecReadScalarByteArrayOp IntVec 8 W32) = 1122-primOpTag (VecReadScalarByteArrayOp IntVec 4 W64) = 1123-primOpTag (VecReadScalarByteArrayOp IntVec 64 W8) = 1124-primOpTag (VecReadScalarByteArrayOp IntVec 32 W16) = 1125-primOpTag (VecReadScalarByteArrayOp IntVec 16 W32) = 1126-primOpTag (VecReadScalarByteArrayOp IntVec 8 W64) = 1127-primOpTag (VecReadScalarByteArrayOp WordVec 16 W8) = 1128-primOpTag (VecReadScalarByteArrayOp WordVec 8 W16) = 1129-primOpTag (VecReadScalarByteArrayOp WordVec 4 W32) = 1130-primOpTag (VecReadScalarByteArrayOp WordVec 2 W64) = 1131-primOpTag (VecReadScalarByteArrayOp WordVec 32 W8) = 1132-primOpTag (VecReadScalarByteArrayOp WordVec 16 W16) = 1133-primOpTag (VecReadScalarByteArrayOp WordVec 8 W32) = 1134-primOpTag (VecReadScalarByteArrayOp WordVec 4 W64) = 1135-primOpTag (VecReadScalarByteArrayOp WordVec 64 W8) = 1136-primOpTag (VecReadScalarByteArrayOp WordVec 32 W16) = 1137-primOpTag (VecReadScalarByteArrayOp WordVec 16 W32) = 1138-primOpTag (VecReadScalarByteArrayOp WordVec 8 W64) = 1139-primOpTag (VecReadScalarByteArrayOp FloatVec 4 W32) = 1140-primOpTag (VecReadScalarByteArrayOp FloatVec 2 W64) = 1141-primOpTag (VecReadScalarByteArrayOp FloatVec 8 W32) = 1142-primOpTag (VecReadScalarByteArrayOp FloatVec 4 W64) = 1143-primOpTag (VecReadScalarByteArrayOp FloatVec 16 W32) = 1144-primOpTag (VecReadScalarByteArrayOp FloatVec 8 W64) = 1145-primOpTag (VecWriteScalarByteArrayOp IntVec 16 W8) = 1146-primOpTag (VecWriteScalarByteArrayOp IntVec 8 W16) = 1147-primOpTag (VecWriteScalarByteArrayOp IntVec 4 W32) = 1148-primOpTag (VecWriteScalarByteArrayOp IntVec 2 W64) = 1149-primOpTag (VecWriteScalarByteArrayOp IntVec 32 W8) = 1150-primOpTag (VecWriteScalarByteArrayOp IntVec 16 W16) = 1151-primOpTag (VecWriteScalarByteArrayOp IntVec 8 W32) = 1152-primOpTag (VecWriteScalarByteArrayOp IntVec 4 W64) = 1153-primOpTag (VecWriteScalarByteArrayOp IntVec 64 W8) = 1154-primOpTag (VecWriteScalarByteArrayOp IntVec 32 W16) = 1155-primOpTag (VecWriteScalarByteArrayOp IntVec 16 W32) = 1156-primOpTag (VecWriteScalarByteArrayOp IntVec 8 W64) = 1157-primOpTag (VecWriteScalarByteArrayOp WordVec 16 W8) = 1158-primOpTag (VecWriteScalarByteArrayOp WordVec 8 W16) = 1159-primOpTag (VecWriteScalarByteArrayOp WordVec 4 W32) = 1160-primOpTag (VecWriteScalarByteArrayOp WordVec 2 W64) = 1161-primOpTag (VecWriteScalarByteArrayOp WordVec 32 W8) = 1162-primOpTag (VecWriteScalarByteArrayOp WordVec 16 W16) = 1163-primOpTag (VecWriteScalarByteArrayOp WordVec 8 W32) = 1164-primOpTag (VecWriteScalarByteArrayOp WordVec 4 W64) = 1165-primOpTag (VecWriteScalarByteArrayOp WordVec 64 W8) = 1166-primOpTag (VecWriteScalarByteArrayOp WordVec 32 W16) = 1167-primOpTag (VecWriteScalarByteArrayOp WordVec 16 W32) = 1168-primOpTag (VecWriteScalarByteArrayOp WordVec 8 W64) = 1169-primOpTag (VecWriteScalarByteArrayOp FloatVec 4 W32) = 1170-primOpTag (VecWriteScalarByteArrayOp FloatVec 2 W64) = 1171-primOpTag (VecWriteScalarByteArrayOp FloatVec 8 W32) = 1172-primOpTag (VecWriteScalarByteArrayOp FloatVec 4 W64) = 1173-primOpTag (VecWriteScalarByteArrayOp FloatVec 16 W32) = 1174-primOpTag (VecWriteScalarByteArrayOp FloatVec 8 W64) = 1175-primOpTag (VecIndexScalarOffAddrOp IntVec 16 W8) = 1176-primOpTag (VecIndexScalarOffAddrOp IntVec 8 W16) = 1177-primOpTag (VecIndexScalarOffAddrOp IntVec 4 W32) = 1178-primOpTag (VecIndexScalarOffAddrOp IntVec 2 W64) = 1179-primOpTag (VecIndexScalarOffAddrOp IntVec 32 W8) = 1180-primOpTag (VecIndexScalarOffAddrOp IntVec 16 W16) = 1181-primOpTag (VecIndexScalarOffAddrOp IntVec 8 W32) = 1182-primOpTag (VecIndexScalarOffAddrOp IntVec 4 W64) = 1183-primOpTag (VecIndexScalarOffAddrOp IntVec 64 W8) = 1184-primOpTag (VecIndexScalarOffAddrOp IntVec 32 W16) = 1185-primOpTag (VecIndexScalarOffAddrOp IntVec 16 W32) = 1186-primOpTag (VecIndexScalarOffAddrOp IntVec 8 W64) = 1187-primOpTag (VecIndexScalarOffAddrOp WordVec 16 W8) = 1188-primOpTag (VecIndexScalarOffAddrOp WordVec 8 W16) = 1189-primOpTag (VecIndexScalarOffAddrOp WordVec 4 W32) = 1190-primOpTag (VecIndexScalarOffAddrOp WordVec 2 W64) = 1191-primOpTag (VecIndexScalarOffAddrOp WordVec 32 W8) = 1192-primOpTag (VecIndexScalarOffAddrOp WordVec 16 W16) = 1193-primOpTag (VecIndexScalarOffAddrOp WordVec 8 W32) = 1194-primOpTag (VecIndexScalarOffAddrOp WordVec 4 W64) = 1195-primOpTag (VecIndexScalarOffAddrOp WordVec 64 W8) = 1196-primOpTag (VecIndexScalarOffAddrOp WordVec 32 W16) = 1197-primOpTag (VecIndexScalarOffAddrOp WordVec 16 W32) = 1198-primOpTag (VecIndexScalarOffAddrOp WordVec 8 W64) = 1199-primOpTag (VecIndexScalarOffAddrOp FloatVec 4 W32) = 1200-primOpTag (VecIndexScalarOffAddrOp FloatVec 2 W64) = 1201-primOpTag (VecIndexScalarOffAddrOp FloatVec 8 W32) = 1202-primOpTag (VecIndexScalarOffAddrOp FloatVec 4 W64) = 1203-primOpTag (VecIndexScalarOffAddrOp FloatVec 16 W32) = 1204-primOpTag (VecIndexScalarOffAddrOp FloatVec 8 W64) = 1205-primOpTag (VecReadScalarOffAddrOp IntVec 16 W8) = 1206-primOpTag (VecReadScalarOffAddrOp IntVec 8 W16) = 1207-primOpTag (VecReadScalarOffAddrOp IntVec 4 W32) = 1208-primOpTag (VecReadScalarOffAddrOp IntVec 2 W64) = 1209-primOpTag (VecReadScalarOffAddrOp IntVec 32 W8) = 1210-primOpTag (VecReadScalarOffAddrOp IntVec 16 W16) = 1211-primOpTag (VecReadScalarOffAddrOp IntVec 8 W32) = 1212-primOpTag (VecReadScalarOffAddrOp IntVec 4 W64) = 1213-primOpTag (VecReadScalarOffAddrOp IntVec 64 W8) = 1214-primOpTag (VecReadScalarOffAddrOp IntVec 32 W16) = 1215-primOpTag (VecReadScalarOffAddrOp IntVec 16 W32) = 1216-primOpTag (VecReadScalarOffAddrOp IntVec 8 W64) = 1217-primOpTag (VecReadScalarOffAddrOp WordVec 16 W8) = 1218-primOpTag (VecReadScalarOffAddrOp WordVec 8 W16) = 1219-primOpTag (VecReadScalarOffAddrOp WordVec 4 W32) = 1220-primOpTag (VecReadScalarOffAddrOp WordVec 2 W64) = 1221-primOpTag (VecReadScalarOffAddrOp WordVec 32 W8) = 1222-primOpTag (VecReadScalarOffAddrOp WordVec 16 W16) = 1223-primOpTag (VecReadScalarOffAddrOp WordVec 8 W32) = 1224-primOpTag (VecReadScalarOffAddrOp WordVec 4 W64) = 1225-primOpTag (VecReadScalarOffAddrOp WordVec 64 W8) = 1226-primOpTag (VecReadScalarOffAddrOp WordVec 32 W16) = 1227-primOpTag (VecReadScalarOffAddrOp WordVec 16 W32) = 1228-primOpTag (VecReadScalarOffAddrOp WordVec 8 W64) = 1229-primOpTag (VecReadScalarOffAddrOp FloatVec 4 W32) = 1230-primOpTag (VecReadScalarOffAddrOp FloatVec 2 W64) = 1231-primOpTag (VecReadScalarOffAddrOp FloatVec 8 W32) = 1232-primOpTag (VecReadScalarOffAddrOp FloatVec 4 W64) = 1233-primOpTag (VecReadScalarOffAddrOp FloatVec 16 W32) = 1234-primOpTag (VecReadScalarOffAddrOp FloatVec 8 W64) = 1235-primOpTag (VecWriteScalarOffAddrOp IntVec 16 W8) = 1236-primOpTag (VecWriteScalarOffAddrOp IntVec 8 W16) = 1237-primOpTag (VecWriteScalarOffAddrOp IntVec 4 W32) = 1238-primOpTag (VecWriteScalarOffAddrOp IntVec 2 W64) = 1239-primOpTag (VecWriteScalarOffAddrOp IntVec 32 W8) = 1240-primOpTag (VecWriteScalarOffAddrOp IntVec 16 W16) = 1241-primOpTag (VecWriteScalarOffAddrOp IntVec 8 W32) = 1242-primOpTag (VecWriteScalarOffAddrOp IntVec 4 W64) = 1243-primOpTag (VecWriteScalarOffAddrOp IntVec 64 W8) = 1244-primOpTag (VecWriteScalarOffAddrOp IntVec 32 W16) = 1245-primOpTag (VecWriteScalarOffAddrOp IntVec 16 W32) = 1246-primOpTag (VecWriteScalarOffAddrOp IntVec 8 W64) = 1247-primOpTag (VecWriteScalarOffAddrOp WordVec 16 W8) = 1248-primOpTag (VecWriteScalarOffAddrOp WordVec 8 W16) = 1249-primOpTag (VecWriteScalarOffAddrOp WordVec 4 W32) = 1250-primOpTag (VecWriteScalarOffAddrOp WordVec 2 W64) = 1251-primOpTag (VecWriteScalarOffAddrOp WordVec 32 W8) = 1252-primOpTag (VecWriteScalarOffAddrOp WordVec 16 W16) = 1253-primOpTag (VecWriteScalarOffAddrOp WordVec 8 W32) = 1254-primOpTag (VecWriteScalarOffAddrOp WordVec 4 W64) = 1255-primOpTag (VecWriteScalarOffAddrOp WordVec 64 W8) = 1256-primOpTag (VecWriteScalarOffAddrOp WordVec 32 W16) = 1257-primOpTag (VecWriteScalarOffAddrOp WordVec 16 W32) = 1258-primOpTag (VecWriteScalarOffAddrOp WordVec 8 W64) = 1259-primOpTag (VecWriteScalarOffAddrOp FloatVec 4 W32) = 1260-primOpTag (VecWriteScalarOffAddrOp FloatVec 2 W64) = 1261-primOpTag (VecWriteScalarOffAddrOp FloatVec 8 W32) = 1262-primOpTag (VecWriteScalarOffAddrOp FloatVec 4 W64) = 1263-primOpTag (VecWriteScalarOffAddrOp FloatVec 16 W32) = 1264-primOpTag (VecWriteScalarOffAddrOp FloatVec 8 W64) = 1265-primOpTag PrefetchByteArrayOp3 = 1266-primOpTag PrefetchMutableByteArrayOp3 = 1267-primOpTag PrefetchAddrOp3 = 1268-primOpTag PrefetchValueOp3 = 1269-primOpTag PrefetchByteArrayOp2 = 1270-primOpTag PrefetchMutableByteArrayOp2 = 1271-primOpTag PrefetchAddrOp2 = 1272-primOpTag PrefetchValueOp2 = 1273-primOpTag PrefetchByteArrayOp1 = 1274-primOpTag PrefetchMutableByteArrayOp1 = 1275-primOpTag PrefetchAddrOp1 = 1276-primOpTag PrefetchValueOp1 = 1277-primOpTag PrefetchByteArrayOp0 = 1278-primOpTag PrefetchMutableByteArrayOp0 = 1279-primOpTag PrefetchAddrOp0 = 1280-primOpTag PrefetchValueOp0 = 1281+maxPrimOpTag = 1283+primOpTag :: PrimOp -> Int+primOpTag CharGtOp = 1+primOpTag CharGeOp = 2+primOpTag CharEqOp = 3+primOpTag CharNeOp = 4+primOpTag CharLtOp = 5+primOpTag CharLeOp = 6+primOpTag OrdOp = 7+primOpTag Int8ToIntOp = 8+primOpTag IntToInt8Op = 9+primOpTag Int8NegOp = 10+primOpTag Int8AddOp = 11+primOpTag Int8SubOp = 12+primOpTag Int8MulOp = 13+primOpTag Int8QuotOp = 14+primOpTag Int8RemOp = 15+primOpTag Int8QuotRemOp = 16+primOpTag Int8SllOp = 17+primOpTag Int8SraOp = 18+primOpTag Int8SrlOp = 19+primOpTag Int8ToWord8Op = 20+primOpTag Int8EqOp = 21+primOpTag Int8GeOp = 22+primOpTag Int8GtOp = 23+primOpTag Int8LeOp = 24+primOpTag Int8LtOp = 25+primOpTag Int8NeOp = 26+primOpTag Word8ToWordOp = 27+primOpTag WordToWord8Op = 28+primOpTag Word8AddOp = 29+primOpTag Word8SubOp = 30+primOpTag Word8MulOp = 31+primOpTag Word8QuotOp = 32+primOpTag Word8RemOp = 33+primOpTag Word8QuotRemOp = 34+primOpTag Word8AndOp = 35+primOpTag Word8OrOp = 36+primOpTag Word8XorOp = 37+primOpTag Word8NotOp = 38+primOpTag Word8SllOp = 39+primOpTag Word8SrlOp = 40+primOpTag Word8ToInt8Op = 41+primOpTag Word8EqOp = 42+primOpTag Word8GeOp = 43+primOpTag Word8GtOp = 44+primOpTag Word8LeOp = 45+primOpTag Word8LtOp = 46+primOpTag Word8NeOp = 47+primOpTag Int16ToIntOp = 48+primOpTag IntToInt16Op = 49+primOpTag Int16NegOp = 50+primOpTag Int16AddOp = 51+primOpTag Int16SubOp = 52+primOpTag Int16MulOp = 53+primOpTag Int16QuotOp = 54+primOpTag Int16RemOp = 55+primOpTag Int16QuotRemOp = 56+primOpTag Int16SllOp = 57+primOpTag Int16SraOp = 58+primOpTag Int16SrlOp = 59+primOpTag Int16ToWord16Op = 60+primOpTag Int16EqOp = 61+primOpTag Int16GeOp = 62+primOpTag Int16GtOp = 63+primOpTag Int16LeOp = 64+primOpTag Int16LtOp = 65+primOpTag Int16NeOp = 66+primOpTag Word16ToWordOp = 67+primOpTag WordToWord16Op = 68+primOpTag Word16AddOp = 69+primOpTag Word16SubOp = 70+primOpTag Word16MulOp = 71+primOpTag Word16QuotOp = 72+primOpTag Word16RemOp = 73+primOpTag Word16QuotRemOp = 74+primOpTag Word16AndOp = 75+primOpTag Word16OrOp = 76+primOpTag Word16XorOp = 77+primOpTag Word16NotOp = 78+primOpTag Word16SllOp = 79+primOpTag Word16SrlOp = 80+primOpTag Word16ToInt16Op = 81+primOpTag Word16EqOp = 82+primOpTag Word16GeOp = 83+primOpTag Word16GtOp = 84+primOpTag Word16LeOp = 85+primOpTag Word16LtOp = 86+primOpTag Word16NeOp = 87+primOpTag Int32ToIntOp = 88+primOpTag IntToInt32Op = 89+primOpTag Int32NegOp = 90+primOpTag Int32AddOp = 91+primOpTag Int32SubOp = 92+primOpTag Int32MulOp = 93+primOpTag Int32QuotOp = 94+primOpTag Int32RemOp = 95+primOpTag Int32QuotRemOp = 96+primOpTag Int32SllOp = 97+primOpTag Int32SraOp = 98+primOpTag Int32SrlOp = 99+primOpTag Int32ToWord32Op = 100+primOpTag Int32EqOp = 101+primOpTag Int32GeOp = 102+primOpTag Int32GtOp = 103+primOpTag Int32LeOp = 104+primOpTag Int32LtOp = 105+primOpTag Int32NeOp = 106+primOpTag Word32ToWordOp = 107+primOpTag WordToWord32Op = 108+primOpTag Word32AddOp = 109+primOpTag Word32SubOp = 110+primOpTag Word32MulOp = 111+primOpTag Word32QuotOp = 112+primOpTag Word32RemOp = 113+primOpTag Word32QuotRemOp = 114+primOpTag Word32AndOp = 115+primOpTag Word32OrOp = 116+primOpTag Word32XorOp = 117+primOpTag Word32NotOp = 118+primOpTag Word32SllOp = 119+primOpTag Word32SrlOp = 120+primOpTag Word32ToInt32Op = 121+primOpTag Word32EqOp = 122+primOpTag Word32GeOp = 123+primOpTag Word32GtOp = 124+primOpTag Word32LeOp = 125+primOpTag Word32LtOp = 126+primOpTag Word32NeOp = 127+primOpTag IntAddOp = 128+primOpTag IntSubOp = 129+primOpTag IntMulOp = 130+primOpTag IntMul2Op = 131+primOpTag IntMulMayOfloOp = 132+primOpTag IntQuotOp = 133+primOpTag IntRemOp = 134+primOpTag IntQuotRemOp = 135+primOpTag IntAndOp = 136+primOpTag IntOrOp = 137+primOpTag IntXorOp = 138+primOpTag IntNotOp = 139+primOpTag IntNegOp = 140+primOpTag IntAddCOp = 141+primOpTag IntSubCOp = 142+primOpTag IntGtOp = 143+primOpTag IntGeOp = 144+primOpTag IntEqOp = 145+primOpTag IntNeOp = 146+primOpTag IntLtOp = 147+primOpTag IntLeOp = 148+primOpTag ChrOp = 149+primOpTag IntToWordOp = 150+primOpTag IntToFloatOp = 151+primOpTag IntToDoubleOp = 152+primOpTag WordToFloatOp = 153+primOpTag WordToDoubleOp = 154+primOpTag IntSllOp = 155+primOpTag IntSraOp = 156+primOpTag IntSrlOp = 157+primOpTag WordAddOp = 158+primOpTag WordAddCOp = 159+primOpTag WordSubCOp = 160+primOpTag WordAdd2Op = 161+primOpTag WordSubOp = 162+primOpTag WordMulOp = 163+primOpTag WordMul2Op = 164+primOpTag WordQuotOp = 165+primOpTag WordRemOp = 166+primOpTag WordQuotRemOp = 167+primOpTag WordQuotRem2Op = 168+primOpTag WordAndOp = 169+primOpTag WordOrOp = 170+primOpTag WordXorOp = 171+primOpTag WordNotOp = 172+primOpTag WordSllOp = 173+primOpTag WordSrlOp = 174+primOpTag WordToIntOp = 175+primOpTag WordGtOp = 176+primOpTag WordGeOp = 177+primOpTag WordEqOp = 178+primOpTag WordNeOp = 179+primOpTag WordLtOp = 180+primOpTag WordLeOp = 181+primOpTag PopCnt8Op = 182+primOpTag PopCnt16Op = 183+primOpTag PopCnt32Op = 184+primOpTag PopCnt64Op = 185+primOpTag PopCntOp = 186+primOpTag Pdep8Op = 187+primOpTag Pdep16Op = 188+primOpTag Pdep32Op = 189+primOpTag Pdep64Op = 190+primOpTag PdepOp = 191+primOpTag Pext8Op = 192+primOpTag Pext16Op = 193+primOpTag Pext32Op = 194+primOpTag Pext64Op = 195+primOpTag PextOp = 196+primOpTag Clz8Op = 197+primOpTag Clz16Op = 198+primOpTag Clz32Op = 199+primOpTag Clz64Op = 200+primOpTag ClzOp = 201+primOpTag Ctz8Op = 202+primOpTag Ctz16Op = 203+primOpTag Ctz32Op = 204+primOpTag Ctz64Op = 205+primOpTag CtzOp = 206+primOpTag BSwap16Op = 207+primOpTag BSwap32Op = 208+primOpTag BSwap64Op = 209+primOpTag BSwapOp = 210+primOpTag BRev8Op = 211+primOpTag BRev16Op = 212+primOpTag BRev32Op = 213+primOpTag BRev64Op = 214+primOpTag BRevOp = 215+primOpTag Narrow8IntOp = 216+primOpTag Narrow16IntOp = 217+primOpTag Narrow32IntOp = 218+primOpTag Narrow8WordOp = 219+primOpTag Narrow16WordOp = 220+primOpTag Narrow32WordOp = 221+primOpTag DoubleGtOp = 222+primOpTag DoubleGeOp = 223+primOpTag DoubleEqOp = 224+primOpTag DoubleNeOp = 225+primOpTag DoubleLtOp = 226+primOpTag DoubleLeOp = 227+primOpTag DoubleAddOp = 228+primOpTag DoubleSubOp = 229+primOpTag DoubleMulOp = 230+primOpTag DoubleDivOp = 231+primOpTag DoubleNegOp = 232+primOpTag DoubleFabsOp = 233+primOpTag DoubleToIntOp = 234+primOpTag DoubleToFloatOp = 235+primOpTag DoubleExpOp = 236+primOpTag DoubleExpM1Op = 237+primOpTag DoubleLogOp = 238+primOpTag DoubleLog1POp = 239+primOpTag DoubleSqrtOp = 240+primOpTag DoubleSinOp = 241+primOpTag DoubleCosOp = 242+primOpTag DoubleTanOp = 243+primOpTag DoubleAsinOp = 244+primOpTag DoubleAcosOp = 245+primOpTag DoubleAtanOp = 246+primOpTag DoubleSinhOp = 247+primOpTag DoubleCoshOp = 248+primOpTag DoubleTanhOp = 249+primOpTag DoubleAsinhOp = 250+primOpTag DoubleAcoshOp = 251+primOpTag DoubleAtanhOp = 252+primOpTag DoublePowerOp = 253+primOpTag DoubleDecode_2IntOp = 254+primOpTag DoubleDecode_Int64Op = 255+primOpTag FloatGtOp = 256+primOpTag FloatGeOp = 257+primOpTag FloatEqOp = 258+primOpTag FloatNeOp = 259+primOpTag FloatLtOp = 260+primOpTag FloatLeOp = 261+primOpTag FloatAddOp = 262+primOpTag FloatSubOp = 263+primOpTag FloatMulOp = 264+primOpTag FloatDivOp = 265+primOpTag FloatNegOp = 266+primOpTag FloatFabsOp = 267+primOpTag FloatToIntOp = 268+primOpTag FloatExpOp = 269+primOpTag FloatExpM1Op = 270+primOpTag FloatLogOp = 271+primOpTag FloatLog1POp = 272+primOpTag FloatSqrtOp = 273+primOpTag FloatSinOp = 274+primOpTag FloatCosOp = 275+primOpTag FloatTanOp = 276+primOpTag FloatAsinOp = 277+primOpTag FloatAcosOp = 278+primOpTag FloatAtanOp = 279+primOpTag FloatSinhOp = 280+primOpTag FloatCoshOp = 281+primOpTag FloatTanhOp = 282+primOpTag FloatAsinhOp = 283+primOpTag FloatAcoshOp = 284+primOpTag FloatAtanhOp = 285+primOpTag FloatPowerOp = 286+primOpTag FloatToDoubleOp = 287+primOpTag FloatDecode_IntOp = 288+primOpTag NewArrayOp = 289+primOpTag SameMutableArrayOp = 290+primOpTag ReadArrayOp = 291+primOpTag WriteArrayOp = 292+primOpTag SizeofArrayOp = 293+primOpTag SizeofMutableArrayOp = 294+primOpTag IndexArrayOp = 295+primOpTag UnsafeFreezeArrayOp = 296+primOpTag UnsafeThawArrayOp = 297+primOpTag CopyArrayOp = 298+primOpTag CopyMutableArrayOp = 299+primOpTag CloneArrayOp = 300+primOpTag CloneMutableArrayOp = 301+primOpTag FreezeArrayOp = 302+primOpTag ThawArrayOp = 303+primOpTag CasArrayOp = 304+primOpTag NewSmallArrayOp = 305+primOpTag SameSmallMutableArrayOp = 306+primOpTag ShrinkSmallMutableArrayOp_Char = 307+primOpTag ReadSmallArrayOp = 308+primOpTag WriteSmallArrayOp = 309+primOpTag SizeofSmallArrayOp = 310+primOpTag SizeofSmallMutableArrayOp = 311+primOpTag GetSizeofSmallMutableArrayOp = 312+primOpTag IndexSmallArrayOp = 313+primOpTag UnsafeFreezeSmallArrayOp = 314+primOpTag UnsafeThawSmallArrayOp = 315+primOpTag CopySmallArrayOp = 316+primOpTag CopySmallMutableArrayOp = 317+primOpTag CloneSmallArrayOp = 318+primOpTag CloneSmallMutableArrayOp = 319+primOpTag FreezeSmallArrayOp = 320+primOpTag ThawSmallArrayOp = 321+primOpTag CasSmallArrayOp = 322+primOpTag NewByteArrayOp_Char = 323+primOpTag NewPinnedByteArrayOp_Char = 324+primOpTag NewAlignedPinnedByteArrayOp_Char = 325+primOpTag MutableByteArrayIsPinnedOp = 326+primOpTag ByteArrayIsPinnedOp = 327+primOpTag ByteArrayContents_Char = 328+primOpTag MutableByteArrayContents_Char = 329+primOpTag SameMutableByteArrayOp = 330+primOpTag ShrinkMutableByteArrayOp_Char = 331+primOpTag ResizeMutableByteArrayOp_Char = 332+primOpTag UnsafeFreezeByteArrayOp = 333+primOpTag SizeofByteArrayOp = 334+primOpTag SizeofMutableByteArrayOp = 335+primOpTag GetSizeofMutableByteArrayOp = 336+primOpTag IndexByteArrayOp_Char = 337+primOpTag IndexByteArrayOp_WideChar = 338+primOpTag IndexByteArrayOp_Int = 339+primOpTag IndexByteArrayOp_Word = 340+primOpTag IndexByteArrayOp_Addr = 341+primOpTag IndexByteArrayOp_Float = 342+primOpTag IndexByteArrayOp_Double = 343+primOpTag IndexByteArrayOp_StablePtr = 344+primOpTag IndexByteArrayOp_Int8 = 345+primOpTag IndexByteArrayOp_Int16 = 346+primOpTag IndexByteArrayOp_Int32 = 347+primOpTag IndexByteArrayOp_Int64 = 348+primOpTag IndexByteArrayOp_Word8 = 349+primOpTag IndexByteArrayOp_Word16 = 350+primOpTag IndexByteArrayOp_Word32 = 351+primOpTag IndexByteArrayOp_Word64 = 352+primOpTag IndexByteArrayOp_Word8AsChar = 353+primOpTag IndexByteArrayOp_Word8AsWideChar = 354+primOpTag IndexByteArrayOp_Word8AsInt = 355+primOpTag IndexByteArrayOp_Word8AsWord = 356+primOpTag IndexByteArrayOp_Word8AsAddr = 357+primOpTag IndexByteArrayOp_Word8AsFloat = 358+primOpTag IndexByteArrayOp_Word8AsDouble = 359+primOpTag IndexByteArrayOp_Word8AsStablePtr = 360+primOpTag IndexByteArrayOp_Word8AsInt16 = 361+primOpTag IndexByteArrayOp_Word8AsInt32 = 362+primOpTag IndexByteArrayOp_Word8AsInt64 = 363+primOpTag IndexByteArrayOp_Word8AsWord16 = 364+primOpTag IndexByteArrayOp_Word8AsWord32 = 365+primOpTag IndexByteArrayOp_Word8AsWord64 = 366+primOpTag ReadByteArrayOp_Char = 367+primOpTag ReadByteArrayOp_WideChar = 368+primOpTag ReadByteArrayOp_Int = 369+primOpTag ReadByteArrayOp_Word = 370+primOpTag ReadByteArrayOp_Addr = 371+primOpTag ReadByteArrayOp_Float = 372+primOpTag ReadByteArrayOp_Double = 373+primOpTag ReadByteArrayOp_StablePtr = 374+primOpTag ReadByteArrayOp_Int8 = 375+primOpTag ReadByteArrayOp_Int16 = 376+primOpTag ReadByteArrayOp_Int32 = 377+primOpTag ReadByteArrayOp_Int64 = 378+primOpTag ReadByteArrayOp_Word8 = 379+primOpTag ReadByteArrayOp_Word16 = 380+primOpTag ReadByteArrayOp_Word32 = 381+primOpTag ReadByteArrayOp_Word64 = 382+primOpTag ReadByteArrayOp_Word8AsChar = 383+primOpTag ReadByteArrayOp_Word8AsWideChar = 384+primOpTag ReadByteArrayOp_Word8AsInt = 385+primOpTag ReadByteArrayOp_Word8AsWord = 386+primOpTag ReadByteArrayOp_Word8AsAddr = 387+primOpTag ReadByteArrayOp_Word8AsFloat = 388+primOpTag ReadByteArrayOp_Word8AsDouble = 389+primOpTag ReadByteArrayOp_Word8AsStablePtr = 390+primOpTag ReadByteArrayOp_Word8AsInt16 = 391+primOpTag ReadByteArrayOp_Word8AsInt32 = 392+primOpTag ReadByteArrayOp_Word8AsInt64 = 393+primOpTag ReadByteArrayOp_Word8AsWord16 = 394+primOpTag ReadByteArrayOp_Word8AsWord32 = 395+primOpTag ReadByteArrayOp_Word8AsWord64 = 396+primOpTag WriteByteArrayOp_Char = 397+primOpTag WriteByteArrayOp_WideChar = 398+primOpTag WriteByteArrayOp_Int = 399+primOpTag WriteByteArrayOp_Word = 400+primOpTag WriteByteArrayOp_Addr = 401+primOpTag WriteByteArrayOp_Float = 402+primOpTag WriteByteArrayOp_Double = 403+primOpTag WriteByteArrayOp_StablePtr = 404+primOpTag WriteByteArrayOp_Int8 = 405+primOpTag WriteByteArrayOp_Int16 = 406+primOpTag WriteByteArrayOp_Int32 = 407+primOpTag WriteByteArrayOp_Int64 = 408+primOpTag WriteByteArrayOp_Word8 = 409+primOpTag WriteByteArrayOp_Word16 = 410+primOpTag WriteByteArrayOp_Word32 = 411+primOpTag WriteByteArrayOp_Word64 = 412+primOpTag WriteByteArrayOp_Word8AsChar = 413+primOpTag WriteByteArrayOp_Word8AsWideChar = 414+primOpTag WriteByteArrayOp_Word8AsInt = 415+primOpTag WriteByteArrayOp_Word8AsWord = 416+primOpTag WriteByteArrayOp_Word8AsAddr = 417+primOpTag WriteByteArrayOp_Word8AsFloat = 418+primOpTag WriteByteArrayOp_Word8AsDouble = 419+primOpTag WriteByteArrayOp_Word8AsStablePtr = 420+primOpTag WriteByteArrayOp_Word8AsInt16 = 421+primOpTag WriteByteArrayOp_Word8AsInt32 = 422+primOpTag WriteByteArrayOp_Word8AsInt64 = 423+primOpTag WriteByteArrayOp_Word8AsWord16 = 424+primOpTag WriteByteArrayOp_Word8AsWord32 = 425+primOpTag WriteByteArrayOp_Word8AsWord64 = 426+primOpTag CompareByteArraysOp = 427+primOpTag CopyByteArrayOp = 428+primOpTag CopyMutableByteArrayOp = 429+primOpTag CopyByteArrayToAddrOp = 430+primOpTag CopyMutableByteArrayToAddrOp = 431+primOpTag CopyAddrToByteArrayOp = 432+primOpTag SetByteArrayOp = 433+primOpTag AtomicReadByteArrayOp_Int = 434+primOpTag AtomicWriteByteArrayOp_Int = 435+primOpTag CasByteArrayOp_Int = 436+primOpTag FetchAddByteArrayOp_Int = 437+primOpTag FetchSubByteArrayOp_Int = 438+primOpTag FetchAndByteArrayOp_Int = 439+primOpTag FetchNandByteArrayOp_Int = 440+primOpTag FetchOrByteArrayOp_Int = 441+primOpTag FetchXorByteArrayOp_Int = 442+primOpTag NewArrayArrayOp = 443+primOpTag SameMutableArrayArrayOp = 444+primOpTag UnsafeFreezeArrayArrayOp = 445+primOpTag SizeofArrayArrayOp = 446+primOpTag SizeofMutableArrayArrayOp = 447+primOpTag IndexArrayArrayOp_ByteArray = 448+primOpTag IndexArrayArrayOp_ArrayArray = 449+primOpTag ReadArrayArrayOp_ByteArray = 450+primOpTag ReadArrayArrayOp_MutableByteArray = 451+primOpTag ReadArrayArrayOp_ArrayArray = 452+primOpTag ReadArrayArrayOp_MutableArrayArray = 453+primOpTag WriteArrayArrayOp_ByteArray = 454+primOpTag WriteArrayArrayOp_MutableByteArray = 455+primOpTag WriteArrayArrayOp_ArrayArray = 456+primOpTag WriteArrayArrayOp_MutableArrayArray = 457+primOpTag CopyArrayArrayOp = 458+primOpTag CopyMutableArrayArrayOp = 459+primOpTag AddrAddOp = 460+primOpTag AddrSubOp = 461+primOpTag AddrRemOp = 462+primOpTag AddrToIntOp = 463+primOpTag IntToAddrOp = 464+primOpTag AddrGtOp = 465+primOpTag AddrGeOp = 466+primOpTag AddrEqOp = 467+primOpTag AddrNeOp = 468+primOpTag AddrLtOp = 469+primOpTag AddrLeOp = 470+primOpTag IndexOffAddrOp_Char = 471+primOpTag IndexOffAddrOp_WideChar = 472+primOpTag IndexOffAddrOp_Int = 473+primOpTag IndexOffAddrOp_Word = 474+primOpTag IndexOffAddrOp_Addr = 475+primOpTag IndexOffAddrOp_Float = 476+primOpTag IndexOffAddrOp_Double = 477+primOpTag IndexOffAddrOp_StablePtr = 478+primOpTag IndexOffAddrOp_Int8 = 479+primOpTag IndexOffAddrOp_Int16 = 480+primOpTag IndexOffAddrOp_Int32 = 481+primOpTag IndexOffAddrOp_Int64 = 482+primOpTag IndexOffAddrOp_Word8 = 483+primOpTag IndexOffAddrOp_Word16 = 484+primOpTag IndexOffAddrOp_Word32 = 485+primOpTag IndexOffAddrOp_Word64 = 486+primOpTag ReadOffAddrOp_Char = 487+primOpTag ReadOffAddrOp_WideChar = 488+primOpTag ReadOffAddrOp_Int = 489+primOpTag ReadOffAddrOp_Word = 490+primOpTag ReadOffAddrOp_Addr = 491+primOpTag ReadOffAddrOp_Float = 492+primOpTag ReadOffAddrOp_Double = 493+primOpTag ReadOffAddrOp_StablePtr = 494+primOpTag ReadOffAddrOp_Int8 = 495+primOpTag ReadOffAddrOp_Int16 = 496+primOpTag ReadOffAddrOp_Int32 = 497+primOpTag ReadOffAddrOp_Int64 = 498+primOpTag ReadOffAddrOp_Word8 = 499+primOpTag ReadOffAddrOp_Word16 = 500+primOpTag ReadOffAddrOp_Word32 = 501+primOpTag ReadOffAddrOp_Word64 = 502+primOpTag WriteOffAddrOp_Char = 503+primOpTag WriteOffAddrOp_WideChar = 504+primOpTag WriteOffAddrOp_Int = 505+primOpTag WriteOffAddrOp_Word = 506+primOpTag WriteOffAddrOp_Addr = 507+primOpTag WriteOffAddrOp_Float = 508+primOpTag WriteOffAddrOp_Double = 509+primOpTag WriteOffAddrOp_StablePtr = 510+primOpTag WriteOffAddrOp_Int8 = 511+primOpTag WriteOffAddrOp_Int16 = 512+primOpTag WriteOffAddrOp_Int32 = 513+primOpTag WriteOffAddrOp_Int64 = 514+primOpTag WriteOffAddrOp_Word8 = 515+primOpTag WriteOffAddrOp_Word16 = 516+primOpTag WriteOffAddrOp_Word32 = 517+primOpTag WriteOffAddrOp_Word64 = 518+primOpTag InterlockedExchange_Addr = 519+primOpTag InterlockedExchange_Word = 520+primOpTag CasAddrOp_Addr = 521+primOpTag CasAddrOp_Word = 522+primOpTag FetchAddAddrOp_Word = 523+primOpTag FetchSubAddrOp_Word = 524+primOpTag FetchAndAddrOp_Word = 525+primOpTag FetchNandAddrOp_Word = 526+primOpTag FetchOrAddrOp_Word = 527+primOpTag FetchXorAddrOp_Word = 528+primOpTag AtomicReadAddrOp_Word = 529+primOpTag AtomicWriteAddrOp_Word = 530+primOpTag NewMutVarOp = 531+primOpTag ReadMutVarOp = 532+primOpTag WriteMutVarOp = 533+primOpTag SameMutVarOp = 534+primOpTag AtomicModifyMutVar2Op = 535+primOpTag AtomicModifyMutVar_Op = 536+primOpTag CasMutVarOp = 537+primOpTag CatchOp = 538+primOpTag RaiseOp = 539+primOpTag RaiseIOOp = 540+primOpTag MaskAsyncExceptionsOp = 541+primOpTag MaskUninterruptibleOp = 542+primOpTag UnmaskAsyncExceptionsOp = 543+primOpTag MaskStatus = 544+primOpTag AtomicallyOp = 545+primOpTag RetryOp = 546+primOpTag CatchRetryOp = 547+primOpTag CatchSTMOp = 548+primOpTag NewTVarOp = 549+primOpTag ReadTVarOp = 550+primOpTag ReadTVarIOOp = 551+primOpTag WriteTVarOp = 552+primOpTag SameTVarOp = 553+primOpTag NewMVarOp = 554+primOpTag TakeMVarOp = 555+primOpTag TryTakeMVarOp = 556+primOpTag PutMVarOp = 557+primOpTag TryPutMVarOp = 558+primOpTag ReadMVarOp = 559+primOpTag TryReadMVarOp = 560+primOpTag SameMVarOp = 561+primOpTag IsEmptyMVarOp = 562+primOpTag NewIOPortrOp = 563+primOpTag ReadIOPortOp = 564+primOpTag WriteIOPortOp = 565+primOpTag SameIOPortOp = 566+primOpTag DelayOp = 567+primOpTag WaitReadOp = 568+primOpTag WaitWriteOp = 569+primOpTag ForkOp = 570+primOpTag ForkOnOp = 571+primOpTag KillThreadOp = 572+primOpTag YieldOp = 573+primOpTag MyThreadIdOp = 574+primOpTag LabelThreadOp = 575+primOpTag IsCurrentThreadBoundOp = 576+primOpTag NoDuplicateOp = 577+primOpTag ThreadStatusOp = 578+primOpTag MkWeakOp = 579+primOpTag MkWeakNoFinalizerOp = 580+primOpTag AddCFinalizerToWeakOp = 581+primOpTag DeRefWeakOp = 582+primOpTag FinalizeWeakOp = 583+primOpTag TouchOp = 584+primOpTag MakeStablePtrOp = 585+primOpTag DeRefStablePtrOp = 586+primOpTag EqStablePtrOp = 587+primOpTag MakeStableNameOp = 588+primOpTag EqStableNameOp = 589+primOpTag StableNameToIntOp = 590+primOpTag CompactNewOp = 591+primOpTag CompactResizeOp = 592+primOpTag CompactContainsOp = 593+primOpTag CompactContainsAnyOp = 594+primOpTag CompactGetFirstBlockOp = 595+primOpTag CompactGetNextBlockOp = 596+primOpTag CompactAllocateBlockOp = 597+primOpTag CompactFixupPointersOp = 598+primOpTag CompactAdd = 599+primOpTag CompactAddWithSharing = 600+primOpTag CompactSize = 601+primOpTag ReallyUnsafePtrEqualityOp = 602+primOpTag ParOp = 603+primOpTag SparkOp = 604+primOpTag SeqOp = 605+primOpTag GetSparkOp = 606+primOpTag NumSparks = 607+primOpTag KeepAliveOp = 608+primOpTag DataToTagOp = 609+primOpTag TagToEnumOp = 610+primOpTag AddrToAnyOp = 611+primOpTag AnyToAddrOp = 612+primOpTag MkApUpd0_Op = 613+primOpTag NewBCOOp = 614+primOpTag UnpackClosureOp = 615+primOpTag ClosureSizeOp = 616+primOpTag GetApStackValOp = 617+primOpTag GetCCSOfOp = 618+primOpTag GetCurrentCCSOp = 619+primOpTag ClearCCSOp = 620+primOpTag WhereFromOp = 621+primOpTag TraceEventOp = 622+primOpTag TraceEventBinaryOp = 623+primOpTag TraceMarkerOp = 624+primOpTag SetThreadAllocationCounter = 625+primOpTag (VecBroadcastOp IntVec 16 W8) = 626+primOpTag (VecBroadcastOp IntVec 8 W16) = 627+primOpTag (VecBroadcastOp IntVec 4 W32) = 628+primOpTag (VecBroadcastOp IntVec 2 W64) = 629+primOpTag (VecBroadcastOp IntVec 32 W8) = 630+primOpTag (VecBroadcastOp IntVec 16 W16) = 631+primOpTag (VecBroadcastOp IntVec 8 W32) = 632+primOpTag (VecBroadcastOp IntVec 4 W64) = 633+primOpTag (VecBroadcastOp IntVec 64 W8) = 634+primOpTag (VecBroadcastOp IntVec 32 W16) = 635+primOpTag (VecBroadcastOp IntVec 16 W32) = 636+primOpTag (VecBroadcastOp IntVec 8 W64) = 637+primOpTag (VecBroadcastOp WordVec 16 W8) = 638+primOpTag (VecBroadcastOp WordVec 8 W16) = 639+primOpTag (VecBroadcastOp WordVec 4 W32) = 640+primOpTag (VecBroadcastOp WordVec 2 W64) = 641+primOpTag (VecBroadcastOp WordVec 32 W8) = 642+primOpTag (VecBroadcastOp WordVec 16 W16) = 643+primOpTag (VecBroadcastOp WordVec 8 W32) = 644+primOpTag (VecBroadcastOp WordVec 4 W64) = 645+primOpTag (VecBroadcastOp WordVec 64 W8) = 646+primOpTag (VecBroadcastOp WordVec 32 W16) = 647+primOpTag (VecBroadcastOp WordVec 16 W32) = 648+primOpTag (VecBroadcastOp WordVec 8 W64) = 649+primOpTag (VecBroadcastOp FloatVec 4 W32) = 650+primOpTag (VecBroadcastOp FloatVec 2 W64) = 651+primOpTag (VecBroadcastOp FloatVec 8 W32) = 652+primOpTag (VecBroadcastOp FloatVec 4 W64) = 653+primOpTag (VecBroadcastOp FloatVec 16 W32) = 654+primOpTag (VecBroadcastOp FloatVec 8 W64) = 655+primOpTag (VecPackOp IntVec 16 W8) = 656+primOpTag (VecPackOp IntVec 8 W16) = 657+primOpTag (VecPackOp IntVec 4 W32) = 658+primOpTag (VecPackOp IntVec 2 W64) = 659+primOpTag (VecPackOp IntVec 32 W8) = 660+primOpTag (VecPackOp IntVec 16 W16) = 661+primOpTag (VecPackOp IntVec 8 W32) = 662+primOpTag (VecPackOp IntVec 4 W64) = 663+primOpTag (VecPackOp IntVec 64 W8) = 664+primOpTag (VecPackOp IntVec 32 W16) = 665+primOpTag (VecPackOp IntVec 16 W32) = 666+primOpTag (VecPackOp IntVec 8 W64) = 667+primOpTag (VecPackOp WordVec 16 W8) = 668+primOpTag (VecPackOp WordVec 8 W16) = 669+primOpTag (VecPackOp WordVec 4 W32) = 670+primOpTag (VecPackOp WordVec 2 W64) = 671+primOpTag (VecPackOp WordVec 32 W8) = 672+primOpTag (VecPackOp WordVec 16 W16) = 673+primOpTag (VecPackOp WordVec 8 W32) = 674+primOpTag (VecPackOp WordVec 4 W64) = 675+primOpTag (VecPackOp WordVec 64 W8) = 676+primOpTag (VecPackOp WordVec 32 W16) = 677+primOpTag (VecPackOp WordVec 16 W32) = 678+primOpTag (VecPackOp WordVec 8 W64) = 679+primOpTag (VecPackOp FloatVec 4 W32) = 680+primOpTag (VecPackOp FloatVec 2 W64) = 681+primOpTag (VecPackOp FloatVec 8 W32) = 682+primOpTag (VecPackOp FloatVec 4 W64) = 683+primOpTag (VecPackOp FloatVec 16 W32) = 684+primOpTag (VecPackOp FloatVec 8 W64) = 685+primOpTag (VecUnpackOp IntVec 16 W8) = 686+primOpTag (VecUnpackOp IntVec 8 W16) = 687+primOpTag (VecUnpackOp IntVec 4 W32) = 688+primOpTag (VecUnpackOp IntVec 2 W64) = 689+primOpTag (VecUnpackOp IntVec 32 W8) = 690+primOpTag (VecUnpackOp IntVec 16 W16) = 691+primOpTag (VecUnpackOp IntVec 8 W32) = 692+primOpTag (VecUnpackOp IntVec 4 W64) = 693+primOpTag (VecUnpackOp IntVec 64 W8) = 694+primOpTag (VecUnpackOp IntVec 32 W16) = 695+primOpTag (VecUnpackOp IntVec 16 W32) = 696+primOpTag (VecUnpackOp IntVec 8 W64) = 697+primOpTag (VecUnpackOp WordVec 16 W8) = 698+primOpTag (VecUnpackOp WordVec 8 W16) = 699+primOpTag (VecUnpackOp WordVec 4 W32) = 700+primOpTag (VecUnpackOp WordVec 2 W64) = 701+primOpTag (VecUnpackOp WordVec 32 W8) = 702+primOpTag (VecUnpackOp WordVec 16 W16) = 703+primOpTag (VecUnpackOp WordVec 8 W32) = 704+primOpTag (VecUnpackOp WordVec 4 W64) = 705+primOpTag (VecUnpackOp WordVec 64 W8) = 706+primOpTag (VecUnpackOp WordVec 32 W16) = 707+primOpTag (VecUnpackOp WordVec 16 W32) = 708+primOpTag (VecUnpackOp WordVec 8 W64) = 709+primOpTag (VecUnpackOp FloatVec 4 W32) = 710+primOpTag (VecUnpackOp FloatVec 2 W64) = 711+primOpTag (VecUnpackOp FloatVec 8 W32) = 712+primOpTag (VecUnpackOp FloatVec 4 W64) = 713+primOpTag (VecUnpackOp FloatVec 16 W32) = 714+primOpTag (VecUnpackOp FloatVec 8 W64) = 715+primOpTag (VecInsertOp IntVec 16 W8) = 716+primOpTag (VecInsertOp IntVec 8 W16) = 717+primOpTag (VecInsertOp IntVec 4 W32) = 718+primOpTag (VecInsertOp IntVec 2 W64) = 719+primOpTag (VecInsertOp IntVec 32 W8) = 720+primOpTag (VecInsertOp IntVec 16 W16) = 721+primOpTag (VecInsertOp IntVec 8 W32) = 722+primOpTag (VecInsertOp IntVec 4 W64) = 723+primOpTag (VecInsertOp IntVec 64 W8) = 724+primOpTag (VecInsertOp IntVec 32 W16) = 725+primOpTag (VecInsertOp IntVec 16 W32) = 726+primOpTag (VecInsertOp IntVec 8 W64) = 727+primOpTag (VecInsertOp WordVec 16 W8) = 728+primOpTag (VecInsertOp WordVec 8 W16) = 729+primOpTag (VecInsertOp WordVec 4 W32) = 730+primOpTag (VecInsertOp WordVec 2 W64) = 731+primOpTag (VecInsertOp WordVec 32 W8) = 732+primOpTag (VecInsertOp WordVec 16 W16) = 733+primOpTag (VecInsertOp WordVec 8 W32) = 734+primOpTag (VecInsertOp WordVec 4 W64) = 735+primOpTag (VecInsertOp WordVec 64 W8) = 736+primOpTag (VecInsertOp WordVec 32 W16) = 737+primOpTag (VecInsertOp WordVec 16 W32) = 738+primOpTag (VecInsertOp WordVec 8 W64) = 739+primOpTag (VecInsertOp FloatVec 4 W32) = 740+primOpTag (VecInsertOp FloatVec 2 W64) = 741+primOpTag (VecInsertOp FloatVec 8 W32) = 742+primOpTag (VecInsertOp FloatVec 4 W64) = 743+primOpTag (VecInsertOp FloatVec 16 W32) = 744+primOpTag (VecInsertOp FloatVec 8 W64) = 745+primOpTag (VecAddOp IntVec 16 W8) = 746+primOpTag (VecAddOp IntVec 8 W16) = 747+primOpTag (VecAddOp IntVec 4 W32) = 748+primOpTag (VecAddOp IntVec 2 W64) = 749+primOpTag (VecAddOp IntVec 32 W8) = 750+primOpTag (VecAddOp IntVec 16 W16) = 751+primOpTag (VecAddOp IntVec 8 W32) = 752+primOpTag (VecAddOp IntVec 4 W64) = 753+primOpTag (VecAddOp IntVec 64 W8) = 754+primOpTag (VecAddOp IntVec 32 W16) = 755+primOpTag (VecAddOp IntVec 16 W32) = 756+primOpTag (VecAddOp IntVec 8 W64) = 757+primOpTag (VecAddOp WordVec 16 W8) = 758+primOpTag (VecAddOp WordVec 8 W16) = 759+primOpTag (VecAddOp WordVec 4 W32) = 760+primOpTag (VecAddOp WordVec 2 W64) = 761+primOpTag (VecAddOp WordVec 32 W8) = 762+primOpTag (VecAddOp WordVec 16 W16) = 763+primOpTag (VecAddOp WordVec 8 W32) = 764+primOpTag (VecAddOp WordVec 4 W64) = 765+primOpTag (VecAddOp WordVec 64 W8) = 766+primOpTag (VecAddOp WordVec 32 W16) = 767+primOpTag (VecAddOp WordVec 16 W32) = 768+primOpTag (VecAddOp WordVec 8 W64) = 769+primOpTag (VecAddOp FloatVec 4 W32) = 770+primOpTag (VecAddOp FloatVec 2 W64) = 771+primOpTag (VecAddOp FloatVec 8 W32) = 772+primOpTag (VecAddOp FloatVec 4 W64) = 773+primOpTag (VecAddOp FloatVec 16 W32) = 774+primOpTag (VecAddOp FloatVec 8 W64) = 775+primOpTag (VecSubOp IntVec 16 W8) = 776+primOpTag (VecSubOp IntVec 8 W16) = 777+primOpTag (VecSubOp IntVec 4 W32) = 778+primOpTag (VecSubOp IntVec 2 W64) = 779+primOpTag (VecSubOp IntVec 32 W8) = 780+primOpTag (VecSubOp IntVec 16 W16) = 781+primOpTag (VecSubOp IntVec 8 W32) = 782+primOpTag (VecSubOp IntVec 4 W64) = 783+primOpTag (VecSubOp IntVec 64 W8) = 784+primOpTag (VecSubOp IntVec 32 W16) = 785+primOpTag (VecSubOp IntVec 16 W32) = 786+primOpTag (VecSubOp IntVec 8 W64) = 787+primOpTag (VecSubOp WordVec 16 W8) = 788+primOpTag (VecSubOp WordVec 8 W16) = 789+primOpTag (VecSubOp WordVec 4 W32) = 790+primOpTag (VecSubOp WordVec 2 W64) = 791+primOpTag (VecSubOp WordVec 32 W8) = 792+primOpTag (VecSubOp WordVec 16 W16) = 793+primOpTag (VecSubOp WordVec 8 W32) = 794+primOpTag (VecSubOp WordVec 4 W64) = 795+primOpTag (VecSubOp WordVec 64 W8) = 796+primOpTag (VecSubOp WordVec 32 W16) = 797+primOpTag (VecSubOp WordVec 16 W32) = 798+primOpTag (VecSubOp WordVec 8 W64) = 799+primOpTag (VecSubOp FloatVec 4 W32) = 800+primOpTag (VecSubOp FloatVec 2 W64) = 801+primOpTag (VecSubOp FloatVec 8 W32) = 802+primOpTag (VecSubOp FloatVec 4 W64) = 803+primOpTag (VecSubOp FloatVec 16 W32) = 804+primOpTag (VecSubOp FloatVec 8 W64) = 805+primOpTag (VecMulOp IntVec 16 W8) = 806+primOpTag (VecMulOp IntVec 8 W16) = 807+primOpTag (VecMulOp IntVec 4 W32) = 808+primOpTag (VecMulOp IntVec 2 W64) = 809+primOpTag (VecMulOp IntVec 32 W8) = 810+primOpTag (VecMulOp IntVec 16 W16) = 811+primOpTag (VecMulOp IntVec 8 W32) = 812+primOpTag (VecMulOp IntVec 4 W64) = 813+primOpTag (VecMulOp IntVec 64 W8) = 814+primOpTag (VecMulOp IntVec 32 W16) = 815+primOpTag (VecMulOp IntVec 16 W32) = 816+primOpTag (VecMulOp IntVec 8 W64) = 817+primOpTag (VecMulOp WordVec 16 W8) = 818+primOpTag (VecMulOp WordVec 8 W16) = 819+primOpTag (VecMulOp WordVec 4 W32) = 820+primOpTag (VecMulOp WordVec 2 W64) = 821+primOpTag (VecMulOp WordVec 32 W8) = 822+primOpTag (VecMulOp WordVec 16 W16) = 823+primOpTag (VecMulOp WordVec 8 W32) = 824+primOpTag (VecMulOp WordVec 4 W64) = 825+primOpTag (VecMulOp WordVec 64 W8) = 826+primOpTag (VecMulOp WordVec 32 W16) = 827+primOpTag (VecMulOp WordVec 16 W32) = 828+primOpTag (VecMulOp WordVec 8 W64) = 829+primOpTag (VecMulOp FloatVec 4 W32) = 830+primOpTag (VecMulOp FloatVec 2 W64) = 831+primOpTag (VecMulOp FloatVec 8 W32) = 832+primOpTag (VecMulOp FloatVec 4 W64) = 833+primOpTag (VecMulOp FloatVec 16 W32) = 834+primOpTag (VecMulOp FloatVec 8 W64) = 835+primOpTag (VecDivOp FloatVec 4 W32) = 836+primOpTag (VecDivOp FloatVec 2 W64) = 837+primOpTag (VecDivOp FloatVec 8 W32) = 838+primOpTag (VecDivOp FloatVec 4 W64) = 839+primOpTag (VecDivOp FloatVec 16 W32) = 840+primOpTag (VecDivOp FloatVec 8 W64) = 841+primOpTag (VecQuotOp IntVec 16 W8) = 842+primOpTag (VecQuotOp IntVec 8 W16) = 843+primOpTag (VecQuotOp IntVec 4 W32) = 844+primOpTag (VecQuotOp IntVec 2 W64) = 845+primOpTag (VecQuotOp IntVec 32 W8) = 846+primOpTag (VecQuotOp IntVec 16 W16) = 847+primOpTag (VecQuotOp IntVec 8 W32) = 848+primOpTag (VecQuotOp IntVec 4 W64) = 849+primOpTag (VecQuotOp IntVec 64 W8) = 850+primOpTag (VecQuotOp IntVec 32 W16) = 851+primOpTag (VecQuotOp IntVec 16 W32) = 852+primOpTag (VecQuotOp IntVec 8 W64) = 853+primOpTag (VecQuotOp WordVec 16 W8) = 854+primOpTag (VecQuotOp WordVec 8 W16) = 855+primOpTag (VecQuotOp WordVec 4 W32) = 856+primOpTag (VecQuotOp WordVec 2 W64) = 857+primOpTag (VecQuotOp WordVec 32 W8) = 858+primOpTag (VecQuotOp WordVec 16 W16) = 859+primOpTag (VecQuotOp WordVec 8 W32) = 860+primOpTag (VecQuotOp WordVec 4 W64) = 861+primOpTag (VecQuotOp WordVec 64 W8) = 862+primOpTag (VecQuotOp WordVec 32 W16) = 863+primOpTag (VecQuotOp WordVec 16 W32) = 864+primOpTag (VecQuotOp WordVec 8 W64) = 865+primOpTag (VecRemOp IntVec 16 W8) = 866+primOpTag (VecRemOp IntVec 8 W16) = 867+primOpTag (VecRemOp IntVec 4 W32) = 868+primOpTag (VecRemOp IntVec 2 W64) = 869+primOpTag (VecRemOp IntVec 32 W8) = 870+primOpTag (VecRemOp IntVec 16 W16) = 871+primOpTag (VecRemOp IntVec 8 W32) = 872+primOpTag (VecRemOp IntVec 4 W64) = 873+primOpTag (VecRemOp IntVec 64 W8) = 874+primOpTag (VecRemOp IntVec 32 W16) = 875+primOpTag (VecRemOp IntVec 16 W32) = 876+primOpTag (VecRemOp IntVec 8 W64) = 877+primOpTag (VecRemOp WordVec 16 W8) = 878+primOpTag (VecRemOp WordVec 8 W16) = 879+primOpTag (VecRemOp WordVec 4 W32) = 880+primOpTag (VecRemOp WordVec 2 W64) = 881+primOpTag (VecRemOp WordVec 32 W8) = 882+primOpTag (VecRemOp WordVec 16 W16) = 883+primOpTag (VecRemOp WordVec 8 W32) = 884+primOpTag (VecRemOp WordVec 4 W64) = 885+primOpTag (VecRemOp WordVec 64 W8) = 886+primOpTag (VecRemOp WordVec 32 W16) = 887+primOpTag (VecRemOp WordVec 16 W32) = 888+primOpTag (VecRemOp WordVec 8 W64) = 889+primOpTag (VecNegOp IntVec 16 W8) = 890+primOpTag (VecNegOp IntVec 8 W16) = 891+primOpTag (VecNegOp IntVec 4 W32) = 892+primOpTag (VecNegOp IntVec 2 W64) = 893+primOpTag (VecNegOp IntVec 32 W8) = 894+primOpTag (VecNegOp IntVec 16 W16) = 895+primOpTag (VecNegOp IntVec 8 W32) = 896+primOpTag (VecNegOp IntVec 4 W64) = 897+primOpTag (VecNegOp IntVec 64 W8) = 898+primOpTag (VecNegOp IntVec 32 W16) = 899+primOpTag (VecNegOp IntVec 16 W32) = 900+primOpTag (VecNegOp IntVec 8 W64) = 901+primOpTag (VecNegOp FloatVec 4 W32) = 902+primOpTag (VecNegOp FloatVec 2 W64) = 903+primOpTag (VecNegOp FloatVec 8 W32) = 904+primOpTag (VecNegOp FloatVec 4 W64) = 905+primOpTag (VecNegOp FloatVec 16 W32) = 906+primOpTag (VecNegOp FloatVec 8 W64) = 907+primOpTag (VecIndexByteArrayOp IntVec 16 W8) = 908+primOpTag (VecIndexByteArrayOp IntVec 8 W16) = 909+primOpTag (VecIndexByteArrayOp IntVec 4 W32) = 910+primOpTag (VecIndexByteArrayOp IntVec 2 W64) = 911+primOpTag (VecIndexByteArrayOp IntVec 32 W8) = 912+primOpTag (VecIndexByteArrayOp IntVec 16 W16) = 913+primOpTag (VecIndexByteArrayOp IntVec 8 W32) = 914+primOpTag (VecIndexByteArrayOp IntVec 4 W64) = 915+primOpTag (VecIndexByteArrayOp IntVec 64 W8) = 916+primOpTag (VecIndexByteArrayOp IntVec 32 W16) = 917+primOpTag (VecIndexByteArrayOp IntVec 16 W32) = 918+primOpTag (VecIndexByteArrayOp IntVec 8 W64) = 919+primOpTag (VecIndexByteArrayOp WordVec 16 W8) = 920+primOpTag (VecIndexByteArrayOp WordVec 8 W16) = 921+primOpTag (VecIndexByteArrayOp WordVec 4 W32) = 922+primOpTag (VecIndexByteArrayOp WordVec 2 W64) = 923+primOpTag (VecIndexByteArrayOp WordVec 32 W8) = 924+primOpTag (VecIndexByteArrayOp WordVec 16 W16) = 925+primOpTag (VecIndexByteArrayOp WordVec 8 W32) = 926+primOpTag (VecIndexByteArrayOp WordVec 4 W64) = 927+primOpTag (VecIndexByteArrayOp WordVec 64 W8) = 928+primOpTag (VecIndexByteArrayOp WordVec 32 W16) = 929+primOpTag (VecIndexByteArrayOp WordVec 16 W32) = 930+primOpTag (VecIndexByteArrayOp WordVec 8 W64) = 931+primOpTag (VecIndexByteArrayOp FloatVec 4 W32) = 932+primOpTag (VecIndexByteArrayOp FloatVec 2 W64) = 933+primOpTag (VecIndexByteArrayOp FloatVec 8 W32) = 934+primOpTag (VecIndexByteArrayOp FloatVec 4 W64) = 935+primOpTag (VecIndexByteArrayOp FloatVec 16 W32) = 936+primOpTag (VecIndexByteArrayOp FloatVec 8 W64) = 937+primOpTag (VecReadByteArrayOp IntVec 16 W8) = 938+primOpTag (VecReadByteArrayOp IntVec 8 W16) = 939+primOpTag (VecReadByteArrayOp IntVec 4 W32) = 940+primOpTag (VecReadByteArrayOp IntVec 2 W64) = 941+primOpTag (VecReadByteArrayOp IntVec 32 W8) = 942+primOpTag (VecReadByteArrayOp IntVec 16 W16) = 943+primOpTag (VecReadByteArrayOp IntVec 8 W32) = 944+primOpTag (VecReadByteArrayOp IntVec 4 W64) = 945+primOpTag (VecReadByteArrayOp IntVec 64 W8) = 946+primOpTag (VecReadByteArrayOp IntVec 32 W16) = 947+primOpTag (VecReadByteArrayOp IntVec 16 W32) = 948+primOpTag (VecReadByteArrayOp IntVec 8 W64) = 949+primOpTag (VecReadByteArrayOp WordVec 16 W8) = 950+primOpTag (VecReadByteArrayOp WordVec 8 W16) = 951+primOpTag (VecReadByteArrayOp WordVec 4 W32) = 952+primOpTag (VecReadByteArrayOp WordVec 2 W64) = 953+primOpTag (VecReadByteArrayOp WordVec 32 W8) = 954+primOpTag (VecReadByteArrayOp WordVec 16 W16) = 955+primOpTag (VecReadByteArrayOp WordVec 8 W32) = 956+primOpTag (VecReadByteArrayOp WordVec 4 W64) = 957+primOpTag (VecReadByteArrayOp WordVec 64 W8) = 958+primOpTag (VecReadByteArrayOp WordVec 32 W16) = 959+primOpTag (VecReadByteArrayOp WordVec 16 W32) = 960+primOpTag (VecReadByteArrayOp WordVec 8 W64) = 961+primOpTag (VecReadByteArrayOp FloatVec 4 W32) = 962+primOpTag (VecReadByteArrayOp FloatVec 2 W64) = 963+primOpTag (VecReadByteArrayOp FloatVec 8 W32) = 964+primOpTag (VecReadByteArrayOp FloatVec 4 W64) = 965+primOpTag (VecReadByteArrayOp FloatVec 16 W32) = 966+primOpTag (VecReadByteArrayOp FloatVec 8 W64) = 967+primOpTag (VecWriteByteArrayOp IntVec 16 W8) = 968+primOpTag (VecWriteByteArrayOp IntVec 8 W16) = 969+primOpTag (VecWriteByteArrayOp IntVec 4 W32) = 970+primOpTag (VecWriteByteArrayOp IntVec 2 W64) = 971+primOpTag (VecWriteByteArrayOp IntVec 32 W8) = 972+primOpTag (VecWriteByteArrayOp IntVec 16 W16) = 973+primOpTag (VecWriteByteArrayOp IntVec 8 W32) = 974+primOpTag (VecWriteByteArrayOp IntVec 4 W64) = 975+primOpTag (VecWriteByteArrayOp IntVec 64 W8) = 976+primOpTag (VecWriteByteArrayOp IntVec 32 W16) = 977+primOpTag (VecWriteByteArrayOp IntVec 16 W32) = 978+primOpTag (VecWriteByteArrayOp IntVec 8 W64) = 979+primOpTag (VecWriteByteArrayOp WordVec 16 W8) = 980+primOpTag (VecWriteByteArrayOp WordVec 8 W16) = 981+primOpTag (VecWriteByteArrayOp WordVec 4 W32) = 982+primOpTag (VecWriteByteArrayOp WordVec 2 W64) = 983+primOpTag (VecWriteByteArrayOp WordVec 32 W8) = 984+primOpTag (VecWriteByteArrayOp WordVec 16 W16) = 985+primOpTag (VecWriteByteArrayOp WordVec 8 W32) = 986+primOpTag (VecWriteByteArrayOp WordVec 4 W64) = 987+primOpTag (VecWriteByteArrayOp WordVec 64 W8) = 988+primOpTag (VecWriteByteArrayOp WordVec 32 W16) = 989+primOpTag (VecWriteByteArrayOp WordVec 16 W32) = 990+primOpTag (VecWriteByteArrayOp WordVec 8 W64) = 991+primOpTag (VecWriteByteArrayOp FloatVec 4 W32) = 992+primOpTag (VecWriteByteArrayOp FloatVec 2 W64) = 993+primOpTag (VecWriteByteArrayOp FloatVec 8 W32) = 994+primOpTag (VecWriteByteArrayOp FloatVec 4 W64) = 995+primOpTag (VecWriteByteArrayOp FloatVec 16 W32) = 996+primOpTag (VecWriteByteArrayOp FloatVec 8 W64) = 997+primOpTag (VecIndexOffAddrOp IntVec 16 W8) = 998+primOpTag (VecIndexOffAddrOp IntVec 8 W16) = 999+primOpTag (VecIndexOffAddrOp IntVec 4 W32) = 1000+primOpTag (VecIndexOffAddrOp IntVec 2 W64) = 1001+primOpTag (VecIndexOffAddrOp IntVec 32 W8) = 1002+primOpTag (VecIndexOffAddrOp IntVec 16 W16) = 1003+primOpTag (VecIndexOffAddrOp IntVec 8 W32) = 1004+primOpTag (VecIndexOffAddrOp IntVec 4 W64) = 1005+primOpTag (VecIndexOffAddrOp IntVec 64 W8) = 1006+primOpTag (VecIndexOffAddrOp IntVec 32 W16) = 1007+primOpTag (VecIndexOffAddrOp IntVec 16 W32) = 1008+primOpTag (VecIndexOffAddrOp IntVec 8 W64) = 1009+primOpTag (VecIndexOffAddrOp WordVec 16 W8) = 1010+primOpTag (VecIndexOffAddrOp WordVec 8 W16) = 1011+primOpTag (VecIndexOffAddrOp WordVec 4 W32) = 1012+primOpTag (VecIndexOffAddrOp WordVec 2 W64) = 1013+primOpTag (VecIndexOffAddrOp WordVec 32 W8) = 1014+primOpTag (VecIndexOffAddrOp WordVec 16 W16) = 1015+primOpTag (VecIndexOffAddrOp WordVec 8 W32) = 1016+primOpTag (VecIndexOffAddrOp WordVec 4 W64) = 1017+primOpTag (VecIndexOffAddrOp WordVec 64 W8) = 1018+primOpTag (VecIndexOffAddrOp WordVec 32 W16) = 1019+primOpTag (VecIndexOffAddrOp WordVec 16 W32) = 1020+primOpTag (VecIndexOffAddrOp WordVec 8 W64) = 1021+primOpTag (VecIndexOffAddrOp FloatVec 4 W32) = 1022+primOpTag (VecIndexOffAddrOp FloatVec 2 W64) = 1023+primOpTag (VecIndexOffAddrOp FloatVec 8 W32) = 1024+primOpTag (VecIndexOffAddrOp FloatVec 4 W64) = 1025+primOpTag (VecIndexOffAddrOp FloatVec 16 W32) = 1026+primOpTag (VecIndexOffAddrOp FloatVec 8 W64) = 1027+primOpTag (VecReadOffAddrOp IntVec 16 W8) = 1028+primOpTag (VecReadOffAddrOp IntVec 8 W16) = 1029+primOpTag (VecReadOffAddrOp IntVec 4 W32) = 1030+primOpTag (VecReadOffAddrOp IntVec 2 W64) = 1031+primOpTag (VecReadOffAddrOp IntVec 32 W8) = 1032+primOpTag (VecReadOffAddrOp IntVec 16 W16) = 1033+primOpTag (VecReadOffAddrOp IntVec 8 W32) = 1034+primOpTag (VecReadOffAddrOp IntVec 4 W64) = 1035+primOpTag (VecReadOffAddrOp IntVec 64 W8) = 1036+primOpTag (VecReadOffAddrOp IntVec 32 W16) = 1037+primOpTag (VecReadOffAddrOp IntVec 16 W32) = 1038+primOpTag (VecReadOffAddrOp IntVec 8 W64) = 1039+primOpTag (VecReadOffAddrOp WordVec 16 W8) = 1040+primOpTag (VecReadOffAddrOp WordVec 8 W16) = 1041+primOpTag (VecReadOffAddrOp WordVec 4 W32) = 1042+primOpTag (VecReadOffAddrOp WordVec 2 W64) = 1043+primOpTag (VecReadOffAddrOp WordVec 32 W8) = 1044+primOpTag (VecReadOffAddrOp WordVec 16 W16) = 1045+primOpTag (VecReadOffAddrOp WordVec 8 W32) = 1046+primOpTag (VecReadOffAddrOp WordVec 4 W64) = 1047+primOpTag (VecReadOffAddrOp WordVec 64 W8) = 1048+primOpTag (VecReadOffAddrOp WordVec 32 W16) = 1049+primOpTag (VecReadOffAddrOp WordVec 16 W32) = 1050+primOpTag (VecReadOffAddrOp WordVec 8 W64) = 1051+primOpTag (VecReadOffAddrOp FloatVec 4 W32) = 1052+primOpTag (VecReadOffAddrOp FloatVec 2 W64) = 1053+primOpTag (VecReadOffAddrOp FloatVec 8 W32) = 1054+primOpTag (VecReadOffAddrOp FloatVec 4 W64) = 1055+primOpTag (VecReadOffAddrOp FloatVec 16 W32) = 1056+primOpTag (VecReadOffAddrOp FloatVec 8 W64) = 1057+primOpTag (VecWriteOffAddrOp IntVec 16 W8) = 1058+primOpTag (VecWriteOffAddrOp IntVec 8 W16) = 1059+primOpTag (VecWriteOffAddrOp IntVec 4 W32) = 1060+primOpTag (VecWriteOffAddrOp IntVec 2 W64) = 1061+primOpTag (VecWriteOffAddrOp IntVec 32 W8) = 1062+primOpTag (VecWriteOffAddrOp IntVec 16 W16) = 1063+primOpTag (VecWriteOffAddrOp IntVec 8 W32) = 1064+primOpTag (VecWriteOffAddrOp IntVec 4 W64) = 1065+primOpTag (VecWriteOffAddrOp IntVec 64 W8) = 1066+primOpTag (VecWriteOffAddrOp IntVec 32 W16) = 1067+primOpTag (VecWriteOffAddrOp IntVec 16 W32) = 1068+primOpTag (VecWriteOffAddrOp IntVec 8 W64) = 1069+primOpTag (VecWriteOffAddrOp WordVec 16 W8) = 1070+primOpTag (VecWriteOffAddrOp WordVec 8 W16) = 1071+primOpTag (VecWriteOffAddrOp WordVec 4 W32) = 1072+primOpTag (VecWriteOffAddrOp WordVec 2 W64) = 1073+primOpTag (VecWriteOffAddrOp WordVec 32 W8) = 1074+primOpTag (VecWriteOffAddrOp WordVec 16 W16) = 1075+primOpTag (VecWriteOffAddrOp WordVec 8 W32) = 1076+primOpTag (VecWriteOffAddrOp WordVec 4 W64) = 1077+primOpTag (VecWriteOffAddrOp WordVec 64 W8) = 1078+primOpTag (VecWriteOffAddrOp WordVec 32 W16) = 1079+primOpTag (VecWriteOffAddrOp WordVec 16 W32) = 1080+primOpTag (VecWriteOffAddrOp WordVec 8 W64) = 1081+primOpTag (VecWriteOffAddrOp FloatVec 4 W32) = 1082+primOpTag (VecWriteOffAddrOp FloatVec 2 W64) = 1083+primOpTag (VecWriteOffAddrOp FloatVec 8 W32) = 1084+primOpTag (VecWriteOffAddrOp FloatVec 4 W64) = 1085+primOpTag (VecWriteOffAddrOp FloatVec 16 W32) = 1086+primOpTag (VecWriteOffAddrOp FloatVec 8 W64) = 1087+primOpTag (VecIndexScalarByteArrayOp IntVec 16 W8) = 1088+primOpTag (VecIndexScalarByteArrayOp IntVec 8 W16) = 1089+primOpTag (VecIndexScalarByteArrayOp IntVec 4 W32) = 1090+primOpTag (VecIndexScalarByteArrayOp IntVec 2 W64) = 1091+primOpTag (VecIndexScalarByteArrayOp IntVec 32 W8) = 1092+primOpTag (VecIndexScalarByteArrayOp IntVec 16 W16) = 1093+primOpTag (VecIndexScalarByteArrayOp IntVec 8 W32) = 1094+primOpTag (VecIndexScalarByteArrayOp IntVec 4 W64) = 1095+primOpTag (VecIndexScalarByteArrayOp IntVec 64 W8) = 1096+primOpTag (VecIndexScalarByteArrayOp IntVec 32 W16) = 1097+primOpTag (VecIndexScalarByteArrayOp IntVec 16 W32) = 1098+primOpTag (VecIndexScalarByteArrayOp IntVec 8 W64) = 1099+primOpTag (VecIndexScalarByteArrayOp WordVec 16 W8) = 1100+primOpTag (VecIndexScalarByteArrayOp WordVec 8 W16) = 1101+primOpTag (VecIndexScalarByteArrayOp WordVec 4 W32) = 1102+primOpTag (VecIndexScalarByteArrayOp WordVec 2 W64) = 1103+primOpTag (VecIndexScalarByteArrayOp WordVec 32 W8) = 1104+primOpTag (VecIndexScalarByteArrayOp WordVec 16 W16) = 1105+primOpTag (VecIndexScalarByteArrayOp WordVec 8 W32) = 1106+primOpTag (VecIndexScalarByteArrayOp WordVec 4 W64) = 1107+primOpTag (VecIndexScalarByteArrayOp WordVec 64 W8) = 1108+primOpTag (VecIndexScalarByteArrayOp WordVec 32 W16) = 1109+primOpTag (VecIndexScalarByteArrayOp WordVec 16 W32) = 1110+primOpTag (VecIndexScalarByteArrayOp WordVec 8 W64) = 1111+primOpTag (VecIndexScalarByteArrayOp FloatVec 4 W32) = 1112+primOpTag (VecIndexScalarByteArrayOp FloatVec 2 W64) = 1113+primOpTag (VecIndexScalarByteArrayOp FloatVec 8 W32) = 1114+primOpTag (VecIndexScalarByteArrayOp FloatVec 4 W64) = 1115+primOpTag (VecIndexScalarByteArrayOp FloatVec 16 W32) = 1116+primOpTag (VecIndexScalarByteArrayOp FloatVec 8 W64) = 1117+primOpTag (VecReadScalarByteArrayOp IntVec 16 W8) = 1118+primOpTag (VecReadScalarByteArrayOp IntVec 8 W16) = 1119+primOpTag (VecReadScalarByteArrayOp IntVec 4 W32) = 1120+primOpTag (VecReadScalarByteArrayOp IntVec 2 W64) = 1121+primOpTag (VecReadScalarByteArrayOp IntVec 32 W8) = 1122+primOpTag (VecReadScalarByteArrayOp IntVec 16 W16) = 1123+primOpTag (VecReadScalarByteArrayOp IntVec 8 W32) = 1124+primOpTag (VecReadScalarByteArrayOp IntVec 4 W64) = 1125+primOpTag (VecReadScalarByteArrayOp IntVec 64 W8) = 1126+primOpTag (VecReadScalarByteArrayOp IntVec 32 W16) = 1127+primOpTag (VecReadScalarByteArrayOp IntVec 16 W32) = 1128+primOpTag (VecReadScalarByteArrayOp IntVec 8 W64) = 1129+primOpTag (VecReadScalarByteArrayOp WordVec 16 W8) = 1130+primOpTag (VecReadScalarByteArrayOp WordVec 8 W16) = 1131+primOpTag (VecReadScalarByteArrayOp WordVec 4 W32) = 1132+primOpTag (VecReadScalarByteArrayOp WordVec 2 W64) = 1133+primOpTag (VecReadScalarByteArrayOp WordVec 32 W8) = 1134+primOpTag (VecReadScalarByteArrayOp WordVec 16 W16) = 1135+primOpTag (VecReadScalarByteArrayOp WordVec 8 W32) = 1136+primOpTag (VecReadScalarByteArrayOp WordVec 4 W64) = 1137+primOpTag (VecReadScalarByteArrayOp WordVec 64 W8) = 1138+primOpTag (VecReadScalarByteArrayOp WordVec 32 W16) = 1139+primOpTag (VecReadScalarByteArrayOp WordVec 16 W32) = 1140+primOpTag (VecReadScalarByteArrayOp WordVec 8 W64) = 1141+primOpTag (VecReadScalarByteArrayOp FloatVec 4 W32) = 1142+primOpTag (VecReadScalarByteArrayOp FloatVec 2 W64) = 1143+primOpTag (VecReadScalarByteArrayOp FloatVec 8 W32) = 1144+primOpTag (VecReadScalarByteArrayOp FloatVec 4 W64) = 1145+primOpTag (VecReadScalarByteArrayOp FloatVec 16 W32) = 1146+primOpTag (VecReadScalarByteArrayOp FloatVec 8 W64) = 1147+primOpTag (VecWriteScalarByteArrayOp IntVec 16 W8) = 1148+primOpTag (VecWriteScalarByteArrayOp IntVec 8 W16) = 1149+primOpTag (VecWriteScalarByteArrayOp IntVec 4 W32) = 1150+primOpTag (VecWriteScalarByteArrayOp IntVec 2 W64) = 1151+primOpTag (VecWriteScalarByteArrayOp IntVec 32 W8) = 1152+primOpTag (VecWriteScalarByteArrayOp IntVec 16 W16) = 1153+primOpTag (VecWriteScalarByteArrayOp IntVec 8 W32) = 1154+primOpTag (VecWriteScalarByteArrayOp IntVec 4 W64) = 1155+primOpTag (VecWriteScalarByteArrayOp IntVec 64 W8) = 1156+primOpTag (VecWriteScalarByteArrayOp IntVec 32 W16) = 1157+primOpTag (VecWriteScalarByteArrayOp IntVec 16 W32) = 1158+primOpTag (VecWriteScalarByteArrayOp IntVec 8 W64) = 1159+primOpTag (VecWriteScalarByteArrayOp WordVec 16 W8) = 1160+primOpTag (VecWriteScalarByteArrayOp WordVec 8 W16) = 1161+primOpTag (VecWriteScalarByteArrayOp WordVec 4 W32) = 1162+primOpTag (VecWriteScalarByteArrayOp WordVec 2 W64) = 1163+primOpTag (VecWriteScalarByteArrayOp WordVec 32 W8) = 1164+primOpTag (VecWriteScalarByteArrayOp WordVec 16 W16) = 1165+primOpTag (VecWriteScalarByteArrayOp WordVec 8 W32) = 1166+primOpTag (VecWriteScalarByteArrayOp WordVec 4 W64) = 1167+primOpTag (VecWriteScalarByteArrayOp WordVec 64 W8) = 1168+primOpTag (VecWriteScalarByteArrayOp WordVec 32 W16) = 1169+primOpTag (VecWriteScalarByteArrayOp WordVec 16 W32) = 1170+primOpTag (VecWriteScalarByteArrayOp WordVec 8 W64) = 1171+primOpTag (VecWriteScalarByteArrayOp FloatVec 4 W32) = 1172+primOpTag (VecWriteScalarByteArrayOp FloatVec 2 W64) = 1173+primOpTag (VecWriteScalarByteArrayOp FloatVec 8 W32) = 1174+primOpTag (VecWriteScalarByteArrayOp FloatVec 4 W64) = 1175+primOpTag (VecWriteScalarByteArrayOp FloatVec 16 W32) = 1176+primOpTag (VecWriteScalarByteArrayOp FloatVec 8 W64) = 1177+primOpTag (VecIndexScalarOffAddrOp IntVec 16 W8) = 1178+primOpTag (VecIndexScalarOffAddrOp IntVec 8 W16) = 1179+primOpTag (VecIndexScalarOffAddrOp IntVec 4 W32) = 1180+primOpTag (VecIndexScalarOffAddrOp IntVec 2 W64) = 1181+primOpTag (VecIndexScalarOffAddrOp IntVec 32 W8) = 1182+primOpTag (VecIndexScalarOffAddrOp IntVec 16 W16) = 1183+primOpTag (VecIndexScalarOffAddrOp IntVec 8 W32) = 1184+primOpTag (VecIndexScalarOffAddrOp IntVec 4 W64) = 1185+primOpTag (VecIndexScalarOffAddrOp IntVec 64 W8) = 1186+primOpTag (VecIndexScalarOffAddrOp IntVec 32 W16) = 1187+primOpTag (VecIndexScalarOffAddrOp IntVec 16 W32) = 1188+primOpTag (VecIndexScalarOffAddrOp IntVec 8 W64) = 1189+primOpTag (VecIndexScalarOffAddrOp WordVec 16 W8) = 1190+primOpTag (VecIndexScalarOffAddrOp WordVec 8 W16) = 1191+primOpTag (VecIndexScalarOffAddrOp WordVec 4 W32) = 1192+primOpTag (VecIndexScalarOffAddrOp WordVec 2 W64) = 1193+primOpTag (VecIndexScalarOffAddrOp WordVec 32 W8) = 1194+primOpTag (VecIndexScalarOffAddrOp WordVec 16 W16) = 1195+primOpTag (VecIndexScalarOffAddrOp WordVec 8 W32) = 1196+primOpTag (VecIndexScalarOffAddrOp WordVec 4 W64) = 1197+primOpTag (VecIndexScalarOffAddrOp WordVec 64 W8) = 1198+primOpTag (VecIndexScalarOffAddrOp WordVec 32 W16) = 1199+primOpTag (VecIndexScalarOffAddrOp WordVec 16 W32) = 1200+primOpTag (VecIndexScalarOffAddrOp WordVec 8 W64) = 1201+primOpTag (VecIndexScalarOffAddrOp FloatVec 4 W32) = 1202+primOpTag (VecIndexScalarOffAddrOp FloatVec 2 W64) = 1203+primOpTag (VecIndexScalarOffAddrOp FloatVec 8 W32) = 1204+primOpTag (VecIndexScalarOffAddrOp FloatVec 4 W64) = 1205+primOpTag (VecIndexScalarOffAddrOp FloatVec 16 W32) = 1206+primOpTag (VecIndexScalarOffAddrOp FloatVec 8 W64) = 1207+primOpTag (VecReadScalarOffAddrOp IntVec 16 W8) = 1208+primOpTag (VecReadScalarOffAddrOp IntVec 8 W16) = 1209+primOpTag (VecReadScalarOffAddrOp IntVec 4 W32) = 1210+primOpTag (VecReadScalarOffAddrOp IntVec 2 W64) = 1211+primOpTag (VecReadScalarOffAddrOp IntVec 32 W8) = 1212+primOpTag (VecReadScalarOffAddrOp IntVec 16 W16) = 1213+primOpTag (VecReadScalarOffAddrOp IntVec 8 W32) = 1214+primOpTag (VecReadScalarOffAddrOp IntVec 4 W64) = 1215+primOpTag (VecReadScalarOffAddrOp IntVec 64 W8) = 1216+primOpTag (VecReadScalarOffAddrOp IntVec 32 W16) = 1217+primOpTag (VecReadScalarOffAddrOp IntVec 16 W32) = 1218+primOpTag (VecReadScalarOffAddrOp IntVec 8 W64) = 1219+primOpTag (VecReadScalarOffAddrOp WordVec 16 W8) = 1220+primOpTag (VecReadScalarOffAddrOp WordVec 8 W16) = 1221+primOpTag (VecReadScalarOffAddrOp WordVec 4 W32) = 1222+primOpTag (VecReadScalarOffAddrOp WordVec 2 W64) = 1223+primOpTag (VecReadScalarOffAddrOp WordVec 32 W8) = 1224+primOpTag (VecReadScalarOffAddrOp WordVec 16 W16) = 1225+primOpTag (VecReadScalarOffAddrOp WordVec 8 W32) = 1226+primOpTag (VecReadScalarOffAddrOp WordVec 4 W64) = 1227+primOpTag (VecReadScalarOffAddrOp WordVec 64 W8) = 1228+primOpTag (VecReadScalarOffAddrOp WordVec 32 W16) = 1229+primOpTag (VecReadScalarOffAddrOp WordVec 16 W32) = 1230+primOpTag (VecReadScalarOffAddrOp WordVec 8 W64) = 1231+primOpTag (VecReadScalarOffAddrOp FloatVec 4 W32) = 1232+primOpTag (VecReadScalarOffAddrOp FloatVec 2 W64) = 1233+primOpTag (VecReadScalarOffAddrOp FloatVec 8 W32) = 1234+primOpTag (VecReadScalarOffAddrOp FloatVec 4 W64) = 1235+primOpTag (VecReadScalarOffAddrOp FloatVec 16 W32) = 1236+primOpTag (VecReadScalarOffAddrOp FloatVec 8 W64) = 1237+primOpTag (VecWriteScalarOffAddrOp IntVec 16 W8) = 1238+primOpTag (VecWriteScalarOffAddrOp IntVec 8 W16) = 1239+primOpTag (VecWriteScalarOffAddrOp IntVec 4 W32) = 1240+primOpTag (VecWriteScalarOffAddrOp IntVec 2 W64) = 1241+primOpTag (VecWriteScalarOffAddrOp IntVec 32 W8) = 1242+primOpTag (VecWriteScalarOffAddrOp IntVec 16 W16) = 1243+primOpTag (VecWriteScalarOffAddrOp IntVec 8 W32) = 1244+primOpTag (VecWriteScalarOffAddrOp IntVec 4 W64) = 1245+primOpTag (VecWriteScalarOffAddrOp IntVec 64 W8) = 1246+primOpTag (VecWriteScalarOffAddrOp IntVec 32 W16) = 1247+primOpTag (VecWriteScalarOffAddrOp IntVec 16 W32) = 1248+primOpTag (VecWriteScalarOffAddrOp IntVec 8 W64) = 1249+primOpTag (VecWriteScalarOffAddrOp WordVec 16 W8) = 1250+primOpTag (VecWriteScalarOffAddrOp WordVec 8 W16) = 1251+primOpTag (VecWriteScalarOffAddrOp WordVec 4 W32) = 1252+primOpTag (VecWriteScalarOffAddrOp WordVec 2 W64) = 1253+primOpTag (VecWriteScalarOffAddrOp WordVec 32 W8) = 1254+primOpTag (VecWriteScalarOffAddrOp WordVec 16 W16) = 1255+primOpTag (VecWriteScalarOffAddrOp WordVec 8 W32) = 1256+primOpTag (VecWriteScalarOffAddrOp WordVec 4 W64) = 1257+primOpTag (VecWriteScalarOffAddrOp WordVec 64 W8) = 1258+primOpTag (VecWriteScalarOffAddrOp WordVec 32 W16) = 1259+primOpTag (VecWriteScalarOffAddrOp WordVec 16 W32) = 1260+primOpTag (VecWriteScalarOffAddrOp WordVec 8 W64) = 1261+primOpTag (VecWriteScalarOffAddrOp FloatVec 4 W32) = 1262+primOpTag (VecWriteScalarOffAddrOp FloatVec 2 W64) = 1263+primOpTag (VecWriteScalarOffAddrOp FloatVec 8 W32) = 1264+primOpTag (VecWriteScalarOffAddrOp FloatVec 4 W64) = 1265+primOpTag (VecWriteScalarOffAddrOp FloatVec 16 W32) = 1266+primOpTag (VecWriteScalarOffAddrOp FloatVec 8 W64) = 1267+primOpTag PrefetchByteArrayOp3 = 1268+primOpTag PrefetchMutableByteArrayOp3 = 1269+primOpTag PrefetchAddrOp3 = 1270+primOpTag PrefetchValueOp3 = 1271+primOpTag PrefetchByteArrayOp2 = 1272+primOpTag PrefetchMutableByteArrayOp2 = 1273+primOpTag PrefetchAddrOp2 = 1274+primOpTag PrefetchValueOp2 = 1275+primOpTag PrefetchByteArrayOp1 = 1276+primOpTag PrefetchMutableByteArrayOp1 = 1277+primOpTag PrefetchAddrOp1 = 1278+primOpTag PrefetchValueOp1 = 1279+primOpTag PrefetchByteArrayOp0 = 1280+primOpTag PrefetchMutableByteArrayOp0 = 1281+primOpTag PrefetchAddrOp0 = 1282+primOpTag PrefetchValueOp0 = 1283
ghc-lib/stage0/lib/DerivedConstants.h view
@@ -67,29 +67,29 @@ #define OFFSET_stgGCEnter1 -16 #define OFFSET_stgGCFun -8 #define OFFSET_Capability_r 24-#define OFFSET_Capability_lock 1208+#define OFFSET_Capability_lock 1216 #define OFFSET_Capability_no 944 #define REP_Capability_no b32 #define Capability_no(__ptr__) REP_Capability_no[__ptr__+OFFSET_Capability_no] #define OFFSET_Capability_mut_lists 1016 #define REP_Capability_mut_lists b64 #define Capability_mut_lists(__ptr__) REP_Capability_mut_lists[__ptr__+OFFSET_Capability_mut_lists]-#define OFFSET_Capability_context_switch 1176+#define OFFSET_Capability_context_switch 1184 #define REP_Capability_context_switch b32 #define Capability_context_switch(__ptr__) REP_Capability_context_switch[__ptr__+OFFSET_Capability_context_switch]-#define OFFSET_Capability_interrupt 1180+#define OFFSET_Capability_interrupt 1188 #define REP_Capability_interrupt b32 #define Capability_interrupt(__ptr__) REP_Capability_interrupt[__ptr__+OFFSET_Capability_interrupt]-#define OFFSET_Capability_sparks 1312+#define OFFSET_Capability_sparks 1320 #define REP_Capability_sparks b64 #define Capability_sparks(__ptr__) REP_Capability_sparks[__ptr__+OFFSET_Capability_sparks]-#define OFFSET_Capability_total_allocated 1184+#define OFFSET_Capability_total_allocated 1192 #define REP_Capability_total_allocated b64 #define Capability_total_allocated(__ptr__) REP_Capability_total_allocated[__ptr__+OFFSET_Capability_total_allocated]-#define OFFSET_Capability_weak_ptr_list_hd 1160+#define OFFSET_Capability_weak_ptr_list_hd 1168 #define REP_Capability_weak_ptr_list_hd b64 #define Capability_weak_ptr_list_hd(__ptr__) REP_Capability_weak_ptr_list_hd[__ptr__+OFFSET_Capability_weak_ptr_list_hd]-#define OFFSET_Capability_weak_ptr_list_tl 1168+#define OFFSET_Capability_weak_ptr_list_tl 1176 #define REP_Capability_weak_ptr_list_tl b64 #define Capability_weak_ptr_list_tl(__ptr__) REP_Capability_weak_ptr_list_tl[__ptr__+OFFSET_Capability_weak_ptr_list_tl] #define OFFSET_bdescr_start 0@@ -491,25 +491,25 @@ #define OFFSET_StgCompactNFDataBlock_next 16 #define REP_StgCompactNFDataBlock_next b64 #define StgCompactNFDataBlock_next(__ptr__) REP_StgCompactNFDataBlock_next[__ptr__+OFFSET_StgCompactNFDataBlock_next]-#define OFFSET_RtsFlags_ProfFlags_doHeapProfile 272+#define OFFSET_RtsFlags_ProfFlags_doHeapProfile 280 #define REP_RtsFlags_ProfFlags_doHeapProfile b32 #define RtsFlags_ProfFlags_doHeapProfile(__ptr__) REP_RtsFlags_ProfFlags_doHeapProfile[__ptr__+OFFSET_RtsFlags_ProfFlags_doHeapProfile]-#define OFFSET_RtsFlags_ProfFlags_showCCSOnException 292+#define OFFSET_RtsFlags_ProfFlags_showCCSOnException 301 #define REP_RtsFlags_ProfFlags_showCCSOnException b8 #define RtsFlags_ProfFlags_showCCSOnException(__ptr__) REP_RtsFlags_ProfFlags_showCCSOnException[__ptr__+OFFSET_RtsFlags_ProfFlags_showCCSOnException]-#define OFFSET_RtsFlags_DebugFlags_apply 236+#define OFFSET_RtsFlags_DebugFlags_apply 244 #define REP_RtsFlags_DebugFlags_apply b8 #define RtsFlags_DebugFlags_apply(__ptr__) REP_RtsFlags_DebugFlags_apply[__ptr__+OFFSET_RtsFlags_DebugFlags_apply]-#define OFFSET_RtsFlags_DebugFlags_sanity 231+#define OFFSET_RtsFlags_DebugFlags_sanity 239 #define REP_RtsFlags_DebugFlags_sanity b8 #define RtsFlags_DebugFlags_sanity(__ptr__) REP_RtsFlags_DebugFlags_sanity[__ptr__+OFFSET_RtsFlags_DebugFlags_sanity]-#define OFFSET_RtsFlags_DebugFlags_weak 226+#define OFFSET_RtsFlags_DebugFlags_weak 234 #define REP_RtsFlags_DebugFlags_weak b8 #define RtsFlags_DebugFlags_weak(__ptr__) REP_RtsFlags_DebugFlags_weak[__ptr__+OFFSET_RtsFlags_DebugFlags_weak] #define OFFSET_RtsFlags_GcFlags_initialStkSize 16 #define REP_RtsFlags_GcFlags_initialStkSize b32 #define RtsFlags_GcFlags_initialStkSize(__ptr__) REP_RtsFlags_GcFlags_initialStkSize[__ptr__+OFFSET_RtsFlags_GcFlags_initialStkSize]-#define OFFSET_RtsFlags_MiscFlags_tickInterval 192+#define OFFSET_RtsFlags_MiscFlags_tickInterval 200 #define REP_RtsFlags_MiscFlags_tickInterval b64 #define RtsFlags_MiscFlags_tickInterval(__ptr__) REP_RtsFlags_MiscFlags_tickInterval[__ptr__+OFFSET_RtsFlags_MiscFlags_tickInterval] #define SIZEOF_StgFunInfoExtraFwd 32
ghc-lib/stage0/lib/ghcautoconf.h view
@@ -543,8 +543,11 @@ /* Define to `int' if <sys/types.h> does not define. */ /* #undef pid_t */ -/* The supported LLVM version number */-#define sUPPORTED_LLVM_VERSION (10)+/* The maximum supported LLVM version number */+#define sUPPORTED_LLVM_VERSION_MAX (12)++/* The minimum supported LLVM version number */+#define sUPPORTED_LLVM_VERSION_MIN (10) /* Define to `unsigned int' if <sys/types.h> does not define. */ /* #undef size_t */
ghc-lib/stage0/lib/llvm-targets view
@@ -38,9 +38,11 @@ ,("powerpc64le-unknown-linux-musl", ("e-m:e-i64:64-n32:64", "ppc64le", "+secure-plt")) ,("powerpc64le-unknown-linux", ("e-m:e-i64:64-n32:64", "ppc64le", "")) ,("s390x-ibm-linux", ("E-m:e-i1:8:16-i8:8:16-i64:64-f128:64-a:8:16-n32:64", "z10", ""))+,("riscv64-unknown-linux-gnu", ("e-m:e-p:64:64-i64:64-i128:128-n64-S128", "", "+m +a +f +d +c +relax"))+,("riscv64-unknown-linux", ("e-m:e-p:64:64-i64:64-i128:128-n64-S128", "", "+m +a +f +d +c +relax")) ,("i386-apple-darwin", ("e-m:o-p:32:32-p270:32:32-p271:32:32-p272:64:64-f64:32:64-f80:128-n8:16:32-S128", "penryn", "")) ,("x86_64-apple-darwin", ("e-m:o-p270:32:32-p271:32:32-p272:64:64-i64:64-f80:128-n8:16:32:64-S128", "penryn", ""))-,("arm64-apple-darwin", ("e-m:o-i64:64-i128:128-n32:64-S128", "vortex", "+v8.3a +fp-armv8 +neon +crc +crypto +fullfp16 +ras +lse +rdm +rcpc +zcm +zcz +sha2 +aes"))+,("arm64-apple-darwin", ("e-m:o-i64:64-i128:128-n32:64-S128", "generic", "+v8.3a +fp-armv8 +neon +crc +crypto +fullfp16 +ras +lse +rdm +rcpc +zcm +zcz +sha2 +aes")) ,("armv7-apple-ios", ("e-m:o-p:32:32-Fi8-f64:32:64-v64:32:64-v128:32:128-a:0:32-n32-S32", "generic", "")) ,("aarch64-apple-ios", ("e-m:o-i64:64-i128:128-n32:64-S128", "apple-a7", "+fp-armv8 +neon +crypto +zcm +zcz +sha2 +aes")) ,("i386-apple-ios", ("e-m:o-p:32:32-p270:32:32-p271:32:32-p272:64:64-f64:32:64-f80:128-n8:16:32-S128", "yonah", ""))
includes/CodeGen.Platform.hs view
@@ -380,6 +380,74 @@ # define f14 30 # define f15 31 +#elif defined(MACHREGS_riscv64)++# define zero 0+# define ra 1+# define sp 2+# define gp 3+# define tp 4+# define t0 5+# define t1 6+# define t2 7+# define s0 8+# define s1 9+# define a0 10+# define a1 11+# define a2 12+# define a3 13+# define a4 14+# define a5 15+# define a6 16+# define a7 17+# define s2 18+# define s3 19+# define s4 20+# define s5 21+# define s6 22+# define s7 23+# define s8 24+# define s9 25+# define s10 26+# define s11 27+# define t3 28+# define t4 29+# define t5 30+# define t6 31++# define ft0 32+# define ft1 33+# define ft2 34+# define ft3 35+# define ft4 36+# define ft5 37+# define ft6 38+# define ft7 39+# define fs0 40+# define fs1 41+# define fa0 42+# define fa1 43+# define fa2 44+# define fa3 45+# define fa4 46+# define fa5 47+# define fa6 48+# define fa7 49+# define fs2 50+# define fs3 51+# define fs4 52+# define fs5 53+# define fs6 54+# define fs7 55+# define fs8 56+# define fs9 57+# define fs10 58+# define fs11 59+# define ft8 60+# define ft9 61+# define ft10 62+# define ft11 63+ #endif callerSaves :: GlobalReg -> Bool@@ -667,7 +735,7 @@ #if defined(MACHREGS_i386) || defined(MACHREGS_x86_64) \ || defined(MACHREGS_sparc) || defined(MACHREGS_powerpc) \ || defined(MACHREGS_arm) || defined(MACHREGS_aarch64) \- || defined(MACHREGS_s390x)+ || defined(MACHREGS_s390x) || defined(MACHREGS_riscv64) # if defined(REG_Base) globalRegMaybe BaseReg = Just (RealRegSingle REG_Base) # endif
includes/stg/MachRegs.h view
@@ -663,6 +663,68 @@ #define CALLER_SAVES_D5 #define CALLER_SAVES_D6 +/* -----------------------------------------------------------------------------+ The riscv64 register mapping++ Register | Role(s) | Call effect+ ------------+-----------------------------------------+-------------+ zero | Hard-wired zero | -+ ra | Return address | caller-saved+ sp | Stack pointer | callee-saved+ gp | Global pointer | callee-saved+ tp | Thread pointer | callee-saved+ t0,t1,t2 | - | caller-saved+ s0 | Frame pointer | callee-saved+ s1 | - | callee-saved+ a0,a1 | Arguments / return values | caller-saved+ a2..a7 | Arguments | caller-saved+ s2..s11 | - | callee-saved+ t3..t6 | - | caller-saved+ ft0..ft7 | - | caller-saved+ fs0,fs1 | - | callee-saved+ fa0,fa1 | Arguments / return values | caller-saved+ fa2..fa7 | Arguments | caller-saved+ fs2..fs11 | - | callee-saved+ ft8..ft11 | - | caller-saved++ Each general purpose register as well as each floating-point+ register is 64 bits wide.++ -------------------------------------------------------------------------- */++#elif defined(MACHREGS_riscv64)++#define REG(x) __asm__(#x)++#define REG_Base s1+#define REG_Sp s2+#define REG_Hp s3+#define REG_R1 s4+#define REG_R2 s5+#define REG_R3 s6+#define REG_R4 s7+#define REG_R5 s8+#define REG_R6 s9+#define REG_R7 s10+#define REG_SpLim s11++#define REG_F1 fs0+#define REG_F2 fs1+#define REG_F3 fs2+#define REG_F4 fs3+#define REG_F5 fs4+#define REG_F6 fs5++#define REG_D1 fs6+#define REG_D2 fs7+#define REG_D3 fs8+#define REG_D4 fs9+#define REG_D5 fs10+#define REG_D6 fs11++#define MAX_REAL_FLOAT_REG 6+#define MAX_REAL_DOUBLE_REG 6+ #else #error Cannot find platform to give register info for@@ -717,7 +779,13 @@ #endif #if !defined(MAX_REAL_FLOAT_REG)-# if defined(REG_F4)+# if defined(REG_F7)+# error Please manually define MAX_REAL_FLOAT_REG for this architecture+# elif defined(REG_F6)+# define MAX_REAL_FLOAT_REG 6+# elif defined(REG_F5)+# define MAX_REAL_FLOAT_REG 5+# elif defined(REG_F4) # define MAX_REAL_FLOAT_REG 4 # elif defined(REG_F3) # define MAX_REAL_FLOAT_REG 3@@ -731,7 +799,17 @@ #endif #if !defined(MAX_REAL_DOUBLE_REG)-# if defined(REG_D2)+# if defined(REG_D7)+# error Please manually define MAX_REAL_DOUBLE_REG for this architecture+# elif defined(REG_D6)+# define MAX_REAL_DOUBLE_REG 6+# elif defined(REG_D5)+# define MAX_REAL_DOUBLE_REG 5+# elif defined(REG_D4)+# define MAX_REAL_DOUBLE_REG 4+# elif defined(REG_D3)+# define MAX_REAL_DOUBLE_REG 3+# elif defined(REG_D2) # define MAX_REAL_DOUBLE_REG 2 # elif defined(REG_D1) # define MAX_REAL_DOUBLE_REG 1
libraries/ghci/GHCi/CreateBCO.hs view
@@ -52,6 +52,7 @@ #else do BCO bco# <- linkBCO' arr bco #endif+ -- Note [Updatable CAF BCOs] -- ~~~~~~~~~~~~~~~~~~~~~~~~~ -- Why do we need mkApUpd0 here? Otherwise top-level@@ -76,6 +77,7 @@ then return (HValue (unsafeCoerce# bco#)) else case mkApUpd0# bco# of { (# final_bco #) -> #endif+ return (HValue final_bco) } @@ -126,6 +128,7 @@ BCO bco# <- linkBCO' arr bco writePtrsArrayBCO i bco# marr #endif+ fill (ResolvedBCOPtrBreakArray r) i = do BA mba <- localRef r writePtrsArrayMBA i mba marr@@ -158,6 +161,7 @@ #else writePtrsArrayBCO :: Int -> BCO# -> PtrsArr -> IO () #endif+ writePtrsArrayBCO (I# i) bco (PtrsArr arr) = IO $ \s -> case (unsafeCoerce# writeArray#) arr i bco s of s' -> (# s', () #) @@ -168,6 +172,7 @@ data BCO = BCO BCO# writePtrsArrayMBA :: Int -> MutableByteArray# s -> PtrsArr -> IO () #endif+ writePtrsArrayMBA (I# i) mba (PtrsArr arr) = IO $ \s -> case (unsafeCoerce# writeArray#) arr i mba s of s' -> (# s', () #) @@ -180,6 +185,7 @@ case newBCO# instrs lits ptrs arity bitmap s of (# s1, bco #) -> (# s1, BCO bco #) #endif+ {- Note [BCO empty array] ~~~~~~~~~~~~~~~~~~~~~~
libraries/ghci/GHCi/InfoTable.hsc view
@@ -2,7 +2,21 @@ -- Get definitions for the structs, constants & config etc. #include "Rts.h"+#if !(defined MIN_VERSION_rts)+# if (__GLASGOW_HASKELL__ > 901)+# define MIN_VERSION_rts(major1,major2,minor) (\+ (major1) < 1 ||\+ (major1) == 1 && (major2) < 0 ||\+ (major1) == 1 && (major2) == 0 && (minor) <= 1)+# else+# define MIN_VERSION_rts(major1,major2,minor) (\+ (major1) < 1 ||\+ (major1) == 1 && (major2) < 0 ||\+ (major1) == 1 && (major2) == 0 && (minor) <= 0)+# endif+#endif + -- | -- Run-time info table support. This module provides support for -- creating and reading info tables /in the running program/.@@ -318,7 +332,11 @@ -- Note: Must return proper pointer for use in a closure newExecConItbl :: Bool -> StgInfoTable -> ByteString -> IO (FunPtr ()) newExecConItbl tables_next_to_code obj con_desc+#if RTS_LINKER_USE_MMAP && MIN_VERSION_rts(1,0,1)+ = do+#else = alloca $ \pcode -> do+#endif sz0 <- sizeOfEntryCode tables_next_to_code let lcon_desc = BS.length con_desc + 1{- null terminator -} -- SCARY@@ -328,8 +346,13 @@ -- table, because on a 64-bit platform we reference this string -- with a 32-bit offset relative to the info table, so if we -- allocated the string separately it might be out of range.+#if RTS_LINKER_USE_MMAP && MIN_VERSION_rts(1,0,1)+ wr_ptr <- _allocateWrite (sz + fromIntegral lcon_desc)+ let ex_ptr = wr_ptr+#else wr_ptr <- _allocateExec (sz + fromIntegral lcon_desc) pcode ex_ptr <- peek pcode+#endif let cinfo = StgConInfoTable { conDesc = ex_ptr `plusPtr` fromIntegral sz , infoTable = obj } pokeConItbl tables_next_to_code wr_ptr ex_ptr cinfo@@ -338,6 +361,9 @@ let null_off = fromIntegral sz + fromIntegral (BS.length con_desc) poke (castPtr wr_ptr `plusPtr` null_off) (0 :: Word8) _flushExec sz ex_ptr -- Cache flush (if needed)+#if RTS_LINKER_USE_MMAP && MIN_VERSION_rts(1,0,1)+ _markExec (sz + fromIntegral lcon_desc) ex_ptr+#endif pure $ if tables_next_to_code then castPtrToFunPtr $ ex_ptr `plusPtr` conInfoTableSizeB else castPtrToFunPtr ex_ptr@@ -348,6 +374,12 @@ foreign import ccall unsafe "flushExec" _flushExec :: CUInt -> Ptr a -> IO () +#if RTS_LINKER_USE_MMAP && MIN_VERSION_rts(1,0,1)+foreign import ccall unsafe "allocateWrite"+ _allocateWrite :: CUInt -> IO (Ptr a)+foreign import ccall unsafe "markExec"+ _markExec :: CUInt -> Ptr a -> IO ()+#endif -- ----------------------------------------------------------------------------- -- Constants and config
libraries/ghci/GHCi/Run.hs view
@@ -73,15 +73,15 @@ MkCostCentres mod ccs -> mkCostCentres mod ccs CostCentreStackInfo ptr -> ccsToStrings (fromRemotePtr ptr) NewBreakArray sz -> mkRemoteRef =<< newBreakArray sz- EnableBreakpoint ref ix b -> do- arr <- localRef ref- _ <- if b then setBreakOn arr ix else setBreakOff arr ix+ SetupBreakpoint ref ix cnt -> do+ arr <- localRef ref;+ _ <- setupBreakpoint arr ix cnt return () BreakpointStatus ref ix -> do arr <- localRef ref; r <- getBreak arr ix case r of Nothing -> return False- Just w -> return (w /= 0)+ Just w -> return (w == 0) GetBreakpointVar ref ix -> do aps <- localRef ref mapM mkRemoteRef =<< getIdValFromApStack aps ix
libraries/ghci/GHCi/TH.hs view
@@ -209,6 +209,8 @@ return ((), s { qsMap = M.insert (typeOf k) (toDyn k) (qsMap s) }) qIsExtEnabled x = ghcCmd (IsExtEnabled x) qExtsEnabled = ghcCmd ExtsEnabled+ qPutDoc l s = ghcCmd (PutDoc l s)+ qGetDoc l = ghcCmd (GetDoc l) -- | The implementation of the 'StartTH' message: create -- a new IORef QState, and return a RemoteRef to it.