PageRenderTime 59ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/Language/Haskell/GhcMod/Gap.hs

http://github.com/kazu-yamamoto/ghc-mod
Haskell | 689 lines | 556 code | 84 blank | 49 comment | 3 complexity | 9ababf7b6d3fe79bd4a6de22b321fc94 MD5 | raw file
Possible License(s): AGPL-3.0, BSD-3-Clause
  1. {-# LANGUAGE TypeSynonymInstances, FlexibleInstances, CPP, ScopedTypeVariables, RankNTypes #-}
  2. module Language.Haskell.GhcMod.Gap (
  3. Language.Haskell.GhcMod.Gap.ClsInst
  4. , mkTarget
  5. , withStyle
  6. , GmLogAction
  7. , setLogAction
  8. , getSrcSpan
  9. , getSrcFile
  10. , withInteractiveContext
  11. , ghcCmdOptions
  12. , toStringBuffer
  13. , showSeverityCaption
  14. , setCabalPkg
  15. , setHideAllPackages
  16. , setDeferTypeErrors
  17. , setDeferTypedHoles
  18. , setWarnTypedHoles
  19. , setDumpSplices
  20. , setNoMaxRelevantBindings
  21. , isDumpSplices
  22. , filterOutChildren
  23. , infoThing
  24. , pprInfo
  25. , HasType(..)
  26. , errorMsgSpan
  27. , setErrorMsgSpan
  28. , typeForUser
  29. , nameForUser
  30. , occNameForUser
  31. , deSugar
  32. , showDocWith
  33. , GapThing(..)
  34. , fromTyThing
  35. , fileModSummary
  36. , WarnFlags
  37. , emptyWarnFlags
  38. , GLMatch
  39. , GLMatchI
  40. , getClass
  41. , occName
  42. , listVisibleModuleNames
  43. , listVisibleModules
  44. , lookupModulePackageInAllPackages
  45. , Language.Haskell.GhcMod.Gap.isSynTyCon
  46. , parseModuleHeader
  47. , mkErrStyle'
  48. , everythingStagedWithContext
  49. , withCleanupSession
  50. ) where
  51. import Control.Applicative hiding (empty)
  52. import Control.Monad (filterM)
  53. import CoreSyn (CoreExpr)
  54. import Data.List (intersperse)
  55. import Data.Maybe (catMaybes)
  56. import Data.Time.Clock (UTCTime)
  57. import Data.Traversable hiding (mapM)
  58. import DataCon (dataConRepType)
  59. import Desugar (deSugarExpr)
  60. import DynFlags
  61. import ErrUtils
  62. import Exception
  63. import FastString
  64. import GhcMonad
  65. import HscTypes
  66. import NameSet
  67. import OccName
  68. import Outputable
  69. import PprTyThing
  70. import StringBuffer
  71. import TcType
  72. import Var (varType)
  73. import System.Directory
  74. import SysTools
  75. #if __GLASGOW_HASKELL__ >= 800
  76. import GHCi (stopIServ)
  77. #endif
  78. import qualified Name
  79. import qualified InstEnv
  80. import qualified Pretty
  81. import qualified StringBuffer as SB
  82. #if __GLASGOW_HASKELL__ >= 710
  83. import CoAxiom (coAxiomTyCon)
  84. #endif
  85. #if __GLASGOW_HASKELL__ >= 708
  86. import FamInstEnv
  87. import ConLike (ConLike(..))
  88. import PatSyn
  89. #else
  90. import TcRnTypes
  91. #endif
  92. #if __GLASGOW_HASKELL__ >= 706
  93. import GHC hiding (ClsInst)
  94. #else
  95. import GHC hiding (Instance)
  96. import Control.Arrow hiding ((<+>))
  97. import Data.Convertible
  98. import RdrName (rdrNameOcc)
  99. #endif
  100. #if __GLASGOW_HASKELL__ < 710
  101. import UniqFM (eltsUFM)
  102. import Module
  103. #endif
  104. #if __GLASGOW_HASKELL__ >= 704
  105. import qualified Data.IntSet as I (IntSet, empty)
  106. #endif
  107. #if __GLASGOW_HASKELL__ < 706
  108. import Control.DeepSeq (NFData(rnf))
  109. import Data.ByteString.Lazy.Internal (ByteString(..))
  110. #endif
  111. import Bag
  112. import Lexer as L
  113. import Parser
  114. import SrcLoc
  115. import Packages
  116. import Data.Generics (GenericQ, extQ, gmapQ)
  117. import GHC.SYB.Utils (Stage(..))
  118. import Language.Haskell.GhcMod.Types (Expression(..))
  119. import Prelude
  120. ----------------------------------------------------------------
  121. ----------------------------------------------------------------
  122. --
  123. #if __GLASGOW_HASKELL__ >= 706
  124. type ClsInst = InstEnv.ClsInst
  125. #else
  126. type ClsInst = InstEnv.Instance
  127. #endif
  128. mkTarget :: TargetId -> Bool -> Maybe (SB.StringBuffer, UTCTime) -> Target
  129. #if __GLASGOW_HASKELL__ >= 706
  130. mkTarget = Target
  131. #else
  132. mkTarget tid allowObjCode = Target tid allowObjCode . (fmap . second) convert
  133. #endif
  134. ----------------------------------------------------------------
  135. ----------------------------------------------------------------
  136. withStyle :: DynFlags -> PprStyle -> SDoc -> Pretty.Doc
  137. #if __GLASGOW_HASKELL__ >= 706
  138. withStyle = withPprStyleDoc
  139. #else
  140. withStyle _ = withPprStyleDoc
  141. #endif
  142. #if __GLASGOW_HASKELL__ >= 800
  143. -- flip LogAction
  144. type GmLogAction = WarnReason -> DynFlags -> Severity -> SrcSpan -> PprStyle -> MsgDoc -> IO ()
  145. #elif __GLASGOW_HASKELL__ >= 706
  146. type GmLogAction = forall a. a -> LogAction
  147. #else
  148. type GmLogAction = forall a. a -> DynFlags -> LogAction
  149. #endif
  150. -- DynFlags -> WarnReason -> Severity -> SrcSpan -> PprStyle -> MsgDoc -> IO ()
  151. setLogAction :: DynFlags -> GmLogAction -> DynFlags
  152. setLogAction df f =
  153. #if __GLASGOW_HASKELL__ >= 800
  154. df { log_action = flip f }
  155. #elif __GLASGOW_HASKELL__ >= 706
  156. df { log_action = f (error "setLogAction") }
  157. #else
  158. df { log_action = f (error "setLogAction") df }
  159. #endif
  160. showDocWith :: DynFlags -> Pretty.Mode -> Pretty.Doc -> String
  161. #if __GLASGOW_HASKELL__ >= 800
  162. showDocWith dflags mode = Pretty.renderStyle mstyle where
  163. mstyle = Pretty.style { Pretty.mode = mode, Pretty.lineLength = pprCols dflags }
  164. #elif __GLASGOW_HASKELL__ >= 708
  165. -- Pretty.showDocWith disappeard.
  166. -- https://github.com/ghc/ghc/commit/08a3536e4246e323fbcd8040e0b80001950fe9bc
  167. showDocWith dflags mode = Pretty.showDoc mode (pprCols dflags)
  168. #else
  169. showDocWith _ = Pretty.showDocWith
  170. #endif
  171. ----------------------------------------------------------------
  172. ----------------------------------------------------------------
  173. getSrcSpan :: SrcSpan -> Maybe (Int,Int,Int,Int)
  174. #if __GLASGOW_HASKELL__ >= 702
  175. getSrcSpan (RealSrcSpan spn)
  176. #else
  177. getSrcSpan spn | isGoodSrcSpan spn
  178. #endif
  179. = Just (srcSpanStartLine spn
  180. , srcSpanStartCol spn
  181. , srcSpanEndLine spn
  182. , srcSpanEndCol spn)
  183. getSrcSpan _ = Nothing
  184. getSrcFile :: SrcSpan -> Maybe String
  185. #if __GLASGOW_HASKELL__ >= 702
  186. getSrcFile (RealSrcSpan spn) = Just . unpackFS . srcSpanFile $ spn
  187. #else
  188. getSrcFile spn | isGoodSrcSpan spn = Just . unpackFS . srcSpanFile $ spn
  189. #endif
  190. getSrcFile _ = Nothing
  191. ----------------------------------------------------------------
  192. toStringBuffer :: GhcMonad m => [String] -> m StringBuffer
  193. #if __GLASGOW_HASKELL__ >= 702
  194. toStringBuffer = return . stringToStringBuffer . unlines
  195. #else
  196. toStringBuffer = liftIO . stringToStringBuffer . unlines
  197. #endif
  198. ----------------------------------------------------------------
  199. ghcCmdOptions :: [String]
  200. #if __GLASGOW_HASKELL__ >= 710
  201. -- this also includes -X options and all sorts of other things so the
  202. ghcCmdOptions = flagsForCompletion False
  203. #else
  204. ghcCmdOptions = [ "-f" ++ prefix ++ option
  205. | option <- opts
  206. , prefix <- ["","no-"]
  207. ]
  208. # if __GLASGOW_HASKELL__ >= 704
  209. where opts =
  210. [option | (option,_,_) <- fFlags]
  211. ++ [option | (option,_,_) <- fWarningFlags]
  212. ++ [option | (option,_,_) <- fLangFlags]
  213. # else
  214. where opts =
  215. [option | (option,_,_,_) <- fFlags]
  216. ++ [option | (option,_,_,_) <- fWarningFlags]
  217. ++ [option | (option,_,_,_) <- fLangFlags]
  218. # endif
  219. #endif
  220. ----------------------------------------------------------------
  221. ----------------------------------------------------------------
  222. fileModSummary :: GhcMonad m => FilePath -> m ModSummary
  223. fileModSummary file' = do
  224. mss <- getModuleGraph
  225. file <- liftIO $ canonicalizePath file'
  226. [ms] <- liftIO $ flip filterM mss $ \m ->
  227. (Just file==) <$> canonicalizePath `traverse` ml_hs_file (ms_location m)
  228. return ms
  229. withInteractiveContext :: GhcMonad m => m a -> m a
  230. withInteractiveContext action = gbracket setup teardown body
  231. where
  232. setup = getContext
  233. teardown = setCtx
  234. body _ = do
  235. topImports >>= setCtx
  236. action
  237. topImports = do
  238. ms <- filterM moduleIsInterpreted =<< map ms_mod <$> getModuleGraph
  239. let iis = map (IIModule . modName) ms
  240. #if __GLASGOW_HASKELL__ >= 704
  241. return iis
  242. #else
  243. return (iis,[])
  244. #endif
  245. #if __GLASGOW_HASKELL__ >= 706
  246. modName = moduleName
  247. setCtx = setContext
  248. #elif __GLASGOW_HASKELL__ >= 704
  249. modName = id
  250. setCtx = setContext
  251. #else
  252. modName = ms_mod
  253. setCtx = uncurry setContext
  254. #endif
  255. showSeverityCaption :: Severity -> String
  256. #if __GLASGOW_HASKELL__ >= 706
  257. showSeverityCaption SevWarning = "Warning: "
  258. showSeverityCaption _ = ""
  259. #else
  260. showSeverityCaption = const ""
  261. #endif
  262. ----------------------------------------------------------------
  263. ----------------------------------------------------------------
  264. setCabalPkg :: DynFlags -> DynFlags
  265. #if __GLASGOW_HASKELL__ >= 708
  266. setCabalPkg dflag = gopt_set dflag Opt_BuildingCabalPackage
  267. #else
  268. setCabalPkg dflag = dopt_set dflag Opt_BuildingCabalPackage
  269. #endif
  270. ----------------------------------------------------------------
  271. setHideAllPackages :: DynFlags -> DynFlags
  272. #if __GLASGOW_HASKELL__ >= 708
  273. setHideAllPackages df = gopt_set df Opt_HideAllPackages
  274. #else
  275. setHideAllPackages df = dopt_set df Opt_HideAllPackages
  276. #endif
  277. ----------------------------------------------------------------
  278. setDumpSplices :: DynFlags -> DynFlags
  279. setDumpSplices dflag = dopt_set dflag Opt_D_dump_splices
  280. isDumpSplices :: DynFlags -> Bool
  281. isDumpSplices dflag = dopt Opt_D_dump_splices dflag
  282. ----------------------------------------------------------------
  283. setDeferTypeErrors :: DynFlags -> DynFlags
  284. #if __GLASGOW_HASKELL__ >= 708
  285. setDeferTypeErrors dflag = gopt_set dflag Opt_DeferTypeErrors
  286. #elif __GLASGOW_HASKELL__ >= 706
  287. setDeferTypeErrors dflag = dopt_set dflag Opt_DeferTypeErrors
  288. #else
  289. setDeferTypeErrors = id
  290. #endif
  291. setDeferTypedHoles :: DynFlags -> DynFlags
  292. #if __GLASGOW_HASKELL__ >= 710
  293. setDeferTypedHoles dflag = gopt_set dflag Opt_DeferTypedHoles
  294. #else
  295. setDeferTypedHoles = id
  296. #endif
  297. setWarnTypedHoles :: DynFlags -> DynFlags
  298. #if __GLASGOW_HASKELL__ >= 708
  299. setWarnTypedHoles dflag = wopt_set dflag Opt_WarnTypedHoles
  300. #else
  301. setWarnTypedHoles = id
  302. #endif
  303. ----------------------------------------------------------------
  304. -- | Set 'DynFlags' equivalent to "-fno-max-relevant-bindings".
  305. setNoMaxRelevantBindings :: DynFlags -> DynFlags
  306. #if __GLASGOW_HASKELL__ >= 708
  307. setNoMaxRelevantBindings df = df { maxRelevantBinds = Nothing }
  308. #else
  309. setNoMaxRelevantBindings = id
  310. #endif
  311. ----------------------------------------------------------------
  312. ----------------------------------------------------------------
  313. class HasType a where
  314. getType :: GhcMonad m => TypecheckedModule -> a -> m (Maybe (SrcSpan, Type))
  315. instance HasType (LHsBind Id) where
  316. #if __GLASGOW_HASKELL__ >= 708
  317. getType _ (L spn FunBind{fun_matches = m}) = return $ Just (spn, typ)
  318. where in_tys = mg_arg_tys m
  319. out_typ = mg_res_ty m
  320. typ = mkFunTys in_tys out_typ
  321. #else
  322. getType _ (L spn FunBind{fun_matches = MatchGroup _ typ}) = return $ Just (spn, typ)
  323. #endif
  324. getType _ _ = return Nothing
  325. ----------------------------------------------------------------
  326. ----------------------------------------------------------------
  327. -- from ghc/InteractiveUI.hs
  328. filterOutChildren :: (a -> TyThing) -> [a] -> [a]
  329. filterOutChildren get_thing xs
  330. = [x | x <- xs, not (getName (get_thing x) `elemNameSet` implicits)]
  331. where
  332. implicits = mkNameSet [getName t | x <- xs, t <- implicitTyThings (get_thing x)]
  333. infoThing :: GhcMonad m => (FilePath -> FilePath) -> Expression -> m SDoc
  334. infoThing m (Expression str) = do
  335. names <- parseName str
  336. #if __GLASGOW_HASKELL__ >= 708
  337. mb_stuffs <- mapM (getInfo False) names
  338. let filtered = filterOutChildren (\(t,_f,_i,_fam) -> t) (catMaybes mb_stuffs)
  339. #else
  340. mb_stuffs <- mapM getInfo names
  341. let filtered = filterOutChildren (\(t,_f,_i) -> t) (catMaybes mb_stuffs)
  342. #endif
  343. return $ vcat (intersperse (text "") $ map (pprInfo m False) filtered)
  344. #if __GLASGOW_HASKELL__ >= 708
  345. pprInfo :: (FilePath -> FilePath) -> Bool -> (TyThing, GHC.Fixity, [ClsInst], [FamInst]) -> SDoc
  346. pprInfo m _ (thing, fixity, insts, famInsts)
  347. = pprTyThingInContextLoc' thing
  348. $$ show_fixity fixity
  349. $$ vcat (map pprInstance' insts)
  350. $$ vcat (map pprFamInst' famInsts)
  351. #else
  352. pprInfo :: (FilePath -> FilePath) -> PrintExplicitForalls -> (TyThing, GHC.Fixity, [ClsInst]) -> SDoc
  353. pprInfo m pefas (thing, fixity, insts)
  354. = pprTyThingInContextLoc' pefas thing
  355. $$ show_fixity fixity
  356. $$ vcat (map pprInstance' insts)
  357. #endif
  358. where
  359. show_fixity fx
  360. | fx == defaultFixity = Outputable.empty
  361. | otherwise = ppr fx <+> ppr (getName thing)
  362. #if __GLASGOW_HASKELL__ >= 708
  363. pprTyThingInContextLoc' thing' = showWithLoc (pprDefinedAt' thing') (pprTyThingInContext thing')
  364. #if __GLASGOW_HASKELL__ >= 710
  365. pprFamInst' (FamInst { fi_flavor = DataFamilyInst rep_tc })
  366. = pprTyThingInContextLoc (ATyCon rep_tc)
  367. pprFamInst' (FamInst { fi_flavor = SynFamilyInst, fi_axiom = axiom
  368. , fi_tys = lhs_tys, fi_rhs = rhs })
  369. = showWithLoc (pprDefinedAt' (getName axiom)) $
  370. hang (ptext (sLit "type instance") <+> pprTypeApp (coAxiomTyCon axiom) lhs_tys)
  371. 2 (equals <+> ppr rhs)
  372. #else
  373. pprFamInst' ispec = showWithLoc (pprDefinedAt' (getName ispec)) (pprFamInstHdr ispec)
  374. #endif
  375. #else
  376. pprTyThingInContextLoc' pefas' thing' = showWithLoc (pprDefinedAt' thing') (pprTyThingInContext pefas' thing')
  377. #endif
  378. showWithLoc loc doc
  379. = hang doc 2 (char '\t' <> comment <+> loc)
  380. -- The tab tries to make them line up a bit
  381. where
  382. comment = ptext (sLit "--")
  383. pprInstance' ispec = hang (pprInstanceHdr ispec)
  384. 2 (ptext (sLit "--") <+> pprDefinedAt' (getName ispec))
  385. pprDefinedAt' thing' = ptext (sLit "Defined") <+> pprNameDefnLoc' (getName thing')
  386. pprNameDefnLoc' name
  387. = case Name.nameSrcLoc name of
  388. RealSrcLoc s -> ptext (sLit "at") <+> ppr (subst s)
  389. UnhelpfulLoc s
  390. | Name.isInternalName name || Name.isSystemName name
  391. -> ptext (sLit "at") <+> ftext s
  392. | otherwise
  393. -> ptext (sLit "in") <+> quotes (ppr (nameModule name))
  394. where subst s = mkRealSrcLoc (realFP s) (srcLocLine s) (srcLocCol s)
  395. realFP = mkFastString . m . unpackFS . srcLocFile
  396. ----------------------------------------------------------------
  397. ----------------------------------------------------------------
  398. errorMsgSpan :: ErrMsg -> SrcSpan
  399. #if __GLASGOW_HASKELL__ >= 708
  400. errorMsgSpan = errMsgSpan
  401. #else
  402. errorMsgSpan = head . errMsgSpans
  403. #endif
  404. setErrorMsgSpan :: ErrMsg -> SrcSpan -> ErrMsg
  405. #if __GLASGOW_HASKELL__ >= 708
  406. setErrorMsgSpan err s = err { errMsgSpan = s }
  407. #else
  408. setErrorMsgSpan err s = err { errMsgSpans = [s] }
  409. #endif
  410. typeForUser :: Type -> SDoc
  411. #if __GLASGOW_HASKELL__ >= 708
  412. typeForUser = pprTypeForUser
  413. #else
  414. typeForUser = pprTypeForUser False
  415. #endif
  416. nameForUser :: Name -> SDoc
  417. nameForUser = pprOccName . getOccName
  418. occNameForUser :: OccName -> SDoc
  419. occNameForUser = pprOccName
  420. deSugar :: TypecheckedModule -> LHsExpr Id -> HscEnv
  421. -> IO (Maybe CoreExpr)
  422. #if __GLASGOW_HASKELL__ >= 708
  423. deSugar _ e hs_env = snd <$> deSugarExpr hs_env e
  424. #else
  425. deSugar tcm e hs_env = snd <$> deSugarExpr hs_env modu rn_env ty_env e
  426. where
  427. modu = ms_mod $ pm_mod_summary $ tm_parsed_module tcm
  428. tcgEnv = fst $ tm_internals_ tcm
  429. rn_env = tcg_rdr_env tcgEnv
  430. ty_env = tcg_type_env tcgEnv
  431. #endif
  432. ----------------------------------------------------------------
  433. ----------------------------------------------------------------
  434. data GapThing = GtA Type
  435. | GtT TyCon
  436. | GtN
  437. #if __GLASGOW_HASKELL__ >= 800
  438. | GtPatSyn PatSyn
  439. #endif
  440. fromTyThing :: TyThing -> GapThing
  441. fromTyThing (AnId i) = GtA $ varType i
  442. #if __GLASGOW_HASKELL__ >= 708
  443. fromTyThing (AConLike (RealDataCon d)) = GtA $ dataConRepType d
  444. #if __GLASGOW_HASKELL__ >= 800
  445. fromTyThing (AConLike (PatSynCon p)) = GtPatSyn p
  446. #else
  447. fromTyThing (AConLike (PatSynCon p)) = GtA $ patSynType p
  448. #endif
  449. #else
  450. fromTyThing (ADataCon d) = GtA $ dataConRepType d
  451. #endif
  452. fromTyThing (ATyCon t) = GtT t
  453. fromTyThing _ = GtN
  454. ----------------------------------------------------------------
  455. ----------------------------------------------------------------
  456. #if __GLASGOW_HASKELL__ >= 704
  457. type WarnFlags = I.IntSet
  458. emptyWarnFlags :: WarnFlags
  459. emptyWarnFlags = I.empty
  460. #else
  461. type WarnFlags = [WarningFlag]
  462. emptyWarnFlags :: WarnFlags
  463. emptyWarnFlags = []
  464. #endif
  465. ----------------------------------------------------------------
  466. ----------------------------------------------------------------
  467. #if __GLASGOW_HASKELL__ >= 708
  468. type GLMatch = LMatch RdrName (LHsExpr RdrName)
  469. type GLMatchI = LMatch Id (LHsExpr Id)
  470. #else
  471. type GLMatch = LMatch RdrName
  472. type GLMatchI = LMatch Id
  473. #endif
  474. getClass :: [LInstDecl Name] -> Maybe (Name, SrcSpan)
  475. #if __GLASGOW_HASKELL__ >= 800
  476. -- Instance declarations of sort 'instance F (G a)'
  477. getClass [L loc (ClsInstD (ClsInstDecl {cid_poly_ty = HsIB _ (L _ (HsForAllTy _ (L _ (HsAppTy (L _ (HsTyVar (L _ className))) _))))}))] = Just (className, loc)
  478. -- Instance declarations of sort 'instance F G' (no variables)
  479. getClass [L loc (ClsInstD (ClsInstDecl {cid_poly_ty = HsIB _ (L _ (HsAppTy (L _ (HsTyVar (L _ className))) _))}))] = Just (className, loc)
  480. #elif __GLASGOW_HASKELL__ >= 710
  481. -- Instance declarations of sort 'instance F (G a)'
  482. getClass [L loc (ClsInstD (ClsInstDecl {cid_poly_ty = (L _ (HsForAllTy _ _ _ _ (L _ (HsAppTy (L _ (HsTyVar className)) _))))}))] = Just (className, loc)
  483. -- Instance declarations of sort 'instance F G' (no variables)
  484. getClass [L loc (ClsInstD (ClsInstDecl {cid_poly_ty = (L _ (HsAppTy (L _ (HsTyVar className)) _))}))] = Just (className, loc)
  485. #elif __GLASGOW_HASKELL__ >= 708
  486. -- Instance declarations of sort 'instance F (G a)'
  487. getClass [L loc (ClsInstD (ClsInstDecl {cid_poly_ty = (L _ (HsForAllTy _ _ _ (L _ (HsAppTy (L _ (HsTyVar className)) _))))}))] = Just (className, loc)
  488. -- Instance declarations of sort 'instance F G' (no variables)
  489. getClass [L loc (ClsInstD (ClsInstDecl {cid_poly_ty = (L _ (HsAppTy (L _ (HsTyVar className)) _))}))] = Just (className, loc)
  490. #elif __GLASGOW_HASKELL__ >= 706
  491. getClass [L loc (ClsInstD (L _ (HsForAllTy _ _ _ (L _ (HsAppTy (L _ (HsTyVar className)) _)))) _ _ _)] = Just (className, loc)
  492. getClass[L loc (ClsInstD (L _ (HsAppTy (L _ (HsTyVar className)) _)) _ _ _)] = Just (className, loc)
  493. #else
  494. getClass [L loc (InstDecl (L _ (HsForAllTy _ _ _ (L _ (HsAppTy (L _ (HsTyVar className)) _)))) _ _ _)] = Just (className, loc)
  495. getClass [L loc (InstDecl (L _ (HsAppTy (L _ (HsTyVar className)) _)) _ _ _)] = Just (className, loc)
  496. #endif
  497. getClass _ = Nothing
  498. #if __GLASGOW_HASKELL__ < 706
  499. occName :: RdrName -> OccName
  500. occName = rdrNameOcc
  501. #endif
  502. ----------------------------------------------------------------
  503. #if __GLASGOW_HASKELL__ < 710
  504. -- Copied from ghc/InteractiveUI.hs
  505. allExposedPackageConfigs :: DynFlags -> [PackageConfig]
  506. allExposedPackageConfigs df = filter exposed $ eltsUFM $ pkgIdMap $ pkgState df
  507. allExposedModules :: DynFlags -> [ModuleName]
  508. allExposedModules df = concat $ map exposedModules $ allExposedPackageConfigs df
  509. listVisibleModuleNames :: DynFlags -> [ModuleName]
  510. listVisibleModuleNames = allExposedModules
  511. #endif
  512. lookupModulePackageInAllPackages ::
  513. DynFlags -> ModuleName -> [String]
  514. lookupModulePackageInAllPackages df mn =
  515. #if __GLASGOW_HASKELL__ >= 710
  516. unpackSPId . sourcePackageId . snd <$> lookupModuleInAllPackages df mn
  517. where
  518. unpackSPId (SourcePackageId fs) = unpackFS fs
  519. #else
  520. unpackPId . sourcePackageId . fst <$> lookupModuleInAllPackages df mn
  521. where
  522. unpackPId pid = packageIdString $ mkPackageId pid
  523. -- n ++ "-" ++ showVersion v
  524. #endif
  525. listVisibleModules :: DynFlags -> [GHC.Module]
  526. listVisibleModules df = let
  527. #if __GLASGOW_HASKELL__ >= 710
  528. modNames = listVisibleModuleNames df
  529. mods = [ m | mn <- modNames, (m, _) <- lookupModuleInAllPackages df mn ]
  530. #else
  531. pkgCfgs = allExposedPackageConfigs df
  532. mods = [ mkModule pid modname | p <- pkgCfgs
  533. , let pid = packageConfigId p
  534. , modname <- exposedModules p ]
  535. #endif
  536. in mods
  537. isSynTyCon :: TyCon -> Bool
  538. #if __GLASGOW_HASKELL__ >= 710
  539. isSynTyCon = GHC.isTypeSynonymTyCon
  540. #else
  541. isSynTyCon = GHC.isSynTyCon
  542. #endif
  543. parseModuleHeader
  544. :: String -- ^ Haskell module source text (full Unicode is supported)
  545. -> DynFlags
  546. -> FilePath -- ^ the filename (for source locations)
  547. -> Either ErrorMessages (WarningMessages, Located (HsModule RdrName))
  548. parseModuleHeader str dflags filename =
  549. let
  550. loc = mkRealSrcLoc (mkFastString filename) 1 1
  551. buf = stringToStringBuffer str
  552. in
  553. case L.unP Parser.parseHeader (mkPState dflags buf loc) of
  554. PFailed sp err ->
  555. #if __GLASGOW_HASKELL__ >= 706
  556. Left (unitBag (mkPlainErrMsg dflags sp err))
  557. #else
  558. Left (unitBag (mkPlainErrMsg sp err))
  559. #endif
  560. POk pst rdr_module ->
  561. let (warns,_) = getMessages pst in
  562. Right (warns, rdr_module)
  563. mkErrStyle' :: DynFlags -> PrintUnqualified -> PprStyle
  564. #if __GLASGOW_HASKELL__ >= 706
  565. mkErrStyle' = Outputable.mkErrStyle
  566. #else
  567. mkErrStyle' _ = Outputable.mkErrStyle
  568. #endif
  569. #if __GLASGOW_HASKELL__ < 706
  570. instance NFData ByteString where
  571. rnf Empty = ()
  572. rnf (Chunk _ b) = rnf b
  573. #endif
  574. -- | Like 'everything', but avoid known potholes, based on the 'Stage' that
  575. -- generated the Ast.
  576. everythingStagedWithContext :: Stage -> s -> (r -> r -> r) -> r -> GenericQ (s -> (r, s)) -> GenericQ r
  577. everythingStagedWithContext stage s0 f z q x
  578. | (const False
  579. #if __GLASGOW_HASKELL__ <= 708
  580. `extQ` postTcType
  581. #endif
  582. `extQ` fixity `extQ` nameSet) x = z
  583. | otherwise = foldl f r (gmapQ (everythingStagedWithContext stage s' f z q) x)
  584. where nameSet = const (stage `elem` [Parser,TypeChecker]) :: NameSet -> Bool
  585. #if __GLASGOW_HASKELL__ <= 708
  586. postTcType = const (stage<TypeChecker) :: PostTcType -> Bool
  587. #endif
  588. fixity = const (stage<Renamer) :: GHC.Fixity -> Bool
  589. (r, s') = q x s0
  590. withCleanupSession :: GhcMonad m => m a -> m a
  591. #if __GLASGOW_HASKELL__ >= 800
  592. withCleanupSession ghc = ghc `gfinally` cleanup
  593. where
  594. cleanup = do
  595. hsc_env <- getSession
  596. let dflags = hsc_dflags hsc_env
  597. liftIO $ do
  598. cleanTempFiles dflags
  599. cleanTempDirs dflags
  600. stopIServ hsc_env
  601. #else
  602. withCleanupSession action = do
  603. df <- getSessionDynFlags
  604. GHC.defaultCleanupHandler df action
  605. #endif