4b6defd15dc5da04c05bd78c859a8a60aab4312d
[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
11 module CoreLint (
12 lintCoreBindings, lintUnfolding,
13 lintPassResult, lintInteractiveExpr, lintExpr,
14 lintAnnots,
15
16 -- ** Debug output
17 endPass, endPassIO,
18 dumpPassResult,
19 CoreLint.dumpIfSet,
20 ) where
21
22 #include "HsVersions.h"
23
24 import GhcPrelude
25
26 import CoreSyn
27 import CoreFVs
28 import CoreUtils
29 import CoreStats ( coreBindsStats )
30 import CoreMonad
31 import Bag
32 import Literal
33 import DataCon
34 import TysWiredIn
35 import TysPrim
36 import TcType ( isFloatingTy )
37 import Var
38 import VarEnv
39 import VarSet
40 import Name
41 import Id
42 import IdInfo
43 import PprCore
44 import ErrUtils
45 import Coercion
46 import SrcLoc
47 import Kind
48 import Type
49 import RepType
50 import TyCoRep -- checks validity of types/coercions
51 import TyCon
52 import CoAxiom
53 import BasicTypes
54 import ErrUtils as Err
55 import ListSetOps
56 import PrelNames
57 import Outputable
58 import FastString
59 import Util
60 import InstEnv ( instanceDFunId )
61 import OptCoercion ( checkAxInstCo )
62 import UniqSupply
63 import CoreArity ( typeArity )
64 import Demand ( splitStrictSig, isBotRes )
65
66 import HscTypes
67 import DynFlags
68 import Control.Monad
69 import qualified Control.Monad.Fail as MonadFail
70 import MonadUtils
71 import Data.Foldable ( toList )
72 import Data.List.NonEmpty ( NonEmpty )
73 import Data.Maybe
74 import Pair
75 import qualified GHC.LanguageExtensions as LangExt
76
77 {-
78 Note [GHC Formalism]
79 ~~~~~~~~~~~~~~~~~~~~
80 This file implements the type-checking algorithm for System FC, the "official"
81 name of the Core language. Type safety of FC is heart of the claim that
82 executables produced by GHC do not have segmentation faults. Thus, it is
83 useful to be able to reason about System FC independently of reading the code.
84 To this purpose, there is a document core-spec.pdf built in docs/core-spec that
85 contains a formalism of the types and functions dealt with here. If you change
86 just about anything in this file or you change other types/functions throughout
87 the Core language (all signposted to this note), you should update that
88 formalism. See docs/core-spec/README for more info about how to do so.
89
90 Note [check vs lint]
91 ~~~~~~~~~~~~~~~~~~~~
92 This file implements both a type checking algorithm and also general sanity
93 checking. For example, the "sanity checking" checks for TyConApp on the left
94 of an AppTy, which should never happen. These sanity checks don't really
95 affect any notion of type soundness. Yet, it is convenient to do the sanity
96 checks at the same time as the type checks. So, we use the following naming
97 convention:
98
99 - Functions that begin with 'lint'... are involved in type checking. These
100 functions might also do some sanity checking.
101
102 - Functions that begin with 'check'... are *not* involved in type checking.
103 They exist only for sanity checking.
104
105 Issues surrounding variable naming, shadowing, and such are considered *not*
106 to be part of type checking, as the formalism omits these details.
107
108 Summary of checks
109 ~~~~~~~~~~~~~~~~~
110 Checks that a set of core bindings is well-formed. The PprStyle and String
111 just control what we print in the event of an error. The Bool value
112 indicates whether we have done any specialisation yet (in which case we do
113 some extra checks).
114
115 We check for
116 (a) type errors
117 (b) Out-of-scope type variables
118 (c) Out-of-scope local variables
119 (d) Ill-kinded types
120 (e) Incorrect unsafe coercions
121
122 If we have done specialisation the we check that there are
123 (a) No top-level bindings of primitive (unboxed type)
124
125 Outstanding issues:
126
127 -- Things are *not* OK if:
128 --
129 -- * Unsaturated type app before specialisation has been done;
130 --
131 -- * Oversaturated type app after specialisation (eta reduction
132 -- may well be happening...);
133
134
135 Note [Linting function types]
136 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
137 As described in Note [Representation of function types], all saturated
138 applications of funTyCon are represented with the FunTy constructor. We check
139 this invariant in lintType.
140
141 Note [Linting type lets]
142 ~~~~~~~~~~~~~~~~~~~~~~~~
143 In the desugarer, it's very very convenient to be able to say (in effect)
144 let a = Type Int in <body>
145 That is, use a type let. See Note [Type let] in CoreSyn.
146
147 However, when linting <body> we need to remember that a=Int, else we might
148 reject a correct program. So we carry a type substitution (in this example
149 [a -> Int]) and apply this substitution before comparing types. The functin
150 lintInTy :: Type -> LintM (Type, Kind)
151 returns a substituted type.
152
153 When we encounter a binder (like x::a) we must apply the substitution
154 to the type of the binding variable. lintBinders does this.
155
156 For Ids, the type-substituted Id is added to the in_scope set (which
157 itself is part of the TCvSubst we are carrying down), and when we
158 find an occurrence of an Id, we fetch it from the in-scope set.
159
160 Note [Bad unsafe coercion]
161 ~~~~~~~~~~~~~~~~~~~~~~~~~~
162 For discussion see https://ghc.haskell.org/trac/ghc/wiki/BadUnsafeCoercions
163 Linter introduces additional rules that checks improper coercion between
164 different types, called bad coercions. Following coercions are forbidden:
165
166 (a) coercions between boxed and unboxed values;
167 (b) coercions between unlifted values of the different sizes, here
168 active size is checked, i.e. size of the actual value but not
169 the space allocated for value;
170 (c) coercions between floating and integral boxed values, this check
171 is not yet supported for unboxed tuples, as no semantics were
172 specified for that;
173 (d) coercions from / to vector type
174 (e) If types are unboxed tuples then tuple (# A_1,..,A_n #) can be
175 coerced to (# B_1,..,B_m #) if n=m and for each pair A_i, B_i rules
176 (a-e) holds.
177
178 Note [Join points]
179 ~~~~~~~~~~~~~~~~~~
180 We check the rules listed in Note [Invariants on join points] in CoreSyn. The
181 only one that causes any difficulty is the first: All occurrences must be tail
182 calls. To this end, along with the in-scope set, we remember in le_joins the
183 subset of in-scope Ids that are valid join ids. For example:
184
185 join j x = ... in
186 case e of
187 A -> jump j y -- good
188 B -> case (jump j z) of -- BAD
189 C -> join h = jump j w in ... -- good
190 D -> let x = jump j v in ... -- BAD
191
192 A join point remains valid in case branches, so when checking the A
193 branch, j is still valid. When we check the scrutinee of the inner
194 case, however, we set le_joins to empty, and catch the
195 error. Similarly, join points can occur free in RHSes of other join
196 points but not the RHSes of value bindings (thunks and functions).
197
198 ************************************************************************
199 * *
200 Beginning and ending passes
201 * *
202 ************************************************************************
203
204 These functions are not CoreM monad stuff, but they probably ought to
205 be, and it makes a conveneint place. place for them. They print out
206 stuff before and after core passes, and do Core Lint when necessary.
207 -}
208
209 endPass :: CoreToDo -> CoreProgram -> [CoreRule] -> CoreM ()
210 endPass pass binds rules
211 = do { hsc_env <- getHscEnv
212 ; print_unqual <- getPrintUnqualified
213 ; liftIO $ endPassIO hsc_env print_unqual pass binds rules }
214
215 endPassIO :: HscEnv -> PrintUnqualified
216 -> CoreToDo -> CoreProgram -> [CoreRule] -> IO ()
217 -- Used by the IO-is CorePrep too
218 endPassIO hsc_env print_unqual pass binds rules
219 = do { dumpPassResult dflags print_unqual mb_flag
220 (ppr pass) (pprPassDetails pass) binds rules
221 ; lintPassResult hsc_env pass binds }
222 where
223 dflags = hsc_dflags hsc_env
224 mb_flag = case coreDumpFlag pass of
225 Just flag | dopt flag dflags -> Just flag
226 | dopt Opt_D_verbose_core2core dflags -> Just flag
227 _ -> Nothing
228
229 dumpIfSet :: DynFlags -> Bool -> CoreToDo -> SDoc -> SDoc -> IO ()
230 dumpIfSet dflags dump_me pass extra_info doc
231 = Err.dumpIfSet dflags dump_me (showSDoc dflags (ppr pass <+> extra_info)) doc
232
233 dumpPassResult :: DynFlags
234 -> PrintUnqualified
235 -> Maybe DumpFlag -- Just df => show details in a file whose
236 -- name is specified by df
237 -> SDoc -- Header
238 -> SDoc -- Extra info to appear after header
239 -> CoreProgram -> [CoreRule]
240 -> IO ()
241 dumpPassResult dflags unqual mb_flag hdr extra_info binds rules
242 = do { forM_ mb_flag $ \flag ->
243 Err.dumpSDoc dflags unqual flag (showSDoc dflags hdr) dump_doc
244
245 -- Report result size
246 -- This has the side effect of forcing the intermediate to be evaluated
247 -- if it's not already forced by a -ddump flag.
248 ; Err.debugTraceMsg dflags 2 size_doc
249 }
250
251 where
252 size_doc = sep [text "Result size of" <+> hdr, nest 2 (equals <+> ppr (coreBindsStats binds))]
253
254 dump_doc = vcat [ nest 2 extra_info
255 , size_doc
256 , blankLine
257 , pprCoreBindingsWithSize binds
258 , ppUnless (null rules) pp_rules ]
259 pp_rules = vcat [ blankLine
260 , text "------ Local rules for imported ids --------"
261 , pprRules rules ]
262
263 coreDumpFlag :: CoreToDo -> Maybe DumpFlag
264 coreDumpFlag (CoreDoSimplify {}) = Just Opt_D_verbose_core2core
265 coreDumpFlag (CoreDoPluginPass {}) = Just Opt_D_verbose_core2core
266 coreDumpFlag CoreDoFloatInwards = Just Opt_D_verbose_core2core
267 coreDumpFlag (CoreDoFloatOutwards {}) = Just Opt_D_verbose_core2core
268 coreDumpFlag CoreLiberateCase = Just Opt_D_verbose_core2core
269 coreDumpFlag CoreDoStaticArgs = Just Opt_D_verbose_core2core
270 coreDumpFlag CoreDoCallArity = Just Opt_D_dump_call_arity
271 coreDumpFlag CoreDoExitify = Just Opt_D_dump_exitify
272 coreDumpFlag CoreDoStrictness = Just Opt_D_dump_stranal
273 coreDumpFlag CoreDoWorkerWrapper = Just Opt_D_dump_worker_wrapper
274 coreDumpFlag CoreDoSpecialising = Just Opt_D_dump_spec
275 coreDumpFlag CoreDoSpecConstr = Just Opt_D_dump_spec
276 coreDumpFlag CoreCSE = Just Opt_D_dump_cse
277 coreDumpFlag CoreDoVectorisation = Just Opt_D_dump_vect
278 coreDumpFlag CoreDesugar = Just Opt_D_dump_ds
279 coreDumpFlag CoreDesugarOpt = Just Opt_D_dump_ds
280 coreDumpFlag CoreTidy = Just Opt_D_dump_simpl
281 coreDumpFlag CorePrep = Just Opt_D_dump_prep
282 coreDumpFlag CoreOccurAnal = Just Opt_D_dump_occur_anal
283
284 coreDumpFlag CoreDoPrintCore = Nothing
285 coreDumpFlag (CoreDoRuleCheck {}) = Nothing
286 coreDumpFlag CoreDoNothing = Nothing
287 coreDumpFlag (CoreDoPasses {}) = Nothing
288
289 {-
290 ************************************************************************
291 * *
292 Top-level interfaces
293 * *
294 ************************************************************************
295 -}
296
297 lintPassResult :: HscEnv -> CoreToDo -> CoreProgram -> IO ()
298 lintPassResult hsc_env pass binds
299 | not (gopt Opt_DoCoreLinting dflags)
300 = return ()
301 | otherwise
302 = do { let (warns, errs) = lintCoreBindings dflags pass (interactiveInScope hsc_env) binds
303 ; Err.showPass dflags ("Core Linted result of " ++ showPpr dflags pass)
304 ; displayLintResults dflags pass warns errs binds }
305 where
306 dflags = hsc_dflags hsc_env
307
308 displayLintResults :: DynFlags -> CoreToDo
309 -> Bag Err.MsgDoc -> Bag Err.MsgDoc -> CoreProgram
310 -> IO ()
311 displayLintResults dflags pass warns errs binds
312 | not (isEmptyBag errs)
313 = do { putLogMsg dflags NoReason Err.SevDump noSrcSpan
314 (defaultDumpStyle dflags)
315 (vcat [ lint_banner "errors" (ppr pass), Err.pprMessageBag errs
316 , text "*** Offending Program ***"
317 , pprCoreBindings binds
318 , text "*** End of Offense ***" ])
319 ; Err.ghcExit dflags 1 }
320
321 | not (isEmptyBag warns)
322 , not (hasNoDebugOutput dflags)
323 , showLintWarnings pass
324 -- If the Core linter encounters an error, output to stderr instead of
325 -- stdout (#13342)
326 = putLogMsg dflags NoReason Err.SevInfo noSrcSpan
327 (defaultDumpStyle dflags)
328 (lint_banner "warnings" (ppr pass) $$ Err.pprMessageBag (mapBag ($$ blankLine) warns))
329
330 | otherwise = return ()
331 where
332
333 lint_banner :: String -> SDoc -> SDoc
334 lint_banner string pass = text "*** Core Lint" <+> text string
335 <+> text ": in result of" <+> pass
336 <+> text "***"
337
338 showLintWarnings :: CoreToDo -> Bool
339 -- Disable Lint warnings on the first simplifier pass, because
340 -- there may be some INLINE knots still tied, which is tiresomely noisy
341 showLintWarnings (CoreDoSimplify _ (SimplMode { sm_phase = InitialPhase })) = False
342 showLintWarnings _ = True
343
344 lintInteractiveExpr :: String -> HscEnv -> CoreExpr -> IO ()
345 lintInteractiveExpr what hsc_env expr
346 | not (gopt Opt_DoCoreLinting dflags)
347 = return ()
348 | Just err <- lintExpr dflags (interactiveInScope hsc_env) expr
349 = do { display_lint_err err
350 ; Err.ghcExit dflags 1 }
351 | otherwise
352 = return ()
353 where
354 dflags = hsc_dflags hsc_env
355
356 display_lint_err err
357 = do { putLogMsg dflags NoReason Err.SevDump
358 noSrcSpan (defaultDumpStyle dflags)
359 (vcat [ lint_banner "errors" (text what)
360 , err
361 , text "*** Offending Program ***"
362 , pprCoreExpr expr
363 , text "*** End of Offense ***" ])
364 ; Err.ghcExit dflags 1 }
365
366 interactiveInScope :: HscEnv -> [Var]
367 -- In GHCi we may lint expressions, or bindings arising from 'deriving'
368 -- clauses, that mention variables bound in the interactive context.
369 -- These are Local things (see Note [Interactively-bound Ids in GHCi] in HscTypes).
370 -- So we have to tell Lint about them, lest it reports them as out of scope.
371 --
372 -- We do this by find local-named things that may appear free in interactive
373 -- context. This function is pretty revolting and quite possibly not quite right.
374 -- When we are not in GHCi, the interactive context (hsc_IC hsc_env) is empty
375 -- so this is a (cheap) no-op.
376 --
377 -- See Trac #8215 for an example
378 interactiveInScope hsc_env
379 = tyvars ++ ids
380 where
381 -- C.f. TcRnDriver.setInteractiveContext, Desugar.deSugarExpr
382 ictxt = hsc_IC hsc_env
383 (cls_insts, _fam_insts) = ic_instances ictxt
384 te1 = mkTypeEnvWithImplicits (ic_tythings ictxt)
385 te = extendTypeEnvWithIds te1 (map instanceDFunId cls_insts)
386 ids = typeEnvIds te
387 tyvars = tyCoVarsOfTypesList $ map idType ids
388 -- Why the type variables? How can the top level envt have free tyvars?
389 -- I think it's because of the GHCi debugger, which can bind variables
390 -- f :: [t] -> [t]
391 -- where t is a RuntimeUnk (see TcType)
392
393 lintCoreBindings :: DynFlags -> CoreToDo -> [Var] -> CoreProgram -> (Bag MsgDoc, Bag MsgDoc)
394 -- Returns (warnings, errors)
395 -- If you edit this function, you may need to update the GHC formalism
396 -- See Note [GHC Formalism]
397 lintCoreBindings dflags pass local_in_scope binds
398 = initL dflags flags in_scope_set $
399 addLoc TopLevelBindings $
400 lintLetBndrs TopLevel binders $
401 -- Put all the top-level binders in scope at the start
402 -- This is because transformation rules can bring something
403 -- into use 'unexpectedly'
404 do { checkL (null dups) (dupVars dups)
405 ; checkL (null ext_dups) (dupExtVars ext_dups)
406 ; mapM lint_bind binds }
407 where
408 in_scope_set = mkInScopeSet (mkVarSet local_in_scope)
409
410 flags = LF { lf_check_global_ids = check_globals
411 , lf_check_inline_loop_breakers = check_lbs
412 , lf_check_static_ptrs = check_static_ptrs }
413
414 -- See Note [Checking for global Ids]
415 check_globals = case pass of
416 CoreTidy -> False
417 CorePrep -> False
418 _ -> True
419
420 -- See Note [Checking for INLINE loop breakers]
421 check_lbs = case pass of
422 CoreDesugar -> False
423 CoreDesugarOpt -> False
424 _ -> True
425
426 -- See Note [Checking StaticPtrs]
427 check_static_ptrs | not (xopt LangExt.StaticPointers dflags) = AllowAnywhere
428 | otherwise = case pass of
429 CoreDoFloatOutwards _ -> AllowAtTopLevel
430 CoreTidy -> RejectEverywhere
431 CorePrep -> AllowAtTopLevel
432 _ -> AllowAnywhere
433
434 binders = bindersOfBinds binds
435 (_, dups) = removeDups compare binders
436
437 -- dups_ext checks for names with different uniques
438 -- but but the same External name M.n. We don't
439 -- allow this at top level:
440 -- M.n{r3} = ...
441 -- M.n{r29} = ...
442 -- because they both get the same linker symbol
443 ext_dups = snd (removeDups ord_ext (map Var.varName binders))
444 ord_ext n1 n2 | Just m1 <- nameModule_maybe n1
445 , Just m2 <- nameModule_maybe n2
446 = compare (m1, nameOccName n1) (m2, nameOccName n2)
447 | otherwise = LT
448
449 -- If you edit this function, you may need to update the GHC formalism
450 -- See Note [GHC Formalism]
451 lint_bind (Rec prs) = mapM_ (lintSingleBinding TopLevel Recursive) prs
452 lint_bind (NonRec bndr rhs) = lintSingleBinding TopLevel NonRecursive (bndr,rhs)
453
454 {-
455 ************************************************************************
456 * *
457 \subsection[lintUnfolding]{lintUnfolding}
458 * *
459 ************************************************************************
460
461 Note [Linting Unfoldings from Interfaces]
462 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
463
464 We use this to check all top-level unfoldings that come in from interfaces
465 (it is very painful to catch errors otherwise).
466
467 We do not need to call lintUnfolding on unfoldings that are nested within
468 top-level unfoldings; they are linted when we lint the top-level unfolding;
469 hence the `TopLevelFlag` on `tcPragExpr` in TcIface.
470
471 -}
472
473 lintUnfolding :: DynFlags
474 -> SrcLoc
475 -> VarSet -- Treat these as in scope
476 -> CoreExpr
477 -> Maybe MsgDoc -- Nothing => OK
478
479 lintUnfolding dflags locn vars expr
480 | isEmptyBag errs = Nothing
481 | otherwise = Just (pprMessageBag errs)
482 where
483 in_scope = mkInScopeSet vars
484 (_warns, errs) = initL dflags defaultLintFlags in_scope linter
485 linter = addLoc (ImportedUnfolding locn) $
486 lintCoreExpr expr
487
488 lintExpr :: DynFlags
489 -> [Var] -- Treat these as in scope
490 -> CoreExpr
491 -> Maybe MsgDoc -- Nothing => OK
492
493 lintExpr dflags vars expr
494 | isEmptyBag errs = Nothing
495 | otherwise = Just (pprMessageBag errs)
496 where
497 in_scope = mkInScopeSet (mkVarSet vars)
498 (_warns, errs) = initL dflags defaultLintFlags in_scope linter
499 linter = addLoc TopLevelBindings $
500 lintCoreExpr expr
501
502 {-
503 ************************************************************************
504 * *
505 \subsection[lintCoreBinding]{lintCoreBinding}
506 * *
507 ************************************************************************
508
509 Check a core binding, returning the list of variables bound.
510 -}
511
512 lintSingleBinding :: TopLevelFlag -> RecFlag -> (Id, CoreExpr) -> LintM ()
513 -- If you edit this function, you may need to update the GHC formalism
514 -- See Note [GHC Formalism]
515 lintSingleBinding top_lvl_flag rec_flag (binder,rhs)
516 = addLoc (RhsOf binder) $
517 -- Check the rhs
518 do { ty <- lintRhs binder rhs
519 ; binder_ty <- applySubstTy (idType binder)
520 ; ensureEqTys binder_ty ty (mkRhsMsg binder (text "RHS") ty)
521
522 -- Check that it's not levity-polymorphic
523 -- Do this first, because otherwise isUnliftedType panics
524 -- Annoyingly, this duplicates the test in lintIdBdr,
525 -- because for non-rec lets we call lintSingleBinding first
526 ; checkL (isJoinId binder || not (isTypeLevPoly binder_ty))
527 (badBndrTyMsg binder (text "levity-polymorphic"))
528
529 -- Check the let/app invariant
530 -- See Note [CoreSyn let/app invariant] in CoreSyn
531 ; checkL ( isJoinId binder
532 || not (isUnliftedType binder_ty)
533 || (isNonRec rec_flag && exprOkForSpeculation rhs)
534 || exprIsLiteralString rhs)
535 (badBndrTyMsg binder (text "unlifted"))
536
537 -- Check that if the binder is top-level or recursive, it's not
538 -- demanded. Primitive string literals are exempt as there is no
539 -- computation to perform, see Note [CoreSyn top-level string literals].
540 ; checkL (not (isStrictId binder)
541 || (isNonRec rec_flag && not (isTopLevel top_lvl_flag))
542 || exprIsLiteralString rhs)
543 (mkStrictMsg binder)
544
545 -- Check that if the binder is at the top level and has type Addr#,
546 -- that it is a string literal, see
547 -- Note [CoreSyn top-level string literals].
548 ; checkL (not (isTopLevel top_lvl_flag && binder_ty `eqType` addrPrimTy)
549 || exprIsLiteralString rhs)
550 (mkTopNonLitStrMsg binder)
551
552 ; flags <- getLintFlags
553
554 -- Check that a join-point binder has a valid type
555 -- NB: lintIdBinder has checked that it is not top-level bound
556 ; case isJoinId_maybe binder of
557 Nothing -> return ()
558 Just arity -> checkL (isValidJoinPointType arity binder_ty)
559 (mkInvalidJoinPointMsg binder binder_ty)
560
561 ; when (lf_check_inline_loop_breakers flags
562 && isStableUnfolding (realIdUnfolding binder)
563 && isStrongLoopBreaker (idOccInfo binder)
564 && isInlinePragma (idInlinePragma binder))
565 (addWarnL (text "INLINE binder is (non-rule) loop breaker:" <+> ppr binder))
566 -- Only non-rule loop breakers inhibit inlining
567
568 -- Check whether arity and demand type are consistent (only if demand analysis
569 -- already happened)
570 --
571 -- Note (Apr 2014): this is actually ok. See Note [Demand analysis for trivial right-hand sides]
572 -- in DmdAnal. After eta-expansion in CorePrep the rhs is no longer trivial.
573 -- ; let dmdTy = idStrictness binder
574 -- ; checkL (case dmdTy of
575 -- StrictSig dmd_ty -> idArity binder >= dmdTypeDepth dmd_ty || exprIsTrivial rhs)
576 -- (mkArityMsg binder)
577
578 -- Check that the binder's arity is within the bounds imposed by
579 -- the type and the strictness signature. See Note [exprArity invariant]
580 -- and Note [Trimming arity]
581 ; checkL (typeArity (idType binder) `lengthAtLeast` idArity binder)
582 (text "idArity" <+> ppr (idArity binder) <+>
583 text "exceeds typeArity" <+>
584 ppr (length (typeArity (idType binder))) <> colon <+>
585 ppr binder)
586
587 ; case splitStrictSig (idStrictness binder) of
588 (demands, result_info) | isBotRes result_info ->
589 checkL (demands `lengthAtLeast` idArity binder)
590 (text "idArity" <+> ppr (idArity binder) <+>
591 text "exceeds arity imposed by the strictness signature" <+>
592 ppr (idStrictness binder) <> colon <+>
593 ppr binder)
594 _ -> return ()
595
596 ; mapM_ (lintCoreRule binder binder_ty) (idCoreRules binder)
597
598 ; addLoc (UnfoldingOf binder) $
599 lintIdUnfolding binder binder_ty (idUnfolding binder) }
600
601 -- We should check the unfolding, if any, but this is tricky because
602 -- the unfolding is a SimplifiableCoreExpr. Give up for now.
603
604 -- | Checks the RHS of bindings. It only differs from 'lintCoreExpr'
605 -- in that it doesn't reject occurrences of the function 'makeStatic' when they
606 -- appear at the top level and @lf_check_static_ptrs == AllowAtTopLevel@, and
607 -- for join points, it skips the outer lambdas that take arguments to the
608 -- join point.
609 --
610 -- See Note [Checking StaticPtrs].
611 lintRhs :: Id -> CoreExpr -> LintM OutType
612 lintRhs bndr rhs
613 | Just arity <- isJoinId_maybe bndr
614 = lint_join_lams arity arity True rhs
615 | AlwaysTailCalled arity <- tailCallInfo (idOccInfo bndr)
616 = lint_join_lams arity arity False rhs
617 where
618 lint_join_lams 0 _ _ rhs
619 = lintCoreExpr rhs
620
621 lint_join_lams n tot enforce (Lam var expr)
622 = addLoc (LambdaBodyOf var) $
623 lintBinder LambdaBind var $ \ var' ->
624 do { body_ty <- lint_join_lams (n-1) tot enforce expr
625 ; return $ mkLamType var' body_ty }
626
627 lint_join_lams n tot True _other
628 = failWithL $ mkBadJoinArityMsg bndr tot (tot-n) rhs
629 lint_join_lams _ _ False rhs
630 = markAllJoinsBad $ lintCoreExpr rhs
631 -- Future join point, not yet eta-expanded
632 -- Body is not a tail position
633
634 -- Allow applications of the data constructor @StaticPtr@ at the top
635 -- but produce errors otherwise.
636 lintRhs _bndr rhs = fmap lf_check_static_ptrs getLintFlags >>= go
637 where
638 -- Allow occurrences of 'makeStatic' at the top-level but produce errors
639 -- otherwise.
640 go AllowAtTopLevel
641 | (binders0, rhs') <- collectTyBinders rhs
642 , Just (fun, t, info, e) <- collectMakeStaticArgs rhs'
643 = markAllJoinsBad $
644 foldr
645 -- imitate @lintCoreExpr (Lam ...)@
646 (\var loopBinders ->
647 addLoc (LambdaBodyOf var) $
648 lintBinder LambdaBind var $ \var' ->
649 do { body_ty <- loopBinders
650 ; return $ mkLamType var' body_ty }
651 )
652 -- imitate @lintCoreExpr (App ...)@
653 (do fun_ty <- lintCoreExpr fun
654 addLoc (AnExpr rhs') $ lintCoreArgs fun_ty [Type t, info, e]
655 )
656 binders0
657 go _ = markAllJoinsBad $ lintCoreExpr rhs
658
659 lintIdUnfolding :: Id -> Type -> Unfolding -> LintM ()
660 lintIdUnfolding bndr bndr_ty (CoreUnfolding { uf_tmpl = rhs, uf_src = src })
661 | isStableSource src
662 = do { ty <- lintRhs bndr rhs
663 ; ensureEqTys bndr_ty ty (mkRhsMsg bndr (text "unfolding") ty) }
664
665 lintIdUnfolding bndr bndr_ty (DFunUnfolding { df_con = con, df_bndrs = bndrs
666 , df_args = args })
667 = do { ty <- lintBinders LambdaBind bndrs $ \ bndrs' ->
668 do { res_ty <- lintCoreArgs (dataConRepType con) args
669 ; return (mkLamTypes bndrs' res_ty) }
670 ; ensureEqTys bndr_ty ty (mkRhsMsg bndr (text "dfun unfolding") ty) }
671
672 lintIdUnfolding _ _ _
673 = return () -- Do not Lint unstable unfoldings, because that leads
674 -- to exponential behaviour; c.f. CoreFVs.idUnfoldingVars
675
676 {-
677 Note [Checking for INLINE loop breakers]
678 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
679 It's very suspicious if a strong loop breaker is marked INLINE.
680
681 However, the desugarer generates instance methods with INLINE pragmas
682 that form a mutually recursive group. Only after a round of
683 simplification are they unravelled. So we suppress the test for
684 the desugarer.
685
686 ************************************************************************
687 * *
688 \subsection[lintCoreExpr]{lintCoreExpr}
689 * *
690 ************************************************************************
691 -}
692
693 -- For OutType, OutKind, the substitution has been applied,
694 -- but has not been linted yet
695
696 type LintedType = Type -- Substitution applied, and type is linted
697 type LintedKind = Kind
698
699 lintCoreExpr :: CoreExpr -> LintM OutType
700 -- The returned type has the substitution from the monad
701 -- already applied to it:
702 -- lintCoreExpr e subst = exprType (subst e)
703 --
704 -- The returned "type" can be a kind, if the expression is (Type ty)
705
706 -- If you edit this function, you may need to update the GHC formalism
707 -- See Note [GHC Formalism]
708 lintCoreExpr (Var var)
709 = lintVarOcc var 0
710
711 lintCoreExpr (Lit lit)
712 = return (literalType lit)
713
714 lintCoreExpr (Cast expr co)
715 = do { expr_ty <- markAllJoinsBad $ lintCoreExpr expr
716 ; co' <- applySubstCo co
717 ; (_, k2, from_ty, to_ty, r) <- lintCoercion co'
718 ; lintL (classifiesTypeWithValues k2)
719 (text "Target of cast not # or *:" <+> ppr co)
720 ; lintRole co' Representational r
721 ; ensureEqTys from_ty expr_ty (mkCastErr expr co' from_ty expr_ty)
722 ; return to_ty }
723
724 lintCoreExpr (Tick tickish expr)
725 = do case tickish of
726 Breakpoint _ ids -> forM_ ids $ \id -> do
727 checkDeadIdOcc id
728 lookupIdInScope id
729 _ -> return ()
730 markAllJoinsBadIf block_joins $ lintCoreExpr expr
731 where
732 block_joins = not (tickish `tickishScopesLike` SoftScope)
733 -- TODO Consider whether this is the correct rule. It is consistent with
734 -- the simplifier's behaviour - cost-centre-scoped ticks become part of
735 -- the continuation, and thus they behave like part of an evaluation
736 -- context, but soft-scoped and non-scoped ticks simply wrap the result
737 -- (see Simplify.simplTick).
738
739 lintCoreExpr (Let (NonRec tv (Type ty)) body)
740 | isTyVar tv
741 = -- See Note [Linting type lets]
742 do { ty' <- applySubstTy ty
743 ; lintTyBndr tv $ \ tv' ->
744 do { addLoc (RhsOf tv) $ lintTyKind tv' ty'
745 -- Now extend the substitution so we
746 -- take advantage of it in the body
747 ; extendSubstL tv ty' $
748 addLoc (BodyOfLetRec [tv]) $
749 lintCoreExpr body } }
750
751 lintCoreExpr (Let (NonRec bndr rhs) body)
752 | isId bndr
753 = do { lintSingleBinding NotTopLevel NonRecursive (bndr,rhs)
754 ; addLoc (BodyOfLetRec [bndr])
755 (lintIdBndr NotTopLevel LetBind bndr $ \_ ->
756 addGoodJoins [bndr] $
757 lintCoreExpr body) }
758
759 | otherwise
760 = failWithL (mkLetErr bndr rhs) -- Not quite accurate
761
762 lintCoreExpr e@(Let (Rec pairs) body)
763 = lintLetBndrs NotTopLevel bndrs $
764 addGoodJoins bndrs $
765 do { -- Check that the list of pairs is non-empty
766 checkL (not (null pairs)) (emptyRec e)
767
768 -- Check that there are no duplicated binders
769 ; checkL (null dups) (dupVars dups)
770
771 -- Check that either all the binders are joins, or none
772 ; checkL (all isJoinId bndrs || all (not . isJoinId) bndrs) $
773 mkInconsistentRecMsg bndrs
774
775 ; mapM_ (lintSingleBinding NotTopLevel Recursive) pairs
776 ; addLoc (BodyOfLetRec bndrs) (lintCoreExpr body) }
777 where
778 bndrs = map fst pairs
779 (_, dups) = removeDups compare bndrs
780
781 lintCoreExpr e@(App _ _)
782 = addLoc (AnExpr e) $
783 do { fun_ty <- lintCoreFun fun (length args)
784 ; lintCoreArgs fun_ty args }
785 where
786 (fun, args) = collectArgs e
787
788 lintCoreExpr (Lam var expr)
789 = addLoc (LambdaBodyOf var) $
790 markAllJoinsBad $
791 lintBinder LambdaBind var $ \ var' ->
792 do { body_ty <- lintCoreExpr expr
793 ; return $ mkLamType var' body_ty }
794
795 lintCoreExpr e@(Case scrut var alt_ty alts) =
796 -- Check the scrutinee
797 do { let scrut_diverges = exprIsBottom scrut
798 ; scrut_ty <- markAllJoinsBad $ lintCoreExpr scrut
799 ; (alt_ty, _) <- lintInTy alt_ty
800 ; (var_ty, _) <- lintInTy (idType var)
801
802 -- See Note [No alternatives lint check]
803 ; when (null alts) $
804 do { checkL (not (exprIsHNF scrut))
805 (text "No alternatives for a case scrutinee in head-normal form:" <+> ppr scrut)
806 ; checkWarnL scrut_diverges
807 (text "No alternatives for a case scrutinee not known to diverge for sure:" <+> ppr scrut)
808 }
809
810 -- See Note [Rules for floating-point comparisons] in PrelRules
811 ; let isLitPat (LitAlt _, _ , _) = True
812 isLitPat _ = False
813 ; checkL (not $ isFloatingTy scrut_ty && any isLitPat alts)
814 (ptext (sLit $ "Lint warning: Scrutinising floating-point " ++
815 "expression with literal pattern in case " ++
816 "analysis (see Trac #9238).")
817 $$ text "scrut" <+> ppr scrut)
818
819 ; case tyConAppTyCon_maybe (idType var) of
820 Just tycon
821 | debugIsOn
822 , isAlgTyCon tycon
823 , not (isAbstractTyCon tycon)
824 , null (tyConDataCons tycon)
825 , not scrut_diverges
826 -> pprTrace "Lint warning: case binder's type has no constructors" (ppr var <+> ppr (idType var))
827 -- This can legitimately happen for type families
828 $ return ()
829 _otherwise -> return ()
830
831 -- Don't use lintIdBndr on var, because unboxed tuple is legitimate
832
833 ; subst <- getTCvSubst
834 ; ensureEqTys var_ty scrut_ty (mkScrutMsg var var_ty scrut_ty subst)
835
836 ; lintIdBndr NotTopLevel CaseBind var $ \_ ->
837 do { -- Check the alternatives
838 mapM_ (lintCoreAlt scrut_ty alt_ty) alts
839 ; checkCaseAlts e scrut_ty alts
840 ; return alt_ty } }
841
842 -- This case can't happen; linting types in expressions gets routed through
843 -- lintCoreArgs
844 lintCoreExpr (Type ty)
845 = failWithL (text "Type found as expression" <+> ppr ty)
846
847 lintCoreExpr (Coercion co)
848 = do { (k1, k2, ty1, ty2, role) <- lintInCo co
849 ; return (mkHeteroCoercionType role k1 k2 ty1 ty2) }
850
851 ----------------------
852 lintVarOcc :: Var -> Int -- Number of arguments (type or value) being passed
853 -> LintM Type -- returns type of the *variable*
854 lintVarOcc var nargs
855 = do { checkL (isNonCoVarId var)
856 (text "Non term variable" <+> ppr var)
857
858 -- Cneck that the type of the occurrence is the same
859 -- as the type of the binding site
860 ; ty <- applySubstTy (idType var)
861 ; var' <- lookupIdInScope var
862 ; let ty' = idType var'
863 ; ensureEqTys ty ty' $ mkBndrOccTypeMismatchMsg var' var ty' ty
864
865 -- Check for a nested occurrence of the StaticPtr constructor.
866 -- See Note [Checking StaticPtrs].
867 ; lf <- getLintFlags
868 ; when (nargs /= 0 && lf_check_static_ptrs lf /= AllowAnywhere) $
869 checkL (idName var /= makeStaticName) $
870 text "Found makeStatic nested in an expression"
871
872 ; checkDeadIdOcc var
873 ; checkJoinOcc var nargs
874
875 ; return (idType var') }
876
877 lintCoreFun :: CoreExpr
878 -> Int -- Number of arguments (type or val) being passed
879 -> LintM Type -- Returns type of the *function*
880 lintCoreFun (Var var) nargs
881 = lintVarOcc var nargs
882
883 lintCoreFun (Lam var body) nargs
884 -- Act like lintCoreExpr of Lam, but *don't* call markAllJoinsBad; see
885 -- Note [Beta redexes]
886 | nargs /= 0
887 = addLoc (LambdaBodyOf var) $
888 lintBinder LambdaBind var $ \ var' ->
889 do { body_ty <- lintCoreFun body (nargs - 1)
890 ; return $ mkLamType var' body_ty }
891
892 lintCoreFun expr nargs
893 = markAllJoinsBadIf (nargs /= 0) $
894 lintCoreExpr expr
895
896 ------------------
897 checkDeadIdOcc :: Id -> LintM ()
898 -- Occurrences of an Id should never be dead....
899 -- except when we are checking a case pattern
900 checkDeadIdOcc id
901 | isDeadOcc (idOccInfo id)
902 = do { in_case <- inCasePat
903 ; checkL in_case
904 (text "Occurrence of a dead Id" <+> ppr id) }
905 | otherwise
906 = return ()
907
908 ------------------
909 checkJoinOcc :: Id -> JoinArity -> LintM ()
910 -- Check that if the occurrence is a JoinId, then so is the
911 -- binding site, and it's a valid join Id
912 checkJoinOcc var n_args
913 | Just join_arity_occ <- isJoinId_maybe var
914 = do { mb_join_arity_bndr <- lookupJoinId var
915 ; case mb_join_arity_bndr of {
916 Nothing -> -- Binder is not a join point
917 addErrL (invalidJoinOcc var) ;
918
919 Just join_arity_bndr ->
920
921 do { checkL (join_arity_bndr == join_arity_occ) $
922 -- Arity differs at binding site and occurrence
923 mkJoinBndrOccMismatchMsg var join_arity_bndr join_arity_occ
924
925 ; checkL (n_args == join_arity_occ) $
926 -- Arity doesn't match #args
927 mkBadJumpMsg var join_arity_occ n_args } } }
928
929 | otherwise
930 = return ()
931
932 {-
933 Note [No alternatives lint check]
934 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
935 Case expressions with no alternatives are odd beasts, and worth looking at
936 in the linter (cf Trac #10180). We check two things:
937
938 * exprIsHNF is false: certainly, it would be terribly wrong if the
939 scrutinee was already in head normal form.
940
941 * exprIsBottom is true: we should be able to see why GHC believes the
942 scrutinee is diverging for sure.
943
944 In principle, the first check is redundant: exprIsBottom == True will
945 always imply exprIsHNF == False. But the first check is reliable: If
946 exprIsHNF == True, then there definitely is a problem (exprIsHNF errs
947 on the right side). If the second check triggers then it may be the
948 case that the compiler got smarter elsewhere, and the empty case is
949 correct, but that exprIsBottom is unable to see it. In particular, the
950 empty-type check in exprIsBottom is an approximation. Therefore, this
951 check is not fully reliable, and we keep both around.
952
953 Note [Beta redexes]
954 ~~~~~~~~~~~~~~~~~~~
955 Consider:
956
957 join j @x y z = ... in
958 (\@x y z -> jump j @x y z) @t e1 e2
959
960 This is clearly ill-typed, since the jump is inside both an application and a
961 lambda, either of which is enough to disqualify it as a tail call (see Note
962 [Invariants on join points] in CoreSyn). However, strictly from a
963 lambda-calculus perspective, the term doesn't go wrong---after the two beta
964 reductions, the jump *is* a tail call and everything is fine.
965
966 Why would we want to allow this when we have let? One reason is that a compound
967 beta redex (that is, one with more than one argument) has different scoping
968 rules: naively reducing the above example using lets will capture any free
969 occurrence of y in e2. More fundamentally, type lets are tricky; many passes,
970 such as Float Out, tacitly assume that the incoming program's type lets have
971 all been dealt with by the simplifier. Thus we don't want to let-bind any types
972 in, say, CoreSubst.simpleOptPgm, which in some circumstances can run immediately
973 before Float Out.
974
975 All that said, currently CoreSubst.simpleOptPgm is the only thing using this
976 loophole, doing so to avoid re-traversing large functions (beta-reducing a type
977 lambda without introducing a type let requires a substitution). TODO: Improve
978 simpleOptPgm so that we can forget all this ever happened.
979
980 ************************************************************************
981 * *
982 \subsection[lintCoreArgs]{lintCoreArgs}
983 * *
984 ************************************************************************
985
986 The basic version of these functions checks that the argument is a
987 subtype of the required type, as one would expect.
988 -}
989
990
991 lintCoreArgs :: OutType -> [CoreArg] -> LintM OutType
992 lintCoreArgs fun_ty args = foldM lintCoreArg fun_ty args
993
994 lintCoreArg :: OutType -> CoreArg -> LintM OutType
995 lintCoreArg fun_ty (Type arg_ty)
996 = do { checkL (not (isCoercionTy arg_ty))
997 (text "Unnecessary coercion-to-type injection:"
998 <+> ppr arg_ty)
999 ; arg_ty' <- applySubstTy arg_ty
1000 ; lintTyApp fun_ty arg_ty' }
1001
1002 lintCoreArg fun_ty arg
1003 = do { arg_ty <- markAllJoinsBad $ lintCoreExpr arg
1004 -- See Note [Levity polymorphism invariants] in CoreSyn
1005 ; lintL (not (isTypeLevPoly arg_ty))
1006 (text "Levity-polymorphic argument:" <+>
1007 (ppr arg <+> dcolon <+> parens (ppr arg_ty <+> dcolon <+> ppr (typeKind arg_ty))))
1008 -- check for levity polymorphism first, because otherwise isUnliftedType panics
1009
1010 ; checkL (not (isUnliftedType arg_ty) || exprOkForSpeculation arg)
1011 (mkLetAppMsg arg)
1012 ; lintValApp arg fun_ty arg_ty }
1013
1014 -----------------
1015 lintAltBinders :: OutType -- Scrutinee type
1016 -> OutType -- Constructor type
1017 -> [OutVar] -- Binders
1018 -> LintM ()
1019 -- If you edit this function, you may need to update the GHC formalism
1020 -- See Note [GHC Formalism]
1021 lintAltBinders scrut_ty con_ty []
1022 = ensureEqTys con_ty scrut_ty (mkBadPatMsg con_ty scrut_ty)
1023 lintAltBinders scrut_ty con_ty (bndr:bndrs)
1024 | isTyVar bndr
1025 = do { con_ty' <- lintTyApp con_ty (mkTyVarTy bndr)
1026 ; lintAltBinders scrut_ty con_ty' bndrs }
1027 | otherwise
1028 = do { con_ty' <- lintValApp (Var bndr) con_ty (idType bndr)
1029 ; lintAltBinders scrut_ty con_ty' bndrs }
1030
1031 -----------------
1032 lintTyApp :: OutType -> OutType -> LintM OutType
1033 lintTyApp fun_ty arg_ty
1034 | Just (tv,body_ty) <- splitForAllTy_maybe fun_ty
1035 = do { lintTyKind tv arg_ty
1036 ; in_scope <- getInScope
1037 -- substTy needs the set of tyvars in scope to avoid generating
1038 -- uniques that are already in scope.
1039 -- See Note [The substitution invariant] in TyCoRep
1040 ; return (substTyWithInScope in_scope [tv] [arg_ty] body_ty) }
1041
1042 | otherwise
1043 = failWithL (mkTyAppMsg fun_ty arg_ty)
1044
1045 -----------------
1046 lintValApp :: CoreExpr -> OutType -> OutType -> LintM OutType
1047 lintValApp arg fun_ty arg_ty
1048 | Just (arg,res) <- splitFunTy_maybe fun_ty
1049 = do { ensureEqTys arg arg_ty err1
1050 ; return res }
1051 | otherwise
1052 = failWithL err2
1053 where
1054 err1 = mkAppMsg fun_ty arg_ty arg
1055 err2 = mkNonFunAppMsg fun_ty arg_ty arg
1056
1057 lintTyKind :: OutTyVar -> OutType -> LintM ()
1058 -- Both args have had substitution applied
1059
1060 -- If you edit this function, you may need to update the GHC formalism
1061 -- See Note [GHC Formalism]
1062 lintTyKind tyvar arg_ty
1063 -- Arg type might be boxed for a function with an uncommitted
1064 -- tyvar; notably this is used so that we can give
1065 -- error :: forall a:*. String -> a
1066 -- and then apply it to both boxed and unboxed types.
1067 = do { arg_kind <- lintType arg_ty
1068 ; unless (arg_kind `eqType` tyvar_kind)
1069 (addErrL (mkKindErrMsg tyvar arg_ty $$ (text "Linted Arg kind:" <+> ppr arg_kind))) }
1070 where
1071 tyvar_kind = tyVarKind tyvar
1072
1073 {-
1074 ************************************************************************
1075 * *
1076 \subsection[lintCoreAlts]{lintCoreAlts}
1077 * *
1078 ************************************************************************
1079 -}
1080
1081 checkCaseAlts :: CoreExpr -> OutType -> [CoreAlt] -> LintM ()
1082 -- a) Check that the alts are non-empty
1083 -- b1) Check that the DEFAULT comes first, if it exists
1084 -- b2) Check that the others are in increasing order
1085 -- c) Check that there's a default for infinite types
1086 -- NB: Algebraic cases are not necessarily exhaustive, because
1087 -- the simplifier correctly eliminates case that can't
1088 -- possibly match.
1089
1090 checkCaseAlts e ty alts =
1091 do { checkL (all non_deflt con_alts) (mkNonDefltMsg e)
1092 ; checkL (increasing_tag con_alts) (mkNonIncreasingAltsMsg e)
1093
1094 -- For types Int#, Word# with an infinite (well, large!) number of
1095 -- possible values, there should usually be a DEFAULT case
1096 -- But (see Note [Empty case alternatives] in CoreSyn) it's ok to
1097 -- have *no* case alternatives.
1098 -- In effect, this is a kind of partial test. I suppose it's possible
1099 -- that we might *know* that 'x' was 1 or 2, in which case
1100 -- case x of { 1 -> e1; 2 -> e2 }
1101 -- would be fine.
1102 ; checkL (isJust maybe_deflt || not is_infinite_ty || null alts)
1103 (nonExhaustiveAltsMsg e) }
1104 where
1105 (con_alts, maybe_deflt) = findDefault alts
1106
1107 -- Check that successive alternatives have increasing tags
1108 increasing_tag (alt1 : rest@( alt2 : _)) = alt1 `ltAlt` alt2 && increasing_tag rest
1109 increasing_tag _ = True
1110
1111 non_deflt (DEFAULT, _, _) = False
1112 non_deflt _ = True
1113
1114 is_infinite_ty = case tyConAppTyCon_maybe ty of
1115 Nothing -> False
1116 Just tycon -> isPrimTyCon tycon
1117
1118 lintAltExpr :: CoreExpr -> OutType -> LintM ()
1119 lintAltExpr expr ann_ty
1120 = do { actual_ty <- lintCoreExpr expr
1121 ; ensureEqTys actual_ty ann_ty (mkCaseAltMsg expr actual_ty ann_ty) }
1122
1123 lintCoreAlt :: OutType -- Type of scrutinee
1124 -> OutType -- Type of the alternative
1125 -> CoreAlt
1126 -> LintM ()
1127 -- If you edit this function, you may need to update the GHC formalism
1128 -- See Note [GHC Formalism]
1129 lintCoreAlt _ alt_ty (DEFAULT, args, rhs) =
1130 do { lintL (null args) (mkDefaultArgsMsg args)
1131 ; lintAltExpr rhs alt_ty }
1132
1133 lintCoreAlt scrut_ty alt_ty (LitAlt lit, args, rhs)
1134 | litIsLifted lit
1135 = failWithL integerScrutinisedMsg
1136 | otherwise
1137 = do { lintL (null args) (mkDefaultArgsMsg args)
1138 ; ensureEqTys lit_ty scrut_ty (mkBadPatMsg lit_ty scrut_ty)
1139 ; lintAltExpr rhs alt_ty }
1140 where
1141 lit_ty = literalType lit
1142
1143 lintCoreAlt scrut_ty alt_ty alt@(DataAlt con, args, rhs)
1144 | isNewTyCon (dataConTyCon con)
1145 = addErrL (mkNewTyDataConAltMsg scrut_ty alt)
1146 | Just (tycon, tycon_arg_tys) <- splitTyConApp_maybe scrut_ty
1147 = addLoc (CaseAlt alt) $ do
1148 { -- First instantiate the universally quantified
1149 -- type variables of the data constructor
1150 -- We've already check
1151 lintL (tycon == dataConTyCon con) (mkBadConMsg tycon con)
1152 ; let con_payload_ty = piResultTys (dataConRepType con) tycon_arg_tys
1153
1154 -- And now bring the new binders into scope
1155 ; lintBinders CasePatBind args $ \ args' -> do
1156 { addLoc (CasePat alt) (lintAltBinders scrut_ty con_payload_ty args')
1157 ; lintAltExpr rhs alt_ty } }
1158
1159 | otherwise -- Scrut-ty is wrong shape
1160 = addErrL (mkBadAltMsg scrut_ty alt)
1161
1162 {-
1163 ************************************************************************
1164 * *
1165 \subsection[lint-types]{Types}
1166 * *
1167 ************************************************************************
1168 -}
1169
1170 -- When we lint binders, we (one at a time and in order):
1171 -- 1. Lint var types or kinds (possibly substituting)
1172 -- 2. Add the binder to the in scope set, and if its a coercion var,
1173 -- we may extend the substitution to reflect its (possibly) new kind
1174 lintBinders :: BindingSite -> [Var] -> ([Var] -> LintM a) -> LintM a
1175 lintBinders _ [] linterF = linterF []
1176 lintBinders site (var:vars) linterF = lintBinder site var $ \var' ->
1177 lintBinders site vars $ \ vars' ->
1178 linterF (var':vars')
1179
1180 -- If you edit this function, you may need to update the GHC formalism
1181 -- See Note [GHC Formalism]
1182 lintBinder :: BindingSite -> Var -> (Var -> LintM a) -> LintM a
1183 lintBinder site var linterF
1184 | isTyVar var = lintTyBndr var linterF
1185 | isCoVar var = lintCoBndr var linterF
1186 | otherwise = lintIdBndr NotTopLevel site var linterF
1187
1188 lintTyBndr :: InTyVar -> (OutTyVar -> LintM a) -> LintM a
1189 lintTyBndr tv thing_inside
1190 = do { subst <- getTCvSubst
1191 ; let (subst', tv') = substTyVarBndr subst tv
1192 ; lintKind (varType tv')
1193 ; updateTCvSubst subst' (thing_inside tv') }
1194
1195 lintCoBndr :: InCoVar -> (OutCoVar -> LintM a) -> LintM a
1196 lintCoBndr cv thing_inside
1197 = do { subst <- getTCvSubst
1198 ; let (subst', cv') = substCoVarBndr subst cv
1199 ; lintKind (varType cv')
1200 ; lintL (isCoercionType (varType cv'))
1201 (text "CoVar with non-coercion type:" <+> pprTyVar cv)
1202 ; updateTCvSubst subst' (thing_inside cv') }
1203
1204 lintLetBndrs :: TopLevelFlag -> [Var] -> LintM a -> LintM a
1205 lintLetBndrs top_lvl ids linterF
1206 = go ids
1207 where
1208 go [] = linterF
1209 go (id:ids) = lintIdBndr top_lvl LetBind id $ \_ ->
1210 go ids
1211
1212 lintIdBndr :: TopLevelFlag -> BindingSite
1213 -> InVar -> (OutVar -> LintM a) -> LintM a
1214 -- Do substitution on the type of a binder and add the var with this
1215 -- new type to the in-scope set of the second argument
1216 -- ToDo: lint its rules
1217 lintIdBndr top_lvl bind_site id linterF
1218 = ASSERT2( isId id, ppr id )
1219 do { flags <- getLintFlags
1220 ; checkL (not (lf_check_global_ids flags) || isLocalId id)
1221 (text "Non-local Id binder" <+> ppr id)
1222 -- See Note [Checking for global Ids]
1223
1224 -- Check that if the binder is nested, it is not marked as exported
1225 ; checkL (not (isExportedId id) || is_top_lvl)
1226 (mkNonTopExportedMsg id)
1227
1228 -- Check that if the binder is nested, it does not have an external name
1229 ; checkL (not (isExternalName (Var.varName id)) || is_top_lvl)
1230 (mkNonTopExternalNameMsg id)
1231
1232 ; (ty, k) <- lintInTy (idType id)
1233 -- See Note [Levity polymorphism invariants] in CoreSyn
1234 ; lintL (isJoinId id || not (isKindLevPoly k))
1235 (text "Levity-polymorphic binder:" <+>
1236 (ppr id <+> dcolon <+> parens (ppr ty <+> dcolon <+> ppr k)))
1237
1238 -- Check that a join-id is a not-top-level let-binding
1239 ; when (isJoinId id) $
1240 checkL (not is_top_lvl && is_let_bind) $
1241 mkBadJoinBindMsg id
1242
1243 ; let id' = setIdType id ty
1244 ; addInScopeVar id' $ (linterF id') }
1245 where
1246 is_top_lvl = isTopLevel top_lvl
1247 is_let_bind = case bind_site of
1248 LetBind -> True
1249 _ -> False
1250
1251 {-
1252 %************************************************************************
1253 %* *
1254 Types
1255 %* *
1256 %************************************************************************
1257 -}
1258
1259 lintInTy :: InType -> LintM (LintedType, LintedKind)
1260 -- Types only, not kinds
1261 -- Check the type, and apply the substitution to it
1262 -- See Note [Linting type lets]
1263 lintInTy ty
1264 = addLoc (InType ty) $
1265 do { ty' <- applySubstTy ty
1266 ; k <- lintType ty'
1267 ; lintKind k
1268 ; return (ty', k) }
1269
1270 checkTyCon :: TyCon -> LintM ()
1271 checkTyCon tc
1272 = checkL (not (isTcTyCon tc)) (text "Found TcTyCon:" <+> ppr tc)
1273
1274 -------------------
1275 lintType :: OutType -> LintM LintedKind
1276 -- The returned Kind has itself been linted
1277
1278 -- If you edit this function, you may need to update the GHC formalism
1279 -- See Note [GHC Formalism]
1280 lintType (TyVarTy tv)
1281 = do { checkL (isTyVar tv) (mkBadTyVarMsg tv)
1282 ; lintTyCoVarInScope tv
1283 ; return (tyVarKind tv) }
1284 -- We checked its kind when we added it to the envt
1285
1286 lintType ty@(AppTy t1 t2)
1287 | TyConApp {} <- t1
1288 = failWithL $ text "TyConApp to the left of AppTy:" <+> ppr ty
1289 | otherwise
1290 = do { k1 <- lintType t1
1291 ; k2 <- lintType t2
1292 ; lint_ty_app ty k1 [(t2,k2)] }
1293
1294 lintType ty@(TyConApp tc tys)
1295 | Just ty' <- coreView ty
1296 = lintType ty' -- Expand type synonyms, so that we do not bogusly complain
1297 -- about un-saturated type synonyms
1298
1299 -- We should never see a saturated application of funTyCon; such applications
1300 -- should be represented with the FunTy constructor. See Note [Linting
1301 -- function types] and Note [Representation of function types].
1302 | isFunTyCon tc
1303 , tys `lengthIs` 4
1304 = failWithL (hang (text "Saturated application of (->)") 2 (ppr ty))
1305
1306 | isTypeSynonymTyCon tc || isTypeFamilyTyCon tc
1307 -- Also type synonyms and type families
1308 , tys `lengthLessThan` tyConArity tc
1309 = failWithL (hang (text "Un-saturated type application") 2 (ppr ty))
1310
1311 | otherwise
1312 = do { checkTyCon tc
1313 ; ks <- mapM lintType tys
1314 ; lint_ty_app ty (tyConKind tc) (tys `zip` ks) }
1315
1316 -- arrows can related *unlifted* kinds, so this has to be separate from
1317 -- a dependent forall.
1318 lintType ty@(FunTy t1 t2)
1319 = do { k1 <- lintType t1
1320 ; k2 <- lintType t2
1321 ; lintArrow (text "type or kind" <+> quotes (ppr ty)) k1 k2 }
1322
1323 lintType t@(ForAllTy (TvBndr tv _vis) ty)
1324 = do { lintL (isTyVar tv) (text "Covar bound in type:" <+> ppr t)
1325 ; lintTyBndr tv $ \tv' ->
1326 do { k <- lintType ty
1327 ; lintL (not (tv' `elemVarSet` tyCoVarsOfType k))
1328 (text "Variable escape in forall:" <+> ppr t)
1329 ; lintL (classifiesTypeWithValues k)
1330 (text "Non-* and non-# kind in forall:" <+> ppr t)
1331 ; return k }}
1332
1333 lintType ty@(LitTy l) = lintTyLit l >> return (typeKind ty)
1334
1335 lintType (CastTy ty co)
1336 = do { k1 <- lintType ty
1337 ; (k1', k2) <- lintStarCoercion co
1338 ; ensureEqTys k1 k1' (mkCastErr ty co k1' k1)
1339 ; return k2 }
1340
1341 lintType (CoercionTy co)
1342 = do { (k1, k2, ty1, ty2, r) <- lintCoercion co
1343 ; return $ mkHeteroCoercionType r k1 k2 ty1 ty2 }
1344
1345 lintKind :: OutKind -> LintM ()
1346 -- If you edit this function, you may need to update the GHC formalism
1347 -- See Note [GHC Formalism]
1348 lintKind k = do { sk <- lintType k
1349 ; unless (classifiesTypeWithValues sk)
1350 (addErrL (hang (text "Ill-kinded kind:" <+> ppr k)
1351 2 (text "has kind:" <+> ppr sk))) }
1352
1353 -- confirms that a type is really *
1354 lintStar :: SDoc -> OutKind -> LintM ()
1355 lintStar doc k
1356 = lintL (classifiesTypeWithValues k)
1357 (text "Non-*-like kind when *-like expected:" <+> ppr k $$
1358 text "when checking" <+> doc)
1359
1360 lintArrow :: SDoc -> LintedKind -> LintedKind -> LintM LintedKind
1361 -- If you edit this function, you may need to update the GHC formalism
1362 -- See Note [GHC Formalism]
1363 lintArrow what k1 k2 -- Eg lintArrow "type or kind `blah'" k1 k2
1364 -- or lintarrow "coercion `blah'" k1 k2
1365 = do { unless (classifiesTypeWithValues k1) (addErrL (msg (text "argument") k1))
1366 ; unless (classifiesTypeWithValues k2) (addErrL (msg (text "result") k2))
1367 ; return liftedTypeKind }
1368 where
1369 msg ar k
1370 = vcat [ hang (text "Ill-kinded" <+> ar)
1371 2 (text "in" <+> what)
1372 , what <+> text "kind:" <+> ppr k ]
1373
1374 lint_ty_app :: Type -> LintedKind -> [(LintedType,LintedKind)] -> LintM LintedKind
1375 lint_ty_app ty k tys
1376 = lint_app (text "type" <+> quotes (ppr ty)) k tys
1377
1378 ----------------
1379 lint_co_app :: Coercion -> LintedKind -> [(LintedType,LintedKind)] -> LintM LintedKind
1380 lint_co_app ty k tys
1381 = lint_app (text "coercion" <+> quotes (ppr ty)) k tys
1382
1383 ----------------
1384 lintTyLit :: TyLit -> LintM ()
1385 lintTyLit (NumTyLit n)
1386 | n >= 0 = return ()
1387 | otherwise = failWithL msg
1388 where msg = text "Negative type literal:" <+> integer n
1389 lintTyLit (StrTyLit _) = return ()
1390
1391 lint_app :: SDoc -> LintedKind -> [(LintedType,LintedKind)] -> LintM Kind
1392 -- (lint_app d fun_kind arg_tys)
1393 -- We have an application (f arg_ty1 .. arg_tyn),
1394 -- where f :: fun_kind
1395 -- Takes care of linting the OutTypes
1396
1397 -- If you edit this function, you may need to update the GHC formalism
1398 -- See Note [GHC Formalism]
1399 lint_app doc kfn kas
1400 = do { in_scope <- getInScope
1401 -- We need the in_scope set to satisfy the invariant in
1402 -- Note [The substitution invariant] in TyCoRep
1403 ; foldlM (go_app in_scope) kfn kas }
1404 where
1405 fail_msg extra = vcat [ hang (text "Kind application error in") 2 doc
1406 , nest 2 (text "Function kind =" <+> ppr kfn)
1407 , nest 2 (text "Arg kinds =" <+> ppr kas)
1408 , extra ]
1409
1410 go_app in_scope kfn tka
1411 | Just kfn' <- coreView kfn
1412 = go_app in_scope kfn' tka
1413
1414 go_app _ (FunTy kfa kfb) tka@(_,ka)
1415 = do { unless (ka `eqType` kfa) $
1416 addErrL (fail_msg (text "Fun:" <+> (ppr kfa $$ ppr tka)))
1417 ; return kfb }
1418
1419 go_app in_scope (ForAllTy (TvBndr kv _vis) kfn) tka@(ta,ka)
1420 = do { let kv_kind = tyVarKind kv
1421 ; unless (ka `eqType` kv_kind) $
1422 addErrL (fail_msg (text "Forall:" <+> (ppr kv $$ ppr kv_kind $$ ppr tka)))
1423 ; return (substTyWithInScope in_scope [kv] [ta] kfn) }
1424
1425 go_app _ kfn ka
1426 = failWithL (fail_msg (text "Not a fun:" <+> (ppr kfn $$ ppr ka)))
1427
1428 {- *********************************************************************
1429 * *
1430 Linting rules
1431 * *
1432 ********************************************************************* -}
1433
1434 lintCoreRule :: OutVar -> OutType -> CoreRule -> LintM ()
1435 lintCoreRule _ _ (BuiltinRule {})
1436 = return () -- Don't bother
1437
1438 lintCoreRule fun fun_ty rule@(Rule { ru_name = name, ru_bndrs = bndrs
1439 , ru_args = args, ru_rhs = rhs })
1440 = lintBinders LambdaBind bndrs $ \ _ ->
1441 do { lhs_ty <- foldM lintCoreArg fun_ty args
1442 ; rhs_ty <- case isJoinId_maybe fun of
1443 Just join_arity
1444 -> do { checkL (args `lengthIs` join_arity) $
1445 mkBadJoinPointRuleMsg fun join_arity rule
1446 -- See Note [Rules for join points]
1447 ; lintCoreExpr rhs }
1448 _ -> markAllJoinsBad $ lintCoreExpr rhs
1449 ; ensureEqTys lhs_ty rhs_ty $
1450 (rule_doc <+> vcat [ text "lhs type:" <+> ppr lhs_ty
1451 , text "rhs type:" <+> ppr rhs_ty ])
1452 ; let bad_bndrs = filter is_bad_bndr bndrs
1453
1454 ; checkL (null bad_bndrs)
1455 (rule_doc <+> text "unbound" <+> ppr bad_bndrs)
1456 -- See Note [Linting rules]
1457 }
1458 where
1459 rule_doc = text "Rule" <+> doubleQuotes (ftext name) <> colon
1460
1461 lhs_fvs = exprsFreeVars args
1462 rhs_fvs = exprFreeVars rhs
1463
1464 is_bad_bndr :: Var -> Bool
1465 -- See Note [Unbound RULE binders] in Rules
1466 is_bad_bndr bndr = not (bndr `elemVarSet` lhs_fvs)
1467 && bndr `elemVarSet` rhs_fvs
1468 && isNothing (isReflCoVar_maybe bndr)
1469
1470
1471 {- Note [Linting rules]
1472 ~~~~~~~~~~~~~~~~~~~~~~~
1473 It's very bad if simplifying a rule means that one of the template
1474 variables (ru_bndrs) that /is/ mentioned on the RHS becomes
1475 not-mentioned in the LHS (ru_args). How can that happen? Well, in
1476 Trac #10602, SpecConstr stupidly constructed a rule like
1477
1478 forall x,c1,c2.
1479 f (x |> c1 |> c2) = ....
1480
1481 But simplExpr collapses those coercions into one. (Indeed in
1482 Trac #10602, it collapsed to the identity and was removed altogether.)
1483
1484 We don't have a great story for what to do here, but at least
1485 this check will nail it.
1486
1487 NB (Trac #11643): it's possible that a variable listed in the
1488 binders becomes not-mentioned on both LHS and RHS. Here's a silly
1489 example:
1490 RULE forall x y. f (g x y) = g (x+1) (y-1)
1491 And suppose worker/wrapper decides that 'x' is Absent. Then
1492 we'll end up with
1493 RULE forall x y. f ($gw y) = $gw (x+1)
1494 This seems sufficiently obscure that there isn't enough payoff to
1495 try to trim the forall'd binder list.
1496
1497 Note [Rules for join points]
1498 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1499
1500 A join point cannot be partially applied. However, the left-hand side of a rule
1501 for a join point is effectively a *pattern*, not a piece of code, so there's an
1502 argument to be made for allowing a situation like this:
1503
1504 join $sj :: Int -> Int -> String
1505 $sj n m = ...
1506 j :: forall a. Eq a => a -> a -> String
1507 {-# RULES "SPEC j" jump j @ Int $dEq = jump $sj #-}
1508 j @a $dEq x y = ...
1509
1510 Applying this rule can't turn a well-typed program into an ill-typed one, so
1511 conceivably we could allow it. But we can always eta-expand such an
1512 "undersaturated" rule (see 'CoreArity.etaExpandToJoinPointRule'), and in fact
1513 the simplifier would have to in order to deal with the RHS. So we take a
1514 conservative view and don't allow undersaturated rules for join points. See
1515 Note [Rules and join points] in OccurAnal for further discussion.
1516 -}
1517
1518 {-
1519 ************************************************************************
1520 * *
1521 Linting coercions
1522 * *
1523 ************************************************************************
1524 -}
1525
1526 lintInCo :: InCoercion -> LintM (LintedKind, LintedKind, LintedType, LintedType, Role)
1527 -- Check the coercion, and apply the substitution to it
1528 -- See Note [Linting type lets]
1529 lintInCo co
1530 = addLoc (InCo co) $
1531 do { co' <- applySubstCo co
1532 ; lintCoercion co' }
1533
1534 -- lints a coercion, confirming that its lh kind and its rh kind are both *
1535 -- also ensures that the role is Nominal
1536 lintStarCoercion :: OutCoercion -> LintM (LintedType, LintedType)
1537 lintStarCoercion g
1538 = do { (k1, k2, t1, t2, r) <- lintCoercion g
1539 ; lintStar (text "the kind of the left type in" <+> ppr g) k1
1540 ; lintStar (text "the kind of the right type in" <+> ppr g) k2
1541 ; lintRole g Nominal r
1542 ; return (t1, t2) }
1543
1544 lintCoercion :: OutCoercion -> LintM (LintedKind, LintedKind, LintedType, LintedType, Role)
1545 -- Check the kind of a coercion term, returning the kind
1546 -- Post-condition: the returned OutTypes are lint-free
1547 --
1548 -- If lintCoercion co = (k1, k2, s1, s2, r)
1549 -- then co :: s1 ~r s2
1550 -- s1 :: k2
1551 -- s2 :: k2
1552
1553 -- If you edit this function, you may need to update the GHC formalism
1554 -- See Note [GHC Formalism]
1555 lintCoercion (Refl r ty)
1556 = do { k <- lintType ty
1557 ; return (k, k, ty, ty, r) }
1558
1559 lintCoercion co@(TyConAppCo r tc cos)
1560 | tc `hasKey` funTyConKey
1561 , [_rep1,_rep2,_co1,_co2] <- cos
1562 = do { failWithL (text "Saturated TyConAppCo (->):" <+> ppr co)
1563 } -- All saturated TyConAppCos should be FunCos
1564
1565 | Just {} <- synTyConDefn_maybe tc
1566 = failWithL (text "Synonym in TyConAppCo:" <+> ppr co)
1567
1568 | otherwise
1569 = do { checkTyCon tc
1570 ; (k's, ks, ss, ts, rs) <- mapAndUnzip5M lintCoercion cos
1571 ; k' <- lint_co_app co (tyConKind tc) (ss `zip` k's)
1572 ; k <- lint_co_app co (tyConKind tc) (ts `zip` ks)
1573 ; _ <- zipWith3M lintRole cos (tyConRolesX r tc) rs
1574 ; return (k', k, mkTyConApp tc ss, mkTyConApp tc ts, r) }
1575
1576 lintCoercion co@(AppCo co1 co2)
1577 | TyConAppCo {} <- co1
1578 = failWithL (text "TyConAppCo to the left of AppCo:" <+> ppr co)
1579 | Refl _ (TyConApp {}) <- co1
1580 = failWithL (text "Refl (TyConApp ...) to the left of AppCo:" <+> ppr co)
1581 | otherwise
1582 = do { (k1, k2, s1, s2, r1) <- lintCoercion co1
1583 ; (k'1, k'2, t1, t2, r2) <- lintCoercion co2
1584 ; k3 <- lint_co_app co k1 [(t1,k'1)]
1585 ; k4 <- lint_co_app co k2 [(t2,k'2)]
1586 ; if r1 == Phantom
1587 then lintL (r2 == Phantom || r2 == Nominal)
1588 (text "Second argument in AppCo cannot be R:" $$
1589 ppr co)
1590 else lintRole co Nominal r2
1591 ; return (k3, k4, mkAppTy s1 t1, mkAppTy s2 t2, r1) }
1592
1593 ----------
1594 lintCoercion (ForAllCo tv1 kind_co co)
1595 = do { (_, k2) <- lintStarCoercion kind_co
1596 ; let tv2 = setTyVarKind tv1 k2
1597 ; addInScopeVar tv1 $
1598 do {
1599 ; (k3, k4, t1, t2, r) <- lintCoercion co
1600 ; in_scope <- getInScope
1601 ; let tyl = mkInvForAllTy tv1 t1
1602 subst = mkTvSubst in_scope $
1603 -- We need both the free vars of the `t2` and the
1604 -- free vars of the range of the substitution in
1605 -- scope. All the free vars of `t2` and `kind_co` should
1606 -- already be in `in_scope`, because they've been
1607 -- linted and `tv2` has the same unique as `tv1`.
1608 -- See Note [The substitution invariant]
1609 unitVarEnv tv1 (TyVarTy tv2 `mkCastTy` mkSymCo kind_co)
1610 tyr = mkInvForAllTy tv2 $
1611 substTy subst t2
1612 ; return (k3, k4, tyl, tyr, r) } }
1613
1614 lintCoercion co@(FunCo r co1 co2)
1615 = do { (k1,k'1,s1,t1,r1) <- lintCoercion co1
1616 ; (k2,k'2,s2,t2,r2) <- lintCoercion co2
1617 ; k <- lintArrow (text "coercion" <+> quotes (ppr co)) k1 k2
1618 ; k' <- lintArrow (text "coercion" <+> quotes (ppr co)) k'1 k'2
1619 ; lintRole co1 r r1
1620 ; lintRole co2 r r2
1621 ; return (k, k', mkFunTy s1 s2, mkFunTy t1 t2, r) }
1622
1623 lintCoercion (CoVarCo cv)
1624 | not (isCoVar cv)
1625 = failWithL (hang (text "Bad CoVarCo:" <+> ppr cv)
1626 2 (text "With offending type:" <+> ppr (varType cv)))
1627 | otherwise
1628 = do { lintTyCoVarInScope cv
1629 ; cv' <- lookupIdInScope cv
1630 ; lintUnliftedCoVar cv
1631 ; return $ coVarKindsTypesRole cv' }
1632
1633 -- See Note [Bad unsafe coercion]
1634 lintCoercion co@(UnivCo prov r ty1 ty2)
1635 = do { k1 <- lintType ty1
1636 ; k2 <- lintType ty2
1637 ; case prov of
1638 UnsafeCoerceProv -> return () -- no extra checks
1639
1640 PhantomProv kco -> do { lintRole co Phantom r
1641 ; check_kinds kco k1 k2 }
1642
1643 ProofIrrelProv kco -> do { lintL (isCoercionTy ty1) $
1644 mkBadProofIrrelMsg ty1 co
1645 ; lintL (isCoercionTy ty2) $
1646 mkBadProofIrrelMsg ty2 co
1647 ; check_kinds kco k1 k2 }
1648
1649 PluginProv _ -> return () -- no extra checks
1650 HoleProv h -> addErrL $
1651 text "Unfilled coercion hole:" <+> ppr h
1652
1653 ; when (r /= Phantom && classifiesTypeWithValues k1
1654 && classifiesTypeWithValues k2)
1655 (checkTypes ty1 ty2)
1656 ; return (k1, k2, ty1, ty2, r) }
1657 where
1658 report s = hang (text $ "Unsafe coercion: " ++ s)
1659 2 (vcat [ text "From:" <+> ppr ty1
1660 , text " To:" <+> ppr ty2])
1661 isUnBoxed :: PrimRep -> Bool
1662 isUnBoxed = not . isGcPtrRep
1663
1664 -- see #9122 for discussion of these checks
1665 checkTypes t1 t2
1666 = do { checkWarnL (not lev_poly1)
1667 (report "left-hand type is levity-polymorphic")
1668 ; checkWarnL (not lev_poly2)
1669 (report "right-hand type is levity-polymorphic")
1670 ; when (not (lev_poly1 || lev_poly2)) $
1671 do { checkWarnL (reps1 `equalLength` reps2)
1672 (report "between values with different # of reps")
1673 ; zipWithM_ validateCoercion reps1 reps2 }}
1674 where
1675 lev_poly1 = isTypeLevPoly t1
1676 lev_poly2 = isTypeLevPoly t2
1677
1678 -- don't look at these unless lev_poly1/2 are False
1679 -- Otherwise, we get #13458
1680 reps1 = typePrimRep t1
1681 reps2 = typePrimRep t2
1682
1683 validateCoercion :: PrimRep -> PrimRep -> LintM ()
1684 validateCoercion rep1 rep2
1685 = do { dflags <- getDynFlags
1686 ; checkWarnL (isUnBoxed rep1 == isUnBoxed rep2)
1687 (report "between unboxed and boxed value")
1688 ; checkWarnL (TyCon.primRepSizeB dflags rep1
1689 == TyCon.primRepSizeB dflags rep2)
1690 (report "between unboxed values of different size")
1691 ; let fl = liftM2 (==) (TyCon.primRepIsFloat rep1)
1692 (TyCon.primRepIsFloat rep2)
1693 ; case fl of
1694 Nothing -> addWarnL (report "between vector types")
1695 Just False -> addWarnL (report "between float and integral values")
1696 _ -> return ()
1697 }
1698
1699 check_kinds kco k1 k2 = do { (k1', k2') <- lintStarCoercion kco
1700 ; ensureEqTys k1 k1' (mkBadUnivCoMsg CLeft co)
1701 ; ensureEqTys k2 k2' (mkBadUnivCoMsg CRight co) }
1702
1703
1704 lintCoercion (SymCo co)
1705 = do { (k1, k2, ty1, ty2, r) <- lintCoercion co
1706 ; return (k2, k1, ty2, ty1, r) }
1707
1708 lintCoercion co@(TransCo co1 co2)
1709 = do { (k1a, _k1b, ty1a, ty1b, r1) <- lintCoercion co1
1710 ; (_k2a, k2b, ty2a, ty2b, r2) <- lintCoercion co2
1711 ; ensureEqTys ty1b ty2a
1712 (hang (text "Trans coercion mis-match:" <+> ppr co)
1713 2 (vcat [ppr ty1a, ppr ty1b, ppr ty2a, ppr ty2b]))
1714 ; lintRole co r1 r2
1715 ; return (k1a, k2b, ty1a, ty2b, r1) }
1716
1717 lintCoercion the_co@(NthCo n co)
1718 = do { (_, _, s, t, r) <- lintCoercion co
1719 ; case (splitForAllTy_maybe s, splitForAllTy_maybe t) of
1720 { (Just (tv_s, _ty_s), Just (tv_t, _ty_t))
1721 | n == 0
1722 -> return (ks, kt, ts, tt, Nominal)
1723 where
1724 ts = tyVarKind tv_s
1725 tt = tyVarKind tv_t
1726 ks = typeKind ts
1727 kt = typeKind tt
1728
1729 ; _ -> case (splitTyConApp_maybe s, splitTyConApp_maybe t) of
1730 { (Just (tc_s, tys_s), Just (tc_t, tys_t))
1731 | tc_s == tc_t
1732 , isInjectiveTyCon tc_s r
1733 -- see Note [NthCo and newtypes] in TyCoRep
1734 , tys_s `equalLength` tys_t
1735 , tys_s `lengthExceeds` n
1736 -> return (ks, kt, ts, tt, tr)
1737 where
1738 ts = getNth tys_s n
1739 tt = getNth tys_t n
1740 tr = nthRole r tc_s n
1741 ks = typeKind ts
1742 kt = typeKind tt
1743
1744 ; _ -> failWithL (hang (text "Bad getNth:")
1745 2 (ppr the_co $$ ppr s $$ ppr t)) }}}
1746
1747 lintCoercion the_co@(LRCo lr co)
1748 = do { (_,_,s,t,r) <- lintCoercion co
1749 ; lintRole co Nominal r
1750 ; case (splitAppTy_maybe s, splitAppTy_maybe t) of
1751 (Just s_pr, Just t_pr)
1752 -> return (ks_pick, kt_pick, s_pick, t_pick, Nominal)
1753 where
1754 s_pick = pickLR lr s_pr
1755 t_pick = pickLR lr t_pr
1756 ks_pick = typeKind s_pick
1757 kt_pick = typeKind t_pick
1758
1759 _ -> failWithL (hang (text "Bad LRCo:")
1760 2 (ppr the_co $$ ppr s $$ ppr t)) }
1761
1762 lintCoercion (InstCo co arg)
1763 = do { (k3, k4, t1',t2', r) <- lintCoercion co
1764 ; (k1',k2',s1,s2, r') <- lintCoercion arg
1765 ; lintRole arg Nominal r'
1766 ; in_scope <- getInScope
1767 ; case (splitForAllTy_maybe t1', splitForAllTy_maybe t2') of
1768 (Just (tv1,t1), Just (tv2,t2))
1769 | k1' `eqType` tyVarKind tv1
1770 , k2' `eqType` tyVarKind tv2
1771 -> return (k3, k4,
1772 substTyWithInScope in_scope [tv1] [s1] t1,
1773 substTyWithInScope in_scope [tv2] [s2] t2, r)
1774 | otherwise
1775 -> failWithL (text "Kind mis-match in inst coercion")
1776 _ -> failWithL (text "Bad argument of inst") }
1777
1778 lintCoercion co@(AxiomInstCo con ind cos)
1779 = do { unless (0 <= ind && ind < numBranches (coAxiomBranches con))
1780 (bad_ax (text "index out of range"))
1781 ; let CoAxBranch { cab_tvs = ktvs
1782 , cab_cvs = cvs
1783 , cab_roles = roles
1784 , cab_lhs = lhs
1785 , cab_rhs = rhs } = coAxiomNthBranch con ind
1786 ; unless (cos `equalLength` (ktvs ++ cvs)) $
1787 bad_ax (text "lengths")
1788 ; subst <- getTCvSubst
1789 ; let empty_subst = zapTCvSubst subst
1790 ; (subst_l, subst_r) <- foldlM check_ki
1791 (empty_subst, empty_subst)
1792 (zip3 (ktvs ++ cvs) roles cos)
1793 ; let lhs' = substTys subst_l lhs
1794 rhs' = substTy subst_r rhs
1795 ; case checkAxInstCo co of
1796 Just bad_branch -> bad_ax $ text "inconsistent with" <+>
1797 pprCoAxBranch con bad_branch
1798 Nothing -> return ()
1799 ; let s2 = mkTyConApp (coAxiomTyCon con) lhs'
1800 ; return (typeKind s2, typeKind rhs', s2, rhs', coAxiomRole con) }
1801 where
1802 bad_ax what = addErrL (hang (text "Bad axiom application" <+> parens what)
1803 2 (ppr co))
1804
1805 check_ki (subst_l, subst_r) (ktv, role, arg)
1806 = do { (k', k'', s', t', r) <- lintCoercion arg
1807 ; lintRole arg role r
1808 ; let ktv_kind_l = substTy subst_l (tyVarKind ktv)
1809 ktv_kind_r = substTy subst_r (tyVarKind ktv)
1810 ; unless (k' `eqType` ktv_kind_l)
1811 (bad_ax (text "check_ki1" <+> vcat [ ppr co, ppr k', ppr ktv, ppr ktv_kind_l ] ))
1812 ; unless (k'' `eqType` ktv_kind_r)
1813 (bad_ax (text "check_ki2" <+> vcat [ ppr co, ppr k'', ppr ktv, ppr ktv_kind_r ] ))
1814 ; return (extendTCvSubst subst_l ktv s',
1815 extendTCvSubst subst_r ktv t') }
1816
1817 lintCoercion (CoherenceCo co1 co2)
1818 = do { (_, k2, t1, t2, r) <- lintCoercion co1
1819 ; let lhsty = mkCastTy t1 co2
1820 ; k1' <- lintType lhsty
1821 ; return (k1', k2, lhsty, t2, r) }
1822
1823 lintCoercion (KindCo co)
1824 = do { (k1, k2, _, _, _) <- lintCoercion co
1825 ; return (liftedTypeKind, liftedTypeKind, k1, k2, Nominal) }
1826
1827 lintCoercion (SubCo co')
1828 = do { (k1,k2,s,t,r) <- lintCoercion co'
1829 ; lintRole co' Nominal r
1830 ; return (k1,k2,s,t,Representational) }
1831
1832 lintCoercion this@(AxiomRuleCo co cs)
1833 = do { eqs <- mapM lintCoercion cs
1834 ; lintRoles 0 (coaxrAsmpRoles co) eqs
1835 ; case coaxrProves co [ Pair l r | (_,_,l,r,_) <- eqs ] of
1836 Nothing -> err "Malformed use of AxiomRuleCo" [ ppr this ]
1837 Just (Pair l r) ->
1838 return (typeKind l, typeKind r, l, r, coaxrRole co) }
1839 where
1840 err m xs = failWithL $
1841 hang (text m) 2 $ vcat (text "Rule:" <+> ppr (coaxrName co) : xs)
1842
1843 lintRoles n (e : es) ((_,_,_,_,r) : rs)
1844 | e == r = lintRoles (n+1) es rs
1845 | otherwise = err "Argument roles mismatch"
1846 [ text "In argument:" <+> int (n+1)
1847 , text "Expected:" <+> ppr e
1848 , text "Found:" <+> ppr r ]
1849 lintRoles _ [] [] = return ()
1850 lintRoles n [] rs = err "Too many coercion arguments"
1851 [ text "Expected:" <+> int n
1852 , text "Provided:" <+> int (n + length rs) ]
1853
1854 lintRoles n es [] = err "Not enough coercion arguments"
1855 [ text "Expected:" <+> int (n + length es)
1856 , text "Provided:" <+> int n ]
1857
1858 ----------
1859 lintUnliftedCoVar :: CoVar -> LintM ()
1860 lintUnliftedCoVar cv
1861 = when (not (isUnliftedType (coVarKind cv))) $
1862 failWithL (text "Bad lifted equality:" <+> ppr cv
1863 <+> dcolon <+> ppr (coVarKind cv))
1864
1865 {-
1866 ************************************************************************
1867 * *
1868 \subsection[lint-monad]{The Lint monad}
1869 * *
1870 ************************************************************************
1871 -}
1872
1873 -- If you edit this type, you may need to update the GHC formalism
1874 -- See Note [GHC Formalism]
1875 data LintEnv
1876 = LE { le_flags :: LintFlags -- Linting the result of this pass
1877 , le_loc :: [LintLocInfo] -- Locations
1878 , le_subst :: TCvSubst -- Current type substitution; we also use this
1879 -- to keep track of all the variables in scope,
1880 -- both Ids and TyVars
1881 , le_joins :: IdSet -- Join points in scope that are valid
1882 -- A subset of teh InScopeSet in le_subst
1883 -- See Note [Join points]
1884 , le_dynflags :: DynFlags -- DynamicFlags
1885 }
1886
1887 data LintFlags
1888 = LF { lf_check_global_ids :: Bool -- See Note [Checking for global Ids]
1889 , lf_check_inline_loop_breakers :: Bool -- See Note [Checking for INLINE loop breakers]
1890 , lf_check_static_ptrs :: StaticPtrCheck
1891 -- ^ See Note [Checking StaticPtrs]
1892 }
1893
1894 -- See Note [Checking StaticPtrs]
1895 data StaticPtrCheck
1896 = AllowAnywhere
1897 -- ^ Allow 'makeStatic' to occur anywhere.
1898 | AllowAtTopLevel
1899 -- ^ Allow 'makeStatic' calls at the top-level only.
1900 | RejectEverywhere
1901 -- ^ Reject any 'makeStatic' occurrence.
1902 deriving Eq
1903
1904 defaultLintFlags :: LintFlags
1905 defaultLintFlags = LF { lf_check_global_ids = False
1906 , lf_check_inline_loop_breakers = True
1907 , lf_check_static_ptrs = AllowAnywhere
1908 }
1909
1910 newtype LintM a =
1911 LintM { unLintM ::
1912 LintEnv ->
1913 WarnsAndErrs -> -- Error and warning messages so far
1914 (Maybe a, WarnsAndErrs) } -- Result and messages (if any)
1915
1916 type WarnsAndErrs = (Bag MsgDoc, Bag MsgDoc)
1917
1918 {- Note [Checking for global Ids]
1919 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1920 Before CoreTidy, all locally-bound Ids must be LocalIds, even
1921 top-level ones. See Note [Exported LocalIds] and Trac #9857.
1922
1923 Note [Checking StaticPtrs]
1924 ~~~~~~~~~~~~~~~~~~~~~~~~~~
1925 See Note [Grand plan for static forms] in StaticPtrTable for an overview.
1926
1927 Every occurrence of the function 'makeStatic' should be moved to the
1928 top level by the FloatOut pass. It's vital that we don't have nested
1929 'makeStatic' occurrences after CorePrep, because we populate the Static
1930 Pointer Table from the top-level bindings. See SimplCore Note [Grand
1931 plan for static forms].
1932
1933 The linter checks that no occurrence is left behind, nested within an
1934 expression. The check is enabled only after the FloatOut, CorePrep,
1935 and CoreTidy passes and only if the module uses the StaticPointers
1936 language extension. Checking more often doesn't help since the condition
1937 doesn't hold until after the first FloatOut pass.
1938
1939 Note [Type substitution]
1940 ~~~~~~~~~~~~~~~~~~~~~~~~
1941 Why do we need a type substitution? Consider
1942 /\(a:*). \(x:a). /\(a:*). id a x
1943 This is ill typed, because (renaming variables) it is really
1944 /\(a:*). \(x:a). /\(b:*). id b x
1945 Hence, when checking an application, we can't naively compare x's type
1946 (at its binding site) with its expected type (at a use site). So we
1947 rename type binders as we go, maintaining a substitution.
1948
1949 The same substitution also supports let-type, current expressed as
1950 (/\(a:*). body) ty
1951 Here we substitute 'ty' for 'a' in 'body', on the fly.
1952 -}
1953
1954 instance Functor LintM where
1955 fmap = liftM
1956
1957 instance Applicative LintM where
1958 pure x = LintM $ \ _ errs -> (Just x, errs)
1959 (<*>) = ap
1960
1961 instance Monad LintM where
1962 fail = MonadFail.fail
1963 m >>= k = LintM (\ env errs ->
1964 let (res, errs') = unLintM m env errs in
1965 case res of
1966 Just r -> unLintM (k r) env errs'
1967 Nothing -> (Nothing, errs'))
1968
1969 instance MonadFail.MonadFail LintM where
1970 fail err = failWithL (text err)
1971
1972 instance HasDynFlags LintM where
1973 getDynFlags = LintM (\ e errs -> (Just (le_dynflags e), errs))
1974
1975 data LintLocInfo
1976 = RhsOf Id -- The variable bound
1977 | LambdaBodyOf Id -- The lambda-binder
1978 | UnfoldingOf Id -- Unfolding of a binder
1979 | BodyOfLetRec [Id] -- One of the binders
1980 | CaseAlt CoreAlt -- Case alternative
1981 | CasePat CoreAlt -- The *pattern* of the case alternative
1982 | AnExpr CoreExpr -- Some expression
1983 | ImportedUnfolding SrcLoc -- Some imported unfolding (ToDo: say which)
1984 | TopLevelBindings
1985 | InType Type -- Inside a type
1986 | InCo Coercion -- Inside a coercion
1987
1988 initL :: DynFlags -> LintFlags -> InScopeSet
1989 -> LintM a -> WarnsAndErrs -- Errors and warnings
1990 initL dflags flags in_scope m
1991 = case unLintM m env (emptyBag, emptyBag) of
1992 (_, errs) -> errs
1993 where
1994 env = LE { le_flags = flags
1995 , le_subst = mkEmptyTCvSubst in_scope
1996 , le_joins = emptyVarSet
1997 , le_loc = []
1998 , le_dynflags = dflags }
1999
2000 getLintFlags :: LintM LintFlags
2001 getLintFlags = LintM $ \ env errs -> (Just (le_flags env), errs)
2002
2003 checkL :: Bool -> MsgDoc -> LintM ()
2004 checkL True _ = return ()
2005 checkL False msg = failWithL msg
2006
2007 -- like checkL, but relevant to type checking
2008 lintL :: Bool -> MsgDoc -> LintM ()
2009 lintL = checkL
2010
2011 checkWarnL :: Bool -> MsgDoc -> LintM ()
2012 checkWarnL True _ = return ()
2013 checkWarnL False msg = addWarnL msg
2014
2015 failWithL :: MsgDoc -> LintM a
2016 failWithL msg = LintM $ \ env (warns,errs) ->
2017 (Nothing, (warns, addMsg env errs msg))
2018
2019 addErrL :: MsgDoc -> LintM ()
2020 addErrL msg = LintM $ \ env (warns,errs) ->
2021 (Just (), (warns, addMsg env errs msg))
2022
2023 addWarnL :: MsgDoc -> LintM ()
2024 addWarnL msg = LintM $ \ env (warns,errs) ->
2025 (Just (), (addMsg env warns msg, errs))
2026
2027 addMsg :: LintEnv -> Bag MsgDoc -> MsgDoc -> Bag MsgDoc
2028 addMsg env msgs msg
2029 = ASSERT( notNull locs )
2030 msgs `snocBag` mk_msg msg
2031 where
2032 locs = le_loc env
2033 (loc, cxt1) = dumpLoc (head locs)
2034 cxts = [snd (dumpLoc loc) | loc <- locs]
2035 context = ifPprDebug (vcat (reverse cxts) $$ cxt1 $$
2036 text "Substitution:" <+> ppr (le_subst env))
2037 cxt1
2038
2039 mk_msg msg = mkLocMessage SevWarning (mkSrcSpan loc loc) (context $$ msg)
2040
2041 addLoc :: LintLocInfo -> LintM a -> LintM a
2042 addLoc extra_loc m
2043 = LintM $ \ env errs ->
2044 unLintM m (env { le_loc = extra_loc : le_loc env }) errs
2045
2046 inCasePat :: LintM Bool -- A slight hack; see the unique call site
2047 inCasePat = LintM $ \ env errs -> (Just (is_case_pat env), errs)
2048 where
2049 is_case_pat (LE { le_loc = CasePat {} : _ }) = True
2050 is_case_pat _other = False
2051
2052 addInScopeVar :: Var -> LintM a -> LintM a
2053 addInScopeVar var m
2054 = LintM $ \ env errs ->
2055 unLintM m (env { le_subst = extendTCvInScope (le_subst env) var
2056 , le_joins = delVarSet (le_joins env) var
2057 }) errs
2058
2059 extendSubstL :: TyVar -> Type -> LintM a -> LintM a
2060 extendSubstL tv ty m
2061 = LintM $ \ env errs ->
2062 unLintM m (env { le_subst = Type.extendTvSubst (le_subst env) tv ty }) errs
2063
2064 updateTCvSubst :: TCvSubst -> LintM a -> LintM a
2065 updateTCvSubst subst' m
2066 = LintM $ \ env errs -> unLintM m (env { le_subst = subst' }) errs
2067
2068 markAllJoinsBad :: LintM a -> LintM a
2069 markAllJoinsBad m
2070 = LintM $ \ env errs -> unLintM m (env { le_joins = emptyVarSet }) errs
2071
2072 markAllJoinsBadIf :: Bool -> LintM a -> LintM a
2073 markAllJoinsBadIf True m = markAllJoinsBad m
2074 markAllJoinsBadIf False m = m
2075
2076 addGoodJoins :: [Var] -> LintM a -> LintM a
2077 addGoodJoins vars thing_inside
2078 | null join_ids
2079 = thing_inside
2080 | otherwise
2081 = LintM $ \ env errs -> unLintM thing_inside (add_joins env) errs
2082 where
2083 add_joins env = env { le_joins = le_joins env `extendVarSetList` join_ids }
2084 join_ids = filter isJoinId vars
2085
2086 getValidJoins :: LintM IdSet
2087 getValidJoins = LintM (\ env errs -> (Just (le_joins env), errs))
2088
2089 getTCvSubst :: LintM TCvSubst
2090 getTCvSubst = LintM (\ env errs -> (Just (le_subst env), errs))
2091
2092 getInScope :: LintM InScopeSet
2093 getInScope = LintM (\ env errs -> (Just (getTCvInScope $ le_subst env), errs))
2094
2095 applySubstTy :: InType -> LintM OutType
2096 applySubstTy ty = do { subst <- getTCvSubst; return (substTy subst ty) }
2097
2098 applySubstCo :: InCoercion -> LintM OutCoercion
2099 applySubstCo co = do { subst <- getTCvSubst; return (substCo subst co) }
2100
2101 lookupIdInScope :: Id -> LintM Id
2102 lookupIdInScope id
2103 | not (mustHaveLocalBinding id)
2104 = return id -- An imported Id
2105 | otherwise
2106 = do { subst <- getTCvSubst
2107 ; case lookupInScope (getTCvInScope subst) id of
2108 Just v -> return v
2109 Nothing -> do { addErrL out_of_scope
2110 ; return id } }
2111 where
2112 out_of_scope = pprBndr LetBind id <+> text "is out of scope"
2113
2114 lookupJoinId :: Id -> LintM (Maybe JoinArity)
2115 -- Look up an Id which should be a join point, valid here
2116 -- If so, return its arity, if not return Nothing
2117 lookupJoinId id
2118 = do { join_set <- getValidJoins
2119 ; case lookupVarSet join_set id of
2120 Just id' -> return (isJoinId_maybe id')
2121 Nothing -> return Nothing }
2122
2123 lintTyCoVarInScope :: Var -> LintM ()
2124 lintTyCoVarInScope v = lintInScope (text "is out of scope") v
2125
2126 lintInScope :: SDoc -> Var -> LintM ()
2127 lintInScope loc_msg var =
2128 do { subst <- getTCvSubst
2129 ; lintL (not (mustHaveLocalBinding var) || (var `isInScope` subst))
2130 (hsep [pprBndr LetBind var, loc_msg]) }
2131
2132 ensureEqTys :: OutType -> OutType -> MsgDoc -> LintM ()
2133 -- check ty2 is subtype of ty1 (ie, has same structure but usage
2134 -- annotations need only be consistent, not equal)
2135 -- Assumes ty1,ty2 are have already had the substitution applied
2136 ensureEqTys ty1 ty2 msg = lintL (ty1 `eqType` ty2) msg
2137
2138 lintRole :: Outputable thing
2139 => thing -- where the role appeared
2140 -> Role -- expected
2141 -> Role -- actual
2142 -> LintM ()
2143 lintRole co r1 r2
2144 = lintL (r1 == r2)
2145 (text "Role incompatibility: expected" <+> ppr r1 <> comma <+>
2146 text "got" <+> ppr r2 $$
2147 text "in" <+> ppr co)
2148
2149 {-
2150 ************************************************************************
2151 * *
2152 \subsection{Error messages}
2153 * *
2154 ************************************************************************
2155 -}
2156
2157 dumpLoc :: LintLocInfo -> (SrcLoc, SDoc)
2158
2159 dumpLoc (RhsOf v)
2160 = (getSrcLoc v, brackets (text "RHS of" <+> pp_binders [v]))
2161
2162 dumpLoc (LambdaBodyOf b)
2163 = (getSrcLoc b, brackets (text "in body of lambda with binder" <+> pp_binder b))
2164
2165 dumpLoc (UnfoldingOf b)
2166 = (getSrcLoc b, brackets (text "in the unfolding of" <+> pp_binder b))
2167
2168 dumpLoc (BodyOfLetRec [])
2169 = (noSrcLoc, brackets (text "In body of a letrec with no binders"))
2170
2171 dumpLoc (BodyOfLetRec bs@(_:_))
2172 = ( getSrcLoc (head bs), brackets (text "in body of letrec with binders" <+> pp_binders bs))
2173
2174 dumpLoc (AnExpr e)
2175 = (noSrcLoc, text "In the expression:" <+> ppr e)
2176
2177 dumpLoc (CaseAlt (con, args, _))
2178 = (noSrcLoc, text "In a case alternative:" <+> parens (ppr con <+> pp_binders args))
2179
2180 dumpLoc (CasePat (con, args, _))
2181 = (noSrcLoc, text "In the pattern of a case alternative:" <+> parens (ppr con <+> pp_binders args))
2182
2183 dumpLoc (ImportedUnfolding locn)
2184 = (locn, brackets (text "in an imported unfolding"))
2185 dumpLoc TopLevelBindings
2186 = (noSrcLoc, Outputable.empty)
2187 dumpLoc (InType ty)
2188 = (noSrcLoc, text "In the type" <+> quotes (ppr ty))
2189 dumpLoc (InCo co)
2190 = (noSrcLoc, text "In the coercion" <+> quotes (ppr co))
2191
2192 pp_binders :: [Var] -> SDoc
2193 pp_binders bs = sep (punctuate comma (map pp_binder bs))
2194
2195 pp_binder :: Var -> SDoc
2196 pp_binder b | isId b = hsep [ppr b, dcolon, ppr (idType b)]
2197 | otherwise = hsep [ppr b, dcolon, ppr (tyVarKind b)]
2198
2199 ------------------------------------------------------
2200 -- Messages for case expressions
2201
2202 mkDefaultArgsMsg :: [Var] -> MsgDoc
2203 mkDefaultArgsMsg args
2204 = hang (text "DEFAULT case with binders")
2205 4 (ppr args)
2206
2207 mkCaseAltMsg :: CoreExpr -> Type -> Type -> MsgDoc
2208 mkCaseAltMsg e ty1 ty2
2209 = hang (text "Type of case alternatives not the same as the annotation on case:")
2210 4 (vcat [ text "Actual type:" <+> ppr ty1,
2211 text "Annotation on case:" <+> ppr ty2,
2212 text "Alt Rhs:" <+> ppr e ])
2213
2214 mkScrutMsg :: Id -> Type -> Type -> TCvSubst -> MsgDoc
2215 mkScrutMsg var var_ty scrut_ty subst
2216 = vcat [text "Result binder in case doesn't match scrutinee:" <+> ppr var,
2217 text "Result binder type:" <+> ppr var_ty,--(idType var),
2218 text "Scrutinee type:" <+> ppr scrut_ty,
2219 hsep [text "Current TCv subst", ppr subst]]
2220
2221 mkNonDefltMsg, mkNonIncreasingAltsMsg :: CoreExpr -> MsgDoc
2222 mkNonDefltMsg e
2223 = hang (text "Case expression with DEFAULT not at the beginning") 4 (ppr e)
2224 mkNonIncreasingAltsMsg e
2225 = hang (text "Case expression with badly-ordered alternatives") 4 (ppr e)
2226
2227 nonExhaustiveAltsMsg :: CoreExpr -> MsgDoc
2228 nonExhaustiveAltsMsg e
2229 = hang (text "Case expression with non-exhaustive alternatives") 4 (ppr e)
2230
2231 mkBadConMsg :: TyCon -> DataCon -> MsgDoc
2232 mkBadConMsg tycon datacon
2233 = vcat [
2234 text "In a case alternative, data constructor isn't in scrutinee type:",
2235 text "Scrutinee type constructor:" <+> ppr tycon,
2236 text "Data con:" <+> ppr datacon
2237 ]
2238
2239 mkBadPatMsg :: Type -> Type -> MsgDoc
2240 mkBadPatMsg con_result_ty scrut_ty
2241 = vcat [
2242 text "In a case alternative, pattern result type doesn't match scrutinee type:",
2243 text "Pattern result type:" <+> ppr con_result_ty,
2244 text "Scrutinee type:" <+> ppr scrut_ty
2245 ]
2246
2247 integerScrutinisedMsg :: MsgDoc
2248 integerScrutinisedMsg
2249 = text "In a LitAlt, the literal is lifted (probably Integer)"
2250
2251 mkBadAltMsg :: Type -> CoreAlt -> MsgDoc
2252 mkBadAltMsg scrut_ty alt
2253 = vcat [ text "Data alternative when scrutinee is not a tycon application",
2254 text "Scrutinee type:" <+> ppr scrut_ty,
2255 text "Alternative:" <+> pprCoreAlt alt ]
2256
2257 mkNewTyDataConAltMsg :: Type -> CoreAlt -> MsgDoc
2258 mkNewTyDataConAltMsg scrut_ty alt
2259 = vcat [ text "Data alternative for newtype datacon",
2260 text "Scrutinee type:" <+> ppr scrut_ty,
2261 text "Alternative:" <+> pprCoreAlt alt ]
2262
2263
2264 ------------------------------------------------------
2265 -- Other error messages
2266
2267 mkAppMsg :: Type -> Type -> CoreExpr -> MsgDoc
2268 mkAppMsg fun_ty arg_ty arg
2269 = vcat [text "Argument value doesn't match argument type:",
2270 hang (text "Fun type:") 4 (ppr fun_ty),
2271 hang (text "Arg type:") 4 (ppr arg_ty),
2272 hang (text "Arg:") 4 (ppr arg)]
2273
2274 mkNonFunAppMsg :: Type -> Type -> CoreExpr -> MsgDoc
2275 mkNonFunAppMsg fun_ty arg_ty arg
2276 = vcat [text "Non-function type in function position",
2277 hang (text "Fun type:") 4 (ppr fun_ty),
2278 hang (text "Arg type:") 4 (ppr arg_ty),
2279 hang (text "Arg:") 4 (ppr arg)]
2280
2281 mkLetErr :: TyVar -> CoreExpr -> MsgDoc
2282 mkLetErr bndr rhs
2283 = vcat [text "Bad `let' binding:",
2284 hang (text "Variable:")
2285 4 (ppr bndr <+> dcolon <+> ppr (varType bndr)),
2286 hang (text "Rhs:")
2287 4 (ppr rhs)]
2288
2289 mkTyAppMsg :: Type -> Type -> MsgDoc
2290 mkTyAppMsg ty arg_ty
2291 = vcat [text "Illegal type application:",
2292 hang (text "Exp type:")
2293 4 (ppr ty <+> dcolon <+> ppr (typeKind ty)),
2294 hang (text "Arg type:")
2295 4 (ppr arg_ty <+> dcolon <+> ppr (typeKind arg_ty))]
2296
2297 emptyRec :: CoreExpr -> MsgDoc
2298 emptyRec e = hang (text "Empty Rec binding:") 2 (ppr e)
2299
2300 mkRhsMsg :: Id -> SDoc -> Type -> MsgDoc
2301 mkRhsMsg binder what ty
2302 = vcat
2303 [hsep [text "The type of this binder doesn't match the type of its" <+> what <> colon,
2304 ppr binder],
2305 hsep [text "Binder's type:", ppr (idType binder)],
2306 hsep [text "Rhs type:", ppr ty]]
2307
2308 mkLetAppMsg :: CoreExpr -> MsgDoc
2309 mkLetAppMsg e
2310 = hang (text "This argument does not satisfy the let/app invariant:")
2311 2 (ppr e)
2312
2313 badBndrTyMsg :: Id -> SDoc -> MsgDoc
2314 badBndrTyMsg binder what
2315 = vcat [ text "The type of this binder is" <+> what <> colon <+> ppr binder
2316 , text "Binder's type:" <+> ppr (idType binder) ]
2317
2318 mkStrictMsg :: Id -> MsgDoc
2319 mkStrictMsg binder
2320 = vcat [hsep [text "Recursive or top-level binder has strict demand info:",
2321 ppr binder],
2322 hsep [text "Binder's demand info:", ppr (idDemandInfo binder)]
2323 ]
2324
2325 mkNonTopExportedMsg :: Id -> MsgDoc
2326 mkNonTopExportedMsg binder
2327 = hsep [text "Non-top-level binder is marked as exported:", ppr binder]
2328
2329 mkNonTopExternalNameMsg :: Id -> MsgDoc
2330 mkNonTopExternalNameMsg binder
2331 = hsep [text "Non-top-level binder has an external name:", ppr binder]
2332
2333 mkTopNonLitStrMsg :: Id -> MsgDoc
2334 mkTopNonLitStrMsg binder
2335 = hsep [text "Top-level Addr# binder has a non-literal rhs:", ppr binder]
2336
2337 mkKindErrMsg :: TyVar -> Type -> MsgDoc
2338 mkKindErrMsg tyvar arg_ty
2339 = vcat [text "Kinds don't match in type application:",
2340 hang (text "Type variable:")
2341 4 (ppr tyvar <+> dcolon <+> ppr (tyVarKind tyvar)),
2342 hang (text "Arg type:")
2343 4 (ppr arg_ty <+> dcolon <+> ppr (typeKind arg_ty))]
2344
2345 {- Not needed now
2346 mkArityMsg :: Id -> MsgDoc
2347 mkArityMsg binder
2348 = vcat [hsep [text "Demand type has",
2349 ppr (dmdTypeDepth dmd_ty),
2350 text "arguments, rhs has",
2351 ppr (idArity binder),
2352 text "arguments,",
2353 ppr binder],
2354 hsep [text "Binder's strictness signature:", ppr dmd_ty]
2355
2356 ]
2357 where (StrictSig dmd_ty) = idStrictness binder
2358 -}
2359 mkCastErr :: Outputable casted => casted -> Coercion -> Type -> Type -> MsgDoc
2360 mkCastErr expr co from_ty expr_ty
2361 = vcat [text "From-type of Cast differs from type of enclosed expression",
2362 text "From-type:" <+> ppr from_ty,
2363 text "Type of enclosed expr:" <+> ppr expr_ty,
2364 text "Actual enclosed expr:" <+> ppr expr,
2365 text "Coercion used in cast:" <+> ppr co
2366 ]
2367
2368 mkBadUnivCoMsg :: LeftOrRight -> Coercion -> SDoc
2369 mkBadUnivCoMsg lr co
2370 = text "Kind mismatch on the" <+> pprLeftOrRight lr <+>
2371 text "side of a UnivCo:" <+> ppr co
2372
2373 mkBadProofIrrelMsg :: Type -> Coercion -> SDoc
2374 mkBadProofIrrelMsg ty co
2375 = hang (text "Found a non-coercion in a proof-irrelevance UnivCo:")
2376 2 (vcat [ text "type:" <+> ppr ty
2377 , text "co:" <+> ppr co ])
2378
2379 mkBadTyVarMsg :: Var -> SDoc
2380 mkBadTyVarMsg tv
2381 = text "Non-tyvar used in TyVarTy:"
2382 <+> ppr tv <+> dcolon <+> ppr (varType tv)
2383
2384 mkBadJoinBindMsg :: Var -> SDoc
2385 mkBadJoinBindMsg var
2386 = vcat [ text "Bad join point binding:" <+> ppr var
2387 , text "Join points can be bound only by a non-top-level let" ]
2388
2389 mkInvalidJoinPointMsg :: Var -> Type -> SDoc
2390 mkInvalidJoinPointMsg var ty
2391 = hang (text "Join point has invalid type:")
2392 2 (ppr var <+> dcolon <+> ppr ty)
2393
2394 mkBadJoinArityMsg :: Var -> Int -> Int -> CoreExpr -> SDoc
2395 mkBadJoinArityMsg var ar nlams rhs
2396 = vcat [ text "Join point has too few lambdas",
2397 text "Join var:" <+> ppr var,
2398 text "Join arity:" <+> ppr ar,
2399 text "Number of lambdas:" <+> ppr nlams,
2400 text "Rhs = " <+> ppr rhs
2401 ]
2402
2403 invalidJoinOcc :: Var -> SDoc
2404 invalidJoinOcc var
2405 = vcat [ text "Invalid occurrence of a join variable:" <+> ppr var
2406 , text "The binder is either not a join point, or not valid here" ]
2407
2408 mkBadJumpMsg :: Var -> Int -> Int -> SDoc
2409 mkBadJumpMsg var ar nargs
2410 = vcat [ text "Join point invoked with wrong number of arguments",
2411 text "Join var:" <+> ppr var,
2412 text "Join arity:" <+> ppr ar,
2413 text "Number of arguments:" <+> int nargs ]
2414
2415 mkInconsistentRecMsg :: [Var] -> SDoc
2416 mkInconsistentRecMsg bndrs
2417 = vcat [ text "Recursive let binders mix values and join points",
2418 text "Binders:" <+> hsep (map ppr_with_details bndrs) ]
2419 where
2420 ppr_with_details bndr = ppr bndr <> ppr (idDetails bndr)
2421
2422 mkJoinBndrOccMismatchMsg :: Var -> JoinArity -> JoinArity -> SDoc
2423 mkJoinBndrOccMismatchMsg bndr join_arity_bndr join_arity_occ
2424 = vcat [ text "Mismatch in join point arity between binder and occurrence"
2425 , text "Var:" <+> ppr bndr
2426 , text "Arity at binding site:" <+> ppr join_arity_bndr
2427 , text "Arity at occurrence: " <+> ppr join_arity_occ ]
2428
2429 mkBndrOccTypeMismatchMsg :: Var -> Var -> OutType -> OutType -> SDoc
2430 mkBndrOccTypeMismatchMsg bndr var bndr_ty var_ty
2431 = vcat [ text "Mismatch in type between binder and occurrence"
2432 , text "Var:" <+> ppr bndr
2433 , text "Binder type:" <+> ppr bndr_ty
2434 , text "Occurrence type:" <+> ppr var_ty
2435 , text " Before subst:" <+> ppr (idType var) ]
2436
2437 mkBadJoinPointRuleMsg :: JoinId -> JoinArity -> CoreRule -> SDoc
2438 mkBadJoinPointRuleMsg bndr join_arity rule
2439 = vcat [ text "Join point has rule with wrong number of arguments"
2440 , text "Var:" <+> ppr bndr
2441 , text "Join arity:" <+> ppr join_arity
2442 , text "Rule:" <+> ppr rule ]
2443
2444 pprLeftOrRight :: LeftOrRight -> MsgDoc
2445 pprLeftOrRight CLeft = text "left"
2446 pprLeftOrRight CRight = text "right"
2447
2448 dupVars :: [NonEmpty Var] -> MsgDoc
2449 dupVars vars
2450 = hang (text "Duplicate variables brought into scope")
2451 2 (ppr (map toList vars))
2452
2453 dupExtVars :: [NonEmpty Name] -> MsgDoc
2454 dupExtVars vars
2455 = hang (text "Duplicate top-level variables with the same qualified name")
2456 2 (ppr (map toList vars))
2457
2458 {-
2459 ************************************************************************
2460 * *
2461 \subsection{Annotation Linting}
2462 * *
2463 ************************************************************************
2464 -}
2465
2466 -- | This checks whether a pass correctly looks through debug
2467 -- annotations (@SourceNote@). This works a bit different from other
2468 -- consistency checks: We check this by running the given task twice,
2469 -- noting all differences between the results.
2470 lintAnnots :: SDoc -> (ModGuts -> CoreM ModGuts) -> ModGuts -> CoreM ModGuts
2471 lintAnnots pname pass guts = do
2472 -- Run the pass as we normally would
2473 dflags <- getDynFlags
2474 when (gopt Opt_DoAnnotationLinting dflags) $
2475 liftIO $ Err.showPass dflags "Annotation linting - first run"
2476 nguts <- pass guts
2477 -- If appropriate re-run it without debug annotations to make sure
2478 -- that they made no difference.
2479 when (gopt Opt_DoAnnotationLinting dflags) $ do
2480 liftIO $ Err.showPass dflags "Annotation linting - second run"
2481 nguts' <- withoutAnnots pass guts
2482 -- Finally compare the resulting bindings
2483 liftIO $ Err.showPass dflags "Annotation linting - comparison"
2484 let binds = flattenBinds $ mg_binds nguts
2485 binds' = flattenBinds $ mg_binds nguts'
2486 (diffs,_) = diffBinds True (mkRnEnv2 emptyInScopeSet) binds binds'
2487 when (not (null diffs)) $ CoreMonad.putMsg $ vcat
2488 [ lint_banner "warning" pname
2489 , text "Core changes with annotations:"
2490 , withPprStyle (defaultDumpStyle dflags) $ nest 2 $ vcat diffs
2491 ]
2492 -- Return actual new guts
2493 return nguts
2494
2495 -- | Run the given pass without annotations. This means that we both
2496 -- set the debugLevel setting to 0 in the environment as well as all
2497 -- annotations from incoming modules.
2498 withoutAnnots :: (ModGuts -> CoreM ModGuts) -> ModGuts -> CoreM ModGuts
2499 withoutAnnots pass guts = do
2500 -- Remove debug flag from environment.
2501 dflags <- getDynFlags
2502 let removeFlag env = env{ hsc_dflags = dflags{ debugLevel = 0} }
2503 withoutFlag corem =
2504 liftIO =<< runCoreM <$> fmap removeFlag getHscEnv <*> getRuleBase <*>
2505 getUniqueSupplyM <*> getModule <*>
2506 getVisibleOrphanMods <*>
2507 getPrintUnqualified <*> getSrcSpanM <*>
2508 pure corem
2509 -- Nuke existing ticks in module.
2510 -- TODO: Ticks in unfoldings. Maybe change unfolding so it removes
2511 -- them in absence of debugLevel > 0.
2512 let nukeTicks = stripTicksE (not . tickishIsCode)
2513 nukeAnnotsBind :: CoreBind -> CoreBind
2514 nukeAnnotsBind bind = case bind of
2515 Rec bs -> Rec $ map (\(b,e) -> (b, nukeTicks e)) bs
2516 NonRec b e -> NonRec b $ nukeTicks e
2517 nukeAnnotsMod mg@ModGuts{mg_binds=binds}
2518 = mg{mg_binds = map nukeAnnotsBind binds}
2519 -- Perform pass with all changes applied
2520 fmap fst $ withoutFlag $ pass (nukeAnnotsMod guts)