New lint check: Check idArity invariants (#10181)
[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 ; when (null alts) $
661 do { checkL (not (exprIsHNF scrut))
662 (ptext (sLit "No alternatives for a case scrutinee in head-normal form:") <+> ppr scrut)
663 ; checkL (exprIsBottom scrut || isEmptyTy (exprType scrut))
664 (ptext (sLit "No alternatives for a case scrutinee not known to diverge for sure:") <+> ppr scrut)
665 }
666
667 ; case tyConAppTyCon_maybe (idType var) of
668 Just tycon
669 | debugIsOn &&
670 isAlgTyCon tycon &&
671 not (isFamilyTyCon tycon || isAbstractTyCon tycon) &&
672 null (tyConDataCons tycon) ->
673 pprTrace "Lint warning: case binder's type has no constructors" (ppr var <+> ppr (idType var))
674 -- This can legitimately happen for type families
675 $ return ()
676 _otherwise -> return ()
677
678 -- Don't use lintIdBndr on var, because unboxed tuple is legitimate
679
680 ; subst <- getTvSubst
681 ; checkTys var_ty scrut_ty (mkScrutMsg var var_ty scrut_ty subst)
682
683 ; lintAndScopeId var $ \_ ->
684 do { -- Check the alternatives
685 mapM_ (lintCoreAlt scrut_ty alt_ty) alts
686 ; checkCaseAlts e scrut_ty alts
687 ; return alt_ty } }
688
689 -- This case can't happen; linting types in expressions gets routed through
690 -- lintCoreArgs
691 lintCoreExpr (Type ty)
692 = pprPanic "lintCoreExpr" (ppr ty)
693
694 lintCoreExpr (Coercion co)
695 = do { (_kind, ty1, ty2, role) <- lintInCo co
696 ; return (mkCoercionType role ty1 ty2) }
697
698 {-
699 Note [Kind instantiation in coercions]
700 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
701 Consider the following coercion axiom:
702 ax_co [(k_ag :: BOX), (f_aa :: k_ag -> Constraint)] :: T k_ag f_aa ~ f_aa
703
704 Consider the following instantiation:
705 ax_co <* -> *> <Monad>
706
707 We need to split the co_ax_tvs into kind and type variables in order
708 to find out the coercion kind instantiations. Those can only be Refl
709 since we don't have kind coercions. This is just a way to represent
710 kind instantiation.
711
712 We use the number of kind variables to know how to split the coercions
713 instantiations between kind coercions and type coercions. We lint the
714 kind coercions and produce the following substitution which is to be
715 applied in the type variables:
716 k_ag ~~> * -> *
717
718 ************************************************************************
719 * *
720 \subsection[lintCoreArgs]{lintCoreArgs}
721 * *
722 ************************************************************************
723
724 The basic version of these functions checks that the argument is a
725 subtype of the required type, as one would expect.
726 -}
727
728 lintCoreArg :: OutType -> CoreArg -> LintM OutType
729 lintCoreArg fun_ty (Type arg_ty)
730 = do { arg_ty' <- applySubstTy arg_ty
731 ; lintTyApp fun_ty arg_ty' }
732
733 lintCoreArg fun_ty arg
734 = do { arg_ty <- lintCoreExpr arg
735 ; checkL (not (isUnLiftedType arg_ty) || exprOkForSpeculation arg)
736 (mkLetAppMsg arg)
737 ; lintValApp arg fun_ty arg_ty }
738
739 -----------------
740 lintAltBinders :: OutType -- Scrutinee type
741 -> OutType -- Constructor type
742 -> [OutVar] -- Binders
743 -> LintM ()
744 -- If you edit this function, you may need to update the GHC formalism
745 -- See Note [GHC Formalism]
746 lintAltBinders scrut_ty con_ty []
747 = checkTys con_ty scrut_ty (mkBadPatMsg con_ty scrut_ty)
748 lintAltBinders scrut_ty con_ty (bndr:bndrs)
749 | isTyVar bndr
750 = do { con_ty' <- lintTyApp con_ty (mkTyVarTy bndr)
751 ; lintAltBinders scrut_ty con_ty' bndrs }
752 | otherwise
753 = do { con_ty' <- lintValApp (Var bndr) con_ty (idType bndr)
754 ; lintAltBinders scrut_ty con_ty' bndrs }
755
756 -----------------
757 lintTyApp :: OutType -> OutType -> LintM OutType
758 lintTyApp fun_ty arg_ty
759 | Just (tyvar,body_ty) <- splitForAllTy_maybe fun_ty
760 , isTyVar tyvar
761 = do { checkTyKind tyvar arg_ty
762 ; return (substTyWith [tyvar] [arg_ty] body_ty) }
763
764 | otherwise
765 = failWithL (mkTyAppMsg fun_ty arg_ty)
766
767 -----------------
768 lintValApp :: CoreExpr -> OutType -> OutType -> LintM OutType
769 lintValApp arg fun_ty arg_ty
770 | Just (arg,res) <- splitFunTy_maybe fun_ty
771 = do { checkTys arg arg_ty err1
772 ; return res }
773 | otherwise
774 = failWithL err2
775 where
776 err1 = mkAppMsg fun_ty arg_ty arg
777 err2 = mkNonFunAppMsg fun_ty arg_ty arg
778
779 checkTyKind :: OutTyVar -> OutType -> LintM ()
780 -- Both args have had substitution applied
781
782 -- If you edit this function, you may need to update the GHC formalism
783 -- See Note [GHC Formalism]
784 checkTyKind tyvar arg_ty
785 | isSuperKind tyvar_kind -- kind forall
786 = lintKind arg_ty
787 -- Arg type might be boxed for a function with an uncommitted
788 -- tyvar; notably this is used so that we can give
789 -- error :: forall a:*. String -> a
790 -- and then apply it to both boxed and unboxed types.
791 | otherwise -- type forall
792 = do { arg_kind <- lintType arg_ty
793 ; unless (arg_kind `isSubKind` tyvar_kind)
794 (addErrL (mkKindErrMsg tyvar arg_ty $$ (text "xx" <+> ppr arg_kind))) }
795 where
796 tyvar_kind = tyVarKind tyvar
797
798 checkDeadIdOcc :: Id -> LintM ()
799 -- Occurrences of an Id should never be dead....
800 -- except when we are checking a case pattern
801 checkDeadIdOcc id
802 | isDeadOcc (idOccInfo id)
803 = do { in_case <- inCasePat
804 ; checkL in_case
805 (ptext (sLit "Occurrence of a dead Id") <+> ppr id) }
806 | otherwise
807 = return ()
808
809 {-
810 ************************************************************************
811 * *
812 \subsection[lintCoreAlts]{lintCoreAlts}
813 * *
814 ************************************************************************
815 -}
816
817 checkCaseAlts :: CoreExpr -> OutType -> [CoreAlt] -> LintM ()
818 -- a) Check that the alts are non-empty
819 -- b1) Check that the DEFAULT comes first, if it exists
820 -- b2) Check that the others are in increasing order
821 -- c) Check that there's a default for infinite types
822 -- NB: Algebraic cases are not necessarily exhaustive, because
823 -- the simplifer correctly eliminates case that can't
824 -- possibly match.
825
826 checkCaseAlts e ty alts =
827 do { checkL (all non_deflt con_alts) (mkNonDefltMsg e)
828 ; checkL (increasing_tag con_alts) (mkNonIncreasingAltsMsg e)
829
830 -- For types Int#, Word# with an infinite (well, large!) number of
831 -- possible values, there should usually be a DEFAULT case
832 -- But (see Note [Empty case alternatives] in CoreSyn) it's ok to
833 -- have *no* case alternatives.
834 -- In effect, this is a kind of partial test. I suppose it's possible
835 -- that we might *know* that 'x' was 1 or 2, in which case
836 -- case x of { 1 -> e1; 2 -> e2 }
837 -- would be fine.
838 ; checkL (isJust maybe_deflt || not is_infinite_ty || null alts)
839 (nonExhaustiveAltsMsg e) }
840 where
841 (con_alts, maybe_deflt) = findDefault alts
842
843 -- Check that successive alternatives have increasing tags
844 increasing_tag (alt1 : rest@( alt2 : _)) = alt1 `ltAlt` alt2 && increasing_tag rest
845 increasing_tag _ = True
846
847 non_deflt (DEFAULT, _, _) = False
848 non_deflt _ = True
849
850 is_infinite_ty = case tyConAppTyCon_maybe ty of
851 Nothing -> False
852 Just tycon -> isPrimTyCon tycon
853
854 checkAltExpr :: CoreExpr -> OutType -> LintM ()
855 checkAltExpr expr ann_ty
856 = do { actual_ty <- lintCoreExpr expr
857 ; checkTys actual_ty ann_ty (mkCaseAltMsg expr actual_ty ann_ty) }
858
859 lintCoreAlt :: OutType -- Type of scrutinee
860 -> OutType -- Type of the alternative
861 -> CoreAlt
862 -> LintM ()
863 -- If you edit this function, you may need to update the GHC formalism
864 -- See Note [GHC Formalism]
865 lintCoreAlt _ alt_ty (DEFAULT, args, rhs) =
866 do { checkL (null args) (mkDefaultArgsMsg args)
867 ; checkAltExpr rhs alt_ty }
868
869 lintCoreAlt scrut_ty alt_ty (LitAlt lit, args, rhs)
870 | litIsLifted lit
871 = failWithL integerScrutinisedMsg
872 | otherwise
873 = do { checkL (null args) (mkDefaultArgsMsg args)
874 ; checkTys lit_ty scrut_ty (mkBadPatMsg lit_ty scrut_ty)
875 ; checkAltExpr rhs alt_ty }
876 where
877 lit_ty = literalType lit
878
879 lintCoreAlt scrut_ty alt_ty alt@(DataAlt con, args, rhs)
880 | isNewTyCon (dataConTyCon con)
881 = addErrL (mkNewTyDataConAltMsg scrut_ty alt)
882 | Just (tycon, tycon_arg_tys) <- splitTyConApp_maybe scrut_ty
883 = addLoc (CaseAlt alt) $ do
884 { -- First instantiate the universally quantified
885 -- type variables of the data constructor
886 -- We've already check
887 checkL (tycon == dataConTyCon con) (mkBadConMsg tycon con)
888 ; let con_payload_ty = applyTys (dataConRepType con) tycon_arg_tys
889
890 -- And now bring the new binders into scope
891 ; lintBinders args $ \ args' -> do
892 { addLoc (CasePat alt) (lintAltBinders scrut_ty con_payload_ty args')
893 ; checkAltExpr rhs alt_ty } }
894
895 | otherwise -- Scrut-ty is wrong shape
896 = addErrL (mkBadAltMsg scrut_ty alt)
897
898 {-
899 ************************************************************************
900 * *
901 \subsection[lint-types]{Types}
902 * *
903 ************************************************************************
904 -}
905
906 -- When we lint binders, we (one at a time and in order):
907 -- 1. Lint var types or kinds (possibly substituting)
908 -- 2. Add the binder to the in scope set, and if its a coercion var,
909 -- we may extend the substitution to reflect its (possibly) new kind
910 lintBinders :: [Var] -> ([Var] -> LintM a) -> LintM a
911 lintBinders [] linterF = linterF []
912 lintBinders (var:vars) linterF = lintBinder var $ \var' ->
913 lintBinders vars $ \ vars' ->
914 linterF (var':vars')
915
916 -- If you edit this function, you may need to update the GHC formalism
917 -- See Note [GHC Formalism]
918 lintBinder :: Var -> (Var -> LintM a) -> LintM a
919 lintBinder var linterF
920 | isId var = lintIdBndr var linterF
921 | otherwise = lintTyBndr var linterF
922
923 lintTyBndr :: InTyVar -> (OutTyVar -> LintM a) -> LintM a
924 lintTyBndr tv thing_inside
925 = do { subst <- getTvSubst
926 ; let (subst', tv') = Type.substTyVarBndr subst tv
927 ; lintTyBndrKind tv'
928 ; updateTvSubst subst' (thing_inside tv') }
929
930 lintIdBndr :: Id -> (Id -> LintM a) -> LintM a
931 -- Do substitution on the type of a binder and add the var with this
932 -- new type to the in-scope set of the second argument
933 -- ToDo: lint its rules
934
935 lintIdBndr id linterF
936 = do { lintAndScopeId id $ \id' -> linterF id' }
937
938 lintAndScopeIds :: [Var] -> ([Var] -> LintM a) -> LintM a
939 lintAndScopeIds ids linterF
940 = go ids
941 where
942 go [] = linterF []
943 go (id:ids) = lintAndScopeId id $ \id ->
944 lintAndScopeIds ids $ \ids ->
945 linterF (id:ids)
946
947 lintAndScopeId :: InVar -> (OutVar -> LintM a) -> LintM a
948 lintAndScopeId id linterF
949 = do { flags <- getLintFlags
950 ; checkL (not (lf_check_global_ids flags) || isLocalId id)
951 (ptext (sLit "Non-local Id binder") <+> ppr id)
952 -- See Note [Checking for global Ids]
953 ; ty <- lintInTy (idType id)
954 ; let id' = setIdType id ty
955 ; addInScopeVar id' $ (linterF id') }
956
957 {-
958 ************************************************************************
959 * *
960 Types and kinds
961 * *
962 ************************************************************************
963
964 We have a single linter for types and kinds. That is convenient
965 because sometimes it's not clear whether the thing we are looking
966 at is a type or a kind.
967 -}
968
969 lintInTy :: InType -> LintM LintedType
970 -- Types only, not kinds
971 -- Check the type, and apply the substitution to it
972 -- See Note [Linting type lets]
973 lintInTy ty
974 = addLoc (InType ty) $
975 do { ty' <- applySubstTy ty
976 ; _k <- lintType ty'
977 ; return ty' }
978
979 -------------------
980 lintTyBndrKind :: OutTyVar -> LintM ()
981 -- Handles both type and kind foralls.
982 lintTyBndrKind tv = lintKind (tyVarKind tv)
983
984 -------------------
985 lintType :: OutType -> LintM LintedKind
986 -- The returned Kind has itself been linted
987
988 -- If you edit this function, you may need to update the GHC formalism
989 -- See Note [GHC Formalism]
990 lintType (TyVarTy tv)
991 = do { checkTyCoVarInScope tv
992 ; return (tyVarKind tv) }
993 -- We checked its kind when we added it to the envt
994
995 lintType ty@(AppTy t1 t2)
996 = do { k1 <- lintType t1
997 ; k2 <- lintType t2
998 ; lint_ty_app ty k1 [(t2,k2)] }
999
1000 lintType ty@(FunTy t1 t2) -- (->) has two different rules, for types and kinds
1001 = do { k1 <- lintType t1
1002 ; k2 <- lintType t2
1003 ; lintArrow (ptext (sLit "type or kind") <+> quotes (ppr ty)) k1 k2 }
1004
1005 lintType ty@(TyConApp tc tys)
1006 | Just ty' <- coreView ty
1007 = lintType ty' -- Expand type synonyms, so that we do not bogusly complain
1008 -- about un-saturated type synonyms
1009
1010 | isUnLiftedTyCon tc || isTypeSynonymTyCon tc || isTypeFamilyTyCon tc
1011 -- See Note [The kind invariant] in TypeRep
1012 -- Also type synonyms and type families
1013 , length tys < tyConArity tc
1014 = failWithL (hang (ptext (sLit "Un-saturated type application")) 2 (ppr ty))
1015
1016 | otherwise
1017 = do { ks <- mapM lintType tys
1018 ; lint_ty_app ty (tyConKind tc) (tys `zip` ks) }
1019
1020 lintType (ForAllTy tv ty)
1021 = do { lintTyBndrKind tv
1022 ; addInScopeVar tv (lintType ty) }
1023
1024 lintType ty@(LitTy l) = lintTyLit l >> return (typeKind ty)
1025
1026 lintKind :: OutKind -> LintM ()
1027 -- If you edit this function, you may need to update the GHC formalism
1028 -- See Note [GHC Formalism]
1029 lintKind k = do { sk <- lintType k
1030 ; unless (isSuperKind sk)
1031 (addErrL (hang (ptext (sLit "Ill-kinded kind:") <+> ppr k)
1032 2 (ptext (sLit "has kind:") <+> ppr sk))) }
1033
1034 lintArrow :: SDoc -> LintedKind -> LintedKind -> LintM LintedKind
1035 -- If you edit this function, you may need to update the GHC formalism
1036 -- See Note [GHC Formalism]
1037 lintArrow what k1 k2 -- Eg lintArrow "type or kind `blah'" k1 k2
1038 -- or lintarrow "coercion `blah'" k1 k2
1039 | isSuperKind k1
1040 = return superKind
1041 | otherwise
1042 = do { unless (okArrowArgKind k1) (addErrL (msg (ptext (sLit "argument")) k1))
1043 ; unless (okArrowResultKind k2) (addErrL (msg (ptext (sLit "result")) k2))
1044 ; return liftedTypeKind }
1045 where
1046 msg ar k
1047 = vcat [ hang (ptext (sLit "Ill-kinded") <+> ar)
1048 2 (ptext (sLit "in") <+> what)
1049 , what <+> ptext (sLit "kind:") <+> ppr k ]
1050
1051 lint_ty_app :: Type -> LintedKind -> [(LintedType,LintedKind)] -> LintM LintedKind
1052 lint_ty_app ty k tys
1053 = lint_app (ptext (sLit "type") <+> quotes (ppr ty)) k tys
1054
1055 ----------------
1056 lint_co_app :: Coercion -> LintedKind -> [(LintedType,LintedKind)] -> LintM LintedKind
1057 lint_co_app ty k tys
1058 = lint_app (ptext (sLit "coercion") <+> quotes (ppr ty)) k tys
1059
1060 ----------------
1061 lintTyLit :: TyLit -> LintM ()
1062 lintTyLit (NumTyLit n)
1063 | n >= 0 = return ()
1064 | otherwise = failWithL msg
1065 where msg = ptext (sLit "Negative type literal:") <+> integer n
1066 lintTyLit (StrTyLit _) = return ()
1067
1068 lint_app :: SDoc -> LintedKind -> [(LintedType,LintedKind)] -> LintM Kind
1069 -- (lint_app d fun_kind arg_tys)
1070 -- We have an application (f arg_ty1 .. arg_tyn),
1071 -- where f :: fun_kind
1072 -- Takes care of linting the OutTypes
1073
1074 -- If you edit this function, you may need to update the GHC formalism
1075 -- See Note [GHC Formalism]
1076 lint_app doc kfn kas
1077 = foldlM go_app kfn kas
1078 where
1079 fail_msg = vcat [ hang (ptext (sLit "Kind application error in")) 2 doc
1080 , nest 2 (ptext (sLit "Function kind =") <+> ppr kfn)
1081 , nest 2 (ptext (sLit "Arg kinds =") <+> ppr kas) ]
1082
1083 go_app kfn ka
1084 | Just kfn' <- coreView kfn
1085 = go_app kfn' ka
1086
1087 go_app (FunTy kfa kfb) (_,ka)
1088 = do { unless (ka `isSubKind` kfa) (addErrL fail_msg)
1089 ; return kfb }
1090
1091 go_app (ForAllTy kv kfn) (ta,ka)
1092 = do { unless (ka `isSubKind` tyVarKind kv) (addErrL fail_msg)
1093 ; return (substKiWith [kv] [ta] kfn) }
1094
1095 go_app _ _ = failWithL fail_msg
1096
1097 {-
1098 ************************************************************************
1099 * *
1100 Linting coercions
1101 * *
1102 ************************************************************************
1103 -}
1104
1105 lintInCo :: InCoercion -> LintM (LintedKind, LintedType, LintedType, Role)
1106 -- Check the coercion, and apply the substitution to it
1107 -- See Note [Linting type lets]
1108 lintInCo co
1109 = addLoc (InCo co) $
1110 do { co' <- applySubstCo co
1111 ; lintCoercion co' }
1112
1113 lintCoercion :: OutCoercion -> LintM (LintedKind, LintedType, LintedType, Role)
1114 -- Check the kind of a coercion term, returning the kind
1115 -- Post-condition: the returned OutTypes are lint-free
1116 -- and have the same kind as each other
1117
1118 -- If you edit this function, you may need to update the GHC formalism
1119 -- See Note [GHC Formalism]
1120 lintCoercion (Refl r ty)
1121 = do { k <- lintType ty
1122 ; return (k, ty, ty, r) }
1123
1124 lintCoercion co@(TyConAppCo r tc cos)
1125 | tc `hasKey` funTyConKey
1126 , [co1,co2] <- cos
1127 = do { (k1,s1,t1,r1) <- lintCoercion co1
1128 ; (k2,s2,t2,r2) <- lintCoercion co2
1129 ; rk <- lintArrow (ptext (sLit "coercion") <+> quotes (ppr co)) k1 k2
1130 ; checkRole co1 r r1
1131 ; checkRole co2 r r2
1132 ; return (rk, mkFunTy s1 s2, mkFunTy t1 t2, r) }
1133
1134 | Just {} <- synTyConDefn_maybe tc
1135 = failWithL (ptext (sLit "Synonym in TyConAppCo:") <+> ppr co)
1136
1137 | otherwise
1138 = do { (ks,ss,ts,rs) <- mapAndUnzip4M lintCoercion cos
1139 ; rk <- lint_co_app co (tyConKind tc) (ss `zip` ks)
1140 ; _ <- zipWith3M checkRole cos (tyConRolesX r tc) rs
1141 ; return (rk, mkTyConApp tc ss, mkTyConApp tc ts, r) }
1142
1143 lintCoercion co@(AppCo co1 co2)
1144 = do { (k1,s1,t1,r1) <- lintCoercion co1
1145 ; (k2,s2,t2,r2) <- lintCoercion co2
1146 ; rk <- lint_co_app co k1 [(s2,k2)]
1147 ; if r1 == Phantom
1148 then checkL (r2 == Phantom || r2 == Nominal)
1149 (ptext (sLit "Second argument in AppCo cannot be R:") $$
1150 ppr co)
1151 else checkRole co Nominal r2
1152 ; return (rk, mkAppTy s1 s2, mkAppTy t1 t2, r1) }
1153
1154 lintCoercion (ForAllCo tv co)
1155 = do { lintTyBndrKind tv
1156 ; (k, s, t, r) <- addInScopeVar tv (lintCoercion co)
1157 ; return (k, mkForAllTy tv s, mkForAllTy tv t, r) }
1158
1159 lintCoercion (CoVarCo cv)
1160 | not (isCoVar cv)
1161 = failWithL (hang (ptext (sLit "Bad CoVarCo:") <+> ppr cv)
1162 2 (ptext (sLit "With offending type:") <+> ppr (varType cv)))
1163 | otherwise
1164 = do { checkTyCoVarInScope cv
1165 ; cv' <- lookupIdInScope cv
1166 ; let (s,t) = coVarKind cv'
1167 k = typeKind s
1168 r = coVarRole cv'
1169 ; when (isSuperKind k) $
1170 do { checkL (r == Nominal) (hang (ptext (sLit "Non-nominal kind equality"))
1171 2 (ppr cv))
1172 ; checkL (s `eqKind` t) (hang (ptext (sLit "Non-refl kind equality"))
1173 2 (ppr cv)) }
1174 ; return (k, s, t, r) }
1175
1176 -- See Note [Bad unsafe coercion]
1177 lintCoercion (UnivCo _prov r ty1 ty2)
1178 = do { k1 <- lintType ty1
1179 ; k2 <- lintType ty2
1180 -- ; unless (k1 `eqKind` k2) $
1181 -- failWithL (hang (ptext (sLit "Unsafe coercion changes kind"))
1182 -- 2 (ppr co))
1183 ; when (r /= Phantom && isSubOpenTypeKind k1 && isSubOpenTypeKind k2)
1184 (checkTypes ty1 ty2)
1185 ; return (k1, ty1, ty2, r) }
1186 where
1187 report s = hang (text $ "Unsafe coercion between " ++ s)
1188 2 (vcat [ text "From:" <+> ppr ty1
1189 , text " To:" <+> ppr ty2])
1190 isUnBoxed :: PrimRep -> Bool
1191 isUnBoxed PtrRep = False
1192 isUnBoxed _ = True
1193 checkTypes t1 t2
1194 = case (repType t1, repType t2) of
1195 (UnaryRep _, UnaryRep _) ->
1196 validateCoercion (typePrimRep t1)
1197 (typePrimRep t2)
1198 (UbxTupleRep rep1, UbxTupleRep rep2) -> do
1199 checkWarnL (length rep1 == length rep2)
1200 (report "unboxed tuples of different length")
1201 zipWithM_ checkTypes rep1 rep2
1202 _ -> addWarnL (report "unboxed tuple and ordinary type")
1203 validateCoercion :: PrimRep -> PrimRep -> LintM ()
1204 validateCoercion rep1 rep2
1205 = do { dflags <- getDynFlags
1206 ; checkWarnL (isUnBoxed rep1 == isUnBoxed rep2)
1207 (report "unboxed and boxed value")
1208 ; checkWarnL (TyCon.primRepSizeW dflags rep1
1209 == TyCon.primRepSizeW dflags rep2)
1210 (report "unboxed values of different size")
1211 ; let fl = liftM2 (==) (TyCon.primRepIsFloat rep1)
1212 (TyCon.primRepIsFloat rep2)
1213 ; case fl of
1214 Nothing -> addWarnL (report "vector types")
1215 Just False -> addWarnL (report "float and integral values")
1216 _ -> return ()
1217 }
1218
1219 lintCoercion (SymCo co)
1220 = do { (k, ty1, ty2, r) <- lintCoercion co
1221 ; return (k, ty2, ty1, r) }
1222
1223 lintCoercion co@(TransCo co1 co2)
1224 = do { (k1, ty1a, ty1b, r1) <- lintCoercion co1
1225 ; (_, ty2a, ty2b, r2) <- lintCoercion co2
1226 ; checkL (ty1b `eqType` ty2a)
1227 (hang (ptext (sLit "Trans coercion mis-match:") <+> ppr co)
1228 2 (vcat [ppr ty1a, ppr ty1b, ppr ty2a, ppr ty2b]))
1229 ; checkRole co r1 r2
1230 ; return (k1, ty1a, ty2b, r1) }
1231
1232 lintCoercion the_co@(NthCo n co)
1233 = do { (_,s,t,r) <- lintCoercion co
1234 ; case (splitTyConApp_maybe s, splitTyConApp_maybe t) of
1235 (Just (tc_s, tys_s), Just (tc_t, tys_t))
1236 | tc_s == tc_t
1237 , tys_s `equalLength` tys_t
1238 , n < length tys_s
1239 -> return (ks, ts, tt, tr)
1240 where
1241 ts = getNth tys_s n
1242 tt = getNth tys_t n
1243 tr = nthRole r tc_s n
1244 ks = typeKind ts
1245
1246 _ -> failWithL (hang (ptext (sLit "Bad getNth:"))
1247 2 (ppr the_co $$ ppr s $$ ppr t)) }
1248
1249 lintCoercion the_co@(LRCo lr co)
1250 = do { (_,s,t,r) <- lintCoercion co
1251 ; checkRole co Nominal r
1252 ; case (splitAppTy_maybe s, splitAppTy_maybe t) of
1253 (Just s_pr, Just t_pr)
1254 -> return (k, s_pick, t_pick, Nominal)
1255 where
1256 s_pick = pickLR lr s_pr
1257 t_pick = pickLR lr t_pr
1258 k = typeKind s_pick
1259
1260 _ -> failWithL (hang (ptext (sLit "Bad LRCo:"))
1261 2 (ppr the_co $$ ppr s $$ ppr t)) }
1262
1263 lintCoercion (InstCo co arg_ty)
1264 = do { (k,s,t,r) <- lintCoercion co
1265 ; arg_kind <- lintType arg_ty
1266 ; case (splitForAllTy_maybe s, splitForAllTy_maybe t) of
1267 (Just (tv1,ty1), Just (tv2,ty2))
1268 | arg_kind `isSubKind` tyVarKind tv1
1269 -> return (k, substTyWith [tv1] [arg_ty] ty1,
1270 substTyWith [tv2] [arg_ty] ty2, r)
1271 | otherwise
1272 -> failWithL (ptext (sLit "Kind mis-match in inst coercion"))
1273 _ -> failWithL (ptext (sLit "Bad argument of inst")) }
1274
1275 lintCoercion co@(AxiomInstCo con ind cos)
1276 = do { unless (0 <= ind && ind < brListLength (coAxiomBranches con))
1277 (bad_ax (ptext (sLit "index out of range")))
1278 -- See Note [Kind instantiation in coercions]
1279 ; let CoAxBranch { cab_tvs = ktvs
1280 , cab_roles = roles
1281 , cab_lhs = lhs
1282 , cab_rhs = rhs } = coAxiomNthBranch con ind
1283 ; unless (equalLength ktvs cos) (bad_ax (ptext (sLit "lengths")))
1284 ; in_scope <- getInScope
1285 ; let empty_subst = mkTvSubst in_scope emptyTvSubstEnv
1286 ; (subst_l, subst_r) <- foldlM check_ki
1287 (empty_subst, empty_subst)
1288 (zip3 ktvs roles cos)
1289 ; let lhs' = Type.substTys subst_l lhs
1290 rhs' = Type.substTy subst_r rhs
1291 ; case checkAxInstCo co of
1292 Just bad_branch -> bad_ax $ ptext (sLit "inconsistent with") <+> (pprCoAxBranch (coAxiomTyCon con) bad_branch)
1293 Nothing -> return ()
1294 ; return (typeKind rhs', mkTyConApp (coAxiomTyCon con) lhs', rhs', coAxiomRole con) }
1295 where
1296 bad_ax what = addErrL (hang (ptext (sLit "Bad axiom application") <+> parens what)
1297 2 (ppr co))
1298
1299 check_ki (subst_l, subst_r) (ktv, role, co)
1300 = do { (k, t1, t2, r) <- lintCoercion co
1301 ; checkRole co role r
1302 ; let ktv_kind = Type.substTy subst_l (tyVarKind ktv)
1303 -- Using subst_l is ok, because subst_l and subst_r
1304 -- must agree on kind equalities
1305 ; unless (k `isSubKind` ktv_kind)
1306 (bad_ax (ptext (sLit "check_ki2") <+> vcat [ ppr co, ppr k, ppr ktv, ppr ktv_kind ] ))
1307 ; return (Type.extendTvSubst subst_l ktv t1,
1308 Type.extendTvSubst subst_r ktv t2) }
1309
1310 lintCoercion co@(SubCo co')
1311 = do { (k,s,t,r) <- lintCoercion co'
1312 ; checkRole co Nominal r
1313 ; return (k,s,t,Representational) }
1314
1315
1316 lintCoercion this@(AxiomRuleCo co ts cs)
1317 = do _ks <- mapM lintType ts
1318 eqs <- mapM lintCoercion cs
1319
1320 let tyNum = length ts
1321
1322 case compare (coaxrTypeArity co) tyNum of
1323 EQ -> return ()
1324 LT -> err "Too many type arguments"
1325 [ txt "expected" <+> int (coaxrTypeArity co)
1326 , txt "provided" <+> int tyNum ]
1327 GT -> err "Not enough type arguments"
1328 [ txt "expected" <+> int (coaxrTypeArity co)
1329 , txt "provided" <+> int tyNum ]
1330 checkRoles 0 (coaxrAsmpRoles co) eqs
1331
1332 case coaxrProves co ts [ Pair l r | (_,l,r,_) <- eqs ] of
1333 Nothing -> err "Malformed use of AxiomRuleCo" [ ppr this ]
1334 Just (Pair l r) ->
1335 do kL <- lintType l
1336 kR <- lintType r
1337 unless (eqKind kL kR)
1338 $ err "Kind error in CoAxiomRule"
1339 [ppr kL <+> txt "/=" <+> ppr kR]
1340 return (kL, l, r, coaxrRole co)
1341 where
1342 txt = ptext . sLit
1343 err m xs = failWithL $
1344 hang (txt m) 2 $ vcat (txt "Rule:" <+> ppr (coaxrName co) : xs)
1345
1346 checkRoles n (e : es) ((_,_,_,r) : rs)
1347 | e == r = checkRoles (n+1) es rs
1348 | otherwise = err "Argument roles mismatch"
1349 [ txt "In argument:" <+> int (n+1)
1350 , txt "Expected:" <+> ppr e
1351 , txt "Found:" <+> ppr r ]
1352 checkRoles _ [] [] = return ()
1353 checkRoles n [] rs = err "Too many coercion arguments"
1354 [ txt "Expected:" <+> int n
1355 , txt "Provided:" <+> int (n + length rs) ]
1356
1357 checkRoles n es [] = err "Not enough coercion arguments"
1358 [ txt "Expected:" <+> int (n + length es)
1359 , txt "Provided:" <+> int n ]
1360
1361 {-
1362 ************************************************************************
1363 * *
1364 \subsection[lint-monad]{The Lint monad}
1365 * *
1366 ************************************************************************
1367 -}
1368
1369 -- If you edit this type, you may need to update the GHC formalism
1370 -- See Note [GHC Formalism]
1371 data LintEnv
1372 = LE { le_flags :: LintFlags -- Linting the result of this pass
1373 , le_loc :: [LintLocInfo] -- Locations
1374 , le_subst :: TvSubst -- Current type substitution; we also use this
1375 -- to keep track of all the variables in scope,
1376 -- both Ids and TyVars
1377 , le_dynflags :: DynFlags -- DynamicFlags
1378 }
1379
1380 data LintFlags
1381 = LF { lf_check_global_ids :: Bool -- See Note [Checking for global Ids]
1382 , lf_check_inline_loop_breakers :: Bool -- See Note [Checking for INLINE loop breakers]
1383 }
1384
1385 defaultLintFlags :: LintFlags
1386 defaultLintFlags = LF { lf_check_global_ids = False
1387 , lf_check_inline_loop_breakers = True }
1388
1389 newtype LintM a =
1390 LintM { unLintM ::
1391 LintEnv ->
1392 WarnsAndErrs -> -- Error and warning messages so far
1393 (Maybe a, WarnsAndErrs) } -- Result and messages (if any)
1394
1395 type WarnsAndErrs = (Bag MsgDoc, Bag MsgDoc)
1396
1397 {- Note [Checking for global Ids]
1398 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1399 Before CoreTidy, all locally-bound Ids must be LocalIds, even
1400 top-level ones. See Note [Exported LocalIds] and Trac #9857.
1401
1402 Note [Type substitution]
1403 ~~~~~~~~~~~~~~~~~~~~~~~~
1404 Why do we need a type substitution? Consider
1405 /\(a:*). \(x:a). /\(a:*). id a x
1406 This is ill typed, because (renaming variables) it is really
1407 /\(a:*). \(x:a). /\(b:*). id b x
1408 Hence, when checking an application, we can't naively compare x's type
1409 (at its binding site) with its expected type (at a use site). So we
1410 rename type binders as we go, maintaining a substitution.
1411
1412 The same substitution also supports let-type, current expressed as
1413 (/\(a:*). body) ty
1414 Here we substitute 'ty' for 'a' in 'body', on the fly.
1415 -}
1416
1417 instance Functor LintM where
1418 fmap = liftM
1419
1420 instance Applicative LintM where
1421 pure = return
1422 (<*>) = ap
1423
1424 instance Monad LintM where
1425 return x = LintM (\ _ errs -> (Just x, errs))
1426 fail err = failWithL (text err)
1427 m >>= k = LintM (\ env errs ->
1428 let (res, errs') = unLintM m env errs in
1429 case res of
1430 Just r -> unLintM (k r) env errs'
1431 Nothing -> (Nothing, errs'))
1432
1433 instance HasDynFlags LintM where
1434 getDynFlags = LintM (\ e errs -> (Just (le_dynflags e), errs))
1435
1436 data LintLocInfo
1437 = RhsOf Id -- The variable bound
1438 | LambdaBodyOf Id -- The lambda-binder
1439 | BodyOfLetRec [Id] -- One of the binders
1440 | CaseAlt CoreAlt -- Case alternative
1441 | CasePat CoreAlt -- The *pattern* of the case alternative
1442 | AnExpr CoreExpr -- Some expression
1443 | ImportedUnfolding SrcLoc -- Some imported unfolding (ToDo: say which)
1444 | TopLevelBindings
1445 | InType Type -- Inside a type
1446 | InCo Coercion -- Inside a coercion
1447
1448 initL :: DynFlags -> LintFlags -> LintM a -> WarnsAndErrs -- Errors and warnings
1449 initL dflags flags m
1450 = case unLintM m env (emptyBag, emptyBag) of
1451 (_, errs) -> errs
1452 where
1453 env = LE { le_flags = flags, le_subst = emptyTvSubst, le_loc = [], le_dynflags = dflags }
1454
1455 getLintFlags :: LintM LintFlags
1456 getLintFlags = LintM $ \ env errs -> (Just (le_flags env), errs)
1457
1458 checkL :: Bool -> MsgDoc -> LintM ()
1459 checkL True _ = return ()
1460 checkL False msg = failWithL msg
1461
1462 checkWarnL :: Bool -> MsgDoc -> LintM ()
1463 checkWarnL True _ = return ()
1464 checkWarnL False msg = addWarnL msg
1465
1466 failWithL :: MsgDoc -> LintM a
1467 failWithL msg = LintM $ \ env (warns,errs) ->
1468 (Nothing, (warns, addMsg env errs msg))
1469
1470 addErrL :: MsgDoc -> LintM ()
1471 addErrL msg = LintM $ \ env (warns,errs) ->
1472 (Just (), (warns, addMsg env errs msg))
1473
1474 addWarnL :: MsgDoc -> LintM ()
1475 addWarnL msg = LintM $ \ env (warns,errs) ->
1476 (Just (), (addMsg env warns msg, errs))
1477
1478 addMsg :: LintEnv -> Bag MsgDoc -> MsgDoc -> Bag MsgDoc
1479 addMsg env msgs msg
1480 = ASSERT( notNull locs )
1481 msgs `snocBag` mk_msg msg
1482 where
1483 locs = le_loc env
1484 (loc, cxt1) = dumpLoc (head locs)
1485 cxts = [snd (dumpLoc loc) | loc <- locs]
1486 context | opt_PprStyle_Debug = vcat (reverse cxts) $$ cxt1 $$
1487 ptext (sLit "Substitution:") <+> ppr (le_subst env)
1488 | otherwise = cxt1
1489
1490 mk_msg msg = mkLocMessage SevWarning (mkSrcSpan loc loc) (context $$ msg)
1491
1492 addLoc :: LintLocInfo -> LintM a -> LintM a
1493 addLoc extra_loc m
1494 = LintM $ \ env errs ->
1495 unLintM m (env { le_loc = extra_loc : le_loc env }) errs
1496
1497 inCasePat :: LintM Bool -- A slight hack; see the unique call site
1498 inCasePat = LintM $ \ env errs -> (Just (is_case_pat env), errs)
1499 where
1500 is_case_pat (LE { le_loc = CasePat {} : _ }) = True
1501 is_case_pat _other = False
1502
1503 addInScopeVars :: [Var] -> LintM a -> LintM a
1504 addInScopeVars vars m
1505 = LintM $ \ env errs ->
1506 unLintM m (env { le_subst = extendTvInScopeList (le_subst env) vars })
1507 errs
1508
1509 addInScopeVar :: Var -> LintM a -> LintM a
1510 addInScopeVar var m
1511 = LintM $ \ env errs ->
1512 unLintM m (env { le_subst = extendTvInScope (le_subst env) var }) errs
1513
1514 extendSubstL :: TyVar -> Type -> LintM a -> LintM a
1515 extendSubstL tv ty m
1516 = LintM $ \ env errs ->
1517 unLintM m (env { le_subst = Type.extendTvSubst (le_subst env) tv ty }) errs
1518
1519 updateTvSubst :: TvSubst -> LintM a -> LintM a
1520 updateTvSubst subst' m
1521 = LintM $ \ env errs -> unLintM m (env { le_subst = subst' }) errs
1522
1523 getTvSubst :: LintM TvSubst
1524 getTvSubst = LintM (\ env errs -> (Just (le_subst env), errs))
1525
1526 getInScope :: LintM InScopeSet
1527 getInScope = LintM (\ env errs -> (Just (getTvInScope (le_subst env)), errs))
1528
1529 applySubstTy :: InType -> LintM OutType
1530 applySubstTy ty = do { subst <- getTvSubst; return (Type.substTy subst ty) }
1531
1532 applySubstCo :: InCoercion -> LintM OutCoercion
1533 applySubstCo co = do { subst <- getTvSubst; return (substCo (tvCvSubst subst) co) }
1534
1535 lookupIdInScope :: Id -> LintM Id
1536 lookupIdInScope id
1537 | not (mustHaveLocalBinding id)
1538 = return id -- An imported Id
1539 | otherwise
1540 = do { subst <- getTvSubst
1541 ; case lookupInScope (getTvInScope subst) id of
1542 Just v -> return v
1543 Nothing -> do { addErrL out_of_scope
1544 ; return id } }
1545 where
1546 out_of_scope = pprBndr LetBind id <+> ptext (sLit "is out of scope")
1547
1548
1549 oneTupleDataConId :: Id -- Should not happen
1550 oneTupleDataConId = dataConWorkId (tupleCon BoxedTuple 1)
1551
1552 checkBndrIdInScope :: Var -> Var -> LintM ()
1553 checkBndrIdInScope binder id
1554 = checkInScope msg id
1555 where
1556 msg = ptext (sLit "is out of scope inside info for") <+>
1557 ppr binder
1558
1559 checkTyCoVarInScope :: Var -> LintM ()
1560 checkTyCoVarInScope v = checkInScope (ptext (sLit "is out of scope")) v
1561
1562 checkInScope :: SDoc -> Var -> LintM ()
1563 checkInScope loc_msg var =
1564 do { subst <- getTvSubst
1565 ; checkL (not (mustHaveLocalBinding var) || (var `isInScope` subst))
1566 (hsep [pprBndr LetBind var, loc_msg]) }
1567
1568 checkTys :: OutType -> OutType -> MsgDoc -> LintM ()
1569 -- check ty2 is subtype of ty1 (ie, has same structure but usage
1570 -- annotations need only be consistent, not equal)
1571 -- Assumes ty1,ty2 are have alrady had the substitution applied
1572 checkTys ty1 ty2 msg = checkL (ty1 `eqType` ty2) msg
1573
1574 checkRole :: Coercion
1575 -> Role -- expected
1576 -> Role -- actual
1577 -> LintM ()
1578 checkRole co r1 r2
1579 = checkL (r1 == r2)
1580 (ptext (sLit "Role incompatibility: expected") <+> ppr r1 <> comma <+>
1581 ptext (sLit "got") <+> ppr r2 $$
1582 ptext (sLit "in") <+> ppr co)
1583
1584 {-
1585 ************************************************************************
1586 * *
1587 \subsection{Error messages}
1588 * *
1589 ************************************************************************
1590 -}
1591
1592 dumpLoc :: LintLocInfo -> (SrcLoc, SDoc)
1593
1594 dumpLoc (RhsOf v)
1595 = (getSrcLoc v, brackets (ptext (sLit "RHS of") <+> pp_binders [v]))
1596
1597 dumpLoc (LambdaBodyOf b)
1598 = (getSrcLoc b, brackets (ptext (sLit "in body of lambda with binder") <+> pp_binder b))
1599
1600 dumpLoc (BodyOfLetRec [])
1601 = (noSrcLoc, brackets (ptext (sLit "In body of a letrec with no binders")))
1602
1603 dumpLoc (BodyOfLetRec bs@(_:_))
1604 = ( getSrcLoc (head bs), brackets (ptext (sLit "in body of letrec with binders") <+> pp_binders bs))
1605
1606 dumpLoc (AnExpr e)
1607 = (noSrcLoc, text "In the expression:" <+> ppr e)
1608
1609 dumpLoc (CaseAlt (con, args, _))
1610 = (noSrcLoc, text "In a case alternative:" <+> parens (ppr con <+> pp_binders args))
1611
1612 dumpLoc (CasePat (con, args, _))
1613 = (noSrcLoc, text "In the pattern of a case alternative:" <+> parens (ppr con <+> pp_binders args))
1614
1615 dumpLoc (ImportedUnfolding locn)
1616 = (locn, brackets (ptext (sLit "in an imported unfolding")))
1617 dumpLoc TopLevelBindings
1618 = (noSrcLoc, Outputable.empty)
1619 dumpLoc (InType ty)
1620 = (noSrcLoc, text "In the type" <+> quotes (ppr ty))
1621 dumpLoc (InCo co)
1622 = (noSrcLoc, text "In the coercion" <+> quotes (ppr co))
1623
1624 pp_binders :: [Var] -> SDoc
1625 pp_binders bs = sep (punctuate comma (map pp_binder bs))
1626
1627 pp_binder :: Var -> SDoc
1628 pp_binder b | isId b = hsep [ppr b, dcolon, ppr (idType b)]
1629 | otherwise = hsep [ppr b, dcolon, ppr (tyVarKind b)]
1630
1631 ------------------------------------------------------
1632 -- Messages for case expressions
1633
1634 mkDefaultArgsMsg :: [Var] -> MsgDoc
1635 mkDefaultArgsMsg args
1636 = hang (text "DEFAULT case with binders")
1637 4 (ppr args)
1638
1639 mkCaseAltMsg :: CoreExpr -> Type -> Type -> MsgDoc
1640 mkCaseAltMsg e ty1 ty2
1641 = hang (text "Type of case alternatives not the same as the annotation on case:")
1642 4 (vcat [ppr ty1, ppr ty2, ppr e])
1643
1644 mkScrutMsg :: Id -> Type -> Type -> TvSubst -> MsgDoc
1645 mkScrutMsg var var_ty scrut_ty subst
1646 = vcat [text "Result binder in case doesn't match scrutinee:" <+> ppr var,
1647 text "Result binder type:" <+> ppr var_ty,--(idType var),
1648 text "Scrutinee type:" <+> ppr scrut_ty,
1649 hsep [ptext (sLit "Current TV subst"), ppr subst]]
1650
1651 mkNonDefltMsg, mkNonIncreasingAltsMsg :: CoreExpr -> MsgDoc
1652 mkNonDefltMsg e
1653 = hang (text "Case expression with DEFAULT not at the beginnning") 4 (ppr e)
1654 mkNonIncreasingAltsMsg e
1655 = hang (text "Case expression with badly-ordered alternatives") 4 (ppr e)
1656
1657 nonExhaustiveAltsMsg :: CoreExpr -> MsgDoc
1658 nonExhaustiveAltsMsg e
1659 = hang (text "Case expression with non-exhaustive alternatives") 4 (ppr e)
1660
1661 mkBadConMsg :: TyCon -> DataCon -> MsgDoc
1662 mkBadConMsg tycon datacon
1663 = vcat [
1664 text "In a case alternative, data constructor isn't in scrutinee type:",
1665 text "Scrutinee type constructor:" <+> ppr tycon,
1666 text "Data con:" <+> ppr datacon
1667 ]
1668
1669 mkBadPatMsg :: Type -> Type -> MsgDoc
1670 mkBadPatMsg con_result_ty scrut_ty
1671 = vcat [
1672 text "In a case alternative, pattern result type doesn't match scrutinee type:",
1673 text "Pattern result type:" <+> ppr con_result_ty,
1674 text "Scrutinee type:" <+> ppr scrut_ty
1675 ]
1676
1677 integerScrutinisedMsg :: MsgDoc
1678 integerScrutinisedMsg
1679 = text "In a LitAlt, the literal is lifted (probably Integer)"
1680
1681 mkBadAltMsg :: Type -> CoreAlt -> MsgDoc
1682 mkBadAltMsg scrut_ty alt
1683 = vcat [ text "Data alternative when scrutinee is not a tycon application",
1684 text "Scrutinee type:" <+> ppr scrut_ty,
1685 text "Alternative:" <+> pprCoreAlt alt ]
1686
1687 mkNewTyDataConAltMsg :: Type -> CoreAlt -> MsgDoc
1688 mkNewTyDataConAltMsg scrut_ty alt
1689 = vcat [ text "Data alternative for newtype datacon",
1690 text "Scrutinee type:" <+> ppr scrut_ty,
1691 text "Alternative:" <+> pprCoreAlt alt ]
1692
1693
1694 ------------------------------------------------------
1695 -- Other error messages
1696
1697 mkAppMsg :: Type -> Type -> CoreExpr -> MsgDoc
1698 mkAppMsg fun_ty arg_ty arg
1699 = vcat [ptext (sLit "Argument value doesn't match argument type:"),
1700 hang (ptext (sLit "Fun type:")) 4 (ppr fun_ty),
1701 hang (ptext (sLit "Arg type:")) 4 (ppr arg_ty),
1702 hang (ptext (sLit "Arg:")) 4 (ppr arg)]
1703
1704 mkNonFunAppMsg :: Type -> Type -> CoreExpr -> MsgDoc
1705 mkNonFunAppMsg fun_ty arg_ty arg
1706 = vcat [ptext (sLit "Non-function type in function position"),
1707 hang (ptext (sLit "Fun type:")) 4 (ppr fun_ty),
1708 hang (ptext (sLit "Arg type:")) 4 (ppr arg_ty),
1709 hang (ptext (sLit "Arg:")) 4 (ppr arg)]
1710
1711 mkLetErr :: TyVar -> CoreExpr -> MsgDoc
1712 mkLetErr bndr rhs
1713 = vcat [ptext (sLit "Bad `let' binding:"),
1714 hang (ptext (sLit "Variable:"))
1715 4 (ppr bndr <+> dcolon <+> ppr (varType bndr)),
1716 hang (ptext (sLit "Rhs:"))
1717 4 (ppr rhs)]
1718
1719 mkTyAppMsg :: Type -> Type -> MsgDoc
1720 mkTyAppMsg ty arg_ty
1721 = vcat [text "Illegal type application:",
1722 hang (ptext (sLit "Exp type:"))
1723 4 (ppr ty <+> dcolon <+> ppr (typeKind ty)),
1724 hang (ptext (sLit "Arg type:"))
1725 4 (ppr arg_ty <+> dcolon <+> ppr (typeKind arg_ty))]
1726
1727 mkRhsMsg :: Id -> SDoc -> Type -> MsgDoc
1728 mkRhsMsg binder what ty
1729 = vcat
1730 [hsep [ptext (sLit "The type of this binder doesn't match the type of its") <+> what <> colon,
1731 ppr binder],
1732 hsep [ptext (sLit "Binder's type:"), ppr (idType binder)],
1733 hsep [ptext (sLit "Rhs type:"), ppr ty]]
1734
1735 mkLetAppMsg :: CoreExpr -> MsgDoc
1736 mkLetAppMsg e
1737 = hang (ptext (sLit "This argument does not satisfy the let/app invariant:"))
1738 2 (ppr e)
1739
1740 mkRhsPrimMsg :: Id -> CoreExpr -> MsgDoc
1741 mkRhsPrimMsg binder _rhs
1742 = vcat [hsep [ptext (sLit "The type of this binder is primitive:"),
1743 ppr binder],
1744 hsep [ptext (sLit "Binder's type:"), ppr (idType binder)]
1745 ]
1746
1747 mkStrictMsg :: Id -> MsgDoc
1748 mkStrictMsg binder
1749 = vcat [hsep [ptext (sLit "Recursive or top-level binder has strict demand info:"),
1750 ppr binder],
1751 hsep [ptext (sLit "Binder's demand info:"), ppr (idDemandInfo binder)]
1752 ]
1753
1754 mkNonTopExportedMsg :: Id -> MsgDoc
1755 mkNonTopExportedMsg binder
1756 = hsep [ptext (sLit "Non-top-level binder is marked as exported:"), ppr binder]
1757
1758 mkNonTopExternalNameMsg :: Id -> MsgDoc
1759 mkNonTopExternalNameMsg binder
1760 = hsep [ptext (sLit "Non-top-level binder has an external name:"), ppr binder]
1761
1762 mkKindErrMsg :: TyVar -> Type -> MsgDoc
1763 mkKindErrMsg tyvar arg_ty
1764 = vcat [ptext (sLit "Kinds don't match in type application:"),
1765 hang (ptext (sLit "Type variable:"))
1766 4 (ppr tyvar <+> dcolon <+> ppr (tyVarKind tyvar)),
1767 hang (ptext (sLit "Arg type:"))
1768 4 (ppr arg_ty <+> dcolon <+> ppr (typeKind arg_ty))]
1769
1770 {- Not needed now
1771 mkArityMsg :: Id -> MsgDoc
1772 mkArityMsg binder
1773 = vcat [hsep [ptext (sLit "Demand type has"),
1774 ppr (dmdTypeDepth dmd_ty),
1775 ptext (sLit "arguments, rhs has"),
1776 ppr (idArity binder),
1777 ptext (sLit "arguments,"),
1778 ppr binder],
1779 hsep [ptext (sLit "Binder's strictness signature:"), ppr dmd_ty]
1780
1781 ]
1782 where (StrictSig dmd_ty) = idStrictness binder
1783 -}
1784 mkCastErr :: CoreExpr -> Coercion -> Type -> Type -> MsgDoc
1785 mkCastErr expr co from_ty expr_ty
1786 = vcat [ptext (sLit "From-type of Cast differs from type of enclosed expression"),
1787 ptext (sLit "From-type:") <+> ppr from_ty,
1788 ptext (sLit "Type of enclosed expr:") <+> ppr expr_ty,
1789 ptext (sLit "Actual enclosed expr:") <+> ppr expr,
1790 ptext (sLit "Coercion used in cast:") <+> ppr co
1791 ]
1792
1793 dupVars :: [[Var]] -> MsgDoc
1794 dupVars vars
1795 = hang (ptext (sLit "Duplicate variables brought into scope"))
1796 2 (ppr vars)
1797
1798 dupExtVars :: [[Name]] -> MsgDoc
1799 dupExtVars vars
1800 = hang (ptext (sLit "Duplicate top-level variables with the same qualified name"))
1801 2 (ppr vars)
1802
1803 {-
1804 ************************************************************************
1805 * *
1806 \subsection{Annotation Linting}
1807 * *
1808 ************************************************************************
1809 -}
1810
1811 -- | This checks whether a pass correctly looks through debug
1812 -- annotations (@SourceNote@). This works a bit different from other
1813 -- consistency checks: We check this by running the given task twice,
1814 -- noting all differences between the results.
1815 lintAnnots :: SDoc -> (ModGuts -> CoreM ModGuts) -> ModGuts -> CoreM ModGuts
1816 lintAnnots pname pass guts = do
1817 -- Run the pass as we normally would
1818 dflags <- getDynFlags
1819 when (gopt Opt_DoAnnotationLinting dflags) $
1820 liftIO $ Err.showPass dflags "Annotation linting - first run"
1821 nguts <- pass guts
1822 -- If appropriate re-run it without debug annotations to make sure
1823 -- that they made no difference.
1824 when (gopt Opt_DoAnnotationLinting dflags) $ do
1825 liftIO $ Err.showPass dflags "Annotation linting - second run"
1826 nguts' <- withoutAnnots pass guts
1827 -- Finally compare the resulting bindings
1828 liftIO $ Err.showPass dflags "Annotation linting - comparison"
1829 let binds = flattenBinds $ mg_binds nguts
1830 binds' = flattenBinds $ mg_binds nguts'
1831 (diffs,_) = diffBinds True (mkRnEnv2 emptyInScopeSet) binds binds'
1832 when (not (null diffs)) $ CoreMonad.putMsg $ vcat
1833 [ lint_banner "warning" pname
1834 , text "Core changes with annotations:"
1835 , withPprStyle defaultDumpStyle $ nest 2 $ vcat diffs
1836 ]
1837 -- Return actual new guts
1838 return nguts
1839
1840 -- | Run the given pass without annotations. This means that we both
1841 -- remove the @Opt_Debug@ flag from the environment as well as all
1842 -- annotations from incoming modules.
1843 withoutAnnots :: (ModGuts -> CoreM ModGuts) -> ModGuts -> CoreM ModGuts
1844 withoutAnnots pass guts = do
1845 -- Remove debug flag from environment.
1846 dflags <- getDynFlags
1847 let removeFlag env = env{hsc_dflags = gopt_unset dflags Opt_Debug}
1848 withoutFlag corem =
1849 liftIO =<< runCoreM <$> fmap removeFlag getHscEnv <*> getRuleBase <*>
1850 getUniqueSupplyM <*> getModule <*>
1851 getPrintUnqualified <*> pure corem
1852 -- Nuke existing ticks in module.
1853 -- TODO: Ticks in unfoldings. Maybe change unfolding so it removes
1854 -- them in absence of @Opt_Debug@?
1855 let nukeTicks = stripTicksE (not . tickishIsCode)
1856 nukeAnnotsBind :: CoreBind -> CoreBind
1857 nukeAnnotsBind bind = case bind of
1858 Rec bs -> Rec $ map (\(b,e) -> (b, nukeTicks e)) bs
1859 NonRec b e -> NonRec b $ nukeTicks e
1860 nukeAnnotsMod mg@ModGuts{mg_binds=binds}
1861 = mg{mg_binds = map nukeAnnotsBind binds}
1862 -- Perform pass with all changes applied
1863 fmap fst $ withoutFlag $ pass (nukeAnnotsMod guts)