- = do { warn_var <- newIORef emptyBag
- ; let { if_genv = IfGblEnv { if_rec_types = Just (mod, return type_env) }
- ; if_lenv = mkIfLclEnv mod (ptext SLIT("GHC error in desugarer lookup in") <+> ppr mod)
- ; gbl_env = DsGblEnv { ds_mod = mod,
- ds_if_env = (if_genv, if_lenv),
- ds_warns = warn_var }
- ; lcl_env = DsLclEnv { ds_meta = emptyNameEnv,
- ds_loc = noSrcSpan } }
-
- ; res <- initTcRnIf 'd' hsc_env gbl_env lcl_env thing_inside
-
- ; warns <- readIORef warn_var
- ; return (res, mapBag mk_warn warns)
- }
- where
- print_unqual = mkPrintUnqualified rdr_env
-
- mk_warn :: (SrcSpan,SDoc) -> WarnMsg
- mk_warn (loc,sdoc) = mkWarnMsg loc print_unqual sdoc
+ = do { msg_var <- newIORef (emptyBag, emptyBag)
+ ; let dflags = hsc_dflags hsc_env
+ ; (ds_gbl_env, ds_lcl_env) <- mkDsEnvs dflags mod rdr_env type_env msg_var
+
+ ; either_res <- initTcRnIf 'd' hsc_env ds_gbl_env ds_lcl_env $
+ tryM thing_inside -- Catch exceptions (= errors during desugaring)
+
+ -- Display any errors and warnings
+ -- Note: if -Werror is used, we don't signal an error here.
+ ; msgs <- readIORef msg_var
+ ; printErrorsAndWarnings dflags msgs
+
+ ; let final_res | errorsFound dflags msgs = Nothing
+ | otherwise = case either_res of
+ Right res -> Just res
+ Left exn -> pprPanic "initDs" (text (show exn))
+ -- The (Left exn) case happens when the thing_inside throws
+ -- a UserError exception. Then it should have put an error
+ -- message in msg_var, so we just discard the exception
+
+ ; return final_res }
+
+initDsTc :: DsM a -> TcM a
+initDsTc thing_inside
+ = do { this_mod <- getModule
+ ; tcg_env <- getGblEnv
+ ; msg_var <- getErrsVar
+ ; dflags <- getDOpts
+ ; let type_env = tcg_type_env tcg_env
+ rdr_env = tcg_rdr_env tcg_env
+ ; ds_envs <- liftIO $ mkDsEnvs dflags this_mod rdr_env type_env msg_var
+ ; setEnvs ds_envs thing_inside }
+
+mkDsEnvs :: DynFlags -> Module -> GlobalRdrEnv -> TypeEnv -> IORef Messages -> IO (DsGblEnv, DsLclEnv)
+mkDsEnvs dflags mod rdr_env type_env msg_var
+ = do -- TODO: unnecessarily monadic
+ let if_genv = IfGblEnv { if_rec_types = Just (mod, return type_env) }
+ if_lenv = mkIfLclEnv mod (ptext (sLit "GHC error in desugarer lookup in") <+> ppr mod)
+ gbl_env = DsGblEnv { ds_mod = mod,
+ ds_if_env = (if_genv, if_lenv),
+ ds_unqual = mkPrintUnqualified dflags rdr_env,
+ ds_msgs = msg_var}
+ lcl_env = DsLclEnv { ds_meta = emptyNameEnv,
+ ds_loc = noSrcSpan }
+
+ return (gbl_env, lcl_env)
+