Small refactor in desugar of pattern matching
[ghc.git] / compiler / deSugar / DsMonad.hs
1 {-
2 (c) The University of Glasgow 2006
3 (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4
5
6 @DsMonad@: monadery used in desugaring
7 -}
8
9 {-# LANGUAGE FlexibleInstances, FlexibleContexts #-}
10 {-# OPTIONS_GHC -fno-warn-orphans #-} -- instance MonadThings is necessarily an orphan
11
12 module DsMonad (
13 DsM, mapM, mapAndUnzipM,
14 initDs, initDsTc, initTcDsForSolver, initDsWithModGuts, fixDs,
15 foldlM, foldrM, whenGOptM, unsetGOptM, unsetWOptM, xoptM,
16 Applicative(..),(<$>),
17
18 duplicateLocalDs, newSysLocalDsNoLP, newSysLocalDs,
19 newSysLocalsDsNoLP, newSysLocalsDs, newUniqueId,
20 newFailLocalDs, newPredVarDs,
21 getSrcSpanDs, putSrcSpanDs,
22 mkPrintUnqualifiedDs,
23 newUnique,
24 UniqSupply, newUniqueSupply,
25 getGhcModeDs, dsGetFamInstEnvs,
26 dsLookupGlobal, dsLookupGlobalId, dsLookupTyCon,
27 dsLookupDataCon, dsLookupConLike,
28
29 DsMetaEnv, DsMetaVal(..), dsGetMetaEnv, dsLookupMetaEnv, dsExtendMetaEnv,
30
31 -- Getting and setting EvVars and term constraints in local environment
32 getDictsDs, addDictsDs, getTmCsDs, addTmCsDs,
33
34 -- Iterations for pm checking
35 incrCheckPmIterDs, resetPmIterDs, dsGetCompleteMatches,
36
37 -- Warnings and errors
38 DsWarning, warnDs, warnIfSetDs, errDs, errDsCoreExpr,
39 failWithDs, failDs, discardWarningsDs,
40 askNoErrsDs,
41
42 -- Data types
43 DsMatchContext(..),
44 EquationInfo(..), MatchResult(..), DsWrapper, idDsWrapper,
45 CanItFail(..), orFail,
46
47 -- Levity polymorphism
48 dsNoLevPoly, dsNoLevPolyExpr, dsWhenNoErrs,
49
50 -- Trace injection
51 pprRuntimeTrace
52 ) where
53
54 import GhcPrelude
55
56 import TcRnMonad
57 import FamInstEnv
58 import CoreSyn
59 import MkCore ( unitExpr )
60 import CoreUtils ( exprType, isExprLevPoly )
61 import HsSyn
62 import TcIface
63 import TcMType ( checkForLevPolyX, formatLevPolyErr )
64 import PrelNames
65 import RdrName
66 import HscTypes
67 import Bag
68 import DataCon
69 import ConLike
70 import TyCon
71 import PmExpr
72 import Id
73 import Module
74 import Outputable
75 import SrcLoc
76 import Type
77 import UniqSupply
78 import Name
79 import NameEnv
80 import DynFlags
81 import ErrUtils
82 import FastString
83 import Var (EvVar)
84 import UniqFM ( lookupWithDefaultUFM )
85 import Literal ( mkMachString )
86 import CostCentreState
87
88 import Data.IORef
89
90 {-
91 ************************************************************************
92 * *
93 Data types for the desugarer
94 * *
95 ************************************************************************
96 -}
97
98 data DsMatchContext
99 = DsMatchContext (HsMatchContext Name) SrcSpan
100 deriving ()
101
102 instance Outputable DsMatchContext where
103 ppr (DsMatchContext hs_match ss) = ppr ss <+> pprMatchContext hs_match
104
105 data EquationInfo
106 = EqnInfo { eqn_pats :: [Pat GhcTc], -- The patterns for an eqn
107 -- NB: We have /already/ applied decideBangHood to
108 -- these patterns. See Note [decideBangHood] in DsUtils
109
110 eqn_rhs :: MatchResult } -- What to do after match
111
112 instance Outputable EquationInfo where
113 ppr (EqnInfo pats _) = ppr pats
114
115 type DsWrapper = CoreExpr -> CoreExpr
116 idDsWrapper :: DsWrapper
117 idDsWrapper e = e
118
119 -- The semantics of (match vs (EqnInfo wrap pats rhs)) is the MatchResult
120 -- \fail. wrap (case vs of { pats -> rhs fail })
121 -- where vs are not bound by wrap
122
123
124 -- A MatchResult is an expression with a hole in it
125 data MatchResult
126 = MatchResult
127 CanItFail -- Tells whether the failure expression is used
128 (CoreExpr -> DsM CoreExpr)
129 -- Takes a expression to plug in at the
130 -- failure point(s). The expression should
131 -- be duplicatable!
132
133 data CanItFail = CanFail | CantFail
134
135 orFail :: CanItFail -> CanItFail -> CanItFail
136 orFail CantFail CantFail = CantFail
137 orFail _ _ = CanFail
138
139 {-
140 ************************************************************************
141 * *
142 Monad functions
143 * *
144 ************************************************************************
145 -}
146
147 -- Compatibility functions
148 fixDs :: (a -> DsM a) -> DsM a
149 fixDs = fixM
150
151 type DsWarning = (SrcSpan, SDoc)
152 -- Not quite the same as a WarnMsg, we have an SDoc here
153 -- and we'll do the print_unqual stuff later on to turn it
154 -- into a Doc.
155
156 -- | Run a 'DsM' action inside the 'TcM' monad.
157 initDsTc :: DsM a -> TcM a
158 initDsTc thing_inside
159 = do { tcg_env <- getGblEnv
160 ; msg_var <- getErrsVar
161 ; hsc_env <- getTopEnv
162 ; envs <- mkDsEnvsFromTcGbl hsc_env msg_var tcg_env
163 ; setEnvs envs thing_inside
164 }
165
166 -- | Run a 'DsM' action inside the 'IO' monad.
167 initDs :: HscEnv -> TcGblEnv -> DsM a -> IO (Messages, Maybe a)
168 initDs hsc_env tcg_env thing_inside
169 = do { msg_var <- newIORef emptyMessages
170 ; envs <- mkDsEnvsFromTcGbl hsc_env msg_var tcg_env
171 ; runDs hsc_env envs thing_inside
172 }
173
174 -- | Build a set of desugarer environments derived from a 'TcGblEnv'.
175 mkDsEnvsFromTcGbl :: MonadIO m
176 => HscEnv -> IORef Messages -> TcGblEnv
177 -> m (DsGblEnv, DsLclEnv)
178 mkDsEnvsFromTcGbl hsc_env msg_var tcg_env
179 = do { pm_iter_var <- liftIO $ newIORef 0
180 ; cc_st_var <- liftIO $ newIORef newCostCentreState
181 ; let dflags = hsc_dflags hsc_env
182 this_mod = tcg_mod tcg_env
183 type_env = tcg_type_env tcg_env
184 rdr_env = tcg_rdr_env tcg_env
185 fam_inst_env = tcg_fam_inst_env tcg_env
186 complete_matches = hptCompleteSigs hsc_env
187 ++ tcg_complete_matches tcg_env
188 ; return $ mkDsEnvs dflags this_mod rdr_env type_env fam_inst_env
189 msg_var pm_iter_var cc_st_var complete_matches
190 }
191
192 runDs :: HscEnv -> (DsGblEnv, DsLclEnv) -> DsM a -> IO (Messages, Maybe a)
193 runDs hsc_env (ds_gbl, ds_lcl) thing_inside
194 = do { res <- initTcRnIf 'd' hsc_env ds_gbl ds_lcl
195 (tryM thing_inside)
196 ; msgs <- readIORef (ds_msgs ds_gbl)
197 ; let final_res
198 | errorsFound dflags msgs = Nothing
199 | Right r <- res = Just r
200 | otherwise = panic "initDs"
201 ; return (msgs, final_res)
202 }
203 where dflags = hsc_dflags hsc_env
204
205 -- | Run a 'DsM' action in the context of an existing 'ModGuts'
206 initDsWithModGuts :: HscEnv -> ModGuts -> DsM a -> IO (Messages, Maybe a)
207 initDsWithModGuts hsc_env guts thing_inside
208 = do { pm_iter_var <- newIORef 0
209 ; cc_st_var <- newIORef newCostCentreState
210 ; msg_var <- newIORef emptyMessages
211 ; let dflags = hsc_dflags hsc_env
212 type_env = typeEnvFromEntities ids (mg_tcs guts) (mg_fam_insts guts)
213 rdr_env = mg_rdr_env guts
214 fam_inst_env = mg_fam_inst_env guts
215 this_mod = mg_module guts
216 complete_matches = hptCompleteSigs hsc_env
217 ++ mg_complete_sigs guts
218
219 bindsToIds (NonRec v _) = [v]
220 bindsToIds (Rec binds) = map fst binds
221 ids = concatMap bindsToIds (mg_binds guts)
222
223 envs = mkDsEnvs dflags this_mod rdr_env type_env
224 fam_inst_env msg_var pm_iter_var
225 cc_st_var complete_matches
226 ; runDs hsc_env envs thing_inside
227 }
228
229 initTcDsForSolver :: TcM a -> DsM (Messages, Maybe a)
230 -- Spin up a TcM context so that we can run the constraint solver
231 -- Returns any error messages generated by the constraint solver
232 -- and (Just res) if no error happened; Nothing if an error happened
233 --
234 -- Simon says: I'm not very happy about this. We spin up a complete TcM monad
235 -- only to immediately refine it to a TcS monad.
236 -- Better perhaps to make TcS into its own monad, rather than building on TcS
237 -- But that may in turn interact with plugins
238
239 initTcDsForSolver thing_inside
240 = do { (gbl, lcl) <- getEnvs
241 ; hsc_env <- getTopEnv
242
243 ; let DsGblEnv { ds_mod = mod
244 , ds_fam_inst_env = fam_inst_env } = gbl
245
246 DsLclEnv { dsl_loc = loc } = lcl
247
248 ; liftIO $ initTc hsc_env HsSrcFile False mod loc $
249 updGblEnv (\tc_gbl -> tc_gbl { tcg_fam_inst_env = fam_inst_env }) $
250 thing_inside }
251
252 mkDsEnvs :: DynFlags -> Module -> GlobalRdrEnv -> TypeEnv -> FamInstEnv
253 -> IORef Messages -> IORef Int -> IORef CostCentreState
254 -> [CompleteMatch] -> (DsGblEnv, DsLclEnv)
255 mkDsEnvs dflags mod rdr_env type_env fam_inst_env msg_var pmvar cc_st_var
256 complete_matches
257 = let if_genv = IfGblEnv { if_doc = text "mkDsEnvs",
258 if_rec_types = Just (mod, return type_env) }
259 if_lenv = mkIfLclEnv mod (text "GHC error in desugarer lookup in" <+> ppr mod)
260 False -- not boot!
261 real_span = realSrcLocSpan (mkRealSrcLoc (moduleNameFS (moduleName mod)) 1 1)
262 completeMatchMap = mkCompleteMatchMap complete_matches
263 gbl_env = DsGblEnv { ds_mod = mod
264 , ds_fam_inst_env = fam_inst_env
265 , ds_if_env = (if_genv, if_lenv)
266 , ds_unqual = mkPrintUnqualified dflags rdr_env
267 , ds_msgs = msg_var
268 , ds_complete_matches = completeMatchMap
269 , ds_cc_st = cc_st_var
270 }
271 lcl_env = DsLclEnv { dsl_meta = emptyNameEnv
272 , dsl_loc = real_span
273 , dsl_dicts = emptyBag
274 , dsl_tm_cs = emptyBag
275 , dsl_pm_iter = pmvar
276 }
277 in (gbl_env, lcl_env)
278
279
280 {-
281 ************************************************************************
282 * *
283 Operations in the monad
284 * *
285 ************************************************************************
286
287 And all this mysterious stuff is so we can occasionally reach out and
288 grab one or more names. @newLocalDs@ isn't exported---exported
289 functions are defined with it. The difference in name-strings makes
290 it easier to read debugging output.
291
292 Note [Levity polymorphism checking]
293 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
294 According to the "Levity Polymorphism" paper (PLDI '17), levity
295 polymorphism is forbidden in precisely two places: in the type of a bound
296 term-level argument and in the type of an argument to a function. The paper
297 explains it more fully, but briefly: expressions in these contexts need to be
298 stored in registers, and it's hard (read, impossible) to store something
299 that's levity polymorphic.
300
301 We cannot check for bad levity polymorphism conveniently in the type checker,
302 because we can't tell, a priori, which levity metavariables will be solved.
303 At one point, I (Richard) thought we could check in the zonker, but it's hard
304 to know where precisely are the abstracted variables and the arguments. So
305 we check in the desugarer, the only place where we can see the Core code and
306 still report respectable syntax to the user. This covers the vast majority
307 of cases; see calls to DsMonad.dsNoLevPoly and friends.
308
309 Levity polymorphism is also prohibited in the types of binders, and the
310 desugarer checks for this in GHC-generated Ids. (The zonker handles
311 the user-writted ids in zonkIdBndr.) This is done in newSysLocalDsNoLP.
312 The newSysLocalDs variant is used in the vast majority of cases where
313 the binder is obviously not levity polymorphic, omitting the check.
314 It would be nice to ASSERT that there is no levity polymorphism here,
315 but we can't, because of the fixM in DsArrows. It's all OK, though:
316 Core Lint will catch an error here.
317
318 However, the desugarer is the wrong place for certain checks. In particular,
319 the desugarer can't report a sensible error message if an HsWrapper is malformed.
320 After all, GHC itself produced the HsWrapper. So we store some message text
321 in the appropriate HsWrappers (e.g. WpFun) that we can print out in the
322 desugarer.
323
324 There are a few more checks in places where Core is generated outside the
325 desugarer. For example, in datatype and class declarations, where levity
326 polymorphism is checked for during validity checking. It would be nice to
327 have one central place for all this, but that doesn't seem possible while
328 still reporting nice error messages.
329
330 -}
331
332 -- Make a new Id with the same print name, but different type, and new unique
333 newUniqueId :: Id -> Type -> DsM Id
334 newUniqueId id = mk_local (occNameFS (nameOccName (idName id)))
335
336 duplicateLocalDs :: Id -> DsM Id
337 duplicateLocalDs old_local
338 = do { uniq <- newUnique
339 ; return (setIdUnique old_local uniq) }
340
341 newPredVarDs :: PredType -> DsM Var
342 newPredVarDs pred
343 = newSysLocalDs pred
344
345 newSysLocalDsNoLP, newSysLocalDs, newFailLocalDs :: Type -> DsM Id
346 newSysLocalDsNoLP = mk_local (fsLit "ds")
347
348 -- this variant should be used when the caller can be sure that the variable type
349 -- is not levity-polymorphic. It is necessary when the type is knot-tied because
350 -- of the fixM used in DsArrows. See Note [Levity polymorphism checking]
351 newSysLocalDs = mkSysLocalOrCoVarM (fsLit "ds")
352 newFailLocalDs = mkSysLocalOrCoVarM (fsLit "fail")
353 -- the fail variable is used only in a situation where we can tell that
354 -- levity-polymorphism is impossible.
355
356 newSysLocalsDsNoLP, newSysLocalsDs :: [Type] -> DsM [Id]
357 newSysLocalsDsNoLP = mapM newSysLocalDsNoLP
358 newSysLocalsDs = mapM newSysLocalDs
359
360 mk_local :: FastString -> Type -> DsM Id
361 mk_local fs ty = do { dsNoLevPoly ty (text "When trying to create a variable of type:" <+>
362 ppr ty) -- could improve the msg with another
363 -- parameter indicating context
364 ; mkSysLocalOrCoVarM fs ty }
365
366 {-
367 We can also reach out and either set/grab location information from
368 the @SrcSpan@ being carried around.
369 -}
370
371 getGhcModeDs :: DsM GhcMode
372 getGhcModeDs = getDynFlags >>= return . ghcMode
373
374 -- | Get in-scope type constraints (pm check)
375 getDictsDs :: DsM (Bag EvVar)
376 getDictsDs = do { env <- getLclEnv; return (dsl_dicts env) }
377
378 -- | Add in-scope type constraints (pm check)
379 addDictsDs :: Bag EvVar -> DsM a -> DsM a
380 addDictsDs ev_vars
381 = updLclEnv (\env -> env { dsl_dicts = unionBags ev_vars (dsl_dicts env) })
382
383 -- | Get in-scope term constraints (pm check)
384 getTmCsDs :: DsM (Bag SimpleEq)
385 getTmCsDs = do { env <- getLclEnv; return (dsl_tm_cs env) }
386
387 -- | Add in-scope term constraints (pm check)
388 addTmCsDs :: Bag SimpleEq -> DsM a -> DsM a
389 addTmCsDs tm_cs
390 = updLclEnv (\env -> env { dsl_tm_cs = unionBags tm_cs (dsl_tm_cs env) })
391
392 -- | Increase the counter for elapsed pattern match check iterations.
393 -- If the current counter is already over the limit, fail
394 incrCheckPmIterDs :: DsM Int
395 incrCheckPmIterDs = do
396 env <- getLclEnv
397 cnt <- readTcRef (dsl_pm_iter env)
398 max_iters <- maxPmCheckIterations <$> getDynFlags
399 if cnt >= max_iters
400 then failM
401 else updTcRef (dsl_pm_iter env) (+1)
402 return cnt
403
404 -- | Reset the counter for pattern match check iterations to zero
405 resetPmIterDs :: DsM ()
406 resetPmIterDs = do { env <- getLclEnv; writeTcRef (dsl_pm_iter env) 0 }
407
408 getSrcSpanDs :: DsM SrcSpan
409 getSrcSpanDs = do { env <- getLclEnv
410 ; return (RealSrcSpan (dsl_loc env)) }
411
412 putSrcSpanDs :: SrcSpan -> DsM a -> DsM a
413 putSrcSpanDs (UnhelpfulSpan {}) thing_inside
414 = thing_inside
415 putSrcSpanDs (RealSrcSpan real_span) thing_inside
416 = updLclEnv (\ env -> env {dsl_loc = real_span}) thing_inside
417
418 -- | Emit a warning for the current source location
419 -- NB: Warns whether or not -Wxyz is set
420 warnDs :: WarnReason -> SDoc -> DsM ()
421 warnDs reason warn
422 = do { env <- getGblEnv
423 ; loc <- getSrcSpanDs
424 ; dflags <- getDynFlags
425 ; let msg = makeIntoWarning reason $
426 mkWarnMsg dflags loc (ds_unqual env) warn
427 ; updMutVar (ds_msgs env) (\ (w,e) -> (w `snocBag` msg, e)) }
428
429 -- | Emit a warning only if the correct WarnReason is set in the DynFlags
430 warnIfSetDs :: WarningFlag -> SDoc -> DsM ()
431 warnIfSetDs flag warn
432 = whenWOptM flag $
433 warnDs (Reason flag) warn
434
435 errDs :: SDoc -> DsM ()
436 errDs err
437 = do { env <- getGblEnv
438 ; loc <- getSrcSpanDs
439 ; dflags <- getDynFlags
440 ; let msg = mkErrMsg dflags loc (ds_unqual env) err
441 ; updMutVar (ds_msgs env) (\ (w,e) -> (w, e `snocBag` msg)) }
442
443 -- | Issue an error, but return the expression for (), so that we can continue
444 -- reporting errors.
445 errDsCoreExpr :: SDoc -> DsM CoreExpr
446 errDsCoreExpr err
447 = do { errDs err
448 ; return unitExpr }
449
450 failWithDs :: SDoc -> DsM a
451 failWithDs err
452 = do { errDs err
453 ; failM }
454
455 failDs :: DsM a
456 failDs = failM
457
458 -- (askNoErrsDs m) runs m
459 -- If m fails,
460 -- then (askNoErrsDs m) fails
461 -- If m succeeds with result r,
462 -- then (askNoErrsDs m) succeeds with result (r, b),
463 -- where b is True iff m generated no errors
464 -- Regardless of success or failure,
465 -- propagate any errors/warnings generated by m
466 --
467 -- c.f. TcRnMonad.askNoErrs
468 askNoErrsDs :: DsM a -> DsM (a, Bool)
469 askNoErrsDs thing_inside
470 = do { errs_var <- newMutVar emptyMessages
471 ; env <- getGblEnv
472 ; mb_res <- tryM $ -- Be careful to catch exceptions
473 -- so that we propagate errors correctly
474 -- (Trac #13642)
475 setGblEnv (env { ds_msgs = errs_var }) $
476 thing_inside
477
478 -- Propagate errors
479 ; msgs@(warns, errs) <- readMutVar errs_var
480 ; updMutVar (ds_msgs env) (\ (w,e) -> (w `unionBags` warns, e `unionBags` errs))
481
482 -- And return
483 ; case mb_res of
484 Left _ -> failM
485 Right res -> do { dflags <- getDynFlags
486 ; let errs_found = errorsFound dflags msgs
487 ; return (res, not errs_found) } }
488
489 mkPrintUnqualifiedDs :: DsM PrintUnqualified
490 mkPrintUnqualifiedDs = ds_unqual <$> getGblEnv
491
492 instance MonadThings (IOEnv (Env DsGblEnv DsLclEnv)) where
493 lookupThing = dsLookupGlobal
494
495 dsLookupGlobal :: Name -> DsM TyThing
496 -- Very like TcEnv.tcLookupGlobal
497 dsLookupGlobal name
498 = do { env <- getGblEnv
499 ; setEnvs (ds_if_env env)
500 (tcIfaceGlobal name) }
501
502 dsLookupGlobalId :: Name -> DsM Id
503 dsLookupGlobalId name
504 = tyThingId <$> dsLookupGlobal name
505
506 dsLookupTyCon :: Name -> DsM TyCon
507 dsLookupTyCon name
508 = tyThingTyCon <$> dsLookupGlobal name
509
510 dsLookupDataCon :: Name -> DsM DataCon
511 dsLookupDataCon name
512 = tyThingDataCon <$> dsLookupGlobal name
513
514 dsLookupConLike :: Name -> DsM ConLike
515 dsLookupConLike name
516 = tyThingConLike <$> dsLookupGlobal name
517
518
519 dsGetFamInstEnvs :: DsM FamInstEnvs
520 -- Gets both the external-package inst-env
521 -- and the home-pkg inst env (includes module being compiled)
522 dsGetFamInstEnvs
523 = do { eps <- getEps; env <- getGblEnv
524 ; return (eps_fam_inst_env eps, ds_fam_inst_env env) }
525
526 dsGetMetaEnv :: DsM (NameEnv DsMetaVal)
527 dsGetMetaEnv = do { env <- getLclEnv; return (dsl_meta env) }
528
529 -- | The @COMPLETE@ pragams provided by the user for a given `TyCon`.
530 dsGetCompleteMatches :: TyCon -> DsM [CompleteMatch]
531 dsGetCompleteMatches tc = do
532 eps <- getEps
533 env <- getGblEnv
534 let lookup_completes ufm = lookupWithDefaultUFM ufm [] tc
535 eps_matches_list = lookup_completes $ eps_complete_matches eps
536 env_matches_list = lookup_completes $ ds_complete_matches env
537 return $ eps_matches_list ++ env_matches_list
538
539 dsLookupMetaEnv :: Name -> DsM (Maybe DsMetaVal)
540 dsLookupMetaEnv name = do { env <- getLclEnv; return (lookupNameEnv (dsl_meta env) name) }
541
542 dsExtendMetaEnv :: DsMetaEnv -> DsM a -> DsM a
543 dsExtendMetaEnv menv thing_inside
544 = updLclEnv (\env -> env { dsl_meta = dsl_meta env `plusNameEnv` menv }) thing_inside
545
546 discardWarningsDs :: DsM a -> DsM a
547 -- Ignore warnings inside the thing inside;
548 -- used to ignore inaccessable cases etc. inside generated code
549 discardWarningsDs thing_inside
550 = do { env <- getGblEnv
551 ; old_msgs <- readTcRef (ds_msgs env)
552
553 ; result <- thing_inside
554
555 -- Revert messages to old_msgs
556 ; writeTcRef (ds_msgs env) old_msgs
557
558 ; return result }
559
560 -- | Fail with an error message if the type is levity polymorphic.
561 dsNoLevPoly :: Type -> SDoc -> DsM ()
562 -- See Note [Levity polymorphism checking]
563 dsNoLevPoly ty doc = checkForLevPolyX errDs doc ty
564
565 -- | Check an expression for levity polymorphism, failing if it is
566 -- levity polymorphic.
567 dsNoLevPolyExpr :: CoreExpr -> SDoc -> DsM ()
568 -- See Note [Levity polymorphism checking]
569 dsNoLevPolyExpr e doc
570 | isExprLevPoly e = errDs (formatLevPolyErr (exprType e) $$ doc)
571 | otherwise = return ()
572
573 -- | Runs the thing_inside. If there are no errors, then returns the expr
574 -- given. Otherwise, returns unitExpr. This is useful for doing a bunch
575 -- of levity polymorphism checks and then avoiding making a core App.
576 -- (If we make a core App on a levity polymorphic argument, detecting how
577 -- to handle the let/app invariant might call isUnliftedType, which panics
578 -- on a levity polymorphic type.)
579 -- See #12709 for an example of why this machinery is necessary.
580 dsWhenNoErrs :: DsM a -> (a -> CoreExpr) -> DsM CoreExpr
581 dsWhenNoErrs thing_inside mk_expr
582 = do { (result, no_errs) <- askNoErrsDs thing_inside
583 ; return $ if no_errs
584 then mk_expr result
585 else unitExpr }
586
587 -- | Inject a trace message into the compiled program. Whereas
588 -- pprTrace prints out information *while compiling*, pprRuntimeTrace
589 -- captures that information and causes it to be printed *at runtime*
590 -- using Debug.Trace.trace.
591 --
592 -- pprRuntimeTrace hdr doc expr
593 --
594 -- will produce an expression that looks like
595 --
596 -- trace (hdr + doc) expr
597 --
598 -- When using this to debug a module that Debug.Trace depends on,
599 -- it is necessary to import {-# SOURCE #-} Debug.Trace () in that
600 -- module. We could avoid this inconvenience by wiring in Debug.Trace.trace,
601 -- but that doesn't seem worth the effort and maintenance cost.
602 pprRuntimeTrace :: String -- ^ header
603 -> SDoc -- ^ information to output
604 -> CoreExpr -- ^ expression
605 -> DsM CoreExpr
606 pprRuntimeTrace str doc expr = do
607 traceId <- dsLookupGlobalId traceName
608 unpackCStringId <- dsLookupGlobalId unpackCStringName
609 dflags <- getDynFlags
610 let message :: CoreExpr
611 message = App (Var unpackCStringId) $
612 Lit $ mkMachString $ showSDoc dflags (hang (text str) 4 doc)
613 return $ mkApps (Var traceId) [Type (exprType expr), message, expr]