Add Note [No alternatives lint check]
[ghc.git] / compiler / coreSyn / CoreLint.hs
1 {-
2 (c) The University of Glasgow 2006
3 (c) The GRASP/AQUA Project, Glasgow University, 1993-1998
4
5
6 A ``lint'' pass to check for Core correctness
7 -}
8
9 {-# LANGUAGE CPP #-}
10 {-# OPTIONS_GHC -fprof-auto #-}
11
12 module CoreLint (
13 lintCoreBindings, lintUnfolding,
14 lintPassResult, lintInteractiveExpr, lintExpr,
15 lintAnnots,
16
17 -- ** Debug output
18 CoreLint.showPass, showPassIO, endPass, endPassIO,
19 dumpPassResult,
20 CoreLint.dumpIfSet,
21 ) where
22
23 #include "HsVersions.h"
24
25 import CoreSyn
26 import CoreFVs
27 import CoreUtils
28 import CoreMonad
29 import Bag
30 import Literal
31 import DataCon
32 import TysWiredIn
33 import TysPrim
34 import Var
35 import VarEnv
36 import VarSet
37 import Name
38 import Id
39 import PprCore
40 import ErrUtils
41 import Coercion
42 import SrcLoc
43 import Kind
44 import Type
45 import TypeRep
46 import TyCon
47 import CoAxiom
48 import BasicTypes
49 import ErrUtils as Err
50 import StaticFlags
51 import ListSetOps
52 import PrelNames
53 import Outputable
54 import FastString
55 import Util
56 import InstEnv ( instanceDFunId )
57 import OptCoercion ( checkAxInstCo )
58 import UniqSupply
59 import CoreArity ( typeArity )
60 import Demand ( splitStrictSig, isBotRes )
61
62 import HscTypes
63 import DynFlags
64 import Control.Monad
65 import MonadUtils
66 import Data.Maybe
67 import Pair
68
69 {-
70 Note [GHC Formalism]
71 ~~~~~~~~~~~~~~~~~~~~
72 This file implements the type-checking algorithm for System FC, the "official"
73 name of the Core language. Type safety of FC is heart of the claim that
74 executables produced by GHC do not have segmentation faults. Thus, it is
75 useful to be able to reason about System FC independently of reading the code.
76 To this purpose, there is a document ghc.pdf built in docs/core-spec that
77 contains a formalism of the types and functions dealt with here. If you change
78 just about anything in this file or you change other types/functions throughout
79 the Core language (all signposted to this note), you should update that
80 formalism. See docs/core-spec/README for more info about how to do so.
81
82 Summary of checks
83 ~~~~~~~~~~~~~~~~~
84 Checks that a set of core bindings is well-formed. The PprStyle and String
85 just control what we print in the event of an error. The Bool value
86 indicates whether we have done any specialisation yet (in which case we do
87 some extra checks).
88
89 We check for
90 (a) type errors
91 (b) Out-of-scope type variables
92 (c) Out-of-scope local variables
93 (d) Ill-kinded types
94 (e) Incorrect unsafe coercions
95
96 If we have done specialisation the we check that there are
97 (a) No top-level bindings of primitive (unboxed type)
98
99 Outstanding issues:
100
101 -- Things are *not* OK if:
102 --
103 -- * Unsaturated type app before specialisation has been done;
104 --
105 -- * Oversaturated type app after specialisation (eta reduction
106 -- may well be happening...);
107
108
109 Note [Linting type lets]
110 ~~~~~~~~~~~~~~~~~~~~~~~~
111 In the desugarer, it's very very convenient to be able to say (in effect)
112 let a = Type Int in <body>
113 That is, use a type let. See Note [Type let] in CoreSyn.
114
115 However, when linting <body> we need to remember that a=Int, else we might
116 reject a correct program. So we carry a type substitution (in this example
117 [a -> Int]) and apply this substitution before comparing types. The functin
118 lintInTy :: Type -> LintM Type
119 returns a substituted type; that's the only reason it returns anything.
120
121 When we encounter a binder (like x::a) we must apply the substitution
122 to the type of the binding variable. lintBinders does this.
123
124 For Ids, the type-substituted Id is added to the in_scope set (which
125 itself is part of the TvSubst we are carrying down), and when we
126 find an occurrence of an Id, we fetch it from the in-scope set.
127
128 Note [Bad unsafe coercion]
129 ~~~~~~~~~~~~~~~~~~~~~~~~~~
130
131 For discussion see https://ghc.haskell.org/trac/ghc/wiki/BadUnsafeCoercions
132 Linter introduces additional rules that checks improper coercion between
133 different types, called bad coercions. Following coercions are forbidden:
134
135 (a) coercions between boxed and unboxed values;
136 (b) coercions between unlifted values of the different sizes, here
137 active size is checked, i.e. size of the actual value but not
138 the space allocated for value;
139 (c) coercions between floating and integral boxed values, this check
140 is not yet supported for unboxed tuples, as no semantics were
141 specified for that;
142 (d) coercions from / to vector type
143 (e) If types are unboxed tuples then tuple (# A_1,..,A_n #) can be
144 coerced to (# B_1,..,B_m #) if n=m and for each pair A_i, B_i rules
145 (a-e) holds.
146
147 ************************************************************************
148 * *
149 Beginning and ending passes
150 * *
151 ************************************************************************
152
153 These functions are not CoreM monad stuff, but they probably ought to
154 be, and it makes a conveneint place. place for them. They print out
155 stuff before and after core passes, and do Core Lint when necessary.
156 -}
157
158 showPass :: CoreToDo -> CoreM ()
159 showPass pass = do { dflags <- getDynFlags
160 ; liftIO $ showPassIO dflags pass }
161
162 showPassIO :: DynFlags -> CoreToDo -> IO ()
163 showPassIO dflags pass = Err.showPass dflags (showPpr dflags pass)
164
165 endPass :: CoreToDo -> CoreProgram -> [CoreRule] -> CoreM ()
166 endPass pass binds rules
167 = do { hsc_env <- getHscEnv
168 ; print_unqual <- getPrintUnqualified
169 ; liftIO $ endPassIO hsc_env print_unqual pass binds rules }
170
171 endPassIO :: HscEnv -> PrintUnqualified
172 -> CoreToDo -> CoreProgram -> [CoreRule] -> IO ()
173 -- Used by the IO-is CorePrep too
174 endPassIO hsc_env print_unqual pass binds rules
175 = do { dumpPassResult dflags print_unqual mb_flag
176 (ppr pass) (pprPassDetails pass) binds rules
177 ; lintPassResult hsc_env pass binds }
178 where
179 dflags = hsc_dflags hsc_env
180 mb_flag = case coreDumpFlag pass of
181 Just flag | dopt flag dflags -> Just flag
182 | dopt Opt_D_verbose_core2core dflags -> Just flag
183 _ -> Nothing
184
185 dumpIfSet :: DynFlags -> Bool -> CoreToDo -> SDoc -> SDoc -> IO ()
186 dumpIfSet dflags dump_me pass extra_info doc
187 = Err.dumpIfSet dflags dump_me (showSDoc dflags (ppr pass <+> extra_info)) doc
188
189 dumpPassResult :: DynFlags
190 -> PrintUnqualified
191 -> Maybe DumpFlag -- Just df => show details in a file whose
192 -- name is specified by df
193 -> SDoc -- Header
194 -> SDoc -- Extra info to appear after header
195 -> CoreProgram -> [CoreRule]
196 -> IO ()
197 dumpPassResult dflags unqual mb_flag hdr extra_info binds rules
198 | Just flag <- mb_flag
199 = Err.dumpSDoc dflags unqual flag (showSDoc dflags hdr) dump_doc
200
201 | otherwise
202 = Err.debugTraceMsg dflags 2 size_doc
203 -- Report result size
204 -- This has the side effect of forcing the intermediate to be evaluated
205
206 where
207 size_doc = sep [text "Result size of" <+> hdr, nest 2 (equals <+> ppr (coreBindsStats binds))]
208
209 dump_doc = vcat [ nest 2 extra_info
210 , size_doc
211 , blankLine
212 , pprCoreBindings binds
213 , ppUnless (null rules) pp_rules ]
214 pp_rules = vcat [ blankLine
215 , ptext (sLit "------ Local rules for imported ids --------")
216 , pprRules rules ]
217
218 coreDumpFlag :: CoreToDo -> Maybe DumpFlag
219 coreDumpFlag (CoreDoSimplify {}) = Just Opt_D_verbose_core2core
220 coreDumpFlag (CoreDoPluginPass {}) = Just Opt_D_verbose_core2core
221 coreDumpFlag CoreDoFloatInwards = Just Opt_D_verbose_core2core
222 coreDumpFlag (CoreDoFloatOutwards {}) = Just Opt_D_verbose_core2core
223 coreDumpFlag CoreLiberateCase = Just Opt_D_verbose_core2core
224 coreDumpFlag CoreDoStaticArgs = Just Opt_D_verbose_core2core
225 coreDumpFlag CoreDoCallArity = Just Opt_D_dump_call_arity
226 coreDumpFlag CoreDoStrictness = Just Opt_D_dump_stranal
227 coreDumpFlag CoreDoWorkerWrapper = Just Opt_D_dump_worker_wrapper
228 coreDumpFlag CoreDoSpecialising = Just Opt_D_dump_spec
229 coreDumpFlag CoreDoSpecConstr = Just Opt_D_dump_spec
230 coreDumpFlag CoreCSE = Just Opt_D_dump_cse
231 coreDumpFlag CoreDoVectorisation = Just Opt_D_dump_vect
232 coreDumpFlag CoreDesugar = Just Opt_D_dump_ds
233 coreDumpFlag CoreDesugarOpt = Just Opt_D_dump_ds
234 coreDumpFlag CoreTidy = Just Opt_D_dump_simpl
235 coreDumpFlag CorePrep = Just Opt_D_dump_prep
236
237 coreDumpFlag CoreDoPrintCore = Nothing
238 coreDumpFlag (CoreDoRuleCheck {}) = Nothing
239 coreDumpFlag CoreDoNothing = Nothing
240 coreDumpFlag (CoreDoPasses {}) = Nothing
241
242 {-
243 ************************************************************************
244 * *
245 Top-level interfaces
246 * *
247 ************************************************************************
248 -}
249
250 lintPassResult :: HscEnv -> CoreToDo -> CoreProgram -> IO ()
251 lintPassResult hsc_env pass binds
252 | not (gopt Opt_DoCoreLinting dflags)
253 = return ()
254 | otherwise
255 = do { let (warns, errs) = lintCoreBindings dflags pass (interactiveInScope hsc_env) binds
256 ; Err.showPass dflags ("Core Linted result of " ++ showPpr dflags pass)
257 ; displayLintResults dflags pass warns errs binds }
258 where
259 dflags = hsc_dflags hsc_env
260
261 displayLintResults :: DynFlags -> CoreToDo
262 -> Bag Err.MsgDoc -> Bag Err.MsgDoc -> CoreProgram
263 -> IO ()
264 displayLintResults dflags pass warns errs binds
265 | not (isEmptyBag errs)
266 = do { log_action dflags dflags Err.SevDump noSrcSpan defaultDumpStyle
267 (vcat [ lint_banner "errors" (ppr pass), Err.pprMessageBag errs
268 , ptext (sLit "*** Offending Program ***")
269 , pprCoreBindings binds
270 , ptext (sLit "*** End of Offense ***") ])
271 ; Err.ghcExit dflags 1 }
272
273 | not (isEmptyBag warns)
274 , not opt_NoDebugOutput
275 , showLintWarnings pass
276 = log_action dflags dflags Err.SevDump noSrcSpan defaultDumpStyle
277 (lint_banner "warnings" (ppr pass) $$ Err.pprMessageBag warns)
278
279 | otherwise = return ()
280 where
281
282 lint_banner :: String -> SDoc -> SDoc
283 lint_banner string pass = ptext (sLit "*** Core Lint") <+> text string
284 <+> ptext (sLit ": in result of") <+> pass
285 <+> ptext (sLit "***")
286
287 showLintWarnings :: CoreToDo -> Bool
288 -- Disable Lint warnings on the first simplifier pass, because
289 -- there may be some INLINE knots still tied, which is tiresomely noisy
290 showLintWarnings (CoreDoSimplify _ (SimplMode { sm_phase = InitialPhase })) = False
291 showLintWarnings _ = True
292
293 lintInteractiveExpr :: String -> HscEnv -> CoreExpr -> IO ()
294 lintInteractiveExpr what hsc_env expr
295 | not (gopt Opt_DoCoreLinting dflags)
296 = return ()
297 | Just err <- lintExpr dflags (interactiveInScope hsc_env) expr
298 = do { display_lint_err err
299 ; Err.ghcExit dflags 1 }
300 | otherwise
301 = return ()
302 where
303 dflags = hsc_dflags hsc_env
304
305 display_lint_err err
306 = do { log_action dflags dflags Err.SevDump noSrcSpan defaultDumpStyle
307 (vcat [ lint_banner "errors" (text what)
308 , err
309 , ptext (sLit "*** Offending Program ***")
310 , pprCoreExpr expr
311 , ptext (sLit "*** End of Offense ***") ])
312 ; Err.ghcExit dflags 1 }
313
314 interactiveInScope :: HscEnv -> [Var]
315 -- In GHCi we may lint expressions, or bindings arising from 'deriving'
316 -- clauses, that mention variables bound in the interactive context.
317 -- These are Local things (see Note [Interactively-bound Ids in GHCi] in HscTypes).
318 -- So we have to tell Lint about them, lest it reports them as out of scope.
319 --
320 -- We do this by find local-named things that may appear free in interactive
321 -- context. This function is pretty revolting and quite possibly not quite right.
322 -- When we are not in GHCi, the interactive context (hsc_IC hsc_env) is empty
323 -- so this is a (cheap) no-op.
324 --
325 -- See Trac #8215 for an example
326 interactiveInScope hsc_env
327 = varSetElems tyvars ++ ids
328 where
329 -- C.f. TcRnDriver.setInteractiveContext, Desugar.deSugarExpr
330 ictxt = hsc_IC hsc_env
331 (cls_insts, _fam_insts) = ic_instances ictxt
332 te1 = mkTypeEnvWithImplicits (ic_tythings ictxt)
333 te = extendTypeEnvWithIds te1 (map instanceDFunId cls_insts)
334 ids = typeEnvIds te
335 tyvars = mapUnionVarSet (tyVarsOfType . idType) ids
336 -- Why the type variables? How can the top level envt have free tyvars?
337 -- I think it's because of the GHCi debugger, which can bind variables
338 -- f :: [t] -> [t]
339 -- where t is a RuntimeUnk (see TcType)
340
341 lintCoreBindings :: DynFlags -> CoreToDo -> [Var] -> CoreProgram -> (Bag MsgDoc, Bag MsgDoc)
342 -- Returns (warnings, errors)
343 -- If you edit this function, you may need to update the GHC formalism
344 -- See Note [GHC Formalism]
345 lintCoreBindings dflags pass local_in_scope binds
346 = initL dflags flags $
347 addLoc TopLevelBindings $
348 addInScopeVars local_in_scope $
349 addInScopeVars binders $
350 -- Put all the top-level binders in scope at the start
351 -- This is because transformation rules can bring something
352 -- into use 'unexpectedly'
353 do { checkL (null dups) (dupVars dups)
354 ; checkL (null ext_dups) (dupExtVars ext_dups)
355 ; mapM lint_bind binds }
356 where
357 flags = LF { lf_check_global_ids = check_globals
358 , lf_check_inline_loop_breakers = check_lbs }
359
360 -- See Note [Checking for global Ids]
361 check_globals = case pass of
362 CoreTidy -> False
363 CorePrep -> False
364 _ -> True
365
366 -- See Note [Checking for INLINE loop breakers]
367 check_lbs = case pass of
368 CoreDesugar -> False
369 CoreDesugarOpt -> False
370 _ -> True
371
372 binders = bindersOfBinds binds
373 (_, dups) = removeDups compare binders
374
375 -- dups_ext checks for names with different uniques
376 -- but but the same External name M.n. We don't
377 -- allow this at top level:
378 -- M.n{r3} = ...
379 -- M.n{r29} = ...
380 -- because they both get the same linker symbol
381 ext_dups = snd (removeDups ord_ext (map Var.varName binders))
382 ord_ext n1 n2 | Just m1 <- nameModule_maybe n1
383 , Just m2 <- nameModule_maybe n2
384 = compare (m1, nameOccName n1) (m2, nameOccName n2)
385 | otherwise = LT
386
387 -- If you edit this function, you may need to update the GHC formalism
388 -- See Note [GHC Formalism]
389 lint_bind (Rec prs) = mapM_ (lintSingleBinding TopLevel Recursive) prs
390 lint_bind (NonRec bndr rhs) = lintSingleBinding TopLevel NonRecursive (bndr,rhs)
391
392 {-
393 ************************************************************************
394 * *
395 \subsection[lintUnfolding]{lintUnfolding}
396 * *
397 ************************************************************************
398
399 We use this to check all unfoldings that come in from interfaces
400 (it is very painful to catch errors otherwise):
401 -}
402
403 lintUnfolding :: DynFlags
404 -> SrcLoc
405 -> [Var] -- Treat these as in scope
406 -> CoreExpr
407 -> Maybe MsgDoc -- Nothing => OK
408
409 lintUnfolding dflags locn vars expr
410 | isEmptyBag errs = Nothing
411 | otherwise = Just (pprMessageBag errs)
412 where
413 (_warns, errs) = initL dflags defaultLintFlags linter
414 linter = addLoc (ImportedUnfolding locn) $
415 addInScopeVars vars $
416 lintCoreExpr expr
417
418 lintExpr :: DynFlags
419 -> [Var] -- Treat these as in scope
420 -> CoreExpr
421 -> Maybe MsgDoc -- Nothing => OK
422
423 lintExpr dflags vars expr
424 | isEmptyBag errs = Nothing
425 | otherwise = Just (pprMessageBag errs)
426 where
427 (_warns, errs) = initL dflags defaultLintFlags linter
428 linter = addLoc TopLevelBindings $
429 addInScopeVars vars $
430 lintCoreExpr expr
431
432 {-
433 ************************************************************************
434 * *
435 \subsection[lintCoreBinding]{lintCoreBinding}
436 * *
437 ************************************************************************
438
439 Check a core binding, returning the list of variables bound.
440 -}
441
442 lintSingleBinding :: TopLevelFlag -> RecFlag -> (Id, CoreExpr) -> LintM ()
443 -- If you edit this function, you may need to update the GHC formalism
444 -- See Note [GHC Formalism]
445 lintSingleBinding top_lvl_flag rec_flag (binder,rhs)
446 = addLoc (RhsOf binder) $
447 -- Check the rhs
448 do { ty <- lintCoreExpr rhs
449 ; lintBinder binder -- Check match to RHS type
450 ; binder_ty <- applySubstTy binder_ty
451 ; checkTys binder_ty ty (mkRhsMsg binder (ptext (sLit "RHS")) ty)
452
453 -- Check the let/app invariant
454 -- See Note [CoreSyn let/app invariant] in CoreSyn
455 ; checkL (not (isUnLiftedType binder_ty)
456 || (isNonRec rec_flag && exprOkForSpeculation rhs))
457 (mkRhsPrimMsg binder rhs)
458
459 -- Check that if the binder is top-level or recursive, it's not demanded
460 ; checkL (not (isStrictId binder)
461 || (isNonRec rec_flag && not (isTopLevel top_lvl_flag)))
462 (mkStrictMsg binder)
463
464 -- Check that if the binder is local, it is not marked as exported
465 ; checkL (not (isExportedId binder) || isTopLevel top_lvl_flag)
466 (mkNonTopExportedMsg binder)
467
468 -- Check that if the binder is local, it does not have an external name
469 ; checkL (not (isExternalName (Var.varName binder)) || isTopLevel top_lvl_flag)
470 (mkNonTopExternalNameMsg binder)
471
472 -- Check whether binder's specialisations contain any out-of-scope variables
473 ; mapM_ (checkBndrIdInScope binder) bndr_vars
474
475 ; flags <- getLintFlags
476 ; when (lf_check_inline_loop_breakers flags
477 && isStrongLoopBreaker (idOccInfo binder)
478 && isInlinePragma (idInlinePragma binder))
479 (addWarnL (ptext (sLit "INLINE binder is (non-rule) loop breaker:") <+> ppr binder))
480 -- Only non-rule loop breakers inhibit inlining
481
482 -- Check whether arity and demand type are consistent (only if demand analysis
483 -- already happened)
484 --
485 -- Note (Apr 2014): this is actually ok. See Note [Demand analysis for trivial right-hand sides]
486 -- in DmdAnal. After eta-expansion in CorePrep the rhs is no longer trivial.
487 -- ; let dmdTy = idStrictness binder
488 -- ; checkL (case dmdTy of
489 -- StrictSig dmd_ty -> idArity binder >= dmdTypeDepth dmd_ty || exprIsTrivial rhs)
490 -- (mkArityMsg binder)
491
492 -- Check that the binder's arity is within the bounds imposed by
493 -- the type and the strictness signature. See Note [exprArity invariant]
494 -- and Note [Trimming arity]
495 ; checkL (idArity binder <= length (typeArity (idType binder)))
496 (ptext (sLit "idArity") <+> ppr (idArity binder) <+>
497 ptext (sLit "exceeds typeArity") <+>
498 ppr (length (typeArity (idType binder))) <> colon <+>
499 ppr binder)
500
501 ; case splitStrictSig (idStrictness binder) of
502 (demands, result_info) | isBotRes result_info ->
503 checkL (idArity binder <= length demands)
504 (ptext (sLit "idArity") <+> ppr (idArity binder) <+>
505 ptext (sLit "exceeds arity imposed by the strictness signature") <+>
506 ppr (idStrictness binder) <> colon <+>
507 ppr binder)
508 _ -> return ()
509
510 ; lintIdUnfolding binder binder_ty (idUnfolding binder) }
511
512 -- We should check the unfolding, if any, but this is tricky because
513 -- the unfolding is a SimplifiableCoreExpr. Give up for now.
514 where
515 binder_ty = idType binder
516 bndr_vars = varSetElems (idFreeVars binder)
517
518 -- If you edit this function, you may need to update the GHC formalism
519 -- See Note [GHC Formalism]
520 lintBinder var | isId var = lintIdBndr var $ \_ -> (return ())
521 | otherwise = return ()
522
523 lintIdUnfolding :: Id -> Type -> Unfolding -> LintM ()
524 lintIdUnfolding bndr bndr_ty (CoreUnfolding { uf_tmpl = rhs, uf_src = src })
525 | isStableSource src
526 = do { ty <- lintCoreExpr rhs
527 ; checkTys bndr_ty ty (mkRhsMsg bndr (ptext (sLit "unfolding")) ty) }
528 lintIdUnfolding _ _ _
529 = return () -- We could check more
530
531 {-
532 Note [Checking for INLINE loop breakers]
533 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
534 It's very suspicious if a strong loop breaker is marked INLINE.
535
536 However, the desugarer generates instance methods with INLINE pragmas
537 that form a mutually recursive group. Only after a round of
538 simplification are they unravelled. So we suppress the test for
539 the desugarer.
540
541 ************************************************************************
542 * *
543 \subsection[lintCoreExpr]{lintCoreExpr}
544 * *
545 ************************************************************************
546 -}
547
548 --type InKind = Kind -- Substitution not yet applied
549 type InType = Type
550 type InCoercion = Coercion
551 type InVar = Var
552 type InTyVar = TyVar
553
554 type OutKind = Kind -- Substitution has been applied to this,
555 -- but has not been linted yet
556 type LintedKind = Kind -- Substitution applied, and type is linted
557
558 type OutType = Type -- Substitution has been applied to this,
559 -- but has not been linted yet
560
561 type LintedType = Type -- Substitution applied, and type is linted
562
563 type OutCoercion = Coercion
564 type OutVar = Var
565 type OutTyVar = TyVar
566
567 lintCoreExpr :: CoreExpr -> LintM OutType
568 -- The returned type has the substitution from the monad
569 -- already applied to it:
570 -- lintCoreExpr e subst = exprType (subst e)
571 --
572 -- The returned "type" can be a kind, if the expression is (Type ty)
573
574 -- If you edit this function, you may need to update the GHC formalism
575 -- See Note [GHC Formalism]
576 lintCoreExpr (Var var)
577 = do { checkL (not (var == oneTupleDataConId))
578 (ptext (sLit "Illegal one-tuple"))
579
580 ; checkL (isId var && not (isCoVar var))
581 (ptext (sLit "Non term variable") <+> ppr var)
582
583 ; checkDeadIdOcc var
584 ; var' <- lookupIdInScope var
585 ; return (idType var') }
586
587 lintCoreExpr (Lit lit)
588 = return (literalType lit)
589
590 lintCoreExpr (Cast expr co)
591 = do { expr_ty <- lintCoreExpr expr
592 ; co' <- applySubstCo co
593 ; (_, from_ty, to_ty, r) <- lintCoercion co'
594 ; checkRole co' Representational r
595 ; checkTys from_ty expr_ty (mkCastErr expr co' from_ty expr_ty)
596 ; return to_ty }
597
598 lintCoreExpr (Tick (Breakpoint _ ids) expr)
599 = do forM_ ids $ \id -> do
600 checkDeadIdOcc id
601 lookupIdInScope id
602 lintCoreExpr expr
603
604 lintCoreExpr (Tick _other_tickish expr)
605 = lintCoreExpr expr
606
607 lintCoreExpr (Let (NonRec tv (Type ty)) body)
608 | isTyVar tv
609 = -- See Note [Linting type lets]
610 do { ty' <- applySubstTy ty
611 ; lintTyBndr tv $ \ tv' ->
612 do { addLoc (RhsOf tv) $ checkTyKind tv' ty'
613 -- Now extend the substitution so we
614 -- take advantage of it in the body
615 ; extendSubstL tv' ty' $
616 addLoc (BodyOfLetRec [tv]) $
617 lintCoreExpr body } }
618
619 lintCoreExpr (Let (NonRec bndr rhs) body)
620 | isId bndr
621 = do { lintSingleBinding NotTopLevel NonRecursive (bndr,rhs)
622 ; addLoc (BodyOfLetRec [bndr])
623 (lintAndScopeId bndr $ \_ -> (lintCoreExpr body)) }
624
625 | otherwise
626 = failWithL (mkLetErr bndr rhs) -- Not quite accurate
627
628 lintCoreExpr (Let (Rec pairs) body)
629 = lintAndScopeIds bndrs $ \_ ->
630 do { checkL (null dups) (dupVars dups)
631 ; mapM_ (lintSingleBinding NotTopLevel Recursive) pairs
632 ; addLoc (BodyOfLetRec bndrs) (lintCoreExpr body) }
633 where
634 bndrs = map fst pairs
635 (_, dups) = removeDups compare bndrs
636
637 lintCoreExpr e@(App _ _)
638 = do { fun_ty <- lintCoreExpr fun
639 ; addLoc (AnExpr e) $ foldM lintCoreArg fun_ty args }
640 where
641 (fun, args) = collectArgs e
642
643 lintCoreExpr (Lam var expr)
644 = addLoc (LambdaBodyOf var) $
645 lintBinder var $ \ var' ->
646 do { body_ty <- lintCoreExpr expr
647 ; if isId var' then
648 return (mkFunTy (idType var') body_ty)
649 else
650 return (mkForAllTy var' body_ty)
651 }
652 -- The applySubstTy is needed to apply the subst to var
653
654 lintCoreExpr e@(Case scrut var alt_ty alts) =
655 -- Check the scrutinee
656 do { scrut_ty <- lintCoreExpr scrut
657 ; alt_ty <- lintInTy alt_ty
658 ; var_ty <- lintInTy (idType var)
659
660 -- See Note [No alternatives lint check]
661 ; when (null alts) $
662 do { checkL (not (exprIsHNF scrut))
663 (ptext (sLit "No alternatives for a case scrutinee in head-normal form:") <+> ppr scrut)
664 ; checkL (exprIsBottom scrut || isEmptyTy (exprType scrut))
665 (ptext (sLit "No alternatives for a case scrutinee not known to diverge for sure:") <+> ppr scrut)
666 }
667
668 ; case tyConAppTyCon_maybe (idType var) of
669 Just tycon
670 | debugIsOn &&
671 isAlgTyCon tycon &&
672 not (isFamilyTyCon tycon || isAbstractTyCon tycon) &&
673 null (tyConDataCons tycon) ->
674 pprTrace "Lint warning: case binder's type has no constructors" (ppr var <+> ppr (idType var))
675 -- This can legitimately happen for type families
676 $ return ()
677 _otherwise -> return ()
678
679 -- Don't use lintIdBndr on var, because unboxed tuple is legitimate
680
681 ; subst <- getTvSubst
682 ; checkTys var_ty scrut_ty (mkScrutMsg var var_ty scrut_ty subst)
683
684 ; lintAndScopeId var $ \_ ->
685 do { -- Check the alternatives
686 mapM_ (lintCoreAlt scrut_ty alt_ty) alts
687 ; checkCaseAlts e scrut_ty alts
688 ; return alt_ty } }
689
690 -- This case can't happen; linting types in expressions gets routed through
691 -- lintCoreArgs
692 lintCoreExpr (Type ty)
693 = pprPanic "lintCoreExpr" (ppr ty)
694
695 lintCoreExpr (Coercion co)
696 = do { (_kind, ty1, ty2, role) <- lintInCo co
697 ; return (mkCoercionType role ty1 ty2) }
698
699 {-
700 Note [Kind instantiation in coercions]
701 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
702 Consider the following coercion axiom:
703 ax_co [(k_ag :: BOX), (f_aa :: k_ag -> Constraint)] :: T k_ag f_aa ~ f_aa
704
705 Consider the following instantiation:
706 ax_co <* -> *> <Monad>
707
708 We need to split the co_ax_tvs into kind and type variables in order
709 to find out the coercion kind instantiations. Those can only be Refl
710 since we don't have kind coercions. This is just a way to represent
711 kind instantiation.
712
713 We use the number of kind variables to know how to split the coercions
714 instantiations between kind coercions and type coercions. We lint the
715 kind coercions and produce the following substitution which is to be
716 applied in the type variables:
717 k_ag ~~> * -> *
718
719 Note [No alternatives lint check]
720 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
721
722 Case expressions with no alternatives are odd beasts, and worth looking at
723 in the linter.
724
725 Certainly, it would be terribly wrong if the scrutinee was already in head
726 normal form. That is the first check.
727
728 Furthermore, we should be able to see why GHC believes the scrutinee is
729 diverging for sure. That is the second check. see #10180.
730
731 ************************************************************************
732 * *
733 \subsection[lintCoreArgs]{lintCoreArgs}
734 * *
735 ************************************************************************
736
737 The basic version of these functions checks that the argument is a
738 subtype of the required type, as one would expect.
739 -}
740
741 lintCoreArg :: OutType -> CoreArg -> LintM OutType
742 lintCoreArg fun_ty (Type arg_ty)
743 = do { arg_ty' <- applySubstTy arg_ty
744 ; lintTyApp fun_ty arg_ty' }
745
746 lintCoreArg fun_ty arg
747 = do { arg_ty <- lintCoreExpr arg
748 ; checkL (not (isUnLiftedType arg_ty) || exprOkForSpeculation arg)
749 (mkLetAppMsg arg)
750 ; lintValApp arg fun_ty arg_ty }
751
752 -----------------
753 lintAltBinders :: OutType -- Scrutinee type
754 -> OutType -- Constructor type
755 -> [OutVar] -- Binders
756 -> LintM ()
757 -- If you edit this function, you may need to update the GHC formalism
758 -- See Note [GHC Formalism]
759 lintAltBinders scrut_ty con_ty []
760 = checkTys con_ty scrut_ty (mkBadPatMsg con_ty scrut_ty)
761 lintAltBinders scrut_ty con_ty (bndr:bndrs)
762 | isTyVar bndr
763 = do { con_ty' <- lintTyApp con_ty (mkTyVarTy bndr)
764 ; lintAltBinders scrut_ty con_ty' bndrs }
765 | otherwise
766 = do { con_ty' <- lintValApp (Var bndr) con_ty (idType bndr)
767 ; lintAltBinders scrut_ty con_ty' bndrs }
768
769 -----------------
770 lintTyApp :: OutType -> OutType -> LintM OutType
771 lintTyApp fun_ty arg_ty
772 | Just (tyvar,body_ty) <- splitForAllTy_maybe fun_ty
773 , isTyVar tyvar
774 = do { checkTyKind tyvar arg_ty
775 ; return (substTyWith [tyvar] [arg_ty] body_ty) }
776
777 | otherwise
778 = failWithL (mkTyAppMsg fun_ty arg_ty)
779
780 -----------------
781 lintValApp :: CoreExpr -> OutType -> OutType -> LintM OutType
782 lintValApp arg fun_ty arg_ty
783 | Just (arg,res) <- splitFunTy_maybe fun_ty
784 = do { checkTys arg arg_ty err1
785 ; return res }
786 | otherwise
787 = failWithL err2
788 where
789 err1 = mkAppMsg fun_ty arg_ty arg
790 err2 = mkNonFunAppMsg fun_ty arg_ty arg
791
792 checkTyKind :: OutTyVar -> OutType -> LintM ()
793 -- Both args have had substitution applied
794
795 -- If you edit this function, you may need to update the GHC formalism
796 -- See Note [GHC Formalism]
797 checkTyKind tyvar arg_ty
798 | isSuperKind tyvar_kind -- kind forall
799 = lintKind arg_ty
800 -- Arg type might be boxed for a function with an uncommitted
801 -- tyvar; notably this is used so that we can give
802 -- error :: forall a:*. String -> a
803 -- and then apply it to both boxed and unboxed types.
804 | otherwise -- type forall
805 = do { arg_kind <- lintType arg_ty
806 ; unless (arg_kind `isSubKind` tyvar_kind)
807 (addErrL (mkKindErrMsg tyvar arg_ty $$ (text "xx" <+> ppr arg_kind))) }
808 where
809 tyvar_kind = tyVarKind tyvar
810
811 checkDeadIdOcc :: Id -> LintM ()
812 -- Occurrences of an Id should never be dead....
813 -- except when we are checking a case pattern
814 checkDeadIdOcc id
815 | isDeadOcc (idOccInfo id)
816 = do { in_case <- inCasePat
817 ; checkL in_case
818 (ptext (sLit "Occurrence of a dead Id") <+> ppr id) }
819 | otherwise
820 = return ()
821
822 {-
823 ************************************************************************
824 * *
825 \subsection[lintCoreAlts]{lintCoreAlts}
826 * *
827 ************************************************************************
828 -}
829
830 checkCaseAlts :: CoreExpr -> OutType -> [CoreAlt] -> LintM ()
831 -- a) Check that the alts are non-empty
832 -- b1) Check that the DEFAULT comes first, if it exists
833 -- b2) Check that the others are in increasing order
834 -- c) Check that there's a default for infinite types
835 -- NB: Algebraic cases are not necessarily exhaustive, because
836 -- the simplifer correctly eliminates case that can't
837 -- possibly match.
838
839 checkCaseAlts e ty alts =
840 do { checkL (all non_deflt con_alts) (mkNonDefltMsg e)
841 ; checkL (increasing_tag con_alts) (mkNonIncreasingAltsMsg e)
842
843 -- For types Int#, Word# with an infinite (well, large!) number of
844 -- possible values, there should usually be a DEFAULT case
845 -- But (see Note [Empty case alternatives] in CoreSyn) it's ok to
846 -- have *no* case alternatives.
847 -- In effect, this is a kind of partial test. I suppose it's possible
848 -- that we might *know* that 'x' was 1 or 2, in which case
849 -- case x of { 1 -> e1; 2 -> e2 }
850 -- would be fine.
851 ; checkL (isJust maybe_deflt || not is_infinite_ty || null alts)
852 (nonExhaustiveAltsMsg e) }
853 where
854 (con_alts, maybe_deflt) = findDefault alts
855
856 -- Check that successive alternatives have increasing tags
857 increasing_tag (alt1 : rest@( alt2 : _)) = alt1 `ltAlt` alt2 && increasing_tag rest
858 increasing_tag _ = True
859
860 non_deflt (DEFAULT, _, _) = False
861 non_deflt _ = True
862
863 is_infinite_ty = case tyConAppTyCon_maybe ty of
864 Nothing -> False
865 Just tycon -> isPrimTyCon tycon
866
867 checkAltExpr :: CoreExpr -> OutType -> LintM ()
868 checkAltExpr expr ann_ty
869 = do { actual_ty <- lintCoreExpr expr
870 ; checkTys actual_ty ann_ty (mkCaseAltMsg expr actual_ty ann_ty) }
871
872 lintCoreAlt :: OutType -- Type of scrutinee
873 -> OutType -- Type of the alternative
874 -> CoreAlt
875 -> LintM ()
876 -- If you edit this function, you may need to update the GHC formalism
877 -- See Note [GHC Formalism]
878 lintCoreAlt _ alt_ty (DEFAULT, args, rhs) =
879 do { checkL (null args) (mkDefaultArgsMsg args)
880 ; checkAltExpr rhs alt_ty }
881
882 lintCoreAlt scrut_ty alt_ty (LitAlt lit, args, rhs)
883 | litIsLifted lit
884 = failWithL integerScrutinisedMsg
885 | otherwise
886 = do { checkL (null args) (mkDefaultArgsMsg args)
887 ; checkTys lit_ty scrut_ty (mkBadPatMsg lit_ty scrut_ty)
888 ; checkAltExpr rhs alt_ty }
889 where
890 lit_ty = literalType lit
891
892 lintCoreAlt scrut_ty alt_ty alt@(DataAlt con, args, rhs)
893 | isNewTyCon (dataConTyCon con)
894 = addErrL (mkNewTyDataConAltMsg scrut_ty alt)
895 | Just (tycon, tycon_arg_tys) <- splitTyConApp_maybe scrut_ty
896 = addLoc (CaseAlt alt) $ do
897 { -- First instantiate the universally quantified
898 -- type variables of the data constructor
899 -- We've already check
900 checkL (tycon == dataConTyCon con) (mkBadConMsg tycon con)
901 ; let con_payload_ty = applyTys (dataConRepType con) tycon_arg_tys
902
903 -- And now bring the new binders into scope
904 ; lintBinders args $ \ args' -> do
905 { addLoc (CasePat alt) (lintAltBinders scrut_ty con_payload_ty args')
906 ; checkAltExpr rhs alt_ty } }
907
908 | otherwise -- Scrut-ty is wrong shape
909 = addErrL (mkBadAltMsg scrut_ty alt)
910
911 {-
912 ************************************************************************
913 * *
914 \subsection[lint-types]{Types}
915 * *
916 ************************************************************************
917 -}
918
919 -- When we lint binders, we (one at a time and in order):
920 -- 1. Lint var types or kinds (possibly substituting)
921 -- 2. Add the binder to the in scope set, and if its a coercion var,
922 -- we may extend the substitution to reflect its (possibly) new kind
923 lintBinders :: [Var] -> ([Var] -> LintM a) -> LintM a
924 lintBinders [] linterF = linterF []
925 lintBinders (var:vars) linterF = lintBinder var $ \var' ->
926 lintBinders vars $ \ vars' ->
927 linterF (var':vars')
928
929 -- If you edit this function, you may need to update the GHC formalism
930 -- See Note [GHC Formalism]
931 lintBinder :: Var -> (Var -> LintM a) -> LintM a
932 lintBinder var linterF
933 | isId var = lintIdBndr var linterF
934 | otherwise = lintTyBndr var linterF
935
936 lintTyBndr :: InTyVar -> (OutTyVar -> LintM a) -> LintM a
937 lintTyBndr tv thing_inside
938 = do { subst <- getTvSubst
939 ; let (subst', tv') = Type.substTyVarBndr subst tv
940 ; lintTyBndrKind tv'
941 ; updateTvSubst subst' (thing_inside tv') }
942
943 lintIdBndr :: Id -> (Id -> LintM a) -> LintM a
944 -- Do substitution on the type of a binder and add the var with this
945 -- new type to the in-scope set of the second argument
946 -- ToDo: lint its rules
947
948 lintIdBndr id linterF
949 = do { lintAndScopeId id $ \id' -> linterF id' }
950
951 lintAndScopeIds :: [Var] -> ([Var] -> LintM a) -> LintM a
952 lintAndScopeIds ids linterF
953 = go ids
954 where
955 go [] = linterF []
956 go (id:ids) = lintAndScopeId id $ \id ->
957 lintAndScopeIds ids $ \ids ->
958 linterF (id:ids)
959
960 lintAndScopeId :: InVar -> (OutVar -> LintM a) -> LintM a
961 lintAndScopeId id linterF
962 = do { flags <- getLintFlags
963 ; checkL (not (lf_check_global_ids flags) || isLocalId id)
964 (ptext (sLit "Non-local Id binder") <+> ppr id)
965 -- See Note [Checking for global Ids]
966 ; ty <- lintInTy (idType id)
967 ; let id' = setIdType id ty
968 ; addInScopeVar id' $ (linterF id') }
969
970 {-
971 ************************************************************************
972 * *
973 Types and kinds
974 * *
975 ************************************************************************
976
977 We have a single linter for types and kinds. That is convenient
978 because sometimes it's not clear whether the thing we are looking
979 at is a type or a kind.
980 -}
981
982 lintInTy :: InType -> LintM LintedType
983 -- Types only, not kinds
984 -- Check the type, and apply the substitution to it
985 -- See Note [Linting type lets]
986 lintInTy ty
987 = addLoc (InType ty) $
988 do { ty' <- applySubstTy ty
989 ; _k <- lintType ty'
990 ; return ty' }
991
992 -------------------
993 lintTyBndrKind :: OutTyVar -> LintM ()
994 -- Handles both type and kind foralls.
995 lintTyBndrKind tv = lintKind (tyVarKind tv)
996
997 -------------------
998 lintType :: OutType -> LintM LintedKind
999 -- The returned Kind has itself been linted
1000
1001 -- If you edit this function, you may need to update the GHC formalism
1002 -- See Note [GHC Formalism]
1003 lintType (TyVarTy tv)
1004 = do { checkTyCoVarInScope tv
1005 ; return (tyVarKind tv) }
1006 -- We checked its kind when we added it to the envt
1007
1008 lintType ty@(AppTy t1 t2)
1009 = do { k1 <- lintType t1
1010 ; k2 <- lintType t2
1011 ; lint_ty_app ty k1 [(t2,k2)] }
1012
1013 lintType ty@(FunTy t1 t2) -- (->) has two different rules, for types and kinds
1014 = do { k1 <- lintType t1
1015 ; k2 <- lintType t2
1016 ; lintArrow (ptext (sLit "type or kind") <+> quotes (ppr ty)) k1 k2 }
1017
1018 lintType ty@(TyConApp tc tys)
1019 | Just ty' <- coreView ty
1020 = lintType ty' -- Expand type synonyms, so that we do not bogusly complain
1021 -- about un-saturated type synonyms
1022
1023 | isUnLiftedTyCon tc || isTypeSynonymTyCon tc || isTypeFamilyTyCon tc
1024 -- See Note [The kind invariant] in TypeRep
1025 -- Also type synonyms and type families
1026 , length tys < tyConArity tc
1027 = failWithL (hang (ptext (sLit "Un-saturated type application")) 2 (ppr ty))
1028
1029 | otherwise
1030 = do { ks <- mapM lintType tys
1031 ; lint_ty_app ty (tyConKind tc) (tys `zip` ks) }
1032
1033 lintType (ForAllTy tv ty)
1034 = do { lintTyBndrKind tv
1035 ; addInScopeVar tv (lintType ty) }
1036
1037 lintType ty@(LitTy l) = lintTyLit l >> return (typeKind ty)
1038
1039 lintKind :: OutKind -> LintM ()
1040 -- If you edit this function, you may need to update the GHC formalism
1041 -- See Note [GHC Formalism]
1042 lintKind k = do { sk <- lintType k
1043 ; unless (isSuperKind sk)
1044 (addErrL (hang (ptext (sLit "Ill-kinded kind:") <+> ppr k)
1045 2 (ptext (sLit "has kind:") <+> ppr sk))) }
1046
1047 lintArrow :: SDoc -> LintedKind -> LintedKind -> LintM LintedKind
1048 -- If you edit this function, you may need to update the GHC formalism
1049 -- See Note [GHC Formalism]
1050 lintArrow what k1 k2 -- Eg lintArrow "type or kind `blah'" k1 k2
1051 -- or lintarrow "coercion `blah'" k1 k2
1052 | isSuperKind k1
1053 = return superKind
1054 | otherwise
1055 = do { unless (okArrowArgKind k1) (addErrL (msg (ptext (sLit "argument")) k1))
1056 ; unless (okArrowResultKind k2) (addErrL (msg (ptext (sLit "result")) k2))
1057 ; return liftedTypeKind }
1058 where
1059 msg ar k
1060 = vcat [ hang (ptext (sLit "Ill-kinded") <+> ar)
1061 2 (ptext (sLit "in") <+> what)
1062 , what <+> ptext (sLit "kind:") <+> ppr k ]
1063
1064 lint_ty_app :: Type -> LintedKind -> [(LintedType,LintedKind)] -> LintM LintedKind
1065 lint_ty_app ty k tys
1066 = lint_app (ptext (sLit "type") <+> quotes (ppr ty)) k tys
1067
1068 ----------------
1069 lint_co_app :: Coercion -> LintedKind -> [(LintedType,LintedKind)] -> LintM LintedKind
1070 lint_co_app ty k tys
1071 = lint_app (ptext (sLit "coercion") <+> quotes (ppr ty)) k tys
1072
1073 ----------------
1074 lintTyLit :: TyLit -> LintM ()
1075 lintTyLit (NumTyLit n)
1076 | n >= 0 = return ()
1077 | otherwise = failWithL msg
1078 where msg = ptext (sLit "Negative type literal:") <+> integer n
1079 lintTyLit (StrTyLit _) = return ()
1080
1081 lint_app :: SDoc -> LintedKind -> [(LintedType,LintedKind)] -> LintM Kind
1082 -- (lint_app d fun_kind arg_tys)
1083 -- We have an application (f arg_ty1 .. arg_tyn),
1084 -- where f :: fun_kind
1085 -- Takes care of linting the OutTypes
1086
1087 -- If you edit this function, you may need to update the GHC formalism
1088 -- See Note [GHC Formalism]
1089 lint_app doc kfn kas
1090 = foldlM go_app kfn kas
1091 where
1092 fail_msg = vcat [ hang (ptext (sLit "Kind application error in")) 2 doc
1093 , nest 2 (ptext (sLit "Function kind =") <+> ppr kfn)
1094 , nest 2 (ptext (sLit "Arg kinds =") <+> ppr kas) ]
1095
1096 go_app kfn ka
1097 | Just kfn' <- coreView kfn
1098 = go_app kfn' ka
1099
1100 go_app (FunTy kfa kfb) (_,ka)
1101 = do { unless (ka `isSubKind` kfa) (addErrL fail_msg)
1102 ; return kfb }
1103
1104 go_app (ForAllTy kv kfn) (ta,ka)
1105 = do { unless (ka `isSubKind` tyVarKind kv) (addErrL fail_msg)
1106 ; return (substKiWith [kv] [ta] kfn) }
1107
1108 go_app _ _ = failWithL fail_msg
1109
1110 {-
1111 ************************************************************************
1112 * *
1113 Linting coercions
1114 * *
1115 ************************************************************************
1116 -}
1117
1118 lintInCo :: InCoercion -> LintM (LintedKind, LintedType, LintedType, Role)
1119 -- Check the coercion, and apply the substitution to it
1120 -- See Note [Linting type lets]
1121 lintInCo co
1122 = addLoc (InCo co) $
1123 do { co' <- applySubstCo co
1124 ; lintCoercion co' }
1125
1126 lintCoercion :: OutCoercion -> LintM (LintedKind, LintedType, LintedType, Role)
1127 -- Check the kind of a coercion term, returning the kind
1128 -- Post-condition: the returned OutTypes are lint-free
1129 -- and have the same kind as each other
1130
1131 -- If you edit this function, you may need to update the GHC formalism
1132 -- See Note [GHC Formalism]
1133 lintCoercion (Refl r ty)
1134 = do { k <- lintType ty
1135 ; return (k, ty, ty, r) }
1136
1137 lintCoercion co@(TyConAppCo r tc cos)
1138 | tc `hasKey` funTyConKey
1139 , [co1,co2] <- cos
1140 = do { (k1,s1,t1,r1) <- lintCoercion co1
1141 ; (k2,s2,t2,r2) <- lintCoercion co2
1142 ; rk <- lintArrow (ptext (sLit "coercion") <+> quotes (ppr co)) k1 k2
1143 ; checkRole co1 r r1
1144 ; checkRole co2 r r2
1145 ; return (rk, mkFunTy s1 s2, mkFunTy t1 t2, r) }
1146
1147 | Just {} <- synTyConDefn_maybe tc
1148 = failWithL (ptext (sLit "Synonym in TyConAppCo:") <+> ppr co)
1149
1150 | otherwise
1151 = do { (ks,ss,ts,rs) <- mapAndUnzip4M lintCoercion cos
1152 ; rk <- lint_co_app co (tyConKind tc) (ss `zip` ks)
1153 ; _ <- zipWith3M checkRole cos (tyConRolesX r tc) rs
1154 ; return (rk, mkTyConApp tc ss, mkTyConApp tc ts, r) }
1155
1156 lintCoercion co@(AppCo co1 co2)
1157 = do { (k1,s1,t1,r1) <- lintCoercion co1
1158 ; (k2,s2,t2,r2) <- lintCoercion co2
1159 ; rk <- lint_co_app co k1 [(s2,k2)]
1160 ; if r1 == Phantom
1161 then checkL (r2 == Phantom || r2 == Nominal)
1162 (ptext (sLit "Second argument in AppCo cannot be R:") $$
1163 ppr co)
1164 else checkRole co Nominal r2
1165 ; return (rk, mkAppTy s1 s2, mkAppTy t1 t2, r1) }
1166
1167 lintCoercion (ForAllCo tv co)
1168 = do { lintTyBndrKind tv
1169 ; (k, s, t, r) <- addInScopeVar tv (lintCoercion co)
1170 ; return (k, mkForAllTy tv s, mkForAllTy tv t, r) }
1171
1172 lintCoercion (CoVarCo cv)
1173 | not (isCoVar cv)
1174 = failWithL (hang (ptext (sLit "Bad CoVarCo:") <+> ppr cv)
1175 2 (ptext (sLit "With offending type:") <+> ppr (varType cv)))
1176 | otherwise
1177 = do { checkTyCoVarInScope cv
1178 ; cv' <- lookupIdInScope cv
1179 ; let (s,t) = coVarKind cv'
1180 k = typeKind s
1181 r = coVarRole cv'
1182 ; when (isSuperKind k) $
1183 do { checkL (r == Nominal) (hang (ptext (sLit "Non-nominal kind equality"))
1184 2 (ppr cv))
1185 ; checkL (s `eqKind` t) (hang (ptext (sLit "Non-refl kind equality"))
1186 2 (ppr cv)) }
1187 ; return (k, s, t, r) }
1188
1189 -- See Note [Bad unsafe coercion]
1190 lintCoercion (UnivCo _prov r ty1 ty2)
1191 = do { k1 <- lintType ty1
1192 ; k2 <- lintType ty2
1193 -- ; unless (k1 `eqKind` k2) $
1194 -- failWithL (hang (ptext (sLit "Unsafe coercion changes kind"))
1195 -- 2 (ppr co))
1196 ; when (r /= Phantom && isSubOpenTypeKind k1 && isSubOpenTypeKind k2)
1197 (checkTypes ty1 ty2)
1198 ; return (k1, ty1, ty2, r) }
1199 where
1200 report s = hang (text $ "Unsafe coercion between " ++ s)
1201 2 (vcat [ text "From:" <+> ppr ty1
1202 , text " To:" <+> ppr ty2])
1203 isUnBoxed :: PrimRep -> Bool
1204 isUnBoxed PtrRep = False
1205 isUnBoxed _ = True
1206 checkTypes t1 t2
1207 = case (repType t1, repType t2) of
1208 (UnaryRep _, UnaryRep _) ->
1209 validateCoercion (typePrimRep t1)
1210 (typePrimRep t2)
1211 (UbxTupleRep rep1, UbxTupleRep rep2) -> do
1212 checkWarnL (length rep1 == length rep2)
1213 (report "unboxed tuples of different length")
1214 zipWithM_ checkTypes rep1 rep2
1215 _ -> addWarnL (report "unboxed tuple and ordinary type")
1216 validateCoercion :: PrimRep -> PrimRep -> LintM ()
1217 validateCoercion rep1 rep2
1218 = do { dflags <- getDynFlags
1219 ; checkWarnL (isUnBoxed rep1 == isUnBoxed rep2)
1220 (report "unboxed and boxed value")
1221 ; checkWarnL (TyCon.primRepSizeW dflags rep1
1222 == TyCon.primRepSizeW dflags rep2)
1223 (report "unboxed values of different size")
1224 ; let fl = liftM2 (==) (TyCon.primRepIsFloat rep1)
1225 (TyCon.primRepIsFloat rep2)
1226 ; case fl of
1227 Nothing -> addWarnL (report "vector types")
1228 Just False -> addWarnL (report "float and integral values")
1229 _ -> return ()
1230 }
1231
1232 lintCoercion (SymCo co)
1233 = do { (k, ty1, ty2, r) <- lintCoercion co
1234 ; return (k, ty2, ty1, r) }
1235
1236 lintCoercion co@(TransCo co1 co2)
1237 = do { (k1, ty1a, ty1b, r1) <- lintCoercion co1
1238 ; (_, ty2a, ty2b, r2) <- lintCoercion co2
1239 ; checkL (ty1b `eqType` ty2a)
1240 (hang (ptext (sLit "Trans coercion mis-match:") <+> ppr co)
1241 2 (vcat [ppr ty1a, ppr ty1b, ppr ty2a, ppr ty2b]))
1242 ; checkRole co r1 r2
1243 ; return (k1, ty1a, ty2b, r1) }
1244
1245 lintCoercion the_co@(NthCo n co)
1246 = do { (_,s,t,r) <- lintCoercion co
1247 ; case (splitTyConApp_maybe s, splitTyConApp_maybe t) of
1248 (Just (tc_s, tys_s), Just (tc_t, tys_t))
1249 | tc_s == tc_t
1250 , tys_s `equalLength` tys_t
1251 , n < length tys_s
1252 -> return (ks, ts, tt, tr)
1253 where
1254 ts = getNth tys_s n
1255 tt = getNth tys_t n
1256 tr = nthRole r tc_s n
1257 ks = typeKind ts
1258
1259 _ -> failWithL (hang (ptext (sLit "Bad getNth:"))
1260 2 (ppr the_co $$ ppr s $$ ppr t)) }
1261
1262 lintCoercion the_co@(LRCo lr co)
1263 = do { (_,s,t,r) <- lintCoercion co
1264 ; checkRole co Nominal r
1265 ; case (splitAppTy_maybe s, splitAppTy_maybe t) of
1266 (Just s_pr, Just t_pr)
1267 -> return (k, s_pick, t_pick, Nominal)
1268 where
1269 s_pick = pickLR lr s_pr
1270 t_pick = pickLR lr t_pr
1271 k = typeKind s_pick
1272
1273 _ -> failWithL (hang (ptext (sLit "Bad LRCo:"))
1274 2 (ppr the_co $$ ppr s $$ ppr t)) }
1275
1276 lintCoercion (InstCo co arg_ty)
1277 = do { (k,s,t,r) <- lintCoercion co
1278 ; arg_kind <- lintType arg_ty
1279 ; case (splitForAllTy_maybe s, splitForAllTy_maybe t) of
1280 (Just (tv1,ty1), Just (tv2,ty2))
1281 | arg_kind `isSubKind` tyVarKind tv1
1282 -> return (k, substTyWith [tv1] [arg_ty] ty1,
1283 substTyWith [tv2] [arg_ty] ty2, r)
1284 | otherwise
1285 -> failWithL (ptext (sLit "Kind mis-match in inst coercion"))
1286 _ -> failWithL (ptext (sLit "Bad argument of inst")) }
1287
1288 lintCoercion co@(AxiomInstCo con ind cos)
1289 = do { unless (0 <= ind && ind < brListLength (coAxiomBranches con))
1290 (bad_ax (ptext (sLit "index out of range")))
1291 -- See Note [Kind instantiation in coercions]
1292 ; let CoAxBranch { cab_tvs = ktvs
1293 , cab_roles = roles
1294 , cab_lhs = lhs
1295 , cab_rhs = rhs } = coAxiomNthBranch con ind
1296 ; unless (equalLength ktvs cos) (bad_ax (ptext (sLit "lengths")))
1297 ; in_scope <- getInScope
1298 ; let empty_subst = mkTvSubst in_scope emptyTvSubstEnv
1299 ; (subst_l, subst_r) <- foldlM check_ki
1300 (empty_subst, empty_subst)
1301 (zip3 ktvs roles cos)
1302 ; let lhs' = Type.substTys subst_l lhs
1303 rhs' = Type.substTy subst_r rhs
1304 ; case checkAxInstCo co of
1305 Just bad_branch -> bad_ax $ ptext (sLit "inconsistent with") <+> (pprCoAxBranch (coAxiomTyCon con) bad_branch)
1306 Nothing -> return ()
1307 ; return (typeKind rhs', mkTyConApp (coAxiomTyCon con) lhs', rhs', coAxiomRole con) }
1308 where
1309 bad_ax what = addErrL (hang (ptext (sLit "Bad axiom application") <+> parens what)
1310 2 (ppr co))
1311
1312 check_ki (subst_l, subst_r) (ktv, role, co)
1313 = do { (k, t1, t2, r) <- lintCoercion co
1314 ; checkRole co role r
1315 ; let ktv_kind = Type.substTy subst_l (tyVarKind ktv)
1316 -- Using subst_l is ok, because subst_l and subst_r
1317 -- must agree on kind equalities
1318 ; unless (k `isSubKind` ktv_kind)
1319 (bad_ax (ptext (sLit "check_ki2") <+> vcat [ ppr co, ppr k, ppr ktv, ppr ktv_kind ] ))
1320 ; return (Type.extendTvSubst subst_l ktv t1,
1321 Type.extendTvSubst subst_r ktv t2) }
1322
1323 lintCoercion co@(SubCo co')
1324 = do { (k,s,t,r) <- lintCoercion co'
1325 ; checkRole co Nominal r
1326 ; return (k,s,t,Representational) }
1327
1328
1329 lintCoercion this@(AxiomRuleCo co ts cs)
1330 = do _ks <- mapM lintType ts
1331 eqs <- mapM lintCoercion cs
1332
1333 let tyNum = length ts
1334
1335 case compare (coaxrTypeArity co) tyNum of
1336 EQ -> return ()
1337 LT -> err "Too many type arguments"
1338 [ txt "expected" <+> int (coaxrTypeArity co)
1339 , txt "provided" <+> int tyNum ]
1340 GT -> err "Not enough type arguments"
1341 [ txt "expected" <+> int (coaxrTypeArity co)
1342 , txt "provided" <+> int tyNum ]
1343 checkRoles 0 (coaxrAsmpRoles co) eqs
1344
1345 case coaxrProves co ts [ Pair l r | (_,l,r,_) <- eqs ] of
1346 Nothing -> err "Malformed use of AxiomRuleCo" [ ppr this ]
1347 Just (Pair l r) ->
1348 do kL <- lintType l
1349 kR <- lintType r
1350 unless (eqKind kL kR)
1351 $ err "Kind error in CoAxiomRule"
1352 [ppr kL <+> txt "/=" <+> ppr kR]
1353 return (kL, l, r, coaxrRole co)
1354 where
1355 txt = ptext . sLit
1356 err m xs = failWithL $
1357 hang (txt m) 2 $ vcat (txt "Rule:" <+> ppr (coaxrName co) : xs)
1358
1359 checkRoles n (e : es) ((_,_,_,r) : rs)
1360 | e == r = checkRoles (n+1) es rs
1361 | otherwise = err "Argument roles mismatch"
1362 [ txt "In argument:" <+> int (n+1)
1363 , txt "Expected:" <+> ppr e
1364 , txt "Found:" <+> ppr r ]
1365 checkRoles _ [] [] = return ()
1366 checkRoles n [] rs = err "Too many coercion arguments"
1367 [ txt "Expected:" <+> int n
1368 , txt "Provided:" <+> int (n + length rs) ]
1369
1370 checkRoles n es [] = err "Not enough coercion arguments"
1371 [ txt "Expected:" <+> int (n + length es)
1372 , txt "Provided:" <+> int n ]
1373
1374 {-
1375 ************************************************************************
1376 * *
1377 \subsection[lint-monad]{The Lint monad}
1378 * *
1379 ************************************************************************
1380 -}
1381
1382 -- If you edit this type, you may need to update the GHC formalism
1383 -- See Note [GHC Formalism]
1384 data LintEnv
1385 = LE { le_flags :: LintFlags -- Linting the result of this pass
1386 , le_loc :: [LintLocInfo] -- Locations
1387 , le_subst :: TvSubst -- Current type substitution; we also use this
1388 -- to keep track of all the variables in scope,
1389 -- both Ids and TyVars
1390 , le_dynflags :: DynFlags -- DynamicFlags
1391 }
1392
1393 data LintFlags
1394 = LF { lf_check_global_ids :: Bool -- See Note [Checking for global Ids]
1395 , lf_check_inline_loop_breakers :: Bool -- See Note [Checking for INLINE loop breakers]
1396 }
1397
1398 defaultLintFlags :: LintFlags
1399 defaultLintFlags = LF { lf_check_global_ids = False
1400 , lf_check_inline_loop_breakers = True }
1401
1402 newtype LintM a =
1403 LintM { unLintM ::
1404 LintEnv ->
1405 WarnsAndErrs -> -- Error and warning messages so far
1406 (Maybe a, WarnsAndErrs) } -- Result and messages (if any)
1407
1408 type WarnsAndErrs = (Bag MsgDoc, Bag MsgDoc)
1409
1410 {- Note [Checking for global Ids]
1411 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1412 Before CoreTidy, all locally-bound Ids must be LocalIds, even
1413 top-level ones. See Note [Exported LocalIds] and Trac #9857.
1414
1415 Note [Type substitution]
1416 ~~~~~~~~~~~~~~~~~~~~~~~~
1417 Why do we need a type substitution? Consider
1418 /\(a:*). \(x:a). /\(a:*). id a x
1419 This is ill typed, because (renaming variables) it is really
1420 /\(a:*). \(x:a). /\(b:*). id b x
1421 Hence, when checking an application, we can't naively compare x's type
1422 (at its binding site) with its expected type (at a use site). So we
1423 rename type binders as we go, maintaining a substitution.
1424
1425 The same substitution also supports let-type, current expressed as
1426 (/\(a:*). body) ty
1427 Here we substitute 'ty' for 'a' in 'body', on the fly.
1428 -}
1429
1430 instance Functor LintM where
1431 fmap = liftM
1432
1433 instance Applicative LintM where
1434 pure = return
1435 (<*>) = ap
1436
1437 instance Monad LintM where
1438 return x = LintM (\ _ errs -> (Just x, errs))
1439 fail err = failWithL (text err)
1440 m >>= k = LintM (\ env errs ->
1441 let (res, errs') = unLintM m env errs in
1442 case res of
1443 Just r -> unLintM (k r) env errs'
1444 Nothing -> (Nothing, errs'))
1445
1446 instance HasDynFlags LintM where
1447 getDynFlags = LintM (\ e errs -> (Just (le_dynflags e), errs))
1448
1449 data LintLocInfo
1450 = RhsOf Id -- The variable bound
1451 | LambdaBodyOf Id -- The lambda-binder
1452 | BodyOfLetRec [Id] -- One of the binders
1453 | CaseAlt CoreAlt -- Case alternative
1454 | CasePat CoreAlt -- The *pattern* of the case alternative
1455 | AnExpr CoreExpr -- Some expression
1456 | ImportedUnfolding SrcLoc -- Some imported unfolding (ToDo: say which)
1457 | TopLevelBindings
1458 | InType Type -- Inside a type
1459 | InCo Coercion -- Inside a coercion
1460
1461 initL :: DynFlags -> LintFlags -> LintM a -> WarnsAndErrs -- Errors and warnings
1462 initL dflags flags m
1463 = case unLintM m env (emptyBag, emptyBag) of
1464 (_, errs) -> errs
1465 where
1466 env = LE { le_flags = flags, le_subst = emptyTvSubst, le_loc = [], le_dynflags = dflags }
1467
1468 getLintFlags :: LintM LintFlags
1469 getLintFlags = LintM $ \ env errs -> (Just (le_flags env), errs)
1470
1471 checkL :: Bool -> MsgDoc -> LintM ()
1472 checkL True _ = return ()
1473 checkL False msg = failWithL msg
1474
1475 checkWarnL :: Bool -> MsgDoc -> LintM ()
1476 checkWarnL True _ = return ()
1477 checkWarnL False msg = addWarnL msg
1478
1479 failWithL :: MsgDoc -> LintM a
1480 failWithL msg = LintM $ \ env (warns,errs) ->
1481 (Nothing, (warns, addMsg env errs msg))
1482
1483 addErrL :: MsgDoc -> LintM ()
1484 addErrL msg = LintM $ \ env (warns,errs) ->
1485 (Just (), (warns, addMsg env errs msg))
1486
1487 addWarnL :: MsgDoc -> LintM ()
1488 addWarnL msg = LintM $ \ env (warns,errs) ->
1489 (Just (), (addMsg env warns msg, errs))
1490
1491 addMsg :: LintEnv -> Bag MsgDoc -> MsgDoc -> Bag MsgDoc
1492 addMsg env msgs msg
1493 = ASSERT( notNull locs )
1494 msgs `snocBag` mk_msg msg
1495 where
1496 locs = le_loc env
1497 (loc, cxt1) = dumpLoc (head locs)
1498 cxts = [snd (dumpLoc loc) | loc <- locs]
1499 context | opt_PprStyle_Debug = vcat (reverse cxts) $$ cxt1 $$
1500 ptext (sLit "Substitution:") <+> ppr (le_subst env)
1501 | otherwise = cxt1
1502
1503 mk_msg msg = mkLocMessage SevWarning (mkSrcSpan loc loc) (context $$ msg)
1504
1505 addLoc :: LintLocInfo -> LintM a -> LintM a
1506 addLoc extra_loc m
1507 = LintM $ \ env errs ->
1508 unLintM m (env { le_loc = extra_loc : le_loc env }) errs
1509
1510 inCasePat :: LintM Bool -- A slight hack; see the unique call site
1511 inCasePat = LintM $ \ env errs -> (Just (is_case_pat env), errs)
1512 where
1513 is_case_pat (LE { le_loc = CasePat {} : _ }) = True
1514 is_case_pat _other = False
1515
1516 addInScopeVars :: [Var] -> LintM a -> LintM a
1517 addInScopeVars vars m
1518 = LintM $ \ env errs ->
1519 unLintM m (env { le_subst = extendTvInScopeList (le_subst env) vars })
1520 errs
1521
1522 addInScopeVar :: Var -> LintM a -> LintM a
1523 addInScopeVar var m
1524 = LintM $ \ env errs ->
1525 unLintM m (env { le_subst = extendTvInScope (le_subst env) var }) errs
1526
1527 extendSubstL :: TyVar -> Type -> LintM a -> LintM a
1528 extendSubstL tv ty m
1529 = LintM $ \ env errs ->
1530 unLintM m (env { le_subst = Type.extendTvSubst (le_subst env) tv ty }) errs
1531
1532 updateTvSubst :: TvSubst -> LintM a -> LintM a
1533 updateTvSubst subst' m
1534 = LintM $ \ env errs -> unLintM m (env { le_subst = subst' }) errs
1535
1536 getTvSubst :: LintM TvSubst
1537 getTvSubst = LintM (\ env errs -> (Just (le_subst env), errs))
1538
1539 getInScope :: LintM InScopeSet
1540 getInScope = LintM (\ env errs -> (Just (getTvInScope (le_subst env)), errs))
1541
1542 applySubstTy :: InType -> LintM OutType
1543 applySubstTy ty = do { subst <- getTvSubst; return (Type.substTy subst ty) }
1544
1545 applySubstCo :: InCoercion -> LintM OutCoercion
1546 applySubstCo co = do { subst <- getTvSubst; return (substCo (tvCvSubst subst) co) }
1547
1548 lookupIdInScope :: Id -> LintM Id
1549 lookupIdInScope id
1550 | not (mustHaveLocalBinding id)
1551 = return id -- An imported Id
1552 | otherwise
1553 = do { subst <- getTvSubst
1554 ; case lookupInScope (getTvInScope subst) id of
1555 Just v -> return v
1556 Nothing -> do { addErrL out_of_scope
1557 ; return id } }
1558 where
1559 out_of_scope = pprBndr LetBind id <+> ptext (sLit "is out of scope")
1560
1561
1562 oneTupleDataConId :: Id -- Should not happen
1563 oneTupleDataConId = dataConWorkId (tupleCon BoxedTuple 1)
1564
1565 checkBndrIdInScope :: Var -> Var -> LintM ()
1566 checkBndrIdInScope binder id
1567 = checkInScope msg id
1568 where
1569 msg = ptext (sLit "is out of scope inside info for") <+>
1570 ppr binder
1571
1572 checkTyCoVarInScope :: Var -> LintM ()
1573 checkTyCoVarInScope v = checkInScope (ptext (sLit "is out of scope")) v
1574
1575 checkInScope :: SDoc -> Var -> LintM ()
1576 checkInScope loc_msg var =
1577 do { subst <- getTvSubst
1578 ; checkL (not (mustHaveLocalBinding var) || (var `isInScope` subst))
1579 (hsep [pprBndr LetBind var, loc_msg]) }
1580
1581 checkTys :: OutType -> OutType -> MsgDoc -> LintM ()
1582 -- check ty2 is subtype of ty1 (ie, has same structure but usage
1583 -- annotations need only be consistent, not equal)
1584 -- Assumes ty1,ty2 are have alrady had the substitution applied
1585 checkTys ty1 ty2 msg = checkL (ty1 `eqType` ty2) msg
1586
1587 checkRole :: Coercion
1588 -> Role -- expected
1589 -> Role -- actual
1590 -> LintM ()
1591 checkRole co r1 r2
1592 = checkL (r1 == r2)
1593 (ptext (sLit "Role incompatibility: expected") <+> ppr r1 <> comma <+>
1594 ptext (sLit "got") <+> ppr r2 $$
1595 ptext (sLit "in") <+> ppr co)
1596
1597 {-
1598 ************************************************************************
1599 * *
1600 \subsection{Error messages}
1601 * *
1602 ************************************************************************
1603 -}
1604
1605 dumpLoc :: LintLocInfo -> (SrcLoc, SDoc)
1606
1607 dumpLoc (RhsOf v)
1608 = (getSrcLoc v, brackets (ptext (sLit "RHS of") <+> pp_binders [v]))
1609
1610 dumpLoc (LambdaBodyOf b)
1611 = (getSrcLoc b, brackets (ptext (sLit "in body of lambda with binder") <+> pp_binder b))
1612
1613 dumpLoc (BodyOfLetRec [])
1614 = (noSrcLoc, brackets (ptext (sLit "In body of a letrec with no binders")))
1615
1616 dumpLoc (BodyOfLetRec bs@(_:_))
1617 = ( getSrcLoc (head bs), brackets (ptext (sLit "in body of letrec with binders") <+> pp_binders bs))
1618
1619 dumpLoc (AnExpr e)
1620 = (noSrcLoc, text "In the expression:" <+> ppr e)
1621
1622 dumpLoc (CaseAlt (con, args, _))
1623 = (noSrcLoc, text "In a case alternative:" <+> parens (ppr con <+> pp_binders args))
1624
1625 dumpLoc (CasePat (con, args, _))
1626 = (noSrcLoc, text "In the pattern of a case alternative:" <+> parens (ppr con <+> pp_binders args))
1627
1628 dumpLoc (ImportedUnfolding locn)
1629 = (locn, brackets (ptext (sLit "in an imported unfolding")))
1630 dumpLoc TopLevelBindings
1631 = (noSrcLoc, Outputable.empty)
1632 dumpLoc (InType ty)
1633 = (noSrcLoc, text "In the type" <+> quotes (ppr ty))
1634 dumpLoc (InCo co)
1635 = (noSrcLoc, text "In the coercion" <+> quotes (ppr co))
1636
1637 pp_binders :: [Var] -> SDoc
1638 pp_binders bs = sep (punctuate comma (map pp_binder bs))
1639
1640 pp_binder :: Var -> SDoc
1641 pp_binder b | isId b = hsep [ppr b, dcolon, ppr (idType b)]
1642 | otherwise = hsep [ppr b, dcolon, ppr (tyVarKind b)]
1643
1644 ------------------------------------------------------
1645 -- Messages for case expressions
1646
1647 mkDefaultArgsMsg :: [Var] -> MsgDoc
1648 mkDefaultArgsMsg args
1649 = hang (text "DEFAULT case with binders")
1650 4 (ppr args)
1651
1652 mkCaseAltMsg :: CoreExpr -> Type -> Type -> MsgDoc
1653 mkCaseAltMsg e ty1 ty2
1654 = hang (text "Type of case alternatives not the same as the annotation on case:")
1655 4 (vcat [ppr ty1, ppr ty2, ppr e])
1656
1657 mkScrutMsg :: Id -> Type -> Type -> TvSubst -> MsgDoc
1658 mkScrutMsg var var_ty scrut_ty subst
1659 = vcat [text "Result binder in case doesn't match scrutinee:" <+> ppr var,
1660 text "Result binder type:" <+> ppr var_ty,--(idType var),
1661 text "Scrutinee type:" <+> ppr scrut_ty,
1662 hsep [ptext (sLit "Current TV subst"), ppr subst]]
1663
1664 mkNonDefltMsg, mkNonIncreasingAltsMsg :: CoreExpr -> MsgDoc
1665 mkNonDefltMsg e
1666 = hang (text "Case expression with DEFAULT not at the beginnning") 4 (ppr e)
1667 mkNonIncreasingAltsMsg e
1668 = hang (text "Case expression with badly-ordered alternatives") 4 (ppr e)
1669
1670 nonExhaustiveAltsMsg :: CoreExpr -> MsgDoc
1671 nonExhaustiveAltsMsg e
1672 = hang (text "Case expression with non-exhaustive alternatives") 4 (ppr e)
1673
1674 mkBadConMsg :: TyCon -> DataCon -> MsgDoc
1675 mkBadConMsg tycon datacon
1676 = vcat [
1677 text "In a case alternative, data constructor isn't in scrutinee type:",
1678 text "Scrutinee type constructor:" <+> ppr tycon,
1679 text "Data con:" <+> ppr datacon
1680 ]
1681
1682 mkBadPatMsg :: Type -> Type -> MsgDoc
1683 mkBadPatMsg con_result_ty scrut_ty
1684 = vcat [
1685 text "In a case alternative, pattern result type doesn't match scrutinee type:",
1686 text "Pattern result type:" <+> ppr con_result_ty,
1687 text "Scrutinee type:" <+> ppr scrut_ty
1688 ]
1689
1690 integerScrutinisedMsg :: MsgDoc
1691 integerScrutinisedMsg
1692 = text "In a LitAlt, the literal is lifted (probably Integer)"
1693
1694 mkBadAltMsg :: Type -> CoreAlt -> MsgDoc
1695 mkBadAltMsg scrut_ty alt
1696 = vcat [ text "Data alternative when scrutinee is not a tycon application",
1697 text "Scrutinee type:" <+> ppr scrut_ty,
1698 text "Alternative:" <+> pprCoreAlt alt ]
1699
1700 mkNewTyDataConAltMsg :: Type -> CoreAlt -> MsgDoc
1701 mkNewTyDataConAltMsg scrut_ty alt
1702 = vcat [ text "Data alternative for newtype datacon",
1703 text "Scrutinee type:" <+> ppr scrut_ty,
1704 text "Alternative:" <+> pprCoreAlt alt ]
1705
1706
1707 ------------------------------------------------------
1708 -- Other error messages
1709
1710 mkAppMsg :: Type -> Type -> CoreExpr -> MsgDoc
1711 mkAppMsg fun_ty arg_ty arg
1712 = vcat [ptext (sLit "Argument value doesn't match argument type:"),
1713 hang (ptext (sLit "Fun type:")) 4 (ppr fun_ty),
1714 hang (ptext (sLit "Arg type:")) 4 (ppr arg_ty),
1715 hang (ptext (sLit "Arg:")) 4 (ppr arg)]
1716
1717 mkNonFunAppMsg :: Type -> Type -> CoreExpr -> MsgDoc
1718 mkNonFunAppMsg fun_ty arg_ty arg
1719 = vcat [ptext (sLit "Non-function type in function position"),
1720 hang (ptext (sLit "Fun type:")) 4 (ppr fun_ty),
1721 hang (ptext (sLit "Arg type:")) 4 (ppr arg_ty),
1722 hang (ptext (sLit "Arg:")) 4 (ppr arg)]
1723
1724 mkLetErr :: TyVar -> CoreExpr -> MsgDoc
1725 mkLetErr bndr rhs
1726 = vcat [ptext (sLit "Bad `let' binding:"),
1727 hang (ptext (sLit "Variable:"))
1728 4 (ppr bndr <+> dcolon <+> ppr (varType bndr)),
1729 hang (ptext (sLit "Rhs:"))
1730 4 (ppr rhs)]
1731
1732 mkTyAppMsg :: Type -> Type -> MsgDoc
1733 mkTyAppMsg ty arg_ty
1734 = vcat [text "Illegal type application:",
1735 hang (ptext (sLit "Exp type:"))
1736 4 (ppr ty <+> dcolon <+> ppr (typeKind ty)),
1737 hang (ptext (sLit "Arg type:"))
1738 4 (ppr arg_ty <+> dcolon <+> ppr (typeKind arg_ty))]
1739
1740 mkRhsMsg :: Id -> SDoc -> Type -> MsgDoc
1741 mkRhsMsg binder what ty
1742 = vcat
1743 [hsep [ptext (sLit "The type of this binder doesn't match the type of its") <+> what <> colon,
1744 ppr binder],
1745 hsep [ptext (sLit "Binder's type:"), ppr (idType binder)],
1746 hsep [ptext (sLit "Rhs type:"), ppr ty]]
1747
1748 mkLetAppMsg :: CoreExpr -> MsgDoc
1749 mkLetAppMsg e
1750 = hang (ptext (sLit "This argument does not satisfy the let/app invariant:"))
1751 2 (ppr e)
1752
1753 mkRhsPrimMsg :: Id -> CoreExpr -> MsgDoc
1754 mkRhsPrimMsg binder _rhs
1755 = vcat [hsep [ptext (sLit "The type of this binder is primitive:"),
1756 ppr binder],
1757 hsep [ptext (sLit "Binder's type:"), ppr (idType binder)]
1758 ]
1759
1760 mkStrictMsg :: Id -> MsgDoc
1761 mkStrictMsg binder
1762 = vcat [hsep [ptext (sLit "Recursive or top-level binder has strict demand info:"),
1763 ppr binder],
1764 hsep [ptext (sLit "Binder's demand info:"), ppr (idDemandInfo binder)]
1765 ]
1766
1767 mkNonTopExportedMsg :: Id -> MsgDoc
1768 mkNonTopExportedMsg binder
1769 = hsep [ptext (sLit "Non-top-level binder is marked as exported:"), ppr binder]
1770
1771 mkNonTopExternalNameMsg :: Id -> MsgDoc
1772 mkNonTopExternalNameMsg binder
1773 = hsep [ptext (sLit "Non-top-level binder has an external name:"), ppr binder]
1774
1775 mkKindErrMsg :: TyVar -> Type -> MsgDoc
1776 mkKindErrMsg tyvar arg_ty
1777 = vcat [ptext (sLit "Kinds don't match in type application:"),
1778 hang (ptext (sLit "Type variable:"))
1779 4 (ppr tyvar <+> dcolon <+> ppr (tyVarKind tyvar)),
1780 hang (ptext (sLit "Arg type:"))
1781 4 (ppr arg_ty <+> dcolon <+> ppr (typeKind arg_ty))]
1782
1783 {- Not needed now
1784 mkArityMsg :: Id -> MsgDoc
1785 mkArityMsg binder
1786 = vcat [hsep [ptext (sLit "Demand type has"),
1787 ppr (dmdTypeDepth dmd_ty),
1788 ptext (sLit "arguments, rhs has"),
1789 ppr (idArity binder),
1790 ptext (sLit "arguments,"),
1791 ppr binder],
1792 hsep [ptext (sLit "Binder's strictness signature:"), ppr dmd_ty]
1793
1794 ]
1795 where (StrictSig dmd_ty) = idStrictness binder
1796 -}
1797 mkCastErr :: CoreExpr -> Coercion -> Type -> Type -> MsgDoc
1798 mkCastErr expr co from_ty expr_ty
1799 = vcat [ptext (sLit "From-type of Cast differs from type of enclosed expression"),
1800 ptext (sLit "From-type:") <+> ppr from_ty,
1801 ptext (sLit "Type of enclosed expr:") <+> ppr expr_ty,
1802 ptext (sLit "Actual enclosed expr:") <+> ppr expr,
1803 ptext (sLit "Coercion used in cast:") <+> ppr co
1804 ]
1805
1806 dupVars :: [[Var]] -> MsgDoc
1807 dupVars vars
1808 = hang (ptext (sLit "Duplicate variables brought into scope"))
1809 2 (ppr vars)
1810
1811 dupExtVars :: [[Name]] -> MsgDoc
1812 dupExtVars vars
1813 = hang (ptext (sLit "Duplicate top-level variables with the same qualified name"))
1814 2 (ppr vars)
1815
1816 {-
1817 ************************************************************************
1818 * *
1819 \subsection{Annotation Linting}
1820 * *
1821 ************************************************************************
1822 -}
1823
1824 -- | This checks whether a pass correctly looks through debug
1825 -- annotations (@SourceNote@). This works a bit different from other
1826 -- consistency checks: We check this by running the given task twice,
1827 -- noting all differences between the results.
1828 lintAnnots :: SDoc -> (ModGuts -> CoreM ModGuts) -> ModGuts -> CoreM ModGuts
1829 lintAnnots pname pass guts = do
1830 -- Run the pass as we normally would
1831 dflags <- getDynFlags
1832 when (gopt Opt_DoAnnotationLinting dflags) $
1833 liftIO $ Err.showPass dflags "Annotation linting - first run"
1834 nguts <- pass guts
1835 -- If appropriate re-run it without debug annotations to make sure
1836 -- that they made no difference.
1837 when (gopt Opt_DoAnnotationLinting dflags) $ do
1838 liftIO $ Err.showPass dflags "Annotation linting - second run"
1839 nguts' <- withoutAnnots pass guts
1840 -- Finally compare the resulting bindings
1841 liftIO $ Err.showPass dflags "Annotation linting - comparison"
1842 let binds = flattenBinds $ mg_binds nguts
1843 binds' = flattenBinds $ mg_binds nguts'
1844 (diffs,_) = diffBinds True (mkRnEnv2 emptyInScopeSet) binds binds'
1845 when (not (null diffs)) $ CoreMonad.putMsg $ vcat
1846 [ lint_banner "warning" pname
1847 , text "Core changes with annotations:"
1848 , withPprStyle defaultDumpStyle $ nest 2 $ vcat diffs
1849 ]
1850 -- Return actual new guts
1851 return nguts
1852
1853 -- | Run the given pass without annotations. This means that we both
1854 -- remove the @Opt_Debug@ flag from the environment as well as all
1855 -- annotations from incoming modules.
1856 withoutAnnots :: (ModGuts -> CoreM ModGuts) -> ModGuts -> CoreM ModGuts
1857 withoutAnnots pass guts = do
1858 -- Remove debug flag from environment.
1859 dflags <- getDynFlags
1860 let removeFlag env = env{hsc_dflags = gopt_unset dflags Opt_Debug}
1861 withoutFlag corem =
1862 liftIO =<< runCoreM <$> fmap removeFlag getHscEnv <*> getRuleBase <*>
1863 getUniqueSupplyM <*> getModule <*>
1864 getPrintUnqualified <*> pure corem
1865 -- Nuke existing ticks in module.
1866 -- TODO: Ticks in unfoldings. Maybe change unfolding so it removes
1867 -- them in absence of @Opt_Debug@?
1868 let nukeTicks = stripTicksE (not . tickishIsCode)
1869 nukeAnnotsBind :: CoreBind -> CoreBind
1870 nukeAnnotsBind bind = case bind of
1871 Rec bs -> Rec $ map (\(b,e) -> (b, nukeTicks e)) bs
1872 NonRec b e -> NonRec b $ nukeTicks e
1873 nukeAnnotsMod mg@ModGuts{mg_binds=binds}
1874 = mg{mg_binds = map nukeAnnotsBind binds}
1875 -- Perform pass with all changes applied
1876 fmap fst $ withoutFlag $ pass (nukeAnnotsMod guts)