GHC

ghc-7.10.3: The GHC API

Safe Haskell | None
Language | Haskell2010

GHC

Contents

- Initialisation
- GHC Monad
- Flags and settings
- Targets
- Loading/compiling the program
  - Compiling to Core
- Inspecting the module structure of the program
- Inspecting modules
- Querying the environment
- Printing
- Interactive evaluation
  - EXPERIMENTAL
- Abstract syntax elements
  - Packages
  - Modules
  - Names
  - Identifiers
  - Type constructors
  - Type variables
  - Data constructors
  - Classes
  - Instances
  - Types and Kinds
  - Entities
  - Syntax
  - Fixities
  - Source locations
  - Located
    - Constructing Located
    - Deconstructing Located
    - Combining and comparing Located values
- Exceptions
- Token stream manipulations
- Pure interface to the parser
- API Annotations
- Miscellaneous

Synopsis

- defaultErrorHandler :: (ExceptionMonad m, MonadIO m) => FatalMessager -> FlushOut -> m a -> m a
- defaultCleanupHandler :: (ExceptionMonad m, MonadIO m) => DynFlags -> m a -> m a
- prettyPrintGhcErrors :: ExceptionMonad m => DynFlags -> m a -> m a
- data Ghc a
- data GhcT m a
- class (Functor m, MonadIO m, ExceptionMonad m, HasDynFlags m) => GhcMonad m where
  - getSession :: m HscEnv
  - setSession :: HscEnv -> m ()
- data HscEnv
- runGhc :: Maybe FilePath -> Ghc a -> IO a
- runGhcT :: (ExceptionMonad m, Functor m, MonadIO m) => Maybe FilePath -> GhcT m a -> m a
- initGhcMonad :: GhcMonad m => Maybe FilePath -> m ()
- gcatch :: (ExceptionMonad m, Exception e) => m a -> (e -> m a) -> m a
- gbracket :: ExceptionMonad m => m a -> (a -> m b) -> (a -> m c) -> m c
- gfinally :: ExceptionMonad m => m a -> m b -> m a
- printException :: GhcMonad m => SourceError -> m ()
- handleSourceError :: ExceptionMonad m => (SourceError -> m a) -> m a -> m a
- needsTemplateHaskell :: ModuleGraph -> Bool
- data DynFlags = DynFlags {
  - ghcMode :: GhcMode
  - ghcLink :: GhcLink
  - hscTarget :: HscTarget
  - settings :: Settings
  - sigOf :: SigOf
  - verbosity :: Int
  - optLevel :: Int
  - simplPhases :: Int
  - maxSimplIterations :: Int
  - ruleCheck :: Maybe String
  - strictnessBefore :: [Int]
  - parMakeCount :: Maybe Int
  - enableTimeStats :: Bool
  - ghcHeapSize :: Maybe Int
  - maxRelevantBinds :: Maybe Int
  - simplTickFactor :: Int
  - specConstrThreshold :: Maybe Int
  - specConstrCount :: Maybe Int
  - specConstrRecursive :: Int
  - liberateCaseThreshold :: Maybe Int
  - floatLamArgs :: Maybe Int
  - historySize :: Int
  - cmdlineHcIncludes :: [String]
  - importPaths :: [FilePath]
  - mainModIs :: Module
  - mainFunIs :: Maybe String
  - ctxtStkDepth :: Int
  - tyFunStkDepth :: Int
  - thisPackage :: PackageKey
  - ways :: [Way]
  - buildTag :: String
  - rtsBuildTag :: String
  - splitInfo :: Maybe (String, Int)
  - objectDir :: Maybe String
  - dylibInstallName :: Maybe String
  - hiDir :: Maybe String
  - stubDir :: Maybe String
  - dumpDir :: Maybe String
  - objectSuf :: String
  - hcSuf :: String
  - hiSuf :: String
  - canGenerateDynamicToo :: IORef Bool
  - dynObjectSuf :: String
  - dynHiSuf :: String
  - dllSplitFile :: Maybe FilePath
  - dllSplit :: Maybe [Set String]
  - outputFile :: Maybe String
  - dynOutputFile :: Maybe String
  - outputHi :: Maybe String
  - dynLibLoader :: DynLibLoader
  - dumpPrefix :: Maybe FilePath
  - dumpPrefixForce :: Maybe FilePath
  - ldInputs :: [Option]
  - includePaths :: [String]
  - libraryPaths :: [String]
  - frameworkPaths :: [String]
  - cmdlineFrameworks :: [String]
  - rtsOpts :: Maybe String
  - rtsOptsEnabled :: RtsOptsEnabled
  - hpcDir :: String
  - pluginModNames :: [ModuleName]
  - pluginModNameOpts :: [(ModuleName, String)]
  - hooks :: Hooks
  - depMakefile :: FilePath
  - depIncludePkgDeps :: Bool
  - depExcludeMods :: [ModuleName]
  - depSuffixes :: [String]
  - extraPkgConfs :: [PkgConfRef] -> [PkgConfRef]
  - packageFlags :: [PackageFlag]
  - packageEnv :: Maybe FilePath
  - pkgDatabase :: Maybe [PackageConfig]
  - pkgState :: PackageState
  - filesToClean :: IORef [FilePath]
  - dirsToClean :: IORef (Map FilePath FilePath)
  - filesToNotIntermediateClean :: IORef [FilePath]
  - nextTempSuffix :: IORef Int
  - generatedDumps :: IORef (Set FilePath)
  - dumpFlags :: IntSet
  - generalFlags :: IntSet
  - warningFlags :: IntSet
  - language :: Maybe Language
  - safeHaskell :: SafeHaskellMode
  - safeInfer :: Bool
  - safeInferred :: Bool
  - thOnLoc :: SrcSpan
  - newDerivOnLoc :: SrcSpan
  - overlapInstLoc :: SrcSpan
  - incoherentOnLoc :: SrcSpan
  - pkgTrustOnLoc :: SrcSpan
  - warnSafeOnLoc :: SrcSpan
  - warnUnsafeOnLoc :: SrcSpan
  - trustworthyOnLoc :: SrcSpan
  - extensions :: [OnOff ExtensionFlag]
  - extensionFlags :: IntSet
  - ufCreationThreshold :: Int
  - ufUseThreshold :: Int
  - ufFunAppDiscount :: Int
  - ufDictDiscount :: Int
  - ufKeenessFactor :: Float
  - ufDearOp :: Int
  - maxWorkerArgs :: Int
  - ghciHistSize :: Int
  - log_action :: LogAction
  - flushOut :: FlushOut
  - flushErr :: FlushErr
  - haddockOptions :: Maybe String
  - ghciScripts :: [String]
  - pprUserLength :: Int
  - pprCols :: Int
  - traceLevel :: Int
  - useUnicode :: Bool
  - profAuto :: ProfAuto
  - interactivePrint :: Maybe String
  - llvmVersion :: IORef Int
  - nextWrapperNum :: IORef (ModuleEnv Int)
  - sseVersion :: Maybe SseVersion
  - avx :: Bool
  - avx2 :: Bool
  - avx512cd :: Bool
  - avx512er :: Bool
  - avx512f :: Bool
  - avx512pf :: Bool
  - rtldInfo :: IORef (Maybe LinkerInfo)
  - rtccInfo :: IORef (Maybe CompilerInfo)
  - maxInlineAllocSize :: Int
  - maxInlineMemcpyInsns :: Int
  - maxInlineMemsetInsns :: Int
  }
- data GeneralFlag
  - = Opt_DumpToFile
  - | Opt_D_faststring_stats
  - | Opt_D_dump_minimal_imports
  - | Opt_DoCoreLinting
  - | Opt_DoStgLinting
  - | Opt_DoCmmLinting
  - | Opt_DoAsmLinting
  - | Opt_DoAnnotationLinting
  - | Opt_NoLlvmMangler
  - | Opt_WarnIsError
  - | Opt_PrintExplicitForalls
  - | Opt_PrintExplicitKinds
  - | Opt_CallArity
  - | Opt_Strictness
  - | Opt_LateDmdAnal
  - | Opt_KillAbsence
  - | Opt_KillOneShot
  - | Opt_FullLaziness
  - | Opt_FloatIn
  - | Opt_Specialise
  - | Opt_SpecialiseAggressively
  - | Opt_StaticArgumentTransformation
  - | Opt_CSE
  - | Opt_LiberateCase
  - | Opt_SpecConstr
  - | Opt_DoLambdaEtaExpansion
  - | Opt_IgnoreAsserts
  - | Opt_DoEtaReduction
  - | Opt_CaseMerge
  - | Opt_UnboxStrictFields
  - | Opt_UnboxSmallStrictFields
  - | Opt_DictsCheap
  - | Opt_EnableRewriteRules
  - | Opt_Vectorise
  - | Opt_VectorisationAvoidance
  - | Opt_RegsGraph
  - | Opt_RegsIterative
  - | Opt_PedanticBottoms
  - | Opt_LlvmTBAA
  - | Opt_LlvmPassVectorsInRegisters
  - | Opt_IrrefutableTuples
  - | Opt_CmmSink
  - | Opt_CmmElimCommonBlocks
  - | Opt_OmitYields
  - | Opt_SimpleListLiterals
  - | Opt_FunToThunk
  - | Opt_DictsStrict
  - | Opt_DmdTxDictSel
  - | Opt_Loopification
  - | Opt_IgnoreInterfacePragmas
  - | Opt_OmitInterfacePragmas
  - | Opt_ExposeAllUnfoldings
  - | Opt_WriteInterface
  - | Opt_AutoSccsOnIndividualCafs
  - | Opt_ProfCountEntries
  - | Opt_Pp
  - | Opt_ForceRecomp
  - | Opt_ExcessPrecision
  - | Opt_EagerBlackHoling
  - | Opt_NoHsMain
  - | Opt_SplitObjs
  - | Opt_StgStats
  - | Opt_HideAllPackages
  - | Opt_PrintBindResult
  - | Opt_Haddock
  - | Opt_HaddockOptions
  - | Opt_Hpc_No_Auto
  - | Opt_BreakOnException
  - | Opt_BreakOnError
  - | Opt_PrintEvldWithShow
  - | Opt_PrintBindContents
  - | Opt_GenManifest
  - | Opt_EmbedManifest
  - | Opt_EmitExternalCore
  - | Opt_SharedImplib
  - | Opt_BuildingCabalPackage
  - | Opt_IgnoreDotGhci
  - | Opt_GhciSandbox
  - | Opt_GhciHistory
  - | Opt_HelpfulErrors
  - | Opt_DeferTypeErrors
  - | Opt_DeferTypedHoles
  - | Opt_Parallel
  - | Opt_GranMacros
  - | Opt_PIC
  - | Opt_SccProfilingOn
  - | Opt_Ticky
  - | Opt_Ticky_Allocd
  - | Opt_Ticky_LNE
  - | Opt_Ticky_Dyn_Thunk
  - | Opt_Static
  - | Opt_RPath
  - | Opt_RelativeDynlibPaths
  - | Opt_Hpc
  - | Opt_FlatCache
  - | Opt_SimplPreInlining
  - | Opt_ErrorSpans
  - | Opt_PprCaseAsLet
  - | Opt_PprShowTicks
  - | Opt_SuppressCoercions
  - | Opt_SuppressVarKinds
  - | Opt_SuppressModulePrefixes
  - | Opt_SuppressTypeApplications
  - | Opt_SuppressIdInfo
  - | Opt_SuppressTypeSignatures
  - | Opt_SuppressUniques
  - | Opt_AutoLinkPackages
  - | Opt_ImplicitImportQualified
  - | Opt_KeepHiDiffs
  - | Opt_KeepHcFiles
  - | Opt_KeepSFiles
  - | Opt_KeepTmpFiles
  - | Opt_KeepRawTokenStream
  - | Opt_KeepLlvmFiles
  - | Opt_BuildDynamicToo
  - | Opt_DistrustAllPackages
  - | Opt_PackageTrust
  - | Opt_Debug
- data Severity
  - = SevOutput
  - | SevDump
  - | SevInteractive
  - | SevInfo
  - | SevWarning
  - | SevError
  - | SevFatal
- data HscTarget
  - = HscC
  - | HscAsm
  - | HscLlvm
  - | HscInterpreted
  - | HscNothing
- gopt :: GeneralFlag -> DynFlags -> Bool
- data GhcMode
  - = CompManager
  - | OneShot
  - | MkDepend
- data GhcLink
  - = NoLink
  - | LinkBinary
  - | LinkInMemory
  - | LinkDynLib
  - | LinkStaticLib
- defaultObjectTarget :: Platform -> HscTarget
- parseDynamicFlags :: MonadIO m => DynFlags -> [Located String] -> m (DynFlags, [Located String], [Located String])
- getSessionDynFlags :: GhcMonad m => m DynFlags
- setSessionDynFlags :: GhcMonad m => DynFlags -> m [PackageKey]
- getProgramDynFlags :: GhcMonad m => m DynFlags
- setProgramDynFlags :: GhcMonad m => DynFlags -> m [PackageKey]
- getInteractiveDynFlags :: GhcMonad m => m DynFlags
- setInteractiveDynFlags :: GhcMonad m => DynFlags -> m ()
- parseStaticFlags :: [Located String] -> IO ([Located String], [Located String])
- data Target = Target {
  - targetId :: TargetId
  - targetAllowObjCode :: Bool
  - targetContents :: Maybe (StringBuffer, UTCTime)
  }
- data TargetId
  - = TargetModule ModuleName
  - | TargetFile FilePath (Maybe Phase)
- data Phase
- setTargets :: GhcMonad m => [Target] -> m ()
- getTargets :: GhcMonad m => m [Target]
- addTarget :: GhcMonad m => Target -> m ()
- removeTarget :: GhcMonad m => TargetId -> m ()
- guessTarget :: GhcMonad m => String -> Maybe Phase -> m Target
- depanal :: GhcMonad m => [ModuleName] -> Bool -> m ModuleGraph
- load :: GhcMonad m => LoadHowMuch -> m SuccessFlag
- data LoadHowMuch
  - = LoadAllTargets
  - | LoadUpTo ModuleName
  - | LoadDependenciesOf ModuleName
- data InteractiveImport
  - = IIDecl (ImportDecl RdrName)
  - | IIModule ModuleName
- data SuccessFlag
  - = Succeeded
  - | Failed
- succeeded :: SuccessFlag -> Bool
- failed :: SuccessFlag -> Bool
- defaultWarnErrLogger :: WarnErrLogger
- type WarnErrLogger = forall m. GhcMonad m => Maybe SourceError -> m ()
- workingDirectoryChanged :: GhcMonad m => m ()
- parseModule :: GhcMonad m => ModSummary -> m ParsedModule
- typecheckModule :: GhcMonad m => ParsedModule -> m TypecheckedModule
- desugarModule :: GhcMonad m => TypecheckedModule -> m DesugaredModule
- loadModule :: (TypecheckedMod mod, GhcMonad m) => mod -> m mod
- data ParsedModule = ParsedModule {
  - pm_mod_summary :: ModSummary
  - pm_parsed_source :: ParsedSource
  - pm_extra_src_files :: [FilePath]
  - pm_annotations :: ApiAnns
  }
- data TypecheckedModule = TypecheckedModule {
  - tm_parsed_module :: ParsedModule
  - tm_renamed_source :: Maybe RenamedSource
  - tm_typechecked_source :: TypecheckedSource
  - tm_checked_module_info :: ModuleInfo
  - tm_internals_ :: (TcGblEnv, ModDetails)
  }
- data DesugaredModule = DesugaredModule {
  - dm_typechecked_module :: TypecheckedModule
  - dm_core_module :: ModGuts
  }
- type TypecheckedSource = LHsBinds Id
- type ParsedSource = Located (HsModule RdrName)
- type RenamedSource = (HsGroup Name, [LImportDecl Name], Maybe [LIE Name], Maybe LHsDocString)
- class ParsedMod m => TypecheckedMod m where
  - renamedSource :: m -> Maybe RenamedSource
  - typecheckedSource :: m -> TypecheckedSource
  - moduleInfo :: m -> ModuleInfo
- class ParsedMod m where
  - parsedSource :: m -> ParsedSource
- coreModule :: DesugaredMod m => m -> ModGuts
- data CoreModule = CoreModule {
  - cm_module :: !Module
  - cm_types :: !TypeEnv
  - cm_binds :: CoreProgram
  - cm_safe :: SafeHaskellMode
  }
- compileToCoreModule :: GhcMonad m => FilePath -> m CoreModule
- compileToCoreSimplified :: GhcMonad m => FilePath -> m CoreModule
- type ModuleGraph = [ModSummary]
- data ModSummary = ModSummary {
  - ms_mod :: Module
  - ms_hsc_src :: HscSource
  - ms_location :: ModLocation
  - ms_hs_date :: UTCTime
  - ms_obj_date :: Maybe UTCTime
  - ms_iface_date :: Maybe UTCTime
  - ms_srcimps :: [Located (ImportDecl RdrName)]
  - ms_textual_imps :: [Located (ImportDecl RdrName)]
  - ms_hspp_file :: FilePath
  - ms_hspp_opts :: DynFlags
  - ms_hspp_buf :: Maybe StringBuffer
  }
- ms_mod_name :: ModSummary -> ModuleName
- data ModLocation = ModLocation {
  - ml_hs_file :: Maybe FilePath
  - ml_hi_file :: FilePath
  - ml_obj_file :: FilePath
  }
- getModSummary :: GhcMonad m => ModuleName -> m ModSummary
- getModuleGraph :: GhcMonad m => m ModuleGraph
- isLoaded :: GhcMonad m => ModuleName -> m Bool
- topSortModuleGraph :: Bool -> [ModSummary] -> Maybe ModuleName -> [SCC ModSummary]
- data ModuleInfo
- getModuleInfo :: GhcMonad m => Module -> m (Maybe ModuleInfo)
- modInfoTyThings :: ModuleInfo -> [TyThing]
- modInfoTopLevelScope :: ModuleInfo -> Maybe [Name]
- modInfoExports :: ModuleInfo -> [Name]
- modInfoInstances :: ModuleInfo -> [ClsInst]
- modInfoIsExportedName :: ModuleInfo -> Name -> Bool
- modInfoLookupName :: GhcMonad m => ModuleInfo -> Name -> m (Maybe TyThing)
- modInfoIface :: ModuleInfo -> Maybe ModIface
- modInfoSafe :: ModuleInfo -> SafeHaskellMode
- lookupGlobalName :: GhcMonad m => Name -> m (Maybe TyThing)
- findGlobalAnns :: (GhcMonad m, Typeable a) => ([Word8] -> a) -> AnnTarget Name -> m [a]
- mkPrintUnqualifiedForModule :: GhcMonad m => ModuleInfo -> m (Maybe PrintUnqualified)
- data ModIface = ModIface {
  - mi_module :: !Module
  - mi_sig_of :: !(Maybe Module)
  - mi_iface_hash :: !Fingerprint
  - mi_mod_hash :: !Fingerprint
  - mi_flag_hash :: !Fingerprint
  - mi_orphan :: !WhetherHasOrphans
  - mi_finsts :: !WhetherHasFamInst
  - mi_boot :: !IsBootInterface
  - mi_deps :: Dependencies
  - mi_usages :: [Usage]
  - mi_exports :: ![IfaceExport]
  - mi_exp_hash :: !Fingerprint
  - mi_used_th :: !Bool
  - mi_fixities :: [(OccName, Fixity)]
  - mi_warns :: Warnings
  - mi_anns :: [IfaceAnnotation]
  - mi_decls :: [(Fingerprint, IfaceDecl)]
  - mi_globals :: !(Maybe GlobalRdrEnv)
  - mi_insts :: [IfaceClsInst]
  - mi_fam_insts :: [IfaceFamInst]
  - mi_rules :: [IfaceRule]
  - mi_orphan_hash :: !Fingerprint
  - mi_vect_info :: !IfaceVectInfo
  - mi_warn_fn :: Name -> Maybe WarningTxt
  - mi_fix_fn :: OccName -> Fixity
  - mi_hash_fn :: OccName -> Maybe (OccName, Fingerprint)
  - mi_hpc :: !AnyHpcUsage
  - mi_trust :: !IfaceTrustInfo
  - mi_trust_pkg :: !Bool
  }
- data SafeHaskellMode
  - = Sf_None
  - | Sf_Unsafe
  - | Sf_Trustworthy
  - | Sf_Safe
- data PrintUnqualified
- alwaysQualify :: PrintUnqualified
- getBindings :: GhcMonad m => m [TyThing]
- getInsts :: GhcMonad m => m ([ClsInst], [FamInst])
- getPrintUnqual :: GhcMonad m => m PrintUnqualified
- findModule :: GhcMonad m => ModuleName -> Maybe FastString -> m Module
- lookupModule :: GhcMonad m => ModuleName -> Maybe FastString -> m Module
- isModuleTrusted :: GhcMonad m => Module -> m Bool
- moduleTrustReqs :: GhcMonad m => Module -> m (Bool, [PackageKey])
- setContext :: GhcMonad m => [InteractiveImport] -> m ()
- getContext :: GhcMonad m => m [InteractiveImport]
- getNamesInScope :: GhcMonad m => m [Name]
- getRdrNamesInScope :: GhcMonad m => m [RdrName]
- getGRE :: GhcMonad m => m GlobalRdrEnv
- moduleIsInterpreted :: GhcMonad m => Module -> m Bool
- getInfo :: GhcMonad m => Bool -> Name -> m (Maybe (TyThing, Fixity, [ClsInst], [FamInst]))
- exprType :: GhcMonad m => String -> m Type
- typeKind :: GhcMonad m => Bool -> String -> m (Type, Kind)
- parseName :: GhcMonad m => String -> m [Name]
- data RunResult
  - = RunOk [Name]
  - | RunException SomeException
  - | RunBreak ThreadId [Name] (Maybe BreakInfo)
- runStmt :: GhcMonad m => String -> SingleStep -> m RunResult
- runStmtWithLocation :: GhcMonad m => String -> Int -> String -> SingleStep -> m RunResult
- runDecls :: GhcMonad m => String -> m [Name]
- runDeclsWithLocation :: GhcMonad m => String -> Int -> String -> m [Name]
- runTcInteractive :: HscEnv -> TcRn a -> IO (Messages, Maybe a)
- parseImportDecl :: GhcMonad m => String -> m (ImportDecl RdrName)
- data SingleStep
  - = RunToCompletion
  - | SingleStep
  - | RunAndLogSteps
- resume :: GhcMonad m => (SrcSpan -> Bool) -> SingleStep -> m RunResult
- data Resume
- data History
- getHistorySpan :: GhcMonad m => History -> m SrcSpan
- getHistoryModule :: History -> Module
- getResumeContext :: GhcMonad m => m [Resume]
- abandon :: GhcMonad m => m Bool
- abandonAll :: GhcMonad m => m Bool
- back :: GhcMonad m => m ([Name], Int, SrcSpan)
- forward :: GhcMonad m => m ([Name], Int, SrcSpan)
- showModule :: GhcMonad m => ModSummary -> m String
- isModuleInterpreted :: GhcMonad m => ModSummary -> m Bool
- compileExpr :: GhcMonad m => String -> m HValue
- data HValue
- dynCompileExpr :: GhcMonad m => String -> m Dynamic
- obtainTermFromId :: GhcMonad m => Int -> Bool -> Id -> m Term
- obtainTermFromVal :: GhcMonad m => Int -> Bool -> Type -> a -> m Term
- reconstructType :: HscEnv -> Int -> Id -> IO (Maybe Type)
- modInfoModBreaks :: ModuleInfo -> ModBreaks
- data ModBreaks = ModBreaks {
  - modBreaks_flags :: BreakArray
  - modBreaks_locs :: !(Array BreakIndex SrcSpan)
  - modBreaks_vars :: !(Array BreakIndex [OccName])
  - modBreaks_decls :: !(Array BreakIndex [String])
  }
- type BreakIndex = Int
- data BreakInfo
- data BreakArray
- setBreakOn :: DynFlags -> BreakArray -> Int -> IO Bool
- setBreakOff :: DynFlags -> BreakArray -> Int -> IO Bool
- getBreak :: DynFlags -> BreakArray -> Int -> IO (Maybe Word)
- lookupName :: GhcMonad m => Name -> m (Maybe TyThing)
- setGHCiMonad :: GhcMonad m => String -> m ()
- data PackageKey
- data Module
- mkModule :: PackageKey -> ModuleName -> Module
- pprModule :: Module -> SDoc
- moduleName :: Module -> ModuleName
- modulePackageKey :: Module -> PackageKey
- data ModuleName
- mkModuleName :: String -> ModuleName
- moduleNameString :: ModuleName -> String
- data Name
- isExternalName :: Name -> Bool
- nameModule :: Name -> Module
- pprParenSymName :: NamedThing a => a -> SDoc
- nameSrcSpan :: Name -> SrcSpan
- class NamedThing a where
  - getOccName :: a -> OccName
  - getName :: a -> Name
- data RdrName
  - = Unqual OccName
  - | Qual ModuleName OccName
- type Id = Var
- idType :: Id -> Kind
- isImplicitId :: Id -> Bool
- isDeadBinder :: Id -> Bool
- isExportedId :: Var -> Bool
- isLocalId :: Var -> Bool
- isGlobalId :: Var -> Bool
- isRecordSelector :: Id -> Bool
- isPrimOpId :: Id -> Bool
- isFCallId :: Id -> Bool
- isClassOpId_maybe :: Id -> Maybe Class
- isDataConWorkId :: Id -> Bool
- idDataCon :: Id -> DataCon
- isBottomingId :: Id -> Bool
- isDictonaryId :: Id -> Bool
- recordSelectorFieldLabel :: Id -> (TyCon, FieldLabel)
- data TyCon
- tyConTyVars :: TyCon -> [TyVar]
- tyConDataCons :: TyCon -> [DataCon]
- tyConArity :: TyCon -> Arity
- isClassTyCon :: TyCon -> Bool
- isTypeSynonymTyCon :: TyCon -> Bool
- isTypeFamilyTyCon :: TyCon -> Bool
- isNewTyCon :: TyCon -> Bool
- isPrimTyCon :: TyCon -> Bool
- isFunTyCon :: TyCon -> Bool
- isFamilyTyCon :: TyCon -> Bool
- isOpenFamilyTyCon :: TyCon -> Bool
- isOpenTypeFamilyTyCon :: TyCon -> Bool
- tyConClass_maybe :: TyCon -> Maybe Class
- synTyConRhs_maybe :: TyCon -> Maybe Type
- synTyConDefn_maybe :: TyCon -> Maybe ([TyVar], Type)
- synTyConResKind :: TyCon -> Kind
- type TyVar = Var
- alphaTyVars :: [TyVar]
- data DataCon
- dataConSig :: DataCon -> ([TyVar], ThetaType, [Type], Type)
- dataConType :: DataCon -> Type
- dataConTyCon :: DataCon -> TyCon
- dataConFieldLabels :: DataCon -> [FieldLabel]
- dataConIsInfix :: DataCon -> Bool
- isVanillaDataCon :: DataCon -> Bool
- dataConUserType :: DataCon -> Type
- dataConSrcBangs :: DataCon -> [HsSrcBang]
- data StrictnessMark
  - = MarkedStrict
  - | NotMarkedStrict
- isMarkedStrict :: StrictnessMark -> Bool
- data Class
- classMethods :: Class -> [Id]
- classSCTheta :: Class -> [PredType]
- classTvsFds :: Class -> ([TyVar], [FunDep TyVar])
- classATs :: Class -> [TyCon]
- pprFundeps :: Outputable a => [FunDep a] -> SDoc
- data ClsInst
- instanceDFunId :: ClsInst -> DFunId
- pprInstance :: ClsInst -> SDoc
- pprInstanceHdr :: ClsInst -> SDoc
- pprFamInst :: FamInst -> SDoc
- data FamInst
- data Type
- splitForAllTys :: Type -> ([TyVar], Type)
- funResultTy :: Type -> Type
- pprParendType :: Type -> SDoc
- pprTypeApp :: TyCon -> [Type] -> SDoc
- type Kind = Type
- type PredType = Type
- type ThetaType = [PredType]
- pprForAll :: [TyVar] -> SDoc
- pprThetaArrowTy :: ThetaType -> SDoc
- data TyThing
  - = AnId Id
  - | AConLike ConLike
  - | ATyCon TyCon
  - | ACoAxiom (CoAxiom Branched)
- module HsSyn
- data FixityDirection
  - = InfixL
  - | InfixR
  - | InfixN
- defaultFixity :: Fixity
- maxPrecedence :: Int
- negateFixity :: Fixity
- compareFixity :: Fixity -> Fixity -> (Bool, Bool)
- data SrcLoc
  - = RealSrcLoc !RealSrcLoc
  - | UnhelpfulLoc FastString
- data RealSrcLoc
- mkSrcLoc :: FastString -> Int -> Int -> SrcLoc
- noSrcLoc :: SrcLoc
- srcLocFile :: RealSrcLoc -> FastString
- srcLocLine :: RealSrcLoc -> Int
- srcLocCol :: RealSrcLoc -> Int
- data SrcSpan
  - = RealSrcSpan !RealSrcSpan
  - | UnhelpfulSpan !FastString
- data RealSrcSpan
- mkSrcSpan :: SrcLoc -> SrcLoc -> SrcSpan
- srcLocSpan :: SrcLoc -> SrcSpan
- isGoodSrcSpan :: SrcSpan -> Bool
- noSrcSpan :: SrcSpan
- srcSpanStart :: SrcSpan -> SrcLoc
- srcSpanEnd :: SrcSpan -> SrcLoc
- srcSpanFile :: RealSrcSpan -> FastString
- srcSpanStartLine :: RealSrcSpan -> Int
- srcSpanEndLine :: RealSrcSpan -> Int
- srcSpanStartCol :: RealSrcSpan -> Int
- srcSpanEndCol :: RealSrcSpan -> Int
- data GenLocated l e = L l e
- type Located e = GenLocated SrcSpan e
- noLoc :: e -> Located e
- mkGeneralLocated :: String -> e -> Located e
- getLoc :: GenLocated l e -> l
- unLoc :: GenLocated l e -> e
- eqLocated :: Eq a => Located a -> Located a -> Bool
- cmpLocated :: Ord a => Located a -> Located a -> Ordering
- combineLocs :: Located a -> Located b -> SrcSpan
- addCLoc :: Located a -> Located b -> c -> Located c
- leftmost_smallest :: SrcSpan -> SrcSpan -> Ordering
- leftmost_largest :: SrcSpan -> SrcSpan -> Ordering
- rightmost :: SrcSpan -> SrcSpan -> Ordering
- spans :: SrcSpan -> (Int, Int) -> Bool
- isSubspanOf :: SrcSpan -> SrcSpan -> Bool
- data GhcException
  - = PhaseFailed String ExitCode
  - | Signal Int
  - | UsageError String
  - | CmdLineError String
  - | Panic String
  - | PprPanic String SDoc
  - | Sorry String
  - | PprSorry String SDoc
  - | InstallationError String
  - | ProgramError String
  - | PprProgramError String SDoc
- showGhcException :: GhcException -> String -> String
- data Token
- getTokenStream :: GhcMonad m => Module -> m [Located Token]
- getRichTokenStream :: GhcMonad m => Module -> m [(Located Token, String)]
- showRichTokenStream :: [(Located Token, String)] -> String
- addSourceToTokens :: RealSrcLoc -> StringBuffer -> [Located Token] -> [(Located Token, String)]
- parser :: String -> DynFlags -> FilePath -> Either ErrorMessages (WarningMessages, Located (HsModule RdrName))
- type ApiAnns = (Map ApiAnnKey [SrcSpan], Map SrcSpan [Located AnnotationComment])
- data AnnKeywordId
  - = AnnAs
  - | AnnAt
  - | AnnBang
  - | AnnBackquote
  - | AnnBy
  - | AnnCase
  - | AnnClass
  - | AnnClose
  - | AnnCloseC
  - | AnnCloseP
  - | AnnCloseS
  - | AnnColon
  - | AnnComma
  - | AnnCommaTuple
  - | AnnDarrow
  - | AnnData
  - | AnnDcolon
  - | AnnDefault
  - | AnnDeriving
  - | AnnDo
  - | AnnDot
  - | AnnDotdot
  - | AnnElse
  - | AnnEqual
  - | AnnExport
  - | AnnFamily
  - | AnnForall
  - | AnnForeign
  - | AnnFunId
  - | AnnGroup
  - | AnnHeader
  - | AnnHiding
  - | AnnIf
  - | AnnImport
  - | AnnIn
  - | AnnInfix
  - | AnnInstance
  - | AnnLam
  - | AnnLarrow
  - | AnnLet
  - | AnnMdo
  - | AnnMinus
  - | AnnModule
  - | AnnNewtype
  - | AnnName
  - | AnnOf
  - | AnnOpen
  - | AnnOpenC
  - | AnnOpenP
  - | AnnOpenPE
  - | AnnOpenPTE
  - | AnnOpenS
  - | AnnPackageName
  - | AnnPattern
  - | AnnProc
  - | AnnQualified
  - | AnnRarrow
  - | AnnRec
  - | AnnRole
  - | AnnSafe
  - | AnnSemi
  - | AnnSimpleQuote
  - | AnnStatic
  - | AnnThen
  - | AnnThIdSplice
  - | AnnThIdTySplice
  - | AnnThTyQuote
  - | AnnTilde
  - | AnnTildehsh
  - | AnnType
  - | AnnUnit
  - | AnnUsing
  - | AnnVal
  - | AnnValStr
  - | AnnVbar
  - | AnnWhere
  - | Annlarrowtail
  - | Annrarrowtail
  - | AnnLarrowtail
  - | AnnRarrowtail
  - | AnnEofPos
- data AnnotationComment
  - = AnnDocCommentNext String
  - | AnnDocCommentPrev String
  - | AnnDocCommentNamed String
  - | AnnDocSection Int String
  - | AnnDocOptions String
  - | AnnDocOptionsOld String
  - | AnnLineComment String
  - | AnnBlockComment String
- getAnnotation :: ApiAnns -> SrcSpan -> AnnKeywordId -> [SrcSpan]
- getAndRemoveAnnotation :: ApiAnns -> SrcSpan -> AnnKeywordId -> ([SrcSpan], ApiAnns)
- getAnnotationComments :: ApiAnns -> SrcSpan -> [Located AnnotationComment]
- getAndRemoveAnnotationComments :: ApiAnns -> SrcSpan -> ([Located AnnotationComment], ApiAnns)
- cyclicModuleErr :: [ModSummary] -> SDoc

# Initialisation

defaultErrorHandler :: (ExceptionMonad m, MonadIO m) => FatalMessager -> FlushOut -> m a -> m a

Install some default exception handlers and run the inner computation. Unless you want to handle exceptions yourself, you should wrap this around the top level of your program. The default handlers output the error message(s) to stderr and exit cleanly.

defaultCleanupHandler :: (ExceptionMonad m, MonadIO m) => DynFlags -> m a -> m a

Install a default cleanup handler to remove temporary files deposited by a GHC run. This is separate from `defaultErrorHandler`, because you might want to override the error handling, but still get the ordinary cleanup behaviour.

prettyPrintGhcErrors :: ExceptionMonad m => DynFlags -> m a -> m a

# GHC Monad

data Ghc a

A minimal implementation of a `GhcMonad`. If you need a custom monad, e.g., to maintain additional state consider wrapping this monad or using `GhcT`.

Instances

Monad Ghc |
Functor Ghc |
MonadFix Ghc |
Applicative Ghc |
MonadIO Ghc |
ExceptionMonad Ghc |
HasDynFlags Ghc |
GhcMonad Ghc |

data GhcT m a

A monad transformer to add GHC specific features to another monad.

Note that the wrapped monad must support IO and handling of exceptions.

Instances

Monad m => Monad (GhcT m) |
Functor m => Functor (GhcT m) |
Applicative m => Applicative (GhcT m) |
MonadIO m => MonadIO (GhcT m) |
ExceptionMonad m => ExceptionMonad (GhcT m) |
(Functor m, ExceptionMonad m, MonadIO m) => HasDynFlags (GhcT m) |
(Functor m, ExceptionMonad m, MonadIO m) => GhcMonad (GhcT m) |

class (Functor m, MonadIO m, ExceptionMonad m, HasDynFlags m) => GhcMonad m where

A monad that has all the features needed by GHC API calls.

In short, a GHC monad

- allows embedding of IO actions,
- can log warnings,
- allows handling of (extensible) exceptions, and
- maintains a current session.

If you do not use `Ghc` or `GhcT`, make sure to call `initGhcMonad` before any call to the GHC API functions can occur.

Methods

getSession :: m HscEnv

setSession :: HscEnv -> m ()

Instances

GhcMonad Ghc |
(Functor m, ExceptionMonad m, MonadIO m) => GhcMonad (GhcT m) |

data HscEnv

Hscenv is like `Session`, except that some of the fields are immutable. An HscEnv is used to compile a single module from plain Haskell source code (after preprocessing) to either C, assembly or C--. Things like the module graph don't change during a single compilation.

Historical note: "hsc" used to be the name of the compiler binary, when there was a separate driver and compiler. To compile a single module, the driver would invoke hsc on the source code... so nowadays we think of hsc as the layer of the compiler that deals with compiling a single module.

Instances

ContainsDynFlags HscEnv |

runGhc

Arguments

:: Maybe FilePath | See argument to `initGhcMonad`.
-> Ghc a | The action to perform.
-> IO a |

Run function for the `Ghc` monad.

It initialises the GHC session and warnings via `initGhcMonad`. Each call to this function will create a new session which should not be shared among several threads.

Any errors not handled inside the `Ghc` action are propagated as IO exceptions.

runGhcT

Arguments

:: (ExceptionMonad m, Functor m, MonadIO m) |
=> Maybe FilePath | See argument to `initGhcMonad`.
-> GhcT m a | The action to perform.
-> m a |

Run function for `GhcT` monad transformer.

It initialises the GHC session and warnings via `initGhcMonad`. Each call to this function will create a new session which should not be shared among several threads.

initGhcMonad :: GhcMonad m => Maybe FilePath -> m ()

Initialise a GHC session.

If you implement a custom `GhcMonad` you must call this function in the monad run function. It will initialise the session variable and clear all warnings.

The first argument should point to the directory where GHC's library files reside. More precisely, this should be the output of `ghc --print-libdir` of the version of GHC the module using this API is compiled with. For portability, you should use the `ghc-paths` package, available at http://hackage.haskell.org/package/ghc-paths.

gcatch :: (ExceptionMonad m, Exception e) => m a -> (e -> m a) -> m a

Generalised version of `catch`, allowing an arbitrary exception handling monad instead of just `IO`.

gbracket :: ExceptionMonad m => m a -> (a -> m b) -> (a -> m c) -> m c

Generalised version of `bracket`, allowing an arbitrary exception handling monad instead of just `IO`.

gfinally :: ExceptionMonad m => m a -> m b -> m a

Generalised version of `finally`, allowing an arbitrary exception handling monad instead of just `IO`.

printException :: GhcMonad m => SourceError -> m ()

Print the error message and all warnings. Useful inside exception handlers. Clears warnings after printing.

handleSourceError

Arguments

:: ExceptionMonad m |
=> (SourceError -> m a) | exception handler
-> m a | action to perform
-> m a |

Perform the given action and call the exception handler if the action throws a `SourceError`. See `SourceError` for more information.

needsTemplateHaskell :: ModuleGraph -> Bool

Determines whether a set of modules requires Template Haskell.

Note that if the session's `DynFlags` enabled Template Haskell when `depanal` was called, then each module in the returned module graph will have Template Haskell enabled whether it is actually needed or not.

# Flags and settings

data DynFlags

Contains not only a collection of `GeneralFlag`s but also a plethora of information relating to the compilation of a single file or GHC session

Constructors

DynFlags |
  Fields ghcMode :: GhcMode ghcLink :: GhcLink hscTarget :: HscTarget settings :: Settings sigOf :: SigOf Compiling an hs-boot against impl. verbosity :: Int Verbosity level: see Note [Verbosity levels] optLevel :: Int Optimisation level simplPhases :: Int Number of simplifier phases maxSimplIterations :: Int Max simplifier iterations ruleCheck :: Maybe String strictnessBefore :: [Int] Additional demand analysis parMakeCount :: Maybe Int The number of modules to compile in parallel in --make mode, where Nothing ==> compile as many in parallel as there are CPUs. enableTimeStats :: Bool Enable RTS timing statistics? ghcHeapSize :: Maybe Int The heap size to set. maxRelevantBinds :: Maybe Int Maximum number of bindings from the type envt to show in type error messages simplTickFactor :: Int Multiplier for simplifier ticks specConstrThreshold :: Maybe Int Threshold for SpecConstr specConstrCount :: Maybe Int Max number of specialisations for any one function specConstrRecursive :: Int Max number of specialisations for recursive types Not optional; otherwise ForceSpecConstr can diverge. liberateCaseThreshold :: Maybe Int Threshold for LiberateCase floatLamArgs :: Maybe Int Arg count for lambda floating See CoreMonad.FloatOutSwitches historySize :: Int cmdlineHcIncludes :: [String]
      -#includes
importPaths :: [FilePath] mainModIs :: Module mainFunIs :: Maybe String ctxtStkDepth :: Int Typechecker context stack depth tyFunStkDepth :: Int Typechecker type function stack depth thisPackage :: PackageKey name of package currently being compiled ways :: [Way] Way flags from the command line buildTag :: String The global "way" (e.g. "p" for prof) rtsBuildTag :: String The RTS "way" splitInfo :: Maybe (String, Int) objectDir :: Maybe String dylibInstallName :: Maybe String hiDir :: Maybe String stubDir :: Maybe String dumpDir :: Maybe String objectSuf :: String hcSuf :: String hiSuf :: String canGenerateDynamicToo :: IORef Bool dynObjectSuf :: String dynHiSuf :: String dllSplitFile :: Maybe FilePath dllSplit :: Maybe [Set String] outputFile :: Maybe String dynOutputFile :: Maybe String outputHi :: Maybe String dynLibLoader :: DynLibLoader dumpPrefix :: Maybe FilePath This is set by `runPipeline` based on where its output is going. dumpPrefixForce :: Maybe FilePath Override the `dumpPrefix` set by `runPipeline`. Set by `-ddump-file-prefix` ldInputs :: [Option] includePaths :: [String] libraryPaths :: [String] frameworkPaths :: [String] cmdlineFrameworks :: [String] rtsOpts :: Maybe String rtsOptsEnabled :: RtsOptsEnabled hpcDir :: String Path to store the .mix files pluginModNames :: [ModuleName] pluginModNameOpts :: [(ModuleName, String)] hooks :: Hooks depMakefile :: FilePath depIncludePkgDeps :: Bool depExcludeMods :: [ModuleName] depSuffixes :: [String] extraPkgConfs :: [PkgConfRef] -> [PkgConfRef] The `-package-db` flags given on the command line, in the order they appeared. packageFlags :: [PackageFlag] The `-package` and `-hide-package` flags from the command-line packageEnv :: Maybe FilePath Filepath to the package environment file (if overriding default) pkgDatabase :: Maybe [PackageConfig] pkgState :: PackageState filesToClean :: IORef [FilePath] dirsToClean :: IORef (Map FilePath FilePath) filesToNotIntermediateClean :: IORef [FilePath] nextTempSuffix :: IORef Int generatedDumps :: IORef (Set FilePath) dumpFlags :: IntSet generalFlags :: IntSet warningFlags :: IntSet language :: Maybe Language safeHaskell :: SafeHaskellMode Safe Haskell mode safeInfer :: Bool safeInferred :: Bool thOnLoc :: SrcSpan newDerivOnLoc :: SrcSpan overlapInstLoc :: SrcSpan incoherentOnLoc :: SrcSpan pkgTrustOnLoc :: SrcSpan warnSafeOnLoc :: SrcSpan warnUnsafeOnLoc :: SrcSpan trustworthyOnLoc :: SrcSpan extensions :: [OnOff ExtensionFlag] extensionFlags :: IntSet ufCreationThreshold :: Int ufUseThreshold :: Int ufFunAppDiscount :: Int ufDictDiscount :: Int ufKeenessFactor :: Float ufDearOp :: Int maxWorkerArgs :: Int ghciHistSize :: Int log_action :: LogAction MsgDoc output action: use ErrUtils instead of this if you can flushOut :: FlushOut flushErr :: FlushErr haddockOptions :: Maybe String ghciScripts :: [String] pprUserLength :: Int pprCols :: Int traceLevel :: Int useUnicode :: Bool profAuto :: ProfAuto what kind of {--} to add automatically interactivePrint :: Maybe String llvmVersion :: IORef Int nextWrapperNum :: IORef (ModuleEnv Int) sseVersion :: Maybe SseVersion Machine dependant flags (-mblah stuff) avx :: Bool avx2 :: Bool avx512cd :: Bool avx512er :: Bool avx512f :: Bool avx512pf :: Bool rtldInfo :: IORef (Maybe LinkerInfo) Run-time linker information (what options we need, etc.) rtccInfo :: IORef (Maybe CompilerInfo) Run-time compiler information maxInlineAllocSize :: Int Max size, in bytes, of inline array allocations. maxInlineMemcpyInsns :: Int Only inline memcpy if it generates no more than this many pseudo (roughly: Cmm) instructions. maxInlineMemsetInsns :: Int Only inline memset if it generates no more than this many pseudo (roughly: Cmm) instructions.

data GeneralFlag

Enumerates the simple on-or-off dynamic flags

Constructors

Opt_DumpToFile | Append dump output to files instead of stdout.
Opt_D_faststring_stats |
Opt_D_dump_minimal_imports |
Opt_DoCoreLinting |
Opt_DoStgLinting |
Opt_DoCmmLinting |
Opt_DoAsmLinting |
Opt_DoAnnotationLinting |
Opt_NoLlvmMangler |
Opt_WarnIsError |
Opt_PrintExplicitForalls |
Opt_PrintExplicitKinds |
Opt_CallArity |
Opt_Strictness |
Opt_LateDmdAnal |
Opt_KillAbsence |
Opt_KillOneShot |
Opt_FullLaziness |
Opt_FloatIn |
Opt_Specialise |
Opt_SpecialiseAggressively |
Opt_StaticArgumentTransformation |
Opt_CSE |
Opt_LiberateCase |
Opt_SpecConstr |
Opt_DoLambdaEtaExpansion |
Opt_IgnoreAsserts |
Opt_DoEtaReduction |
Opt_CaseMerge |
Opt_UnboxStrictFields |
Opt_UnboxSmallStrictFields |
Opt_DictsCheap |
Opt_EnableRewriteRules |
Opt_Vectorise |
Opt_VectorisationAvoidance |
Opt_RegsGraph |
Opt_RegsIterative |
Opt_PedanticBottoms |
Opt_LlvmTBAA |
Opt_LlvmPassVectorsInRegisters |
Opt_IrrefutableTuples |
Opt_CmmSink |
Opt_CmmElimCommonBlocks |
Opt_OmitYields |
Opt_SimpleListLiterals |
Opt_FunToThunk |
Opt_DictsStrict |
Opt_DmdTxDictSel |
Opt_Loopification |
Opt_IgnoreInterfacePragmas |
Opt_OmitInterfacePragmas |
Opt_ExposeAllUnfoldings |
Opt_WriteInterface |
Opt_AutoSccsOnIndividualCafs |
Opt_ProfCountEntries |
Opt_Pp |
Opt_ForceRecomp |
Opt_ExcessPrecision |
Opt_EagerBlackHoling |
Opt_NoHsMain |
Opt_SplitObjs |
Opt_StgStats |
Opt_HideAllPackages |
Opt_PrintBindResult |
Opt_Haddock |
Opt_HaddockOptions |
Opt_Hpc_No_Auto |
Opt_BreakOnException |
Opt_BreakOnError |
Opt_PrintEvldWithShow |
Opt_PrintBindContents |
Opt_GenManifest |
Opt_EmbedManifest |
Opt_EmitExternalCore |
Opt_SharedImplib |
Opt_BuildingCabalPackage |
Opt_IgnoreDotGhci |
Opt_GhciSandbox |
Opt_GhciHistory |
Opt_HelpfulErrors |
Opt_DeferTypeErrors |
Opt_DeferTypedHoles |
Opt_Parallel |
Opt_GranMacros |
Opt_PIC |
Opt_SccProfilingOn |
Opt_Ticky |
Opt_Ticky_Allocd |
Opt_Ticky_LNE |
Opt_Ticky_Dyn_Thunk |
Opt_Static |
Opt_RPath |
Opt_RelativeDynlibPaths |
Opt_Hpc |
Opt_FlatCache |
Opt_SimplPreInlining |
Opt_ErrorSpans |
Opt_PprCaseAsLet |
Opt_PprShowTicks |
Opt_SuppressCoercions |
Opt_SuppressVarKinds |
Opt_SuppressModulePrefixes |
Opt_SuppressTypeApplications |
Opt_SuppressIdInfo |
Opt_SuppressTypeSignatures |
Opt_SuppressUniques |
Opt_AutoLinkPackages |
Opt_ImplicitImportQualified |
Opt_KeepHiDiffs |
Opt_KeepHcFiles |
Opt_KeepSFiles |
Opt_KeepTmpFiles |
Opt_KeepRawTokenStream |
Opt_KeepLlvmFiles |
Opt_BuildDynamicToo |
Opt_DistrustAllPackages |
Opt_PackageTrust |
Opt_Debug |

Instances

Enum GeneralFlag |
Eq GeneralFlag |
Show GeneralFlag |

data Severity

Constructors

SevOutput |
SevDump |
SevInteractive |
SevInfo |
SevWarning |
SevError |
SevFatal |

data HscTarget

The target code type of the compilation (if any).

Whenever you change the target, also make sure to set `ghcLink` to something sensible.

`HscNothing` can be used to avoid generating any output, however, note that:

- If a program uses Template Haskell the typechecker may try to run code from an imported module. This will fail if no code has been generated for this module. You can use `needsTemplateHaskell` to detect whether this might be the case and choose to either switch to a different target or avoid typechecking such modules. (The latter may be preferable for security reasons.)

Constructors

HscC | Generate C code.
HscAsm | Generate assembly using the native code generator.
HscLlvm | Generate assembly using the llvm code generator.
HscInterpreted | Generate bytecode. (Requires `LinkInMemory`)
HscNothing | Don't generate any code. See notes above.

Instances

Eq HscTarget |
Show HscTarget |

gopt :: GeneralFlag -> DynFlags -> Bool

Test whether a `GeneralFlag` is set

data GhcMode

The `GhcMode` tells us whether we're doing multi-module compilation (controlled via the GHC API) or one-shot (single-module) compilation. This makes a difference primarily to the Finder: in one-shot mode we look for interface files for imported modules, but in multi-module mode we look for source files in order to check whether they need to be recompiled.

Constructors

CompManager | `--make`, GHCi, etc.
OneShot |
    ghc -c Foo.hs
MkDepend | `ghc -M`, see Finder for why we need this

Instances

Eq GhcMode |
Outputable GhcMode |

data GhcLink

What to do in the link step, if there is one.

Constructors

NoLink | Don't link at all
LinkBinary | Link object code into a binary
LinkInMemory | Use the in-memory dynamic linker (works for both bytecode and object code).
LinkDynLib | Link objects into a dynamic lib (DLL on Windows, DSO on ELF platforms)
LinkStaticLib | Link objects into a static lib

Instances

Eq GhcLink |
Show GhcLink |

defaultObjectTarget :: Platform -> HscTarget

The `HscTarget` value corresponding to the default way to create object files on the current platform.

parseDynamicFlags :: MonadIO m => DynFlags -> [Located String] -> m (DynFlags, [Located String], [Located String])

getSessionDynFlags :: GhcMonad m => m DynFlags

Grabs the DynFlags from the Session

setSessionDynFlags :: GhcMonad m => DynFlags -> m [PackageKey]

Updates both the interactive and program DynFlags in a Session. This also reads the package database (unless it has already been read), and prepares the compilers knowledge about packages. It can be called again to load new packages: just add new package flags to (packageFlags dflags).

Returns a list of new packages that may need to be linked in using the dynamic linker (see `linkPackages`) as a result of new package flags. If you are not doing linking or doing static linking, you can ignore the list of packages returned.

getProgramDynFlags :: GhcMonad m => m DynFlags

Returns the program `DynFlags`.

setProgramDynFlags :: GhcMonad m => DynFlags -> m [PackageKey]

Sets the program `DynFlags`.

getInteractiveDynFlags :: GhcMonad m => m DynFlags

Get the `DynFlags` used to evaluate interactive expressions.

setInteractiveDynFlags :: GhcMonad m => DynFlags -> m ()

Set the `DynFlags` used to evaluate interactive expressions. Note: this cannot be used for changes to packages. Use `setSessionDynFlags`, or `setProgramDynFlags` and then copy the `pkgState` into the interactive `DynFlags`.

parseStaticFlags :: [Located String] -> IO ([Located String], [Located String])

Parses GHC's static flags from a list of command line arguments.

These flags are static in the sense that they can be set only once and they are global, meaning that they affect every instance of GHC running; multiple GHC threads will use the same flags.

This function must be called before any session is started, i.e., before the first call to `withGhc`.

Static flags are more of a hack and are static for more or less historical reasons. In the long run, most static flags should eventually become dynamic flags.

XXX: can we add an auto-generated list of static flags here?

# Targets

data Target

A compilation target.

A target may be supplied with the actual text of the module. If so, use this instead of the file contents (this is for use in an IDE where the file hasn't been saved by the user yet).

Constructors

Target |
Fields targetId :: TargetId module or filename targetAllowObjCode :: Bool object code allowed? targetContents :: Maybe (StringBuffer, UTCTime) in-memory text buffer?

Instances

Outputable Target |

data TargetId

Constructors

TargetModule ModuleName | A module name: search for the file
TargetFile FilePath (Maybe Phase) | A filename: preprocess & parse it to find the module name. If specified, the Phase indicates how to compile this file (which phase to start from). Nothing indicates the starting phase should be determined from the suffix of the filename.

Instances

Eq TargetId |
Outputable TargetId |

data Phase

Instances

Eq Phase |
Show Phase |
Outputable Phase |

setTargets :: GhcMonad m => [Target] -> m ()

Sets the targets for this session. Each target may be a module name or a filename. The targets correspond to the set of root modules for the program/library. Unloading the current program is achieved by setting the current set of targets to be empty, followed by `load`.

getTargets :: GhcMonad m => m [Target]

Returns the current set of targets

addTarget :: GhcMonad m => Target -> m ()

Add another target.

removeTarget :: GhcMonad m => TargetId -> m ()

Remove a target

guessTarget :: GhcMonad m => String -> Maybe Phase -> m Target

Attempts to guess what Target a string refers to. This function implements the `--make`/GHCi command-line syntax for filenames:

- if the string looks like a Haskell source filename, then interpret it as such
- if adding a .hs or .lhs suffix yields the name of an existing file, then use that
- otherwise interpret the string as a module name

# Loading/compiling the program

depanal

Arguments

:: GhcMonad m |
=> [ModuleName] | excluded modules
-> Bool | allow duplicate roots
-> m ModuleGraph |

Perform a dependency analysis starting from the current targets and update the session with the new module graph.

Dependency analysis entails parsing the `import` directives and may therefore require running certain preprocessors.

Note that each `ModSummary` in the module graph caches its `DynFlags`. These `DynFlags` are determined by the current session `DynFlags` and the `OPTIONS` and `LANGUAGE` pragmas of the parsed module. Thus if you want to changes to the `DynFlags` to take effect you need to call this function again.

load :: GhcMonad m => LoadHowMuch -> m SuccessFlag

Try to load the program. See `LoadHowMuch` for the different modes.

This function implements the core of GHC's `--make` mode. It preprocesses, compiles and loads the specified modules, avoiding re-compilation wherever possible. Depending on the target (see `hscTarget`) compilating and loading may result in files being created on disk.

Calls the `reportModuleCompilationResult` callback after each compiling each module, whether successful or not.

Throw a `SourceError` if errors are encountered before the actual compilation starts (e.g., during dependency analysis). All other errors are reported using the callback.

data LoadHowMuch

Describes which modules of the module graph need to be loaded.

Constructors

LoadAllTargets | Load all targets and its dependencies.
LoadUpTo ModuleName | Load only the given module and its dependencies.
LoadDependenciesOf ModuleName | Load only the dependencies of the given module, but not the module itself.

data InteractiveImport

Constructors

IIDecl (ImportDecl RdrName) | Bring the exports of a particular module (filtered by an import decl) into scope
IIModule ModuleName | Bring into scope the entire top-level envt of of this module, including the things imported into it.

Instances

Outputable InteractiveImport |

data SuccessFlag

Constructors

Succeeded |
Failed |

Instances

Outputable SuccessFlag |

succeeded :: SuccessFlag -> Bool

failed :: SuccessFlag -> Bool

defaultWarnErrLogger :: WarnErrLogger

type WarnErrLogger = forall m. GhcMonad m => Maybe SourceError -> m ()

A function called to log warnings and errors.

workingDirectoryChanged :: GhcMonad m => m ()

Inform GHC that the working directory has changed. GHC will flush its cache of module locations, since it may no longer be valid.

Note: Before changing the working directory make sure all threads running in the same session have stopped. If you change the working directory, you should also unload the current program (set targets to empty, followed by load).

parseModule :: GhcMonad m => ModSummary -> m ParsedModule

Parse a module.

Throws a `SourceError` on parse error.

typecheckModule :: GhcMonad m => ParsedModule -> m TypecheckedModule

Typecheck and rename a parsed module.

Throws a `SourceError` if either fails.

desugarModule :: GhcMonad m => TypecheckedModule -> m DesugaredModule

Desugar a typechecked module.

loadModule :: (TypecheckedMod mod, GhcMonad m) => mod -> m mod

Load a module. Input doesn't need to be desugared.

A module must be loaded before dependent modules can be typechecked. This always includes generating a `ModIface` and, depending on the `hscTarget`, may also include code generation.

This function will always cause recompilation and will always overwrite previous compilation results (potentially files on disk).

data ParsedModule

The result of successful parsing.

Constructors

ParsedModule |
Fields pm_mod_summary :: ModSummary pm_parsed_source :: ParsedSource pm_extra_src_files :: [FilePath] pm_annotations :: ApiAnns

Instances

ParsedMod ParsedModule |

data TypecheckedModule

The result of successful typechecking. It also contains the parser result.

Constructors

TypecheckedModule |
Fields tm_parsed_module :: ParsedModule tm_renamed_source :: Maybe RenamedSource tm_typechecked_source :: TypecheckedSource tm_checked_module_info :: ModuleInfo tm_internals_ :: (TcGblEnv, ModDetails)

Instances

TypecheckedMod TypecheckedModule |
ParsedMod TypecheckedModule |

data DesugaredModule

The result of successful desugaring (i.e., translation to core). Also contains all the information of a typechecked module.

Constructors

DesugaredModule |
Fields dm_typechecked_module :: TypecheckedModule dm_core_module :: ModGuts

Instances

TypecheckedMod DesugaredModule |
ParsedMod DesugaredModule |

type TypecheckedSource = LHsBinds Id

type ParsedSource = Located (HsModule RdrName)

type RenamedSource = (HsGroup Name, [LImportDecl Name], Maybe [LIE Name], Maybe LHsDocString)

class ParsedMod m => TypecheckedMod m where

Minimal complete definition

renamedSource, typecheckedSource, moduleInfo, tm_internals

Methods

renamedSource :: m -> Maybe RenamedSource

typecheckedSource :: m -> TypecheckedSource

moduleInfo :: m -> ModuleInfo

Instances

TypecheckedMod DesugaredModule |
TypecheckedMod TypecheckedModule |

class ParsedMod m where

Minimal complete definition

modSummary, parsedSource

Methods

parsedSource :: m -> ParsedSource

Instances

ParsedMod DesugaredModule |
ParsedMod TypecheckedModule |
ParsedMod ParsedModule |

coreModule :: DesugaredMod m => m -> ModGuts

## Compiling to Core

data CoreModule

A CoreModule consists of just the fields of a `ModGuts` that are needed for the `compileToCoreModule` interface.

Constructors

CoreModule |
Fields cm_module :: !Module Module name cm_types :: !TypeEnv Type environment for types declared in this module cm_binds :: CoreProgram Declarations cm_safe :: SafeHaskellMode Safe Haskell mode

Instances

Outputable CoreModule |

compileToCoreModule :: GhcMonad m => FilePath -> m CoreModule

This is the way to get access to the Core bindings corresponding to a module. `compileToCore` parses, typechecks, and desugars the module, then returns the resulting Core module (consisting of the module name, type declarations, and function declarations) if successful.

compileToCoreSimplified :: GhcMonad m => FilePath -> m CoreModule

Like compileToCoreModule, but invokes the simplifier, so as to return simplified and tidied Core.

# Inspecting the module structure of the program

type ModuleGraph = [ModSummary]

A ModuleGraph contains all the nodes from the home package (only). There will be a node for each source module, plus a node for each hi-boot module.

The graph is not necessarily stored in topologically-sorted order. Use `topSortModuleGraph` and `flattenSCC` to achieve this.

data ModSummary

A single node in a `ModuleGraph`. The nodes of the module graph are one of:

- A regular Haskell source module
- A hi-boot source module
- An external-core source module

Constructors

ModSummary |
Fields ms_mod :: Module Identity of the module ms_hsc_src :: HscSource The module source either plain Haskell, hs-boot or external core ms_location :: ModLocation Location of the various files belonging to the module ms_hs_date :: UTCTime Timestamp of source file ms_obj_date :: Maybe UTCTime Timestamp of object, if we have one ms_iface_date :: Maybe UTCTime Timestamp of hi file, if we *only* are typechecking (it is `Nothing` otherwise. See Note [Recompilation checking when typechecking only] and #9243 ms_srcimps :: [Located (ImportDecl RdrName)] Source imports of the module ms_textual_imps :: [Located (ImportDecl RdrName)] Non-source imports of the module from the module *text* ms_hspp_file :: FilePath Filename of preprocessed source file ms_hspp_opts :: DynFlags Cached flags from `OPTIONS`, `INCLUDE` and `LANGUAGE` pragmas in the modules source code ms_hspp_buf :: Maybe StringBuffer The actual preprocessed source, if we have it

Instances

Outputable ModSummary |

ms_mod_name :: ModSummary -> ModuleName

data ModLocation

Where a module lives on the file system: the actual locations of the .hs, .hi and .o files, if we have them

Constructors

ModLocation |
Fields ml_hs_file :: Maybe FilePath ml_hi_file :: FilePath ml_obj_file :: FilePath

Instances

Show ModLocation |
Outputable ModLocation |

getModSummary :: GhcMonad m => ModuleName -> m ModSummary

Return the `ModSummary` of a module with the given name.

The module must be part of the module graph (see `hsc_mod_graph` and `ModuleGraph`). If this is not the case, this function will throw a `GhcApiError`.

This function ignores boot modules and requires that there is only one non-boot module with the given name.

getModuleGraph :: GhcMonad m => m ModuleGraph

Get the module dependency graph.

isLoaded :: GhcMonad m => ModuleName -> m Bool

Return `True` == module is loaded.

topSortModuleGraph

Arguments

:: Bool | Drop hi-boot nodes? (see below)
-> [ModSummary] |
-> Maybe ModuleName | Root module name. If `Nothing`, use the full graph.
-> [SCC ModSummary] |

Topological sort of the module graph

Calculate SCCs of the module graph, possibly dropping the hi-boot nodes The resulting list of strongly-connected-components is in topologically sorted order, starting with the module(s) at the bottom of the dependency graph (ie compile them first) and ending with the ones at the top.

Drop hi-boot nodes (first boolean arg)?

- `False`: treat the hi-boot summaries as nodes of the graph, so the graph must be acyclic
- `True`: eliminate the hi-boot nodes, and instead pretend the a source-import of Foo is an import of Foo The resulting graph has no hi-boot nodes, but can be cyclic

# Inspecting modules

data ModuleInfo

Container for information about a `Module`.

getModuleInfo :: GhcMonad m => Module -> m (Maybe ModuleInfo)

Request information about a loaded `Module`

modInfoTyThings :: ModuleInfo -> [TyThing]

The list of top-level entities defined in a module

modInfoTopLevelScope :: ModuleInfo -> Maybe [Name]

modInfoExports :: ModuleInfo -> [Name]

modInfoInstances :: ModuleInfo -> [ClsInst]

Returns the instances defined by the specified module. Warning: currently unimplemented for package modules.

modInfoIsExportedName :: ModuleInfo -> Name -> Bool

modInfoLookupName :: GhcMonad m => ModuleInfo -> Name -> m (Maybe TyThing)

modInfoIface :: ModuleInfo -> Maybe ModIface

modInfoSafe :: ModuleInfo -> SafeHaskellMode

Retrieve module safe haskell mode

lookupGlobalName :: GhcMonad m => Name -> m (Maybe TyThing)

Looks up a global name: that is, any top-level name in any visible module. Unlike `lookupName`, lookupGlobalName does not use the interactive context, and therefore does not require a preceding `setContext`.

findGlobalAnns :: (GhcMonad m, Typeable a) => ([Word8] -> a) -> AnnTarget Name -> m [a]

mkPrintUnqualifiedForModule :: GhcMonad m => ModuleInfo -> m (Maybe PrintUnqualified)

data ModIface

A `ModIface` plus a `ModDetails` summarises everything we know about a compiled module. The `ModIface` is the stuff *before* linking, and can be written out to an interface file. The 'ModDetails is after linking and can be completely recovered from just the `ModIface`.

When we read an interface file, we also construct a `ModIface` from it, except that we explicitly make the `mi_decls` and a few other fields empty; as when reading we consolidate the declarations etc. into a number of indexed maps and environments in the `ExternalPackageState`.

Constructors

ModIface |
Fields mi_module :: !Module Name of the module we are for mi_sig_of :: !(Maybe Module) Are we a sig of another mod? mi_iface_hash :: !Fingerprint Hash of the whole interface mi_mod_hash :: !Fingerprint Hash of the ABI only mi_flag_hash :: !Fingerprint Hash of the important flags used when compiling this module mi_orphan :: !WhetherHasOrphans Whether this module has orphans mi_finsts :: !WhetherHasFamInst Whether this module has family instances mi_boot :: !IsBootInterface Read from an hi-boot file? mi_deps :: Dependencies The dependencies of the module. This is consulted for directly-imported modules, but not for anything else (hence lazy) mi_usages :: [Usage] Usages; kept sorted so that it's easy to decide whether to write a new iface file (changing usages doesn't affect the hash of this module) NOT STRICT! we read this field lazily from the interface file It is *only* consulted by the recompilation checker mi_exports :: ![IfaceExport] Exports Kept sorted by (mod,occ), to make version comparisons easier Records the modules that are the declaration points for things exported by this module, and the `OccName`s of those things mi_exp_hash :: !Fingerprint Hash of export list mi_used_th :: !Bool Module required TH splices when it was compiled. This disables recompilation avoidance (see #481). mi_fixities :: [(OccName, Fixity)] Fixities NOT STRICT! we read this field lazily from the interface file mi_warns :: Warnings Warnings NOT STRICT! we read this field lazily from the interface file mi_anns :: [IfaceAnnotation] Annotations NOT STRICT! we read this field lazily from the interface file mi_decls :: [(Fingerprint, IfaceDecl)] Type, class and variable declarations The hash of an Id changes if its fixity or deprecations change (as well as its type of course) Ditto data constructors, class operations, except that the hash of the parent class/tycon changes mi_globals :: !(Maybe GlobalRdrEnv) Binds all the things defined at the top level in the original source code for this module. which is NOT the same as mi_exports, nor mi_decls (which may contains declarations for things not actually defined by the user). Used for GHCi and for inspecting the contents of modules via the GHC API only. (We need the source file to figure out the top-level environment, if we didn't compile this module from source then this field contains `Nothing`). Strictly speaking this field should live in the `HomeModInfo`, but that leads to more plumbing. mi_insts :: [IfaceClsInst] Sorted class instance mi_fam_insts :: [IfaceFamInst] Sorted family instances mi_rules :: [IfaceRule] Sorted rules mi_orphan_hash :: !Fingerprint Hash for orphan rules, class and family instances, and vectorise pragmas combined mi_vect_info :: !IfaceVectInfo Vectorisation information mi_warn_fn :: Name -> Maybe WarningTxt Cached lookup for `mi_warns` mi_fix_fn :: OccName -> Fixity Cached lookup for `mi_fixities` mi_hash_fn :: OccName -> Maybe (OccName, Fingerprint) Cached lookup for `mi_decls`. The `Nothing` in `mi_hash_fn` means that the thing isn't in decls. It's useful to know that when seeing if we are up to date wrt. the old interface. The `OccName` is the parent of the name, if it has one. mi_hpc :: !AnyHpcUsage True if this program uses Hpc at any point in the program. mi_trust :: !IfaceTrustInfo Safe Haskell Trust information for this module. mi_trust_pkg :: !Bool Do we require the package this module resides in be trusted to trust this module? This is used for the situation where a module is Safe (so doesn't require the package be trusted itself) but imports some trustworthy modules from its own package (which does require its own package be trusted). See Note [RnNames . Trust Own Package]

Instances

Binary ModIface |

data SafeHaskellMode

The various Safe Haskell modes

Constructors

Sf_None |
Sf_Unsafe |
Sf_Trustworthy |
Sf_Safe |

Instances

Eq SafeHaskellMode |
Show SafeHaskellMode |
Outputable SafeHaskellMode |

# Querying the environment

# Printing

data PrintUnqualified

When printing code that contains original names, we need to map the original names back to something the user understands. This is the purpose of the triple of functions that gets passed around when rendering `SDoc`.

alwaysQualify :: PrintUnqualified

# Interactive evaluation

getBindings :: GhcMonad m => m [TyThing]

Return the bindings for the current interactive session.

getInsts :: GhcMonad m => m ([ClsInst], [FamInst])

Return the instances for the current interactive session.

getPrintUnqual :: GhcMonad m => m PrintUnqualified

findModule :: GhcMonad m => ModuleName -> Maybe FastString -> m Module

Takes a `ModuleName` and possibly a `PackageKey`, and consults the filesystem and package database to find the corresponding `Module`, using the algorithm that is used for an `import` declaration.

lookupModule :: GhcMonad m => ModuleName -> Maybe FastString -> m Module

Like `findModule`, but differs slightly when the module refers to a source file, and the file has not been loaded via `load`. In this case, `findModule` will throw an error (module not loaded), but `lookupModule` will check to see whether the module can also be found in a package, and if so, that package `Module` will be returned. If not, the usual module-not-found error will be thrown.

isModuleTrusted :: GhcMonad m => Module -> m Bool

Check that a module is safe to import (according to Safe Haskell).

We return True to indicate the import is safe and False otherwise although in the False case an error may be thrown first.

moduleTrustReqs :: GhcMonad m => Module -> m (Bool, [PackageKey])

Return if a module is trusted and the pkgs it depends on to be trusted.

setContext :: GhcMonad m => [InteractiveImport] -> m ()

Set the interactive evaluation context.

(setContext imports) sets the ic_imports field (which in turn determines what is in scope at the prompt) to `imports`, and constructs the ic_rn_glb_env environment to reflect it.

We retain in scope all the things defined at the prompt, and kept in ic_tythings. (Indeed, they shadow stuff from ic_imports.)

getContext :: GhcMonad m => m [InteractiveImport]

Get the interactive evaluation context, consisting of a pair of the set of modules from which we take the full top-level scope, and the set of modules from which we take just the exports respectively.

getNamesInScope :: GhcMonad m => m [Name]

Returns all names in scope in the current interactive context

getRdrNamesInScope :: GhcMonad m => m [RdrName]

getGRE :: GhcMonad m => m GlobalRdrEnv

get the GlobalRdrEnv for a session

moduleIsInterpreted :: GhcMonad m => Module -> m Bool

Returns `True` if the specified module is interpreted, and hence has its full top-level scope available.

getInfo :: GhcMonad m => Bool -> Name -> m (Maybe (TyThing, Fixity, [ClsInst], [FamInst]))

Looks up an identifier in the current interactive context (for :info) Filter the instances by the ones whose tycons (or clases resp) are in scope (qualified or otherwise). Otherwise we list a whole lot too many! The exact choice of which ones to show, and which to hide, is a judgement call. (see Trac #1581)

exprType :: GhcMonad m => String -> m Type

Get the type of an expression Returns its most general type

typeKind :: GhcMonad m => Bool -> String -> m (Type, Kind)

Get the kind of a type

parseName :: GhcMonad m => String -> m [Name]

Parses a string as an identifier, and returns the list of `Name`s that the identifier can refer to in the current interactive context.

data RunResult

Constructors

RunOk [Name] | names bound by this evaluation
RunException SomeException | statement raised an exception
RunBreak ThreadId [Name] (Maybe BreakInfo) |

runStmt :: GhcMonad m => String -> SingleStep -> m RunResult

Run a statement in the current interactive context. Statement may bind multple values.

runStmtWithLocation :: GhcMonad m => String -> Int -> String -> SingleStep -> m RunResult

Run a statement in the current interactive context. Passing debug information Statement may bind multple values.

runDecls :: GhcMonad m => String -> m [Name]

runDeclsWithLocation :: GhcMonad m => String -> Int -> String -> m [Name]

runTcInteractive :: HscEnv -> TcRn a -> IO (Messages, Maybe a)

parseImportDecl :: GhcMonad m => String -> m (ImportDecl RdrName)

data SingleStep

Constructors

RunToCompletion |
SingleStep |
RunAndLogSteps |

resume :: GhcMonad m => (SrcSpan -> Bool) -> SingleStep -> m RunResult

data Resume

data History

getHistorySpan :: GhcMonad m => History -> m SrcSpan

getHistoryModule :: History -> Module

getResumeContext :: GhcMonad m => m [Resume]

abandon :: GhcMonad m => m Bool

abandonAll :: GhcMonad m => m Bool

back :: GhcMonad m => m ([Name], Int, SrcSpan)

forward :: GhcMonad m => m ([Name], Int, SrcSpan)

showModule :: GhcMonad m => ModSummary -> m String

isModuleInterpreted :: GhcMonad m => ModSummary -> m Bool

compileExpr :: GhcMonad m => String -> m HValue

data HValue

dynCompileExpr :: GhcMonad m => String -> m Dynamic

obtainTermFromId :: GhcMonad m => Int -> Bool -> Id -> m Term

obtainTermFromVal :: GhcMonad m => Int -> Bool -> Type -> a -> m Term

reconstructType :: HscEnv -> Int -> Id -> IO (Maybe Type)

modInfoModBreaks :: ModuleInfo -> ModBreaks

data ModBreaks

All the information about the breakpoints for a given module

Constructors

ModBreaks |
Fields modBreaks_flags :: BreakArray The array of flags, one per breakpoint, indicating which breakpoints are enabled. modBreaks_locs :: !(Array BreakIndex SrcSpan) An array giving the source span of each breakpoint. modBreaks_vars :: !(Array BreakIndex [OccName]) An array giving the names of the free variables at each breakpoint. modBreaks_decls :: !(Array BreakIndex [String]) An array giving the names of the declarations enclosing each breakpoint.

type BreakIndex = Int

Breakpoint index

data BreakInfo

Instances

Outputable BreakInfo |

data BreakArray

setBreakOn :: DynFlags -> BreakArray -> Int -> IO Bool

setBreakOff :: DynFlags -> BreakArray -> Int -> IO Bool

getBreak :: DynFlags -> BreakArray -> Int -> IO (Maybe Word)

lookupName :: GhcMonad m => Name -> m (Maybe TyThing)

Returns the `TyThing` for a `Name`. The `Name` may refer to any entity known to GHC, including `Name`s defined using `runStmt`.

## EXPERIMENTAL

setGHCiMonad :: GhcMonad m => String -> m ()

Warning: This is experimental! Don't use.

EXPERIMENTAL: DO NOT USE.

Set the monad GHCi lifts user statements into.

Checks that a type (in string form) is an instance of the `GHC.GHCi.GHCiSandboxIO` type class. Sets it to be the GHCi monad if it is, throws an error otherwise.

# Abstract syntax elements

## Packages

data PackageKey

A string which uniquely identifies a package. For wired-in packages, it is just the package name, but for user compiled packages, it is a hash. ToDo: when the key is a hash, we can do more clever things than store the hex representation and hash-cons those strings.

Instances

Eq PackageKey |
Data PackageKey |
Ord PackageKey |
BinaryStringRep PackageKey |
Outputable PackageKey |
Uniquable PackageKey |
Binary PackageKey |

## Modules

data Module

A Module is a pair of a `PackageKey` and a `ModuleName`.

Instances

Eq Module |
Data Module |
Ord Module |
Outputable Module |
Uniquable Module |
Binary Module |

mkModule :: PackageKey -> ModuleName -> Module

pprModule :: Module -> SDoc

moduleName :: Module -> ModuleName

modulePackageKey :: Module -> PackageKey

data ModuleName

A ModuleName is essentially a simple string, e.g. `Data.List`.

Instances

Eq ModuleName |
Data ModuleName |
Ord ModuleName |
BinaryStringRep ModuleName |
Outputable ModuleName |
Uniquable ModuleName |
Binary ModuleName |

mkModuleName :: String -> ModuleName

moduleNameString :: ModuleName -> String

## Names

data Name

A unique, unambigious name for something, containing information about where that thing originated.

Instances

Eq Name |
Data Name |
Ord Name |
OutputableBndr Name |
Outputable Name |
Uniquable Name |
Binary Name |
HasOccName Name |
NamedThing Name |
type PostRn Name ty = ty |
type PostTc Name ty = PlaceHolder |

isExternalName :: Name -> Bool

nameModule :: Name -> Module

pprParenSymName :: NamedThing a => a -> SDoc

print a `NamedThing`, adding parentheses if the name is an operator.

nameSrcSpan :: Name -> SrcSpan

class NamedThing a where

A class allowing convenient access to the `Name` of various datatypes

Minimal complete definition

getName

Methods

getOccName :: a -> OccName

getName :: a -> Name

Instances

NamedThing Name |
NamedThing TyThing |
NamedThing TyCon |
NamedThing DataCon |
NamedThing PatSyn |
NamedThing ConLike |
NamedThing Var |
NamedThing Class |
NamedThing ClsInst |
NamedThing FamInst |
NamedThing TcSigInfo |
NamedThing (CoAxiom br) |

data RdrName

Do not use the data constructors of RdrName directly: prefer the family of functions that creates them, such as `mkRdrUnqual`

- Note: A Located RdrName will only have API Annotations if it is a compound one, e.g.

    `bar`
    ( ~ )

- `AnnKeywordId` : `AnnType`, `AnnOpen` `'('` or `'['` or `'[:'`, `AnnClose` `')'` or `']'` or `':]'`,, `AnnBackquote` `'`'`, `AnnVal`,`AnnTildehsh`, `AnnTilde`,

Constructors

Unqual OccName | Used for ordinary, unqualified occurrences, e.g. `x`, `y` or `Foo`. Create such a `RdrName` with `mkRdrUnqual`
Qual ModuleName OccName | A qualified name written by the user in source code. The module isn't necessarily the module where the thing is defined; just the one from which it is imported. Examples are `Bar.x`, `Bar.y` or `Bar.Foo`. Create such a `RdrName` with `mkRdrQual`

Instances

Eq RdrName |
Data RdrName |
Ord RdrName |
OutputableBndr RdrName |
Outputable RdrName |
HasOccName RdrName |
type PostRn RdrName ty = PlaceHolder |
type PostTc RdrName ty = PlaceHolder |

## Identifiers

type Id = Var

idType :: Id -> Kind

isImplicitId :: Id -> Bool

`isImplicitId` tells whether an `Id`s info is implied by other declarations, so we don't need to put its signature in an interface file, even if it's mentioned in some other interface unfolding.

isDeadBinder :: Id -> Bool

isExportedId :: Var -> Bool

`isExportedIdVar` means "don't throw this away"

isLocalId :: Var -> Bool

isGlobalId :: Var -> Bool

isRecordSelector :: Id -> Bool

isPrimOpId :: Id -> Bool

isFCallId :: Id -> Bool

isClassOpId_maybe :: Id -> Maybe Class

isDataConWorkId :: Id -> Bool

idDataCon :: Id -> DataCon

Get from either the worker or the wrapper `Id` to the `DataCon`. Currently used only in the desugarer.

INVARIANT: `idDataCon (dataConWrapId d) = d`: remember, `dataConWrapId` can return either the wrapper or the worker

isBottomingId :: Id -> Bool

Returns true if an application to n args would diverge

isDictonaryId :: Id -> Bool

recordSelectorFieldLabel :: Id -> (TyCon, FieldLabel)

If the `Id` is that for a record selector, extract the `sel_tycon` and label. Panic otherwise

## Type constructors

data TyCon

TyCons represent type constructors. Type constructors are introduced by things such as:

1) Data declarations: `data Foo = ...` creates the `Foo` type constructor of kind `*`

2) Type synonyms: `type Foo = ...` creates the `Foo` type constructor

3) Newtypes: `newtype Foo a = MkFoo ...` creates the `Foo` type constructor of kind `* -> *`

4) Class declarations: `class Foo where` creates the `Foo` type constructor of kind `*`

This data type also encodes a number of primitive, built in type constructors such as those for function and tuple types.

Instances

Eq TyCon |
Data TyCon |
Ord TyCon |
Outputable TyCon |
Uniquable TyCon |
NamedThing TyCon |

tyConTyVars :: TyCon -> [TyVar]

The kind and type variables used in the type constructor. Invariant: length tyvars = arity Precisely, this list scopes over:

1. The `algTcStupidTheta`
2. The cached types in algTyConRhs.NewTyCon
3. The family instance types if present

Note that it does not scope over the data constructors.

tyConDataCons :: TyCon -> [DataCon]

As `tyConDataCons_maybe`, but returns the empty list of constructors if no constructors could be found

tyConArity :: TyCon -> Arity

Number of arguments this TyCon must receive to be considered saturated (including implicit kind variables)

isClassTyCon :: TyCon -> Bool

Is this `TyCon` that for a class instance?

isTypeSynonymTyCon :: TyCon -> Bool

Is this a `TyCon` representing a regular H98 type synonym (`type`)?

isTypeFamilyTyCon :: TyCon -> Bool

Is this a synonym `TyCon` that can have may have further instances appear?

isNewTyCon :: TyCon -> Bool

Is this `TyCon` that for a `newtype`

isPrimTyCon :: TyCon -> Bool

Does this `TyCon` represent something that cannot be defined in Haskell?

isFunTyCon :: TyCon -> Bool

isFamilyTyCon :: TyCon -> Bool

Is this a `TyCon`, synonym or otherwise, that defines a family?

isOpenFamilyTyCon :: TyCon -> Bool

Is this a `TyCon`, synonym or otherwise, that defines a family with instances?

isOpenTypeFamilyTyCon :: TyCon -> Bool

tyConClass_maybe :: TyCon -> Maybe Class

If this `TyCon` is that for a class instance, return the class it is for. Otherwise returns `Nothing`

synTyConRhs_maybe :: TyCon -> Maybe Type

Extract the information pertaining to the right hand side of a type synonym (`type`) declaration.

synTyConDefn_maybe :: TyCon -> Maybe ([TyVar], Type)

Extract the `TyVar`s bound by a vanilla type synonym and the corresponding (unsubstituted) right hand side.

synTyConResKind :: TyCon -> Kind

Find the result `Kind` of a type synonym, after applying it to its `arity` number of type variables Actually this function works fine on data types too, but they'd always return `*`, so we never need to ask

## Type variables

type TyVar = Var

alphaTyVars :: [TyVar]

## Data constructors

data DataCon

A data constructor

- `AnnKeywordId` : `AnnOpen`, `AnnClose`,`AnnComma`

Instances

Eq DataCon |
Data DataCon |
Ord DataCon |
OutputableBndr DataCon |
Outputable DataCon |
Uniquable DataCon |
NamedThing DataCon |

dataConSig :: DataCon -> ([TyVar], ThetaType, [Type], Type)

The "signature" of the `DataCon` returns, in order:

1) The result of `dataConAllTyVars`,

2) All the `ThetaType`s relating to the `DataCon` (coercion, dictionary, implicit parameter - whatever)

3) The type arguments to the constructor

4) The original result type of the `DataCon`

dataConType :: DataCon -> Type

dataConTyCon :: DataCon -> TyCon

The type constructor that we are building via this data constructor

dataConFieldLabels :: DataCon -> [FieldLabel]

The labels for the fields of this particular `DataCon`

dataConIsInfix :: DataCon -> Bool

Should the `DataCon` be presented infix?

isVanillaDataCon :: DataCon -> Bool

Vanilla `DataCon`s are those that are nice boring Haskell 98 constructors

dataConUserType :: DataCon -> Type

The user-declared type of the data constructor in the nice-to-read form:

    T :: forall a b. a -> b -> T [a]

rather than:

    T :: forall a c. forall b. (c~[a]) => a -> b -> T c

NB: If the constructor is part of a data instance, the result type mentions the family tycon, not the internal one.

dataConSrcBangs :: DataCon -> [HsSrcBang]

The strictness markings written by the porgrammer. The list is in one-to-one correspondence with the arity of the `DataCon`

data StrictnessMark

Constructors

MarkedStrict |
NotMarkedStrict |

Instances

Outputable StrictnessMark |

isMarkedStrict :: StrictnessMark -> Bool

## Classes

data Class

Instances

Eq Class |
Data Class |
Ord Class |
Outputable Class |
Uniquable Class |
NamedThing Class |

classMethods :: Class -> [Id]

classSCTheta :: Class -> [PredType]

classTvsFds :: Class -> ([TyVar], [FunDep TyVar])

classATs :: Class -> [TyCon]

pprFundeps :: Outputable a => [FunDep a] -> SDoc

## Instances

data ClsInst

Instances

Data ClsInst |
Outputable ClsInst |
NamedThing ClsInst |

instanceDFunId :: ClsInst -> DFunId

pprInstance :: ClsInst -> SDoc

pprInstanceHdr :: ClsInst -> SDoc

pprFamInst :: FamInst -> SDoc

Pretty-prints a `FamInst` (type/data family instance) with its defining location.

data FamInst

Instances

Outputable FamInst |
NamedThing FamInst |

## Types and Kinds

data Type

The key representation of types within the compiler

Instances

Data Type |
Outputable Type |

splitForAllTys :: Type -> ([TyVar], Type)

Attempts to take a forall type apart, returning all the immediate such bound type variables and the remainder of the type. Always suceeds, even if that means returning an empty list of `TyVar`s

funResultTy :: Type -> Type

Extract the function result type and panic if that is not possible

pprParendType :: Type -> SDoc

pprTypeApp :: TyCon -> [Type] -> SDoc

type Kind = Type

The key type representing kinds in the compiler. Invariant: a kind is always in one of these forms:

    FunTy k1 k2
    TyConApp PrimTyCon [...]
    TyVar kv   -- (during inference only)
    ForAll ... -- (for top-level coercions)

type PredType = Type

A type of the form `p` of kind `Constraint` represents a value whose type is the Haskell predicate `p`, where a predicate is what occurs before the `=>` in a Haskell type.

We use `PredType` as documentation to mark those types that we guarantee to have this kind.

It can be expanded into its representation, but:

- The type checker must treat it as opaque
- The rest of the compiler treats it as transparent

Consider these examples:

    f :: (Eq a) => a -> Int
    g :: (?x :: Int -> Int) => a -> Int
    h :: (r\l) => {r} => {l::Int | r}

Here the `Eq a` and `?x :: Int -> Int` and `rl` are all called "predicates"

type ThetaType = [PredType]

A collection of `PredType`s

pprForAll :: [TyVar] -> SDoc

pprThetaArrowTy :: ThetaType -> SDoc

## Entities

data TyThing

A typecheckable-thing, essentially anything that has a name

Constructors

AnId Id |
AConLike ConLike |
ATyCon TyCon |
ACoAxiom (CoAxiom Branched) |

Instances

Eq TyThing |
Ord TyThing |
Outputable TyThing |
NamedThing TyThing |

## Syntax

module HsSyn

## Fixities

data FixityDirection

Constructors

InfixL |
InfixR |
InfixN |

Instances

Eq FixityDirection |
Data FixityDirection |
Outputable FixityDirection |
Binary FixityDirection |

defaultFixity :: Fixity

maxPrecedence :: Int

negateFixity :: Fixity

compareFixity :: Fixity -> Fixity -> (Bool, Bool)

## Source locations

data SrcLoc

Constructors

RealSrcLoc !RealSrcLoc |
UnhelpfulLoc FastString |

Instances

Eq SrcLoc |
Ord SrcLoc |
Show SrcLoc |
Outputable SrcLoc |

data RealSrcLoc

Represents a single point within a file

Instances

Eq RealSrcLoc |
Ord RealSrcLoc |
Show RealSrcLoc |
Outputable RealSrcLoc |

mkSrcLoc :: FastString -> Int -> Int -> SrcLoc

noSrcLoc :: SrcLoc

Built-in "bad" `SrcLoc` values for particular locations

srcLocFile :: RealSrcLoc -> FastString

Gives the filename of the `RealSrcLoc`

srcLocLine :: RealSrcLoc -> Int

Raises an error when used on a "bad" `SrcLoc`

srcLocCol :: RealSrcLoc -> Int

Raises an error when used on a "bad" `SrcLoc`

data SrcSpan

Constructors

RealSrcSpan !RealSrcSpan |
UnhelpfulSpan !FastString |

Instances

Eq SrcSpan |
Data SrcSpan |
Ord SrcSpan |
Show SrcSpan |
Outputable SrcSpan |
Binary SrcSpan |
Binary a => Binary (GenLocated SrcSpan a) |

data RealSrcSpan

A SrcSpan delimits a portion of a text file. It could be represented by a pair of (line,column) coordinates, but in fact we optimise slightly by using more compact representations for single-line and zero-length spans, both of which are quite common.

The end position is defined to be the column after the end of the span. That is, a span of (1,1)-(1,2) is one character long, and a span of (1,1)-(1,1) is zero characters long.

Instances

Eq RealSrcSpan |
Data RealSrcSpan |
Ord RealSrcSpan |
Show RealSrcSpan |
Outputable RealSrcSpan |

mkSrcSpan :: SrcLoc -> SrcLoc -> SrcSpan

Create a `SrcSpan` between two points in a file

srcLocSpan :: SrcLoc -> SrcSpan

Create a `SrcSpan` corresponding to a single point

isGoodSrcSpan :: SrcSpan -> Bool

Test if a `SrcSpan` is "good", i.e. has precise location information

noSrcSpan :: SrcSpan

Built-in "bad" `SrcSpan`s for common sources of location uncertainty

srcSpanStart :: SrcSpan -> SrcLoc

Returns the location at the start of the `SrcSpan` or a "bad" `SrcSpan` if that is unavailable

srcSpanEnd :: SrcSpan -> SrcLoc

Returns the location at the end of the `SrcSpan` or a "bad" `SrcSpan` if that is unavailable

srcSpanFile :: RealSrcSpan -> FastString

srcSpanStartLine :: RealSrcSpan -> Int

srcSpanEndLine :: RealSrcSpan -> Int

srcSpanStartCol :: RealSrcSpan -> Int

srcSpanEndCol :: RealSrcSpan -> Int

## Located

data GenLocated l e

We attach SrcSpans to lots of things, so let's have a datatype for it.

Constructors

L l e |

Instances

Functor (GenLocated l) |
Foldable (GenLocated l) |
Traversable (GenLocated l) |
(Eq l, Eq e) => Eq (GenLocated l e) |
(Data l, Data e) => Data (GenLocated l e) |
(Ord l, Ord e) => Ord (GenLocated l e) |
(Outputable l, Outputable e) => Outputable (GenLocated l e) |
Binary a => Binary (GenLocated SrcSpan a) |

type Located e = GenLocated SrcSpan e

### Constructing Located

noLoc :: e -> Located e

mkGeneralLocated :: String -> e -> Located e

### Deconstructing Located

getLoc :: GenLocated l e -> l

unLoc :: GenLocated l e -> e

### Combining and comparing Located values

eqLocated :: Eq a => Located a -> Located a -> Bool

Tests whether the two located things are equal

cmpLocated :: Ord a => Located a -> Located a -> Ordering

Tests the ordering of the two located things

combineLocs :: Located a -> Located b -> SrcSpan

addCLoc :: Located a -> Located b -> c -> Located c

Combine locations from two `Located` things and add them to a third thing

leftmost_smallest :: SrcSpan -> SrcSpan -> Ordering

Alternative strategies for ordering `SrcSpan`s

leftmost_largest :: SrcSpan -> SrcSpan -> Ordering

Alternative strategies for ordering `SrcSpan`s

rightmost :: SrcSpan -> SrcSpan -> Ordering

Alternative strategies for ordering `SrcSpan`s

spans :: SrcSpan -> (Int, Int) -> Bool

Determines whether a span encloses a given line and column index

isSubspanOf

Arguments

:: SrcSpan | The span that may be enclosed by the other
-> SrcSpan | The span it may be enclosed by
-> Bool |

Determines whether a span is enclosed by another one

# Exceptions

data GhcException

GHC's own exception type error messages all take the form:

         location: error

If the location is on the command line, or in GHC itself, then location="ghc". All of the error types below correspond to a location of "ghc", except for ProgramError (where the string is assumed to contain a location already, so we don't print one).

Constructors

PhaseFailed String ExitCode |
Signal Int | Some other fatal signal (SIGHUP,SIGTERM)
UsageError String | Prints the short usage msg after the error
CmdLineError String | A problem with the command line arguments, but don't print usage.
Panic String | The `impossible` happened.
PprPanic String SDoc |
Sorry String | The user tickled something that's known not to work yet, but we're not counting it as a bug.
PprSorry String SDoc |
InstallationError String | An installation problem.
ProgramError String | An error in the user's code, probably.
PprProgramError String SDoc |

Instances

Show GhcException |
Exception GhcException |

showGhcException :: GhcException -> String -> String

Append a description of the given exception to this string.

# Token stream manipulations

data Token

Instances

Show Token |
Outputable Token |

getTokenStream :: GhcMonad m => Module -> m [Located Token]

Return module source as token stream, including comments.

The module must be in the module graph and its source must be available. Throws a `SourceError` on parse error.

getRichTokenStream :: GhcMonad m => Module -> m [(Located Token, String)]

Give even more information on the source than `getTokenStream` This function allows reconstructing the source completely with `showRichTokenStream`.

showRichTokenStream :: [(Located Token, String)] -> String

Take a rich token stream such as produced from `getRichTokenStream` and return source code almost identical to the original code (except for insignificant whitespace.)

addSourceToTokens :: RealSrcLoc -> StringBuffer -> [Located Token] -> [(Located Token, String)]

Given a source location and a StringBuffer corresponding to this location, return a rich token stream with the source associated to the tokens.

# Pure interface to the parser

parser

Arguments

:: String | Haskell module source text (full Unicode is supported)
-> DynFlags | the flags
-> FilePath | the filename (for source locations)
-> Either ErrorMessages (WarningMessages, Located (HsModule RdrName)) |

A pure interface to the module parser.

# API Annotations

type ApiAnns = (Map ApiAnnKey [SrcSpan], Map SrcSpan [Located AnnotationComment])

data AnnKeywordId

API Annotations exist so that tools can perform source to source conversions of Haskell code. They are used to keep track of the various syntactic keywords that are not captured in the existing AST.

The annotations, together with original source comments are made available in the ``pm_annotations`` field of ``ParsedModule``. Comments are only retained if ``Opt_KeepRawTokenStream`` is set in ``DynFlags`` before parsing.

The wiki page describing this feature is https://ghc.haskell.org/trac/ghc/wiki/ApiAnnotations

Note: in general the names of these are taken from the corresponding token, unless otherwise noted See note [Api annotations] above for details of the usage

Constructors

AnnAs |
AnnAt |
AnnBang | `!`
AnnBackquote | '`'
AnnBy |
AnnCase | case or lambda case
AnnClass |
AnnClose | '#)' or '#-}' etc
AnnCloseC | '}'
AnnCloseP | ')'
AnnCloseS | ']'
AnnColon |
AnnComma | as a list separator
AnnCommaTuple | in a RdrName for a tuple
AnnDarrow | '=>'
AnnData |
AnnDcolon | '::'
AnnDefault |
AnnDeriving |
AnnDo |
AnnDot | `.`
AnnDotdot | '..'
AnnElse |
AnnEqual |
AnnExport |
AnnFamily |
AnnForall |
AnnForeign |
AnnFunId | for function name in matches where there are multiple equations for the function.
AnnGroup |
AnnHeader | for CType
AnnHiding |
AnnIf |
AnnImport |
AnnIn |
AnnInfix | 'infix' or 'infixl' or 'infixr'
AnnInstance |
AnnLam |
AnnLarrow | '<-'
AnnLet |
AnnMdo |
AnnMinus | `-`
AnnModule |
AnnNewtype |
AnnName | where a name loses its location in the AST, this carries it
AnnOf |
AnnOpen | '(#' or '{-# LANGUAGE' etc
AnnOpenC | '{'
AnnOpenP | '('
AnnOpenPE | '$('
AnnOpenPTE | '$$('
AnnOpenS | '['
AnnPackageName |
AnnPattern |
AnnProc |
AnnQualified |
AnnRarrow | '->'
AnnRec |
AnnRole |
AnnSafe |
AnnSemi | ';'
AnnSimpleQuote | '''
AnnStatic | `static`
AnnThen |
AnnThIdSplice | `$`
AnnThIdTySplice | `$$`
AnnThTyQuote | double '''
AnnTilde | '~'
AnnTildehsh | `~#`
AnnType |
AnnUnit | '()' for types
AnnUsing |
AnnVal | e.g. INTEGER
AnnValStr | String value, will need quotes when output
AnnVbar | '|'
AnnWhere |
Annlarrowtail | `-<`
Annrarrowtail | '->'
AnnLarrowtail | `-<<`
AnnRarrowtail | `>>-`
AnnEofPos |

Instances

Eq AnnKeywordId |
Data AnnKeywordId |
Ord AnnKeywordId |
Show AnnKeywordId |
Outputable AnnKeywordId |

data AnnotationComment

Constructors

AnnDocCommentNext String | something beginning '-- |'
AnnDocCommentPrev String | something beginning '-- ^'
AnnDocCommentNamed String | something beginning '-- $'
AnnDocSection Int String | a section heading
AnnDocOptions String | doc options (prune, ignore-exports, etc)
AnnDocOptionsOld String | doc options declared "-- # ..."-style
AnnLineComment String | comment starting by "--"
AnnBlockComment String | comment in {- -}

Instances

Eq AnnotationComment |
Data AnnotationComment |
Ord AnnotationComment |
Show AnnotationComment |
Outputable AnnotationComment |

getAnnotation :: ApiAnns -> SrcSpan -> AnnKeywordId -> [SrcSpan]

Retrieve a list of annotation `SrcSpan`s based on the `SrcSpan` of the annotated AST element, and the known type of the annotation.

getAndRemoveAnnotation :: ApiAnns -> SrcSpan -> AnnKeywordId -> ([SrcSpan], ApiAnns)

Retrieve a list of annotation `SrcSpan`s based on the `SrcSpan` of the annotated AST element, and the known type of the annotation. The list is removed from the annotations.

getAnnotationComments :: ApiAnns -> SrcSpan -> [Located AnnotationComment]

Retrieve the comments allocated to the current `SrcSpan`

Note: A given `SrcSpan` may appear in multiple AST elements, beware of duplicates

getAndRemoveAnnotationComments :: ApiAnns -> SrcSpan -> ([Located AnnotationComment], ApiAnns)

Retrieve the comments allocated to the current `SrcSpan`, and remove them from the annotations

# Miscellaneous

cyclicModuleErr :: [ModSummary] -> SDoc