Fix #16517 by bumping the TcLevel for method sigs
[ghc.git] / compiler / typecheck / TcRnDriver.hs
1 {-
2 (c) The University of Glasgow 2006
3 (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4
5 \section[TcRnDriver]{Typechecking a whole module}
6
7 https://ghc.haskell.org/trac/ghc/wiki/Commentary/Compiler/TypeChecker
8 -}
9
10 {-# LANGUAGE CPP #-}
11 {-# LANGUAGE BangPatterns #-}
12 {-# LANGUAGE LambdaCase #-}
13 {-# LANGUAGE NondecreasingIndentation #-}
14 {-# LANGUAGE GeneralizedNewtypeDeriving #-}
15 {-# LANGUAGE ScopedTypeVariables #-}
16 {-# LANGUAGE TypeFamilies #-}
17 {-# LANGUAGE FlexibleContexts #-}
18 {-# LANGUAGE ViewPatterns #-}
19
20 module TcRnDriver (
21 tcRnStmt, tcRnExpr, TcRnExprMode(..), tcRnType,
22 tcRnImportDecls,
23 tcRnLookupRdrName,
24 getModuleInterface,
25 tcRnDeclsi,
26 isGHCiMonad,
27 runTcInteractive, -- Used by GHC API clients (Trac #8878)
28 tcRnLookupName,
29 tcRnGetInfo,
30 tcRnModule, tcRnModuleTcRnM,
31 tcTopSrcDecls,
32 rnTopSrcDecls,
33 checkBootDecl, checkHiBootIface',
34 findExtraSigImports,
35 implicitRequirements,
36 checkUnitId,
37 mergeSignatures,
38 tcRnMergeSignatures,
39 instantiateSignature,
40 tcRnInstantiateSignature,
41 loadUnqualIfaces,
42 -- More private...
43 badReexportedBootThing,
44 checkBootDeclM,
45 missingBootThing,
46 getRenamedStuff, RenamedStuff
47 ) where
48
49 import GhcPrelude
50
51 import {-# SOURCE #-} TcSplice ( finishTH, runRemoteModFinalizers )
52 import RnSplice ( rnTopSpliceDecls, traceSplice, SpliceInfo(..) )
53 import IfaceEnv( externaliseName )
54 import TcHsType
55 import TcValidity( checkValidType )
56 import TcMatches
57 import Inst( deeplyInstantiate )
58 import TcUnify( checkConstraints )
59 import RnTypes
60 import RnExpr
61 import RnUtils ( HsDocContext(..) )
62 import RnFixity ( lookupFixityRn )
63 import MkId
64 import TidyPgm ( globaliseAndTidyId )
65 import TysWiredIn ( unitTy, mkListTy )
66 import Plugins
67 import DynFlags
68 import HsSyn
69 import IfaceSyn ( ShowSub(..), showToHeader )
70 import IfaceType( ShowForAllFlag(..) )
71 import PatSyn( pprPatSynType )
72 import PrelNames
73 import PrelInfo
74 import RdrName
75 import TcHsSyn
76 import TcExpr
77 import TcRnMonad
78 import TcRnExports
79 import TcEvidence
80 import qualified BooleanFormula as BF
81 import PprTyThing( pprTyThingInContext )
82 import CoreFVs( orphNamesOfFamInst )
83 import FamInst
84 import InstEnv
85 import FamInstEnv( FamInst, pprFamInst, famInstsRepTyCons
86 , famInstEnvElts, extendFamInstEnvList, normaliseType )
87 import TcAnnotations
88 import TcBinds
89 import MkIface ( coAxiomToIfaceDecl )
90 import HeaderInfo ( mkPrelImports )
91 import TcDefaults
92 import TcEnv
93 import TcRules
94 import TcForeign
95 import TcInstDcls
96 import TcIface
97 import TcMType
98 import TcType
99 import TcSimplify
100 import TcTyClsDecls
101 import TcTypeable ( mkTypeableBinds )
102 import TcBackpack
103 import LoadIface
104 import RnNames
105 import RnEnv
106 import RnSource
107 import ErrUtils
108 import Id
109 import IdInfo( IdDetails(..) )
110 import VarEnv
111 import Module
112 import UniqFM
113 import Name
114 import NameEnv
115 import NameSet
116 import Avail
117 import TyCon
118 import SrcLoc
119 import HscTypes
120 import ListSetOps
121 import Outputable
122 import ConLike
123 import DataCon
124 import Type
125 import Class
126 import BasicTypes hiding( SuccessFlag(..) )
127 import CoAxiom
128 import Annotations
129 import Data.List ( sortBy, sort )
130 import Data.Ord
131 import FastString
132 import Maybes
133 import Util
134 import Bag
135 import Inst (tcGetInsts)
136 import qualified GHC.LanguageExtensions as LangExt
137 import Data.Data ( Data )
138 import HsDumpAst
139 import qualified Data.Set as S
140
141 import Control.DeepSeq
142 import Control.Monad
143
144 #include "HsVersions.h"
145
146 {-
147 ************************************************************************
148 * *
149 Typecheck and rename a module
150 * *
151 ************************************************************************
152 -}
153
154 -- | Top level entry point for typechecker and renamer
155 tcRnModule :: HscEnv
156 -> ModSummary
157 -> Bool -- True <=> save renamed syntax
158 -> HsParsedModule
159 -> IO (Messages, Maybe TcGblEnv)
160
161 tcRnModule hsc_env mod_sum save_rn_syntax
162 parsedModule@HsParsedModule {hpm_module= (dL->L loc this_module)}
163 | RealSrcSpan real_loc <- loc
164 = withTiming (pure dflags)
165 (text "Renamer/typechecker"<+>brackets (ppr this_mod))
166 (const ()) $
167 initTc hsc_env hsc_src save_rn_syntax this_mod real_loc $
168 withTcPlugins hsc_env $
169
170 tcRnModuleTcRnM hsc_env mod_sum parsedModule pair
171
172 | otherwise
173 = return ((emptyBag, unitBag err_msg), Nothing)
174
175 where
176 hsc_src = ms_hsc_src mod_sum
177 dflags = hsc_dflags hsc_env
178 err_msg = mkPlainErrMsg (hsc_dflags hsc_env) loc $
179 text "Module does not have a RealSrcSpan:" <+> ppr this_mod
180
181 this_pkg = thisPackage (hsc_dflags hsc_env)
182
183 pair :: (Module, SrcSpan)
184 pair@(this_mod,_)
185 | Just (dL->L mod_loc mod) <- hsmodName this_module
186 = (mkModule this_pkg mod, mod_loc)
187
188 | otherwise -- 'module M where' is omitted
189 = (mAIN, srcLocSpan (srcSpanStart loc))
190
191
192
193
194 tcRnModuleTcRnM :: HscEnv
195 -> ModSummary
196 -> HsParsedModule
197 -> (Module, SrcSpan)
198 -> TcRn TcGblEnv
199 -- Factored out separately from tcRnModule so that a Core plugin can
200 -- call the type checker directly
201 tcRnModuleTcRnM hsc_env mod_sum
202 (HsParsedModule {
203 hpm_module =
204 (dL->L loc (HsModule maybe_mod export_ies
205 import_decls local_decls mod_deprec
206 maybe_doc_hdr)),
207 hpm_src_files = src_files
208 })
209 (this_mod, prel_imp_loc)
210 = setSrcSpan loc $
211 do { let { explicit_mod_hdr = isJust maybe_mod
212 ; hsc_src = ms_hsc_src mod_sum }
213 ; -- Load the hi-boot interface for this module, if any
214 -- We do this now so that the boot_names can be passed
215 -- to tcTyAndClassDecls, because the boot_names are
216 -- automatically considered to be loop breakers
217 tcg_env <- getGblEnv
218 ; boot_info <- tcHiBootIface hsc_src this_mod
219 ; setGblEnv (tcg_env { tcg_self_boot = boot_info })
220 $ do
221 { -- Deal with imports; first add implicit prelude
222 implicit_prelude <- xoptM LangExt.ImplicitPrelude
223 ; let { prel_imports = mkPrelImports (moduleName this_mod) prel_imp_loc
224 implicit_prelude import_decls }
225
226 ; whenWOptM Opt_WarnImplicitPrelude $
227 when (notNull prel_imports) $
228 addWarn (Reason Opt_WarnImplicitPrelude) (implicitPreludeWarn)
229
230 ; -- TODO This is a little skeevy; maybe handle a bit more directly
231 let { simplifyImport (dL->L _ idecl) =
232 ( fmap sl_fs (ideclPkgQual idecl) , ideclName idecl)
233 }
234 ; raw_sig_imports <- liftIO
235 $ findExtraSigImports hsc_env hsc_src
236 (moduleName this_mod)
237 ; raw_req_imports <- liftIO
238 $ implicitRequirements hsc_env
239 (map simplifyImport (prel_imports
240 ++ import_decls))
241 ; let { mkImport (Nothing, dL->L _ mod_name) = noLoc
242 $ (simpleImportDecl mod_name)
243 { ideclHiding = Just (False, noLoc [])}
244 ; mkImport _ = panic "mkImport" }
245 ; let { all_imports = prel_imports ++ import_decls
246 ++ map mkImport (raw_sig_imports ++ raw_req_imports) }
247 ; -- OK now finally rename the imports
248 tcg_env <- {-# SCC "tcRnImports" #-}
249 tcRnImports hsc_env all_imports
250
251 ; -- If the whole module is warned about or deprecated
252 -- (via mod_deprec) record that in tcg_warns. If we do thereby add
253 -- a WarnAll, it will override any subsequent deprecations added to tcg_warns
254 let { tcg_env1 = case mod_deprec of
255 Just (dL->L _ txt) ->
256 tcg_env {tcg_warns = WarnAll txt}
257 Nothing -> tcg_env
258 }
259 ; setGblEnv tcg_env1
260 $ do { -- Rename and type check the declarations
261 traceRn "rn1a" empty
262 ; tcg_env <- if isHsBootOrSig hsc_src
263 then tcRnHsBootDecls hsc_src local_decls
264 else {-# SCC "tcRnSrcDecls" #-}
265 tcRnSrcDecls explicit_mod_hdr local_decls
266 ; setGblEnv tcg_env
267 $ do { -- Process the export list
268 traceRn "rn4a: before exports" empty
269 ; tcg_env <- tcRnExports explicit_mod_hdr export_ies
270 tcg_env
271 ; traceRn "rn4b: after exports" empty
272 ; -- Check main is exported(must be after tcRnExports)
273 checkMainExported tcg_env
274 ; -- Compare hi-boot iface (if any) with the real thing
275 -- Must be done after processing the exports
276 tcg_env <- checkHiBootIface tcg_env boot_info
277 ; -- The new type env is already available to stuff
278 -- slurped from interface files, via
279 -- TcEnv.setGlobalTypeEnv. It's important that this
280 -- includes the stuff in checkHiBootIface,
281 -- because the latter might add new bindings for
282 -- boot_dfuns, which may be mentioned in imported
283 -- unfoldings.
284
285 -- Don't need to rename the Haddock documentation,
286 -- it's not parsed by GHC anymore.
287 tcg_env <- return (tcg_env
288 { tcg_doc_hdr = maybe_doc_hdr })
289 ; -- Report unused names
290 -- Do this /after/ typeinference, so that when reporting
291 -- a function with no type signature we can give the
292 -- inferred type
293 reportUnusedNames export_ies tcg_env
294 ; -- add extra source files to tcg_dependent_files
295 addDependentFiles src_files
296 ; tcg_env <- runTypecheckerPlugin mod_sum hsc_env tcg_env
297 ; -- Dump output and return
298 tcDump tcg_env
299 ; return tcg_env }
300 }
301 }
302 }
303
304 implicitPreludeWarn :: SDoc
305 implicitPreludeWarn
306 = text "Module `Prelude' implicitly imported"
307
308 {-
309 ************************************************************************
310 * *
311 Import declarations
312 * *
313 ************************************************************************
314 -}
315
316 tcRnImports :: HscEnv -> [LImportDecl GhcPs] -> TcM TcGblEnv
317 tcRnImports hsc_env import_decls
318 = do { (rn_imports, rdr_env, imports, hpc_info) <- rnImports import_decls ;
319
320 ; this_mod <- getModule
321 ; let { dep_mods :: ModuleNameEnv (ModuleName, IsBootInterface)
322 ; dep_mods = imp_dep_mods imports
323
324 -- We want instance declarations from all home-package
325 -- modules below this one, including boot modules, except
326 -- ourselves. The 'except ourselves' is so that we don't
327 -- get the instances from this module's hs-boot file. This
328 -- filtering also ensures that we don't see instances from
329 -- modules batch (@--make@) compiled before this one, but
330 -- which are not below this one.
331 ; want_instances :: ModuleName -> Bool
332 ; want_instances mod = mod `elemUFM` dep_mods
333 && mod /= moduleName this_mod
334 ; (home_insts, home_fam_insts) = hptInstances hsc_env
335 want_instances
336 } ;
337
338 -- Record boot-file info in the EPS, so that it's
339 -- visible to loadHiBootInterface in tcRnSrcDecls,
340 -- and any other incrementally-performed imports
341 ; updateEps_ (\eps -> eps { eps_is_boot = dep_mods }) ;
342
343 -- Update the gbl env
344 ; updGblEnv ( \ gbl ->
345 gbl {
346 tcg_rdr_env = tcg_rdr_env gbl `plusGlobalRdrEnv` rdr_env,
347 tcg_imports = tcg_imports gbl `plusImportAvails` imports,
348 tcg_rn_imports = rn_imports,
349 tcg_inst_env = extendInstEnvList (tcg_inst_env gbl) home_insts,
350 tcg_fam_inst_env = extendFamInstEnvList (tcg_fam_inst_env gbl)
351 home_fam_insts,
352 tcg_hpc = hpc_info
353 }) $ do {
354
355 ; traceRn "rn1" (ppr (imp_dep_mods imports))
356 -- Fail if there are any errors so far
357 -- The error printing (if needed) takes advantage
358 -- of the tcg_env we have now set
359 -- ; traceIf (text "rdr_env: " <+> ppr rdr_env)
360 ; failIfErrsM
361
362 -- Load any orphan-module (including orphan family
363 -- instance-module) interfaces, so that their rules and
364 -- instance decls will be found. But filter out a
365 -- self hs-boot: these instances will be checked when
366 -- we define them locally.
367 -- (We don't need to load non-orphan family instance
368 -- modules until we either try to use the instances they
369 -- define, or define our own family instances, at which
370 -- point we need to check them for consistency.)
371 ; loadModuleInterfaces (text "Loading orphan modules")
372 (filter (/= this_mod) (imp_orphs imports))
373
374 -- Check type-family consistency between imports.
375 -- See Note [The type family instance consistency story]
376 ; traceRn "rn1: checking family instance consistency {" empty
377 ; let { dir_imp_mods = moduleEnvKeys
378 . imp_mods
379 $ imports }
380 ; checkFamInstConsistency dir_imp_mods
381 ; traceRn "rn1: } checking family instance consistency" empty
382
383 ; getGblEnv } }
384
385 {-
386 ************************************************************************
387 * *
388 Type-checking the top level of a module
389 * *
390 ************************************************************************
391 -}
392
393 tcRnSrcDecls :: Bool -- False => no 'module M(..) where' header at all
394 -> [LHsDecl GhcPs] -- Declarations
395 -> TcM TcGblEnv
396 tcRnSrcDecls explicit_mod_hdr decls
397 = do { -- Do all the declarations
398 ; (tcg_env, tcl_env, lie) <- tc_rn_src_decls decls
399
400 -- Check for the 'main' declaration
401 -- Must do this inside the captureTopConstraints
402 ; (tcg_env, lie_main) <- setEnvs (tcg_env, tcl_env) $
403 -- always set envs *before* captureTopConstraints
404 captureTopConstraints $
405 checkMain explicit_mod_hdr
406
407 ; setEnvs (tcg_env, tcl_env) $ do {
408
409 -- Simplify constraints
410 --
411 -- We do this after checkMain, so that we use the type info
412 -- that checkMain adds
413 --
414 -- We do it with both global and local env in scope:
415 -- * the global env exposes the instances to simplifyTop
416 -- * the local env exposes the local Ids to simplifyTop,
417 -- so that we get better error messages (monomorphism restriction)
418 ; new_ev_binds <- {-# SCC "simplifyTop" #-}
419 simplifyTop (lie `andWC` lie_main)
420
421 -- Emit Typeable bindings
422 ; tcg_env <- mkTypeableBinds
423
424
425 ; traceTc "Tc9" empty
426
427 ; failIfErrsM -- Don't zonk if there have been errors
428 -- It's a waste of time; and we may get debug warnings
429 -- about strangely-typed TyCons!
430 ; traceTc "Tc10" empty
431
432 -- Zonk the final code. This must be done last.
433 -- Even simplifyTop may do some unification.
434 -- This pass also warns about missing type signatures
435 ; (bind_env, ev_binds', binds', fords', imp_specs', rules')
436 <- zonkTcGblEnv new_ev_binds tcg_env
437
438 -- Finalizers must run after constraints are simplified, or some types
439 -- might not be complete when using reify (see #12777).
440 -- and also after we zonk the first time because we run typed splices
441 -- in the zonker which gives rise to the finalisers.
442 ; (tcg_env_mf, _) <- setGblEnv (clearTcGblEnv tcg_env)
443 run_th_modfinalizers
444 ; finishTH
445 ; traceTc "Tc11" empty
446
447 ; -- zonk the new bindings arising from running the finalisers.
448 -- This won't give rise to any more finalisers as you can't nest
449 -- finalisers inside finalisers.
450 ; (bind_env_mf, ev_binds_mf, binds_mf, fords_mf, imp_specs_mf, rules_mf)
451 <- zonkTcGblEnv emptyBag tcg_env_mf
452
453
454 ; let { final_type_env = plusTypeEnv (tcg_type_env tcg_env)
455 (plusTypeEnv bind_env_mf bind_env)
456 ; tcg_env' = tcg_env_mf
457 { tcg_binds = binds' `unionBags` binds_mf,
458 tcg_ev_binds = ev_binds' `unionBags` ev_binds_mf ,
459 tcg_imp_specs = imp_specs' ++ imp_specs_mf ,
460 tcg_rules = rules' ++ rules_mf ,
461 tcg_fords = fords' ++ fords_mf } } ;
462
463 ; setGlobalTypeEnv tcg_env' final_type_env
464
465 } }
466
467 zonkTcGblEnv :: Bag EvBind -> TcGblEnv
468 -> TcM (TypeEnv, Bag EvBind, LHsBinds GhcTc,
469 [LForeignDecl GhcTc], [LTcSpecPrag], [LRuleDecl GhcTc])
470 zonkTcGblEnv new_ev_binds tcg_env =
471 let TcGblEnv { tcg_binds = binds,
472 tcg_ev_binds = cur_ev_binds,
473 tcg_imp_specs = imp_specs,
474 tcg_rules = rules,
475 tcg_fords = fords } = tcg_env
476
477 all_ev_binds = cur_ev_binds `unionBags` new_ev_binds
478
479 in {-# SCC "zonkTopDecls" #-}
480 zonkTopDecls all_ev_binds binds rules imp_specs fords
481
482
483 -- | Remove accumulated bindings, rules and so on from TcGblEnv
484 clearTcGblEnv :: TcGblEnv -> TcGblEnv
485 clearTcGblEnv tcg_env
486 = tcg_env { tcg_binds = emptyBag,
487 tcg_ev_binds = emptyBag ,
488 tcg_imp_specs = [],
489 tcg_rules = [],
490 tcg_fords = [] }
491
492 -- | Runs TH finalizers and renames and typechecks the top-level declarations
493 -- that they could introduce.
494 run_th_modfinalizers :: TcM (TcGblEnv, TcLclEnv)
495 run_th_modfinalizers = do
496 th_modfinalizers_var <- fmap tcg_th_modfinalizers getGblEnv
497 th_modfinalizers <- readTcRef th_modfinalizers_var
498 if null th_modfinalizers
499 then getEnvs
500 else do
501 writeTcRef th_modfinalizers_var []
502 let run_finalizer (lcl_env, f) =
503 setLclEnv lcl_env (runRemoteModFinalizers f)
504
505 (_, lie_th) <- captureTopConstraints $ mapM_ run_finalizer th_modfinalizers
506 -- Finalizers can add top-level declarations with addTopDecls, so
507 -- we have to run tc_rn_src_decls to get them
508 (tcg_env, tcl_env, lie_top_decls) <- tc_rn_src_decls []
509 setEnvs (tcg_env, tcl_env) $ do
510 -- Subsequent rounds of finalizers run after any new constraints are
511 -- simplified, or some types might not be complete when using reify
512 -- (see #12777).
513 new_ev_binds <- {-# SCC "simplifyTop2" #-}
514 simplifyTop (lie_th `andWC` lie_top_decls)
515 addTopEvBinds new_ev_binds run_th_modfinalizers
516 -- addTopDecls can add declarations which add new finalizers.
517
518 tc_rn_src_decls :: [LHsDecl GhcPs]
519 -> TcM (TcGblEnv, TcLclEnv, WantedConstraints)
520 -- Loops around dealing with each top level inter-splice group
521 -- in turn, until it's dealt with the entire module
522 -- Never emits constraints; calls captureTopConstraints internally
523 tc_rn_src_decls ds
524 = {-# SCC "tc_rn_src_decls" #-}
525 do { (first_group, group_tail) <- findSplice ds
526 -- If ds is [] we get ([], Nothing)
527
528 -- Deal with decls up to, but not including, the first splice
529 ; (tcg_env, rn_decls) <- rnTopSrcDecls first_group
530 -- rnTopSrcDecls fails if there are any errors
531
532 -- Get TH-generated top-level declarations and make sure they don't
533 -- contain any splices since we don't handle that at the moment
534 --
535 -- The plumbing here is a bit odd: see Trac #10853
536 ; th_topdecls_var <- fmap tcg_th_topdecls getGblEnv
537 ; th_ds <- readTcRef th_topdecls_var
538 ; writeTcRef th_topdecls_var []
539
540 ; (tcg_env, rn_decls) <-
541 if null th_ds
542 then return (tcg_env, rn_decls)
543 else do { (th_group, th_group_tail) <- findSplice th_ds
544 ; case th_group_tail of
545 { Nothing -> return ()
546 ; Just (SpliceDecl _ (dL->L loc _) _, _) ->
547 setSrcSpan loc
548 $ addErr (text
549 ("Declaration splices are not "
550 ++ "permitted inside top-level "
551 ++ "declarations added with addTopDecls"))
552 ; Just (XSpliceDecl _, _) -> panic "tc_rn_src_decls"
553 }
554 -- Rename TH-generated top-level declarations
555 ; (tcg_env, th_rn_decls) <- setGblEnv tcg_env
556 $ rnTopSrcDecls th_group
557
558 -- Dump generated top-level declarations
559 ; let msg = "top-level declarations added with addTopDecls"
560 ; traceSplice
561 $ SpliceInfo { spliceDescription = msg
562 , spliceIsDecl = True
563 , spliceSource = Nothing
564 , spliceGenerated = ppr th_rn_decls }
565 ; return (tcg_env, appendGroups rn_decls th_rn_decls)
566 }
567
568 -- Type check all declarations
569 -- NB: set the env **before** captureTopConstraints so that error messages
570 -- get reported w.r.t. the right GlobalRdrEnv. It is for this reason that
571 -- the captureTopConstraints must go here, not in tcRnSrcDecls.
572 ; ((tcg_env, tcl_env), lie1) <- setGblEnv tcg_env $
573 captureTopConstraints $
574 tcTopSrcDecls rn_decls
575
576 -- If there is no splice, we're nearly done
577 ; setEnvs (tcg_env, tcl_env) $
578 case group_tail of
579 { Nothing -> return (tcg_env, tcl_env, lie1)
580
581 -- If there's a splice, we must carry on
582 ; Just (SpliceDecl _ (dL->L loc splice) _, rest_ds) ->
583 do { recordTopLevelSpliceLoc loc
584
585 -- Rename the splice expression, and get its supporting decls
586 ; (spliced_decls, splice_fvs) <- rnTopSpliceDecls splice
587
588 -- Glue them on the front of the remaining decls and loop
589 ; (tcg_env, tcl_env, lie2) <-
590 setGblEnv (tcg_env `addTcgDUs` usesOnly splice_fvs) $
591 tc_rn_src_decls (spliced_decls ++ rest_ds)
592
593 ; return (tcg_env, tcl_env, lie1 `andWC` lie2)
594 }
595 ; Just (XSpliceDecl _, _) -> panic "tc_rn_src_decls"
596 }
597 }
598
599 {-
600 ************************************************************************
601 * *
602 Compiling hs-boot source files, and
603 comparing the hi-boot interface with the real thing
604 * *
605 ************************************************************************
606 -}
607
608 tcRnHsBootDecls :: HscSource -> [LHsDecl GhcPs] -> TcM TcGblEnv
609 tcRnHsBootDecls hsc_src decls
610 = do { (first_group, group_tail) <- findSplice decls
611
612 -- Rename the declarations
613 ; (tcg_env, HsGroup { hs_tyclds = tycl_decls
614 , hs_derivds = deriv_decls
615 , hs_fords = for_decls
616 , hs_defds = def_decls
617 , hs_ruleds = rule_decls
618 , hs_annds = _
619 , hs_valds
620 = XValBindsLR (NValBinds val_binds val_sigs) })
621 <- rnTopSrcDecls first_group
622 -- The empty list is for extra dependencies coming from .hs-boot files
623 -- See Note [Extra dependencies from .hs-boot files] in RnSource
624 ; (gbl_env, lie) <- setGblEnv tcg_env $ captureTopConstraints $ do {
625 -- NB: setGblEnv **before** captureTopConstraints so that
626 -- if the latter reports errors, it knows what's in scope
627
628 -- Check for illegal declarations
629 ; case group_tail of
630 Just (SpliceDecl _ d _, _) -> badBootDecl hsc_src "splice" d
631 Just (XSpliceDecl _, _) -> panic "tcRnHsBootDecls"
632 Nothing -> return ()
633 ; mapM_ (badBootDecl hsc_src "foreign") for_decls
634 ; mapM_ (badBootDecl hsc_src "default") def_decls
635 ; mapM_ (badBootDecl hsc_src "rule") rule_decls
636
637 -- Typecheck type/class/instance decls
638 ; traceTc "Tc2 (boot)" empty
639 ; (tcg_env, inst_infos, _deriv_binds)
640 <- tcTyClsInstDecls tycl_decls deriv_decls val_binds
641 ; setGblEnv tcg_env $ do {
642
643 -- Emit Typeable bindings
644 ; tcg_env <- mkTypeableBinds
645 ; setGblEnv tcg_env $ do {
646
647 -- Typecheck value declarations
648 ; traceTc "Tc5" empty
649 ; val_ids <- tcHsBootSigs val_binds val_sigs
650
651 -- Wrap up
652 -- No simplification or zonking to do
653 ; traceTc "Tc7a" empty
654 ; gbl_env <- getGblEnv
655
656 -- Make the final type-env
657 -- Include the dfun_ids so that their type sigs
658 -- are written into the interface file.
659 ; let { type_env0 = tcg_type_env gbl_env
660 ; type_env1 = extendTypeEnvWithIds type_env0 val_ids
661 ; type_env2 = extendTypeEnvWithIds type_env1 dfun_ids
662 ; dfun_ids = map iDFunId inst_infos
663 }
664
665 ; setGlobalTypeEnv gbl_env type_env2
666 }}}
667 ; traceTc "boot" (ppr lie); return gbl_env }
668
669 badBootDecl :: HscSource -> String -> Located decl -> TcM ()
670 badBootDecl hsc_src what (dL->L loc _)
671 = addErrAt loc (char 'A' <+> text what
672 <+> text "declaration is not (currently) allowed in a"
673 <+> (case hsc_src of
674 HsBootFile -> text "hs-boot"
675 HsigFile -> text "hsig"
676 _ -> panic "badBootDecl: should be an hsig or hs-boot file")
677 <+> text "file")
678
679 {-
680 Once we've typechecked the body of the module, we want to compare what
681 we've found (gathered in a TypeEnv) with the hi-boot details (if any).
682 -}
683
684 checkHiBootIface :: TcGblEnv -> SelfBootInfo -> TcM TcGblEnv
685 -- Compare the hi-boot file for this module (if there is one)
686 -- with the type environment we've just come up with
687 -- In the common case where there is no hi-boot file, the list
688 -- of boot_names is empty.
689
690 checkHiBootIface tcg_env boot_info
691 | NoSelfBoot <- boot_info -- Common case
692 = return tcg_env
693
694 | HsBootFile <- tcg_src tcg_env -- Current module is already a hs-boot file!
695 = return tcg_env
696
697 | SelfBoot { sb_mds = boot_details } <- boot_info
698 , TcGblEnv { tcg_binds = binds
699 , tcg_insts = local_insts
700 , tcg_type_env = local_type_env
701 , tcg_exports = local_exports } <- tcg_env
702 = do { -- This code is tricky, see Note [DFun knot-tying]
703 ; dfun_prs <- checkHiBootIface' local_insts local_type_env
704 local_exports boot_details
705
706 -- Now add the boot-dfun bindings $fxblah = $fblah
707 -- to (a) the type envt, and (b) the top-level bindings
708 ; let boot_dfuns = map fst dfun_prs
709 type_env' = extendTypeEnvWithIds local_type_env boot_dfuns
710 dfun_binds = listToBag [ mkVarBind boot_dfun (nlHsVar dfun)
711 | (boot_dfun, dfun) <- dfun_prs ]
712 tcg_env_w_binds
713 = tcg_env { tcg_binds = binds `unionBags` dfun_binds }
714
715 ; type_env' `seq`
716 -- Why the seq? Without, we will put a TypeEnv thunk in
717 -- tcg_type_env_var. That thunk will eventually get
718 -- forced if we are typechecking interfaces, but that
719 -- is no good if we are trying to typecheck the very
720 -- DFun we were going to put in.
721 -- TODO: Maybe setGlobalTypeEnv should be strict.
722 setGlobalTypeEnv tcg_env_w_binds type_env' }
723
724 | otherwise = panic "checkHiBootIface: unreachable code"
725
726 {- Note [DFun impedance matching]
727 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
728 We return a list of "impedance-matching" bindings for the dfuns
729 defined in the hs-boot file, such as
730 $fxEqT = $fEqT
731 We need these because the module and hi-boot file might differ in
732 the name it chose for the dfun: the name of a dfun is not
733 uniquely determined by its type; there might be multiple dfuns
734 which, individually, would map to the same name (in which case
735 we have to disambiguate them.) There's no way for the hi file
736 to know exactly what disambiguation to use... without looking
737 at the hi-boot file itself.
738
739 In fact, the names will always differ because we always pick names
740 prefixed with "$fx" for boot dfuns, and "$f" for real dfuns
741 (so that this impedance matching is always possible).
742
743 Note [DFun knot-tying]
744 ~~~~~~~~~~~~~~~~~~~~~~
745 The 'SelfBootInfo' that is fed into 'checkHiBootIface' comes from
746 typechecking the hi-boot file that we are presently implementing.
747 Suppose we are typechecking the module A: when we typecheck the
748 hi-boot file, whenever we see an identifier A.T, we knot-tie this
749 identifier to the *local* type environment (via if_rec_types.) The
750 contract then is that we don't *look* at 'SelfBootInfo' until we've
751 finished typechecking the module and updated the type environment with
752 the new tycons and ids.
753
754 This most works well, but there is one problem: DFuns! We do not want
755 to look at the mb_insts of the ModDetails in SelfBootInfo, because a
756 dfun in one of those ClsInsts is gotten (in TcIface.tcIfaceInst) by a
757 (lazily evaluated) lookup in the if_rec_types. We could extend the
758 type env, do a setGloblaTypeEnv etc; but that all seems very indirect.
759 It is much more directly simply to extract the DFunIds from the
760 md_types of the SelfBootInfo.
761
762 See Trac #4003, #16038 for why we need to take care here.
763 -}
764
765 checkHiBootIface' :: [ClsInst] -> TypeEnv -> [AvailInfo]
766 -> ModDetails -> TcM [(Id, Id)]
767 -- Variant which doesn't require a full TcGblEnv; you could get the
768 -- local components from another ModDetails.
769 checkHiBootIface'
770 local_insts local_type_env local_exports
771 (ModDetails { md_types = boot_type_env
772 , md_fam_insts = boot_fam_insts
773 , md_exports = boot_exports })
774 = do { traceTc "checkHiBootIface" $ vcat
775 [ ppr boot_type_env, ppr boot_exports]
776
777 -- Check the exports of the boot module, one by one
778 ; mapM_ check_export boot_exports
779
780 -- Check for no family instances
781 ; unless (null boot_fam_insts) $
782 panic ("TcRnDriver.checkHiBootIface: Cannot handle family " ++
783 "instances in boot files yet...")
784 -- FIXME: Why? The actual comparison is not hard, but what would
785 -- be the equivalent to the dfun bindings returned for class
786 -- instances? We can't easily equate tycons...
787
788 -- Check instance declarations
789 -- and generate an impedance-matching binding
790 ; mb_dfun_prs <- mapM check_cls_inst boot_dfuns
791
792 ; failIfErrsM
793
794 ; return (catMaybes mb_dfun_prs) }
795
796 where
797 boot_dfun_names = map idName boot_dfuns
798 boot_dfuns = filter isDFunId $ typeEnvIds boot_type_env
799 -- NB: boot_dfuns is /not/ defined thus: map instanceDFunId md_insts
800 -- We don't want to look at md_insts!
801 -- Why not? See Note [DFun knot-tying]
802
803 check_export boot_avail -- boot_avail is exported by the boot iface
804 | name `elem` boot_dfun_names = return ()
805 | isWiredInName name = return () -- No checking for wired-in names. In particular,
806 -- 'error' is handled by a rather gross hack
807 -- (see comments in GHC.Err.hs-boot)
808
809 -- Check that the actual module exports the same thing
810 | not (null missing_names)
811 = addErrAt (nameSrcSpan (head missing_names))
812 (missingBootThing True (head missing_names) "exported by")
813
814 -- If the boot module does not *define* the thing, we are done
815 -- (it simply re-exports it, and names match, so nothing further to do)
816 | isNothing mb_boot_thing = return ()
817
818 -- Check that the actual module also defines the thing, and
819 -- then compare the definitions
820 | Just real_thing <- lookupTypeEnv local_type_env name,
821 Just boot_thing <- mb_boot_thing
822 = checkBootDeclM True boot_thing real_thing
823
824 | otherwise
825 = addErrTc (missingBootThing True name "defined in")
826 where
827 name = availName boot_avail
828 mb_boot_thing = lookupTypeEnv boot_type_env name
829 missing_names = case lookupNameEnv local_export_env name of
830 Nothing -> [name]
831 Just avail -> availNames boot_avail `minusList` availNames avail
832
833 local_export_env :: NameEnv AvailInfo
834 local_export_env = availsToNameEnv local_exports
835
836 check_cls_inst :: DFunId -> TcM (Maybe (Id, Id))
837 -- Returns a pair of the boot dfun in terms of the equivalent
838 -- real dfun. Delicate (like checkBootDecl) because it depends
839 -- on the types lining up precisely even to the ordering of
840 -- the type variables in the foralls.
841 check_cls_inst boot_dfun
842 | (real_dfun : _) <- find_real_dfun boot_dfun
843 , let local_boot_dfun = Id.mkExportedVanillaId
844 (idName boot_dfun) (idType real_dfun)
845 = return (Just (local_boot_dfun, real_dfun))
846 -- Two tricky points here:
847 --
848 -- * The local_boot_fun should have a Name from the /boot-file/,
849 -- but type from the dfun defined in /this module/.
850 -- That ensures that the TyCon etc inside the type are
851 -- the ones defined in this module, not the ones gotten
852 -- from the hi-boot file, which may have a lot less info
853 -- (Trac #8743, comment:10).
854 --
855 -- * The DFunIds from boot_details are /GlobalIds/, because
856 -- they come from typechecking M.hi-boot.
857 -- But all bindings in this module should be for /LocalIds/,
858 -- otherwise dependency analysis fails (Trac #16038). This
859 -- is another reason for using mkExportedVanillaId, rather
860 -- that modifying boot_dfun, to make local_boot_fun.
861
862 | otherwise
863 = setSrcSpan (getLoc (getName boot_dfun)) $
864 do { traceTc "check_cls_inst" $ vcat
865 [ text "local_insts" <+>
866 vcat (map (ppr . idType . instanceDFunId) local_insts)
867 , text "boot_dfun_ty" <+> ppr (idType boot_dfun) ]
868
869 ; addErrTc (instMisMatch boot_dfun)
870 ; return Nothing }
871
872 find_real_dfun :: DFunId -> [DFunId]
873 find_real_dfun boot_dfun
874 = [dfun | inst <- local_insts
875 , let dfun = instanceDFunId inst
876 , idType dfun `eqType` boot_dfun_ty ]
877 where
878 boot_dfun_ty = idType boot_dfun
879
880
881 -- In general, to perform these checks we have to
882 -- compare the TyThing from the .hi-boot file to the TyThing
883 -- in the current source file. We must be careful to allow alpha-renaming
884 -- where appropriate, and also the boot declaration is allowed to omit
885 -- constructors and class methods.
886 --
887 -- See rnfail055 for a good test of this stuff.
888
889 -- | Compares two things for equivalence between boot-file and normal code,
890 -- reporting an error if they don't match up.
891 checkBootDeclM :: Bool -- ^ True <=> an hs-boot file (could also be a sig)
892 -> TyThing -> TyThing -> TcM ()
893 checkBootDeclM is_boot boot_thing real_thing
894 = whenIsJust (checkBootDecl is_boot boot_thing real_thing) $ \ err ->
895 addErrAt span
896 (bootMisMatch is_boot err real_thing boot_thing)
897 where
898 -- Here we use the span of the boot thing or, if it doesn't have a sensible
899 -- span, that of the real thing,
900 span
901 | let span = nameSrcSpan (getName boot_thing)
902 , isGoodSrcSpan span
903 = span
904 | otherwise
905 = nameSrcSpan (getName real_thing)
906
907 -- | Compares the two things for equivalence between boot-file and normal
908 -- code. Returns @Nothing@ on success or @Just "some helpful info for user"@
909 -- failure. If the difference will be apparent to the user, @Just empty@ is
910 -- perfectly suitable.
911 checkBootDecl :: Bool -> TyThing -> TyThing -> Maybe SDoc
912
913 checkBootDecl _ (AnId id1) (AnId id2)
914 = ASSERT(id1 == id2)
915 check (idType id1 `eqType` idType id2)
916 (text "The two types are different")
917
918 checkBootDecl is_boot (ATyCon tc1) (ATyCon tc2)
919 = checkBootTyCon is_boot tc1 tc2
920
921 checkBootDecl _ (AConLike (RealDataCon dc1)) (AConLike (RealDataCon _))
922 = pprPanic "checkBootDecl" (ppr dc1)
923
924 checkBootDecl _ _ _ = Just empty -- probably shouldn't happen
925
926 -- | Combines two potential error messages
927 andThenCheck :: Maybe SDoc -> Maybe SDoc -> Maybe SDoc
928 Nothing `andThenCheck` msg = msg
929 msg `andThenCheck` Nothing = msg
930 Just d1 `andThenCheck` Just d2 = Just (d1 $$ d2)
931 infixr 0 `andThenCheck`
932
933 -- | If the test in the first parameter is True, succeed with @Nothing@;
934 -- otherwise, return the provided check
935 checkUnless :: Bool -> Maybe SDoc -> Maybe SDoc
936 checkUnless True _ = Nothing
937 checkUnless False k = k
938
939 -- | Run the check provided for every pair of elements in the lists.
940 -- The provided SDoc should name the element type, in the plural.
941 checkListBy :: (a -> a -> Maybe SDoc) -> [a] -> [a] -> SDoc
942 -> Maybe SDoc
943 checkListBy check_fun as bs whats = go [] as bs
944 where
945 herald = text "The" <+> whats <+> text "do not match"
946
947 go [] [] [] = Nothing
948 go docs [] [] = Just (hang (herald <> colon) 2 (vcat $ reverse docs))
949 go docs (x:xs) (y:ys) = case check_fun x y of
950 Just doc -> go (doc:docs) xs ys
951 Nothing -> go docs xs ys
952 go _ _ _ = Just (hang (herald <> colon)
953 2 (text "There are different numbers of" <+> whats))
954
955 -- | If the test in the first parameter is True, succeed with @Nothing@;
956 -- otherwise, fail with the given SDoc.
957 check :: Bool -> SDoc -> Maybe SDoc
958 check True _ = Nothing
959 check False doc = Just doc
960
961 -- | A more perspicuous name for @Nothing@, for @checkBootDecl@ and friends.
962 checkSuccess :: Maybe SDoc
963 checkSuccess = Nothing
964
965 ----------------
966 checkBootTyCon :: Bool -> TyCon -> TyCon -> Maybe SDoc
967 checkBootTyCon is_boot tc1 tc2
968 | not (eqType (tyConKind tc1) (tyConKind tc2))
969 = Just $ text "The types have different kinds" -- First off, check the kind
970
971 | Just c1 <- tyConClass_maybe tc1
972 , Just c2 <- tyConClass_maybe tc2
973 , let (clas_tvs1, clas_fds1, sc_theta1, _, ats1, op_stuff1)
974 = classExtraBigSig c1
975 (clas_tvs2, clas_fds2, sc_theta2, _, ats2, op_stuff2)
976 = classExtraBigSig c2
977 , Just env <- eqVarBndrs emptyRnEnv2 clas_tvs1 clas_tvs2
978 = let
979 eqSig (id1, def_meth1) (id2, def_meth2)
980 = check (name1 == name2)
981 (text "The names" <+> pname1 <+> text "and" <+> pname2 <+>
982 text "are different") `andThenCheck`
983 check (eqTypeX env op_ty1 op_ty2)
984 (text "The types of" <+> pname1 <+>
985 text "are different") `andThenCheck`
986 if is_boot
987 then check (eqMaybeBy eqDM def_meth1 def_meth2)
988 (text "The default methods associated with" <+> pname1 <+>
989 text "are different")
990 else check (subDM op_ty1 def_meth1 def_meth2)
991 (text "The default methods associated with" <+> pname1 <+>
992 text "are not compatible")
993 where
994 name1 = idName id1
995 name2 = idName id2
996 pname1 = quotes (ppr name1)
997 pname2 = quotes (ppr name2)
998 (_, rho_ty1) = splitForAllTys (idType id1)
999 op_ty1 = funResultTy rho_ty1
1000 (_, rho_ty2) = splitForAllTys (idType id2)
1001 op_ty2 = funResultTy rho_ty2
1002
1003 eqAT (ATI tc1 def_ats1) (ATI tc2 def_ats2)
1004 = checkBootTyCon is_boot tc1 tc2 `andThenCheck`
1005 check (eqATDef def_ats1 def_ats2)
1006 (text "The associated type defaults differ")
1007
1008 eqDM (_, VanillaDM) (_, VanillaDM) = True
1009 eqDM (_, GenericDM t1) (_, GenericDM t2) = eqTypeX env t1 t2
1010 eqDM _ _ = False
1011
1012 -- NB: first argument is from hsig, second is from real impl.
1013 -- Order of pattern matching matters.
1014 subDM _ Nothing _ = True
1015 subDM _ _ Nothing = False
1016 -- If the hsig wrote:
1017 --
1018 -- f :: a -> a
1019 -- default f :: a -> a
1020 --
1021 -- this should be validly implementable using an old-fashioned
1022 -- vanilla default method.
1023 subDM t1 (Just (_, GenericDM t2)) (Just (_, VanillaDM))
1024 = eqTypeX env t1 t2
1025 -- This case can occur when merging signatures
1026 subDM t1 (Just (_, VanillaDM)) (Just (_, GenericDM t2))
1027 = eqTypeX env t1 t2
1028 subDM _ (Just (_, VanillaDM)) (Just (_, VanillaDM)) = True
1029 subDM _ (Just (_, GenericDM t1)) (Just (_, GenericDM t2))
1030 = eqTypeX env t1 t2
1031
1032 -- Ignore the location of the defaults
1033 eqATDef Nothing Nothing = True
1034 eqATDef (Just (ty1, _loc1)) (Just (ty2, _loc2)) = eqTypeX env ty1 ty2
1035 eqATDef _ _ = False
1036
1037 eqFD (as1,bs1) (as2,bs2) =
1038 eqListBy (eqTypeX env) (mkTyVarTys as1) (mkTyVarTys as2) &&
1039 eqListBy (eqTypeX env) (mkTyVarTys bs1) (mkTyVarTys bs2)
1040 in
1041 checkRoles roles1 roles2 `andThenCheck`
1042 -- Checks kind of class
1043 check (eqListBy eqFD clas_fds1 clas_fds2)
1044 (text "The functional dependencies do not match") `andThenCheck`
1045 checkUnless (isAbstractTyCon tc1) $
1046 check (eqListBy (eqTypeX env) sc_theta1 sc_theta2)
1047 (text "The class constraints do not match") `andThenCheck`
1048 checkListBy eqSig op_stuff1 op_stuff2 (text "methods") `andThenCheck`
1049 checkListBy eqAT ats1 ats2 (text "associated types") `andThenCheck`
1050 check (classMinimalDef c1 `BF.implies` classMinimalDef c2)
1051 (text "The MINIMAL pragmas are not compatible")
1052
1053 | Just syn_rhs1 <- synTyConRhs_maybe tc1
1054 , Just syn_rhs2 <- synTyConRhs_maybe tc2
1055 , Just env <- eqVarBndrs emptyRnEnv2 (tyConTyVars tc1) (tyConTyVars tc2)
1056 = ASSERT(tc1 == tc2)
1057 checkRoles roles1 roles2 `andThenCheck`
1058 check (eqTypeX env syn_rhs1 syn_rhs2) empty -- nothing interesting to say
1059 -- This allows abstract 'data T a' to be implemented using 'type T = ...'
1060 -- and abstract 'class K a' to be implement using 'type K = ...'
1061 -- See Note [Synonyms implement abstract data]
1062 | not is_boot -- don't support for hs-boot yet
1063 , isAbstractTyCon tc1
1064 , Just (tvs, ty) <- synTyConDefn_maybe tc2
1065 , Just (tc2', args) <- tcSplitTyConApp_maybe ty
1066 = checkSynAbsData tvs ty tc2' args
1067 -- TODO: When it's a synonym implementing a class, we really
1068 -- should check if the fundeps are satisfied, but
1069 -- there is not an obvious way to do this for a constraint synonym.
1070 -- So for now, let it all through (it won't cause segfaults, anyway).
1071 -- Tracked at #12704.
1072
1073 -- This allows abstract 'data T :: Nat' to be implemented using
1074 -- 'type T = 42' Since the kinds already match (we have checked this
1075 -- upfront) all we need to check is that the implementation 'type T
1076 -- = ...' defined an actual literal. See #15138 for the case this
1077 -- handles.
1078 | not is_boot
1079 , isAbstractTyCon tc1
1080 , Just (_,ty2) <- synTyConDefn_maybe tc2
1081 , isJust (isLitTy ty2)
1082 = Nothing
1083
1084 | Just fam_flav1 <- famTyConFlav_maybe tc1
1085 , Just fam_flav2 <- famTyConFlav_maybe tc2
1086 = ASSERT(tc1 == tc2)
1087 let eqFamFlav OpenSynFamilyTyCon OpenSynFamilyTyCon = True
1088 eqFamFlav (DataFamilyTyCon {}) (DataFamilyTyCon {}) = True
1089 -- This case only happens for hsig merging:
1090 eqFamFlav AbstractClosedSynFamilyTyCon AbstractClosedSynFamilyTyCon = True
1091 eqFamFlav AbstractClosedSynFamilyTyCon (ClosedSynFamilyTyCon {}) = True
1092 eqFamFlav (ClosedSynFamilyTyCon {}) AbstractClosedSynFamilyTyCon = True
1093 eqFamFlav (ClosedSynFamilyTyCon ax1) (ClosedSynFamilyTyCon ax2)
1094 = eqClosedFamilyAx ax1 ax2
1095 eqFamFlav (BuiltInSynFamTyCon {}) (BuiltInSynFamTyCon {}) = tc1 == tc2
1096 eqFamFlav _ _ = False
1097 injInfo1 = tyConInjectivityInfo tc1
1098 injInfo2 = tyConInjectivityInfo tc2
1099 in
1100 -- check equality of roles, family flavours and injectivity annotations
1101 -- (NB: Type family roles are always nominal. But the check is
1102 -- harmless enough.)
1103 checkRoles roles1 roles2 `andThenCheck`
1104 check (eqFamFlav fam_flav1 fam_flav2)
1105 (whenPprDebug $
1106 text "Family flavours" <+> ppr fam_flav1 <+> text "and" <+> ppr fam_flav2 <+>
1107 text "do not match") `andThenCheck`
1108 check (injInfo1 == injInfo2) (text "Injectivities do not match")
1109
1110 | isAlgTyCon tc1 && isAlgTyCon tc2
1111 , Just env <- eqVarBndrs emptyRnEnv2 (tyConTyVars tc1) (tyConTyVars tc2)
1112 = ASSERT(tc1 == tc2)
1113 checkRoles roles1 roles2 `andThenCheck`
1114 check (eqListBy (eqTypeX env)
1115 (tyConStupidTheta tc1) (tyConStupidTheta tc2))
1116 (text "The datatype contexts do not match") `andThenCheck`
1117 eqAlgRhs tc1 (algTyConRhs tc1) (algTyConRhs tc2)
1118
1119 | otherwise = Just empty -- two very different types -- should be obvious
1120 where
1121 roles1 = tyConRoles tc1 -- the abstract one
1122 roles2 = tyConRoles tc2
1123 roles_msg = text "The roles do not match." $$
1124 (text "Roles on abstract types default to" <+>
1125 quotes (text "representational") <+> text "in boot files.")
1126
1127 roles_subtype_msg = text "The roles are not compatible:" $$
1128 text "Main module:" <+> ppr roles2 $$
1129 text "Hsig file:" <+> ppr roles1
1130
1131 checkRoles r1 r2
1132 | is_boot || isInjectiveTyCon tc1 Representational -- See Note [Role subtyping]
1133 = check (r1 == r2) roles_msg
1134 | otherwise = check (r2 `rolesSubtypeOf` r1) roles_subtype_msg
1135
1136 -- Note [Role subtyping]
1137 -- ~~~~~~~~~~~~~~~~~~~~~
1138 -- In the current formulation of roles, role subtyping is only OK if the
1139 -- "abstract" TyCon was not representationally injective. Among the most
1140 -- notable examples of non representationally injective TyCons are abstract
1141 -- data, which can be implemented via newtypes (which are not
1142 -- representationally injective). The key example is
1143 -- in this example from #13140:
1144 --
1145 -- -- In an hsig file
1146 -- data T a -- abstract!
1147 -- type role T nominal
1148 --
1149 -- -- Elsewhere
1150 -- foo :: Coercible (T a) (T b) => a -> b
1151 -- foo x = x
1152 --
1153 -- We must NOT allow foo to typecheck, because if we instantiate
1154 -- T with a concrete data type with a phantom role would cause
1155 -- Coercible (T a) (T b) to be provable. Fortunately, if T is not
1156 -- representationally injective, we cannot make the inference that a ~N b if
1157 -- T a ~R T b.
1158 --
1159 -- Unconditional role subtyping would be possible if we setup
1160 -- an extra set of roles saying when we can project out coercions
1161 -- (we call these proj-roles); then it would NOT be valid to instantiate T
1162 -- with a data type at phantom since the proj-role subtyping check
1163 -- would fail. See #13140 for more details.
1164 --
1165 -- One consequence of this is we get no role subtyping for non-abstract
1166 -- data types in signatures. Suppose you have:
1167 --
1168 -- signature A where
1169 -- type role T nominal
1170 -- data T a = MkT
1171 --
1172 -- If you write this, we'll treat T as injective, and make inferences
1173 -- like T a ~R T b ==> a ~N b (mkNthCo). But if we can
1174 -- subsequently replace T with one at phantom role, we would then be able to
1175 -- infer things like T Int ~R T Bool which is bad news.
1176 --
1177 -- We could allow role subtyping here if we didn't treat *any* data types
1178 -- defined in signatures as injective. But this would be a bit surprising,
1179 -- replacing a data type in a module with one in a signature could cause
1180 -- your code to stop typechecking (whereas if you made the type abstract,
1181 -- it is more understandable that the type checker knows less).
1182 --
1183 -- It would have been best if this was purely a question of defaults
1184 -- (i.e., a user could explicitly ask for one behavior or another) but
1185 -- the current role system isn't expressive enough to do this.
1186 -- Having explict proj-roles would solve this problem.
1187
1188 rolesSubtypeOf [] [] = True
1189 -- NB: this relation is the OPPOSITE of the subroling relation
1190 rolesSubtypeOf (x:xs) (y:ys) = x >= y && rolesSubtypeOf xs ys
1191 rolesSubtypeOf _ _ = False
1192
1193 -- Note [Synonyms implement abstract data]
1194 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1195 -- An abstract data type or class can be implemented using a type synonym,
1196 -- but ONLY if the type synonym is nullary and has no type family
1197 -- applications. This arises from two properties of skolem abstract data:
1198 --
1199 -- For any T (with some number of paramaters),
1200 --
1201 -- 1. T is a valid type (it is "curryable"), and
1202 --
1203 -- 2. T is valid in an instance head (no type families).
1204 --
1205 -- See also 'HowAbstract' and Note [Skolem abstract data].
1206
1207 -- | Given @type T tvs = ty@, where @ty@ decomposes into @tc2' args@,
1208 -- check that this synonym is an acceptable implementation of @tc1@.
1209 -- See Note [Synonyms implement abstract data]
1210 checkSynAbsData :: [TyVar] -> Type -> TyCon -> [Type] -> Maybe SDoc
1211 checkSynAbsData tvs ty tc2' args =
1212 check (null (tcTyFamInsts ty))
1213 (text "Illegal type family application in implementation of abstract data.")
1214 `andThenCheck`
1215 check (null tvs)
1216 (text "Illegal parameterized type synonym in implementation of abstract data." $$
1217 text "(Try eta reducing your type synonym so that it is nullary.)")
1218 `andThenCheck`
1219 -- Don't report roles errors unless the type synonym is nullary
1220 checkUnless (not (null tvs)) $
1221 ASSERT( null roles2 )
1222 -- If we have something like:
1223 --
1224 -- signature H where
1225 -- data T a
1226 -- module H where
1227 -- data K a b = ...
1228 -- type T = K Int
1229 --
1230 -- we need to drop the first role of K when comparing!
1231 checkRoles roles1 (drop (length args) (tyConRoles tc2'))
1232 {-
1233 -- Hypothetically, if we were allow to non-nullary type synonyms, here
1234 -- is how you would check the roles
1235 if length tvs == length roles1
1236 then checkRoles roles1 roles2
1237 else case tcSplitTyConApp_maybe ty of
1238 Just (tc2', args) ->
1239 checkRoles roles1 (drop (length args) (tyConRoles tc2') ++ roles2)
1240 Nothing -> Just roles_msg
1241 -}
1242
1243 eqAlgRhs _ AbstractTyCon _rhs2
1244 = checkSuccess -- rhs2 is guaranteed to be injective, since it's an AlgTyCon
1245 eqAlgRhs _ tc1@DataTyCon{} tc2@DataTyCon{} =
1246 checkListBy eqCon (data_cons tc1) (data_cons tc2) (text "constructors")
1247 eqAlgRhs _ tc1@NewTyCon{} tc2@NewTyCon{} =
1248 eqCon (data_con tc1) (data_con tc2)
1249 eqAlgRhs _ _ _ = Just (text "Cannot match a" <+> quotes (text "data") <+>
1250 text "definition with a" <+> quotes (text "newtype") <+>
1251 text "definition")
1252
1253 eqCon c1 c2
1254 = check (name1 == name2)
1255 (text "The names" <+> pname1 <+> text "and" <+> pname2 <+>
1256 text "differ") `andThenCheck`
1257 check (dataConIsInfix c1 == dataConIsInfix c2)
1258 (text "The fixities of" <+> pname1 <+>
1259 text "differ") `andThenCheck`
1260 check (eqListBy eqHsBang (dataConImplBangs c1) (dataConImplBangs c2))
1261 (text "The strictness annotations for" <+> pname1 <+>
1262 text "differ") `andThenCheck`
1263 check (map flSelector (dataConFieldLabels c1) == map flSelector (dataConFieldLabels c2))
1264 (text "The record label lists for" <+> pname1 <+>
1265 text "differ") `andThenCheck`
1266 check (eqType (dataConUserType c1) (dataConUserType c2))
1267 (text "The types for" <+> pname1 <+> text "differ")
1268 where
1269 name1 = dataConName c1
1270 name2 = dataConName c2
1271 pname1 = quotes (ppr name1)
1272 pname2 = quotes (ppr name2)
1273
1274 eqClosedFamilyAx Nothing Nothing = True
1275 eqClosedFamilyAx Nothing (Just _) = False
1276 eqClosedFamilyAx (Just _) Nothing = False
1277 eqClosedFamilyAx (Just (CoAxiom { co_ax_branches = branches1 }))
1278 (Just (CoAxiom { co_ax_branches = branches2 }))
1279 = numBranches branches1 == numBranches branches2
1280 && (and $ zipWith eqClosedFamilyBranch branch_list1 branch_list2)
1281 where
1282 branch_list1 = fromBranches branches1
1283 branch_list2 = fromBranches branches2
1284
1285 eqClosedFamilyBranch (CoAxBranch { cab_tvs = tvs1, cab_cvs = cvs1
1286 , cab_lhs = lhs1, cab_rhs = rhs1 })
1287 (CoAxBranch { cab_tvs = tvs2, cab_cvs = cvs2
1288 , cab_lhs = lhs2, cab_rhs = rhs2 })
1289 | Just env1 <- eqVarBndrs emptyRnEnv2 tvs1 tvs2
1290 , Just env <- eqVarBndrs env1 cvs1 cvs2
1291 = eqListBy (eqTypeX env) lhs1 lhs2 &&
1292 eqTypeX env rhs1 rhs2
1293
1294 | otherwise = False
1295
1296 emptyRnEnv2 :: RnEnv2
1297 emptyRnEnv2 = mkRnEnv2 emptyInScopeSet
1298
1299 ----------------
1300 missingBootThing :: Bool -> Name -> String -> SDoc
1301 missingBootThing is_boot name what
1302 = quotes (ppr name) <+> text "is exported by the"
1303 <+> (if is_boot then text "hs-boot" else text "hsig")
1304 <+> text "file, but not"
1305 <+> text what <+> text "the module"
1306
1307 badReexportedBootThing :: DynFlags -> Bool -> Name -> Name -> SDoc
1308 badReexportedBootThing dflags is_boot name name'
1309 = withPprStyle (mkUserStyle dflags alwaysQualify AllTheWay) $ vcat
1310 [ text "The" <+> (if is_boot then text "hs-boot" else text "hsig")
1311 <+> text "file (re)exports" <+> quotes (ppr name)
1312 , text "but the implementing module exports a different identifier" <+> quotes (ppr name')
1313 ]
1314
1315 bootMisMatch :: Bool -> SDoc -> TyThing -> TyThing -> SDoc
1316 bootMisMatch is_boot extra_info real_thing boot_thing
1317 = pprBootMisMatch is_boot extra_info real_thing real_doc boot_doc
1318 where
1319 to_doc
1320 = pprTyThingInContext $ showToHeader { ss_forall =
1321 if is_boot
1322 then ShowForAllMust
1323 else ShowForAllWhen }
1324
1325 real_doc = to_doc real_thing
1326 boot_doc = to_doc boot_thing
1327
1328 pprBootMisMatch :: Bool -> SDoc -> TyThing -> SDoc -> SDoc -> SDoc
1329 pprBootMisMatch is_boot extra_info real_thing real_doc boot_doc
1330 = vcat
1331 [ ppr real_thing <+>
1332 text "has conflicting definitions in the module",
1333 text "and its" <+>
1334 (if is_boot
1335 then text "hs-boot file"
1336 else text "hsig file"),
1337 text "Main module:" <+> real_doc,
1338 (if is_boot
1339 then text "Boot file: "
1340 else text "Hsig file: ")
1341 <+> boot_doc,
1342 extra_info
1343 ]
1344
1345 instMisMatch :: DFunId -> SDoc
1346 instMisMatch dfun
1347 = hang (text "instance" <+> ppr (idType dfun))
1348 2 (text "is defined in the hs-boot file, but not in the module itself")
1349
1350 {-
1351 ************************************************************************
1352 * *
1353 Type-checking the top level of a module (continued)
1354 * *
1355 ************************************************************************
1356 -}
1357
1358 rnTopSrcDecls :: HsGroup GhcPs -> TcM (TcGblEnv, HsGroup GhcRn)
1359 -- Fails if there are any errors
1360 rnTopSrcDecls group
1361 = do { -- Rename the source decls
1362 traceRn "rn12" empty ;
1363 (tcg_env, rn_decls) <- checkNoErrs $ rnSrcDecls group ;
1364 traceRn "rn13" empty ;
1365 (tcg_env, rn_decls) <- runRenamerPlugin tcg_env rn_decls ;
1366 traceRn "rn13-plugin" empty ;
1367
1368 -- save the renamed syntax, if we want it
1369 let { tcg_env'
1370 | Just grp <- tcg_rn_decls tcg_env
1371 = tcg_env{ tcg_rn_decls = Just (appendGroups grp rn_decls) }
1372 | otherwise
1373 = tcg_env };
1374
1375 -- Dump trace of renaming part
1376 rnDump rn_decls ;
1377 return (tcg_env', rn_decls)
1378 }
1379
1380 tcTopSrcDecls :: HsGroup GhcRn -> TcM (TcGblEnv, TcLclEnv)
1381 tcTopSrcDecls (HsGroup { hs_tyclds = tycl_decls,
1382 hs_derivds = deriv_decls,
1383 hs_fords = foreign_decls,
1384 hs_defds = default_decls,
1385 hs_annds = annotation_decls,
1386 hs_ruleds = rule_decls,
1387 hs_valds = hs_val_binds@(XValBindsLR
1388 (NValBinds val_binds val_sigs)) })
1389 = do { -- Type-check the type and class decls, and all imported decls
1390 -- The latter come in via tycl_decls
1391 traceTc "Tc2 (src)" empty ;
1392
1393 -- Source-language instances, including derivings,
1394 -- and import the supporting declarations
1395 traceTc "Tc3" empty ;
1396 (tcg_env, inst_infos, XValBindsLR (NValBinds deriv_binds deriv_sigs))
1397 <- tcTyClsInstDecls tycl_decls deriv_decls val_binds ;
1398
1399 setGblEnv tcg_env $ do {
1400
1401 -- Generate Applicative/Monad proposal (AMP) warnings
1402 traceTc "Tc3b" empty ;
1403
1404 -- Generate Semigroup/Monoid warnings
1405 traceTc "Tc3c" empty ;
1406 tcSemigroupWarnings ;
1407
1408 -- Foreign import declarations next.
1409 traceTc "Tc4" empty ;
1410 (fi_ids, fi_decls, fi_gres) <- tcForeignImports foreign_decls ;
1411 tcExtendGlobalValEnv fi_ids $ do {
1412
1413 -- Default declarations
1414 traceTc "Tc4a" empty ;
1415 default_tys <- tcDefaults default_decls ;
1416 updGblEnv (\gbl -> gbl { tcg_default = default_tys }) $ do {
1417
1418 -- Value declarations next.
1419 -- It is important that we check the top-level value bindings
1420 -- before the GHC-generated derived bindings, since the latter
1421 -- may be defined in terms of the former. (For instance,
1422 -- the bindings produced in a Data instance.)
1423 traceTc "Tc5" empty ;
1424 tc_envs <- tcTopBinds val_binds val_sigs;
1425 setEnvs tc_envs $ do {
1426
1427 -- Now GHC-generated derived bindings, generics, and selectors
1428 -- Do not generate warnings from compiler-generated code;
1429 -- hence the use of discardWarnings
1430 tc_envs@(tcg_env, tcl_env)
1431 <- discardWarnings (tcTopBinds deriv_binds deriv_sigs) ;
1432 setEnvs tc_envs $ do { -- Environment doesn't change now
1433
1434 -- Second pass over class and instance declarations,
1435 -- now using the kind-checked decls
1436 traceTc "Tc6" empty ;
1437 inst_binds <- tcInstDecls2 (tyClGroupTyClDecls tycl_decls) inst_infos ;
1438
1439 -- Foreign exports
1440 traceTc "Tc7" empty ;
1441 (foe_binds, foe_decls, foe_gres) <- tcForeignExports foreign_decls ;
1442
1443 -- Annotations
1444 annotations <- tcAnnotations annotation_decls ;
1445
1446 -- Rules
1447 rules <- tcRules rule_decls ;
1448
1449 -- Wrap up
1450 traceTc "Tc7a" empty ;
1451 let { all_binds = inst_binds `unionBags`
1452 foe_binds
1453
1454 ; fo_gres = fi_gres `unionBags` foe_gres
1455 ; fo_fvs = foldrBag (\gre fvs -> fvs `addOneFV` gre_name gre)
1456 emptyFVs fo_gres
1457
1458 ; sig_names = mkNameSet (collectHsValBinders hs_val_binds)
1459 `minusNameSet` getTypeSigNames val_sigs
1460
1461 -- Extend the GblEnv with the (as yet un-zonked)
1462 -- bindings, rules, foreign decls
1463 ; tcg_env' = tcg_env { tcg_binds = tcg_binds tcg_env `unionBags` all_binds
1464 , tcg_sigs = tcg_sigs tcg_env `unionNameSet` sig_names
1465 , tcg_rules = tcg_rules tcg_env
1466 ++ flattenRuleDecls rules
1467 , tcg_anns = tcg_anns tcg_env ++ annotations
1468 , tcg_ann_env = extendAnnEnvList (tcg_ann_env tcg_env) annotations
1469 , tcg_fords = tcg_fords tcg_env ++ foe_decls ++ fi_decls
1470 , tcg_dus = tcg_dus tcg_env `plusDU` usesOnly fo_fvs } } ;
1471 -- tcg_dus: see Note [Newtype constructor usage in foreign declarations]
1472
1473 -- See Note [Newtype constructor usage in foreign declarations]
1474 addUsedGREs (bagToList fo_gres) ;
1475
1476 return (tcg_env', tcl_env)
1477 }}}}}}
1478
1479 tcTopSrcDecls _ = panic "tcTopSrcDecls: ValBindsIn"
1480
1481
1482 tcSemigroupWarnings :: TcM ()
1483 tcSemigroupWarnings = do
1484 traceTc "tcSemigroupWarnings" empty
1485 let warnFlag = Opt_WarnSemigroup
1486 tcPreludeClashWarn warnFlag sappendName
1487 tcMissingParentClassWarn warnFlag monoidClassName semigroupClassName
1488
1489
1490 -- | Warn on local definitions of names that would clash with future Prelude
1491 -- elements.
1492 --
1493 -- A name clashes if the following criteria are met:
1494 -- 1. It would is imported (unqualified) from Prelude
1495 -- 2. It is locally defined in the current module
1496 -- 3. It has the same literal name as the reference function
1497 -- 4. It is not identical to the reference function
1498 tcPreludeClashWarn :: WarningFlag
1499 -> Name
1500 -> TcM ()
1501 tcPreludeClashWarn warnFlag name = do
1502 { warn <- woptM warnFlag
1503 ; when warn $ do
1504 { traceTc "tcPreludeClashWarn/wouldBeImported" empty
1505 -- Is the name imported (unqualified) from Prelude? (Point 4 above)
1506 ; rnImports <- fmap (map unLoc . tcg_rn_imports) getGblEnv
1507 -- (Note that this automatically handles -XNoImplicitPrelude, as Prelude
1508 -- will not appear in rnImports automatically if it is set.)
1509
1510 -- Continue only the name is imported from Prelude
1511 ; when (importedViaPrelude name rnImports) $ do
1512 -- Handle 2.-4.
1513 { rdrElts <- fmap (concat . occEnvElts . tcg_rdr_env) getGblEnv
1514
1515 ; let clashes :: GlobalRdrElt -> Bool
1516 clashes x = isLocalDef && nameClashes && isNotInProperModule
1517 where
1518 isLocalDef = gre_lcl x == True
1519 -- Names are identical ...
1520 nameClashes = nameOccName (gre_name x) == nameOccName name
1521 -- ... but not the actual definitions, because we don't want to
1522 -- warn about a bad definition of e.g. <> in Data.Semigroup, which
1523 -- is the (only) proper place where this should be defined
1524 isNotInProperModule = gre_name x /= name
1525
1526 -- List of all offending definitions
1527 clashingElts :: [GlobalRdrElt]
1528 clashingElts = filter clashes rdrElts
1529
1530 ; traceTc "tcPreludeClashWarn/prelude_functions"
1531 (hang (ppr name) 4 (sep [ppr clashingElts]))
1532
1533 ; let warn_msg x = addWarnAt (Reason warnFlag) (nameSrcSpan (gre_name x)) (hsep
1534 [ text "Local definition of"
1535 , (quotes . ppr . nameOccName . gre_name) x
1536 , text "clashes with a future Prelude name." ]
1537 $$
1538 text "This will become an error in a future release." )
1539 ; mapM_ warn_msg clashingElts
1540 }}}
1541
1542 where
1543
1544 -- Is the given name imported via Prelude?
1545 --
1546 -- Possible scenarios:
1547 -- a) Prelude is imported implicitly, issue warnings.
1548 -- b) Prelude is imported explicitly, but without mentioning the name in
1549 -- question. Issue no warnings.
1550 -- c) Prelude is imported hiding the name in question. Issue no warnings.
1551 -- d) Qualified import of Prelude, no warnings.
1552 importedViaPrelude :: Name
1553 -> [ImportDecl GhcRn]
1554 -> Bool
1555 importedViaPrelude name = any importViaPrelude
1556 where
1557 isPrelude :: ImportDecl GhcRn -> Bool
1558 isPrelude imp = unLoc (ideclName imp) == pRELUDE_NAME
1559
1560 -- Implicit (Prelude) import?
1561 isImplicit :: ImportDecl GhcRn -> Bool
1562 isImplicit = ideclImplicit
1563
1564 -- Unqualified import?
1565 isUnqualified :: ImportDecl GhcRn -> Bool
1566 isUnqualified = not . ideclQualified
1567
1568 -- List of explicitly imported (or hidden) Names from a single import.
1569 -- Nothing -> No explicit imports
1570 -- Just (False, <names>) -> Explicit import list of <names>
1571 -- Just (True , <names>) -> Explicit hiding of <names>
1572 importListOf :: ImportDecl GhcRn -> Maybe (Bool, [Name])
1573 importListOf = fmap toImportList . ideclHiding
1574 where
1575 toImportList (h, loc) = (h, map (ieName . unLoc) (unLoc loc))
1576
1577 isExplicit :: ImportDecl GhcRn -> Bool
1578 isExplicit x = case importListOf x of
1579 Nothing -> False
1580 Just (False, explicit)
1581 -> nameOccName name `elem` map nameOccName explicit
1582 Just (True, hidden)
1583 -> nameOccName name `notElem` map nameOccName hidden
1584
1585 -- Check whether the given name would be imported (unqualified) from
1586 -- an import declaration.
1587 importViaPrelude :: ImportDecl GhcRn -> Bool
1588 importViaPrelude x = isPrelude x
1589 && isUnqualified x
1590 && (isImplicit x || isExplicit x)
1591
1592
1593 -- Notation: is* is for classes the type is an instance of, should* for those
1594 -- that it should also be an instance of based on the corresponding
1595 -- is*.
1596 tcMissingParentClassWarn :: WarningFlag
1597 -> Name -- ^ Instances of this ...
1598 -> Name -- ^ should also be instances of this
1599 -> TcM ()
1600 tcMissingParentClassWarn warnFlag isName shouldName
1601 = do { warn <- woptM warnFlag
1602 ; when warn $ do
1603 { traceTc "tcMissingParentClassWarn" empty
1604 ; isClass' <- tcLookupClass_maybe isName
1605 ; shouldClass' <- tcLookupClass_maybe shouldName
1606 ; case (isClass', shouldClass') of
1607 (Just isClass, Just shouldClass) -> do
1608 { localInstances <- tcGetInsts
1609 ; let isInstance m = is_cls m == isClass
1610 isInsts = filter isInstance localInstances
1611 ; traceTc "tcMissingParentClassWarn/isInsts" (ppr isInsts)
1612 ; forM_ isInsts (checkShouldInst isClass shouldClass)
1613 }
1614 (is',should') ->
1615 traceTc "tcMissingParentClassWarn/notIsShould"
1616 (hang (ppr isName <> text "/" <> ppr shouldName) 2 (
1617 (hsep [ quotes (text "Is"), text "lookup for"
1618 , ppr isName
1619 , text "resulted in", ppr is' ])
1620 $$
1621 (hsep [ quotes (text "Should"), text "lookup for"
1622 , ppr shouldName
1623 , text "resulted in", ppr should' ])))
1624 }}
1625 where
1626 -- Check whether the desired superclass exists in a given environment.
1627 checkShouldInst :: Class -- ^ Class of existing instance
1628 -> Class -- ^ Class there should be an instance of
1629 -> ClsInst -- ^ Existing instance
1630 -> TcM ()
1631 checkShouldInst isClass shouldClass isInst
1632 = do { instEnv <- tcGetInstEnvs
1633 ; let (instanceMatches, shouldInsts, _)
1634 = lookupInstEnv False instEnv shouldClass (is_tys isInst)
1635
1636 ; traceTc "tcMissingParentClassWarn/checkShouldInst"
1637 (hang (ppr isInst) 4
1638 (sep [ppr instanceMatches, ppr shouldInsts]))
1639
1640 -- "<location>: Warning: <type> is an instance of <is> but not
1641 -- <should>" e.g. "Foo is an instance of Monad but not Applicative"
1642 ; let instLoc = srcLocSpan . nameSrcLoc $ getName isInst
1643 warnMsg (Just name:_) =
1644 addWarnAt (Reason warnFlag) instLoc $
1645 hsep [ (quotes . ppr . nameOccName) name
1646 , text "is an instance of"
1647 , (ppr . nameOccName . className) isClass
1648 , text "but not"
1649 , (ppr . nameOccName . className) shouldClass ]
1650 <> text "."
1651 $$
1652 hsep [ text "This will become an error in"
1653 , text "a future release." ]
1654 warnMsg _ = pure ()
1655 ; when (null shouldInsts && null instanceMatches) $
1656 warnMsg (is_tcs isInst)
1657 }
1658
1659 tcLookupClass_maybe :: Name -> TcM (Maybe Class)
1660 tcLookupClass_maybe name = tcLookupImported_maybe name >>= \case
1661 Succeeded (ATyCon tc) | cls@(Just _) <- tyConClass_maybe tc -> pure cls
1662 _else -> pure Nothing
1663
1664
1665 ---------------------------
1666 tcTyClsInstDecls :: [TyClGroup GhcRn]
1667 -> [LDerivDecl GhcRn]
1668 -> [(RecFlag, LHsBinds GhcRn)]
1669 -> TcM (TcGblEnv, -- The full inst env
1670 [InstInfo GhcRn], -- Source-code instance decls to
1671 -- process; contains all dfuns for
1672 -- this module
1673 HsValBinds GhcRn) -- Supporting bindings for derived
1674 -- instances
1675
1676 tcTyClsInstDecls tycl_decls deriv_decls binds
1677 = tcAddDataFamConPlaceholders (tycl_decls >>= group_instds) $
1678 tcAddPatSynPlaceholders (getPatSynBinds binds) $
1679 do { (tcg_env, inst_info, datafam_deriv_info)
1680 <- tcTyAndClassDecls tycl_decls ;
1681 ; setGblEnv tcg_env $ do {
1682 -- With the @TyClDecl@s and @InstDecl@s checked we're ready to
1683 -- process the deriving clauses, including data family deriving
1684 -- clauses discovered in @tcTyAndClassDecls@.
1685 --
1686 -- Careful to quit now in case there were instance errors, so that
1687 -- the deriving errors don't pile up as well.
1688 ; failIfErrsM
1689 ; let tyclds = tycl_decls >>= group_tyclds
1690 ; (tcg_env', inst_info', val_binds)
1691 <- tcInstDeclsDeriv datafam_deriv_info tyclds deriv_decls
1692 ; setGblEnv tcg_env' $ do {
1693 failIfErrsM
1694 ; pure (tcg_env', inst_info' ++ inst_info, val_binds)
1695 }}}
1696
1697 {- *********************************************************************
1698 * *
1699 Checking for 'main'
1700 * *
1701 ************************************************************************
1702 -}
1703
1704 checkMain :: Bool -- False => no 'module M(..) where' header at all
1705 -> TcM TcGblEnv
1706 -- If we are in module Main, check that 'main' is defined.
1707 checkMain explicit_mod_hdr
1708 = do { dflags <- getDynFlags
1709 ; tcg_env <- getGblEnv
1710 ; check_main dflags tcg_env explicit_mod_hdr }
1711
1712 check_main :: DynFlags -> TcGblEnv -> Bool -> TcM TcGblEnv
1713 check_main dflags tcg_env explicit_mod_hdr
1714 | mod /= main_mod
1715 = traceTc "checkMain not" (ppr main_mod <+> ppr mod) >>
1716 return tcg_env
1717
1718 | otherwise
1719 = do { mb_main <- lookupGlobalOccRn_maybe main_fn
1720 -- Check that 'main' is in scope
1721 -- It might be imported from another module!
1722 ; case mb_main of {
1723 Nothing -> do { traceTc "checkMain fail" (ppr main_mod <+> ppr main_fn)
1724 ; complain_no_main
1725 ; return tcg_env } ;
1726 Just main_name -> do
1727
1728 { traceTc "checkMain found" (ppr main_mod <+> ppr main_fn)
1729 ; let loc = srcLocSpan (getSrcLoc main_name)
1730 ; ioTyCon <- tcLookupTyCon ioTyConName
1731 ; res_ty <- newFlexiTyVarTy liftedTypeKind
1732 ; let io_ty = mkTyConApp ioTyCon [res_ty]
1733 skol_info = SigSkol (FunSigCtxt main_name False) io_ty []
1734 ; (ev_binds, main_expr)
1735 <- checkConstraints skol_info [] [] $
1736 addErrCtxt mainCtxt $
1737 tcMonoExpr (cL loc (HsVar noExt (cL loc main_name)))
1738 (mkCheckExpType io_ty)
1739
1740 -- See Note [Root-main Id]
1741 -- Construct the binding
1742 -- :Main.main :: IO res_ty = runMainIO res_ty main
1743 ; run_main_id <- tcLookupId runMainIOName
1744 ; let { root_main_name = mkExternalName rootMainKey rOOT_MAIN
1745 (mkVarOccFS (fsLit "main"))
1746 (getSrcSpan main_name)
1747 ; root_main_id = Id.mkExportedVanillaId root_main_name
1748 (mkTyConApp ioTyCon [res_ty])
1749 ; co = mkWpTyApps [res_ty]
1750 -- The ev_binds of the `main` function may contain deferred
1751 -- type error when type of `main` is not `IO a`. The `ev_binds`
1752 -- must be put inside `runMainIO` to ensure the deferred type
1753 -- error can be emitted correctly. See Trac #13838.
1754 ; rhs = nlHsApp (mkLHsWrap co (nlHsVar run_main_id)) $
1755 mkHsDictLet ev_binds main_expr
1756 ; main_bind = mkVarBind root_main_id rhs }
1757
1758 ; return (tcg_env { tcg_main = Just main_name,
1759 tcg_binds = tcg_binds tcg_env
1760 `snocBag` main_bind,
1761 tcg_dus = tcg_dus tcg_env
1762 `plusDU` usesOnly (unitFV main_name)
1763 -- Record the use of 'main', so that we don't
1764 -- complain about it being defined but not used
1765 })
1766 }}}
1767 where
1768 mod = tcg_mod tcg_env
1769 main_mod = mainModIs dflags
1770 main_fn = getMainFun dflags
1771 interactive = ghcLink dflags == LinkInMemory
1772
1773 complain_no_main = unless (interactive && not explicit_mod_hdr)
1774 (addErrTc noMainMsg) -- #12906
1775 -- Without an explicit module header...
1776 -- in interactive mode, don't worry about the absence of 'main'.
1777 -- in other modes, add error message and go on with typechecking.
1778
1779 mainCtxt = text "When checking the type of the" <+> pp_main_fn
1780 noMainMsg = text "The" <+> pp_main_fn
1781 <+> text "is not defined in module" <+> quotes (ppr main_mod)
1782 pp_main_fn = ppMainFn main_fn
1783
1784 -- | Get the unqualified name of the function to use as the \"main\" for the main module.
1785 -- Either returns the default name or the one configured on the command line with -main-is
1786 getMainFun :: DynFlags -> RdrName
1787 getMainFun dflags = case mainFunIs dflags of
1788 Just fn -> mkRdrUnqual (mkVarOccFS (mkFastString fn))
1789 Nothing -> main_RDR_Unqual
1790
1791 -- If we are in module Main, check that 'main' is exported.
1792 checkMainExported :: TcGblEnv -> TcM ()
1793 checkMainExported tcg_env
1794 = case tcg_main tcg_env of
1795 Nothing -> return () -- not the main module
1796 Just main_name ->
1797 do { dflags <- getDynFlags
1798 ; let main_mod = mainModIs dflags
1799 ; when (ghcLink dflags /= LinkInMemory) $ -- #11647
1800 checkTc (main_name `elem`
1801 concatMap availNames (tcg_exports tcg_env)) $
1802 text "The" <+> ppMainFn (nameRdrName main_name) <+>
1803 text "is not exported by module" <+> quotes (ppr main_mod) }
1804
1805 ppMainFn :: RdrName -> SDoc
1806 ppMainFn main_fn
1807 | rdrNameOcc main_fn == mainOcc
1808 = text "IO action" <+> quotes (ppr main_fn)
1809 | otherwise
1810 = text "main IO action" <+> quotes (ppr main_fn)
1811
1812 mainOcc :: OccName
1813 mainOcc = mkVarOccFS (fsLit "main")
1814
1815 {-
1816 Note [Root-main Id]
1817 ~~~~~~~~~~~~~~~~~~~
1818 The function that the RTS invokes is always :Main.main, which we call
1819 root_main_id. (Because GHC allows the user to have a module not
1820 called Main as the main module, we can't rely on the main function
1821 being called "Main.main". That's why root_main_id has a fixed module
1822 ":Main".)
1823
1824 This is unusual: it's a LocalId whose Name has a Module from another
1825 module. Tiresomely, we must filter it out again in MkIface, les we
1826 get two defns for 'main' in the interface file!
1827
1828
1829 *********************************************************
1830 * *
1831 GHCi stuff
1832 * *
1833 *********************************************************
1834 -}
1835
1836 runTcInteractive :: HscEnv -> TcRn a -> IO (Messages, Maybe a)
1837 -- Initialise the tcg_inst_env with instances from all home modules.
1838 -- This mimics the more selective call to hptInstances in tcRnImports
1839 runTcInteractive hsc_env thing_inside
1840 = initTcInteractive hsc_env $ withTcPlugins hsc_env $
1841 do { traceTc "setInteractiveContext" $
1842 vcat [ text "ic_tythings:" <+> vcat (map ppr (ic_tythings icxt))
1843 , text "ic_insts:" <+> vcat (map (pprBndr LetBind . instanceDFunId) ic_insts)
1844 , text "ic_rn_gbl_env (LocalDef)" <+>
1845 vcat (map ppr [ local_gres | gres <- occEnvElts (ic_rn_gbl_env icxt)
1846 , let local_gres = filter isLocalGRE gres
1847 , not (null local_gres) ]) ]
1848
1849 ; let getOrphans m mb_pkg = fmap (\iface -> mi_module iface
1850 : dep_orphs (mi_deps iface))
1851 (loadSrcInterface (text "runTcInteractive") m
1852 False mb_pkg)
1853
1854 ; !orphs <- fmap (force . concat) . forM (ic_imports icxt) $ \i ->
1855 case i of -- force above: see #15111
1856 IIModule n -> getOrphans n Nothing
1857 IIDecl i ->
1858 let mb_pkg = sl_fs <$> ideclPkgQual i in
1859 getOrphans (unLoc (ideclName i)) mb_pkg
1860
1861 ; let imports = emptyImportAvails {
1862 imp_orphs = orphs
1863 }
1864
1865 ; (gbl_env, lcl_env) <- getEnvs
1866 ; let gbl_env' = gbl_env {
1867 tcg_rdr_env = ic_rn_gbl_env icxt
1868 , tcg_type_env = type_env
1869 , tcg_inst_env = extendInstEnvList
1870 (extendInstEnvList (tcg_inst_env gbl_env) ic_insts)
1871 home_insts
1872 , tcg_fam_inst_env = extendFamInstEnvList
1873 (extendFamInstEnvList (tcg_fam_inst_env gbl_env)
1874 ic_finsts)
1875 home_fam_insts
1876 , tcg_field_env = mkNameEnv con_fields
1877 -- setting tcg_field_env is necessary
1878 -- to make RecordWildCards work (test: ghci049)
1879 , tcg_fix_env = ic_fix_env icxt
1880 , tcg_default = ic_default icxt
1881 -- must calculate imp_orphs of the ImportAvails
1882 -- so that instance visibility is done correctly
1883 , tcg_imports = imports
1884 }
1885
1886 ; lcl_env' <- tcExtendLocalTypeEnv lcl_env lcl_ids
1887 ; setEnvs (gbl_env', lcl_env') thing_inside }
1888 where
1889 (home_insts, home_fam_insts) = hptInstances hsc_env (\_ -> True)
1890
1891 icxt = hsc_IC hsc_env
1892 (ic_insts, ic_finsts) = ic_instances icxt
1893 (lcl_ids, top_ty_things) = partitionWith is_closed (ic_tythings icxt)
1894
1895 is_closed :: TyThing -> Either (Name, TcTyThing) TyThing
1896 -- Put Ids with free type variables (always RuntimeUnks)
1897 -- in the *local* type environment
1898 -- See Note [Initialising the type environment for GHCi]
1899 is_closed thing
1900 | AnId id <- thing
1901 , not (isTypeClosedLetBndr id)
1902 = Left (idName id, ATcId { tct_id = id
1903 , tct_info = NotLetBound })
1904 | otherwise
1905 = Right thing
1906
1907 type_env1 = mkTypeEnvWithImplicits top_ty_things
1908 type_env = extendTypeEnvWithIds type_env1 (map instanceDFunId ic_insts)
1909 -- Putting the dfuns in the type_env
1910 -- is just to keep Core Lint happy
1911
1912 con_fields = [ (dataConName c, dataConFieldLabels c)
1913 | ATyCon t <- top_ty_things
1914 , c <- tyConDataCons t ]
1915
1916
1917 {- Note [Initialising the type environment for GHCi]
1918 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1919 Most of the Ids in ic_things, defined by the user in 'let' stmts,
1920 have closed types. E.g.
1921 ghci> let foo x y = x && not y
1922
1923 However the GHCi debugger creates top-level bindings for Ids whose
1924 types have free RuntimeUnk skolem variables, standing for unknown
1925 types. If we don't register these free TyVars as global TyVars then
1926 the typechecker will try to quantify over them and fall over in
1927 skolemiseQuantifiedTyVar. so we must add any free TyVars to the
1928 typechecker's global TyVar set. That is most conveniently by using
1929 tcExtendLocalTypeEnv, which automatically extends the global TyVar
1930 set.
1931
1932 We do this by splitting out the Ids with open types, using 'is_closed'
1933 to do the partition. The top-level things go in the global TypeEnv;
1934 the open, NotTopLevel, Ids, with free RuntimeUnk tyvars, go in the
1935 local TypeEnv.
1936
1937 Note that we don't extend the local RdrEnv (tcl_rdr); all the in-scope
1938 things are already in the interactive context's GlobalRdrEnv.
1939 Extending the local RdrEnv isn't terrible, but it means there is an
1940 entry for the same Name in both global and local RdrEnvs, and that
1941 lead to duplicate "perhaps you meant..." suggestions (e.g. T5564).
1942
1943 We don't bother with the tcl_th_bndrs environment either.
1944 -}
1945
1946 -- | The returned [Id] is the list of new Ids bound by this statement. It can
1947 -- be used to extend the InteractiveContext via extendInteractiveContext.
1948 --
1949 -- The returned TypecheckedHsExpr is of type IO [ () ], a list of the bound
1950 -- values, coerced to ().
1951 tcRnStmt :: HscEnv -> GhciLStmt GhcPs
1952 -> IO (Messages, Maybe ([Id], LHsExpr GhcTc, FixityEnv))
1953 tcRnStmt hsc_env rdr_stmt
1954 = runTcInteractive hsc_env $ do {
1955
1956 -- The real work is done here
1957 ((bound_ids, tc_expr), fix_env) <- tcUserStmt rdr_stmt ;
1958 zonked_expr <- zonkTopLExpr tc_expr ;
1959 zonked_ids <- zonkTopBndrs bound_ids ;
1960
1961 failIfErrsM ; -- we can't do the next step if there are levity polymorphism errors
1962 -- test case: ghci/scripts/T13202{,a}
1963
1964 -- None of the Ids should be of unboxed type, because we
1965 -- cast them all to HValues in the end!
1966 mapM_ bad_unboxed (filter (isUnliftedType . idType) zonked_ids) ;
1967
1968 traceTc "tcs 1" empty ;
1969 this_mod <- getModule ;
1970 global_ids <- mapM (externaliseAndTidyId this_mod) zonked_ids ;
1971 -- Note [Interactively-bound Ids in GHCi] in HscTypes
1972
1973 {- ---------------------------------------------
1974 At one stage I removed any shadowed bindings from the type_env;
1975 they are inaccessible but might, I suppose, cause a space leak if we leave them there.
1976 However, with Template Haskell they aren't necessarily inaccessible. Consider this
1977 GHCi session
1978 Prelude> let f n = n * 2 :: Int
1979 Prelude> fName <- runQ [| f |]
1980 Prelude> $(return $ AppE fName (LitE (IntegerL 7)))
1981 14
1982 Prelude> let f n = n * 3 :: Int
1983 Prelude> $(return $ AppE fName (LitE (IntegerL 7)))
1984 In the last line we use 'fName', which resolves to the *first* 'f'
1985 in scope. If we delete it from the type env, GHCi crashes because
1986 it doesn't expect that.
1987
1988 Hence this code is commented out
1989
1990 -------------------------------------------------- -}
1991
1992 traceOptTcRn Opt_D_dump_tc
1993 (vcat [text "Bound Ids" <+> pprWithCommas ppr global_ids,
1994 text "Typechecked expr" <+> ppr zonked_expr]) ;
1995
1996 return (global_ids, zonked_expr, fix_env)
1997 }
1998 where
1999 bad_unboxed id = addErr (sep [text "GHCi can't bind a variable of unlifted type:",
2000 nest 2 (ppr id <+> dcolon <+> ppr (idType id))])
2001
2002 {-
2003 --------------------------------------------------------------------------
2004 Typechecking Stmts in GHCi
2005
2006 Here is the grand plan, implemented in tcUserStmt
2007
2008 What you type The IO [HValue] that hscStmt returns
2009 ------------- ------------------------------------
2010 let pat = expr ==> let pat = expr in return [coerce HVal x, coerce HVal y, ...]
2011 bindings: [x,y,...]
2012
2013 pat <- expr ==> expr >>= \ pat -> return [coerce HVal x, coerce HVal y, ...]
2014 bindings: [x,y,...]
2015
2016 expr (of IO type) ==> expr >>= \ it -> return [coerce HVal it]
2017 [NB: result not printed] bindings: [it]
2018
2019 expr (of non-IO type, ==> let it = expr in print it >> return [coerce HVal it]
2020 result showable) bindings: [it]
2021
2022 expr (of non-IO type,
2023 result not showable) ==> error
2024 -}
2025
2026 -- | A plan is an attempt to lift some code into the IO monad.
2027 type PlanResult = ([Id], LHsExpr GhcTc)
2028 type Plan = TcM PlanResult
2029
2030 -- | Try the plans in order. If one fails (by raising an exn), try the next.
2031 -- If one succeeds, take it.
2032 runPlans :: [Plan] -> TcM PlanResult
2033 runPlans [] = panic "runPlans"
2034 runPlans [p] = p
2035 runPlans (p:ps) = tryTcDiscardingErrs (runPlans ps) p
2036
2037 -- | Typecheck (and 'lift') a stmt entered by the user in GHCi into the
2038 -- GHCi 'environment'.
2039 --
2040 -- By 'lift' and 'environment we mean that the code is changed to
2041 -- execute properly in an IO monad. See Note [Interactively-bound Ids
2042 -- in GHCi] in HscTypes for more details. We do this lifting by trying
2043 -- different ways ('plans') of lifting the code into the IO monad and
2044 -- type checking each plan until one succeeds.
2045 tcUserStmt :: GhciLStmt GhcPs -> TcM (PlanResult, FixityEnv)
2046
2047 -- An expression typed at the prompt is treated very specially
2048 tcUserStmt (dL->L loc (BodyStmt _ expr _ _))
2049 = do { (rn_expr, fvs) <- checkNoErrs (rnLExpr expr)
2050 -- Don't try to typecheck if the renamer fails!
2051 ; ghciStep <- getGhciStepIO
2052 ; uniq <- newUnique
2053 ; interPrintName <- getInteractivePrintName
2054 ; let fresh_it = itName uniq loc
2055 matches = [mkMatch (mkPrefixFunRhs (cL loc fresh_it)) [] rn_expr
2056 (noLoc emptyLocalBinds)]
2057 -- [it = expr]
2058 the_bind = cL loc $ (mkTopFunBind FromSource
2059 (cL loc fresh_it) matches)
2060 { fun_ext = fvs }
2061 -- Care here! In GHCi the expression might have
2062 -- free variables, and they in turn may have free type variables
2063 -- (if we are at a breakpoint, say). We must put those free vars
2064
2065 -- [let it = expr]
2066 let_stmt = cL loc $ LetStmt noExt $ noLoc $ HsValBinds noExt
2067 $ XValBindsLR
2068 (NValBinds [(NonRecursive,unitBag the_bind)] [])
2069
2070 -- [it <- e]
2071 bind_stmt = cL loc $ BindStmt noExt
2072 (cL loc (VarPat noExt (cL loc fresh_it)))
2073 (nlHsApp ghciStep rn_expr)
2074 (mkRnSyntaxExpr bindIOName)
2075 noSyntaxExpr
2076
2077 -- [; print it]
2078 print_it = cL loc $ BodyStmt noExt
2079 (nlHsApp (nlHsVar interPrintName)
2080 (nlHsVar fresh_it))
2081 (mkRnSyntaxExpr thenIOName)
2082 noSyntaxExpr
2083
2084 -- NewA
2085 no_it_a = cL loc $ BodyStmt noExt (nlHsApps bindIOName
2086 [rn_expr , nlHsVar interPrintName])
2087 (mkRnSyntaxExpr thenIOName)
2088 noSyntaxExpr
2089
2090 no_it_b = cL loc $ BodyStmt noExt (rn_expr)
2091 (mkRnSyntaxExpr thenIOName)
2092 noSyntaxExpr
2093
2094 no_it_c = cL loc $ BodyStmt noExt
2095 (nlHsApp (nlHsVar interPrintName) rn_expr)
2096 (mkRnSyntaxExpr thenIOName)
2097 noSyntaxExpr
2098
2099 -- See Note [GHCi Plans]
2100
2101 it_plans = [
2102 -- Plan A
2103 do { stuff@([it_id], _) <- tcGhciStmts [bind_stmt, print_it]
2104 ; it_ty <- zonkTcType (idType it_id)
2105 ; when (isUnitTy $ it_ty) failM
2106 ; return stuff },
2107
2108 -- Plan B; a naked bind statement
2109 tcGhciStmts [bind_stmt],
2110
2111 -- Plan C; check that the let-binding is typeable all by itself.
2112 -- If not, fail; if so, try to print it.
2113 -- The two-step process avoids getting two errors: one from
2114 -- the expression itself, and one from the 'print it' part
2115 -- This two-step story is very clunky, alas
2116 do { _ <- checkNoErrs (tcGhciStmts [let_stmt])
2117 --- checkNoErrs defeats the error recovery of let-bindings
2118 ; tcGhciStmts [let_stmt, print_it] } ]
2119
2120 -- Plans where we don't bind "it"
2121 no_it_plans = [
2122 tcGhciStmts [no_it_a] ,
2123 tcGhciStmts [no_it_b] ,
2124 tcGhciStmts [no_it_c] ]
2125
2126 ; generate_it <- goptM Opt_NoIt
2127
2128 -- We disable `-fdefer-type-errors` in GHCi for naked expressions.
2129 -- See Note [Deferred type errors in GHCi]
2130
2131 -- NB: The flag `-fdefer-type-errors` implies `-fdefer-type-holes`
2132 -- and `-fdefer-out-of-scope-variables`. However the flag
2133 -- `-fno-defer-type-errors` doesn't imply `-fdefer-type-holes` and
2134 -- `-fno-defer-out-of-scope-variables`. Thus the later two flags
2135 -- also need to be unset here.
2136 ; plan <- unsetGOptM Opt_DeferTypeErrors $
2137 unsetGOptM Opt_DeferTypedHoles $
2138 unsetGOptM Opt_DeferOutOfScopeVariables $
2139 runPlans $ if generate_it
2140 then no_it_plans
2141 else it_plans
2142
2143 ; fix_env <- getFixityEnv
2144 ; return (plan, fix_env) }
2145
2146 {- Note [Deferred type errors in GHCi]
2147 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2148 In GHCi, we ensure that type errors don't get deferred when type checking the
2149 naked expressions. Deferring type errors here is unhelpful because the
2150 expression gets evaluated right away anyway. It also would potentially emit
2151 two redundant type-error warnings, one from each plan.
2152
2153 Trac #14963 reveals another bug that when deferred type errors is enabled
2154 in GHCi, any reference of imported/loaded variables (directly or indirectly)
2155 in interactively issued naked expressions will cause ghc panic. See more
2156 detailed dicussion in Trac #14963.
2157
2158 The interactively issued declarations, statements, as well as the modules
2159 loaded into GHCi, are not affected. That means, for declaration, you could
2160 have
2161
2162 Prelude> :set -fdefer-type-errors
2163 Prelude> x :: IO (); x = putStrLn True
2164 <interactive>:14:26: warning: [-Wdeferred-type-errors]
2165 ? Couldn't match type ‘Bool’ with ‘[Char]’
2166 Expected type: String
2167 Actual type: Bool
2168 ? In the first argument of ‘putStrLn’, namely ‘True’
2169 In the expression: putStrLn True
2170 In an equation for ‘x’: x = putStrLn True
2171
2172 But for naked expressions, you will have
2173
2174 Prelude> :set -fdefer-type-errors
2175 Prelude> putStrLn True
2176 <interactive>:2:10: error:
2177 ? Couldn't match type ‘Bool’ with ‘[Char]’
2178 Expected type: String
2179 Actual type: Bool
2180 ? In the first argument of ‘putStrLn’, namely ‘True’
2181 In the expression: putStrLn True
2182 In an equation for ‘it’: it = putStrLn True
2183
2184 Prelude> let x = putStrLn True
2185 <interactive>:2:18: warning: [-Wdeferred-type-errors]
2186 ? Couldn't match type ‘Bool’ with ‘[Char]’
2187 Expected type: String
2188 Actual type: Bool
2189 ? In the first argument of ‘putStrLn’, namely ‘True’
2190 In the expression: putStrLn True
2191 In an equation for ‘x’: x = putStrLn True
2192 -}
2193
2194 tcUserStmt rdr_stmt@(dL->L loc _)
2195 = do { (([rn_stmt], fix_env), fvs) <- checkNoErrs $
2196 rnStmts GhciStmtCtxt rnLExpr [rdr_stmt] $ \_ -> do
2197 fix_env <- getFixityEnv
2198 return (fix_env, emptyFVs)
2199 -- Don't try to typecheck if the renamer fails!
2200 ; traceRn "tcRnStmt" (vcat [ppr rdr_stmt, ppr rn_stmt, ppr fvs])
2201 ; rnDump rn_stmt ;
2202
2203 ; ghciStep <- getGhciStepIO
2204 ; let gi_stmt
2205 | (dL->L loc (BindStmt ty pat expr op1 op2)) <- rn_stmt
2206 = cL loc $ BindStmt ty pat (nlHsApp ghciStep expr) op1 op2
2207 | otherwise = rn_stmt
2208
2209 ; opt_pr_flag <- goptM Opt_PrintBindResult
2210 ; let print_result_plan
2211 | opt_pr_flag -- The flag says "print result"
2212 , [v] <- collectLStmtBinders gi_stmt -- One binder
2213 = [mk_print_result_plan gi_stmt v]
2214 | otherwise = []
2215
2216 -- The plans are:
2217 -- [stmt; print v] if one binder and not v::()
2218 -- [stmt] otherwise
2219 ; plan <- runPlans (print_result_plan ++ [tcGhciStmts [gi_stmt]])
2220 ; return (plan, fix_env) }
2221 where
2222 mk_print_result_plan stmt v
2223 = do { stuff@([v_id], _) <- tcGhciStmts [stmt, print_v]
2224 ; v_ty <- zonkTcType (idType v_id)
2225 ; when (isUnitTy v_ty || not (isTauTy v_ty)) failM
2226 ; return stuff }
2227 where
2228 print_v = cL loc $ BodyStmt noExt (nlHsApp (nlHsVar printName)
2229 (nlHsVar v))
2230 (mkRnSyntaxExpr thenIOName) noSyntaxExpr
2231
2232 {-
2233 Note [GHCi Plans]
2234 ~~~~~~~~~~~~~~~~~
2235 When a user types an expression in the repl we try to print it in three different
2236 ways. Also, depending on whether -fno-it is set, we bind a variable called `it`
2237 which can be used to refer to the result of the expression subsequently in the repl.
2238
2239 The normal plans are :
2240 A. [it <- e; print e] but not if it::()
2241 B. [it <- e]
2242 C. [let it = e; print it]
2243
2244 When -fno-it is set, the plans are:
2245 A. [e >>= print]
2246 B. [e]
2247 C. [let it = e in print it]
2248
2249 The reason for -fno-it is explained in #14336. `it` can lead to the repl
2250 leaking memory as it is repeatedly queried.
2251 -}
2252
2253 -- | Typecheck the statements given and then return the results of the
2254 -- statement in the form 'IO [()]'.
2255 tcGhciStmts :: [GhciLStmt GhcRn] -> TcM PlanResult
2256 tcGhciStmts stmts
2257 = do { ioTyCon <- tcLookupTyCon ioTyConName ;
2258 ret_id <- tcLookupId returnIOName ; -- return @ IO
2259 let {
2260 ret_ty = mkListTy unitTy ;
2261 io_ret_ty = mkTyConApp ioTyCon [ret_ty] ;
2262 tc_io_stmts = tcStmtsAndThen GhciStmtCtxt tcDoStmt stmts
2263 (mkCheckExpType io_ret_ty) ;
2264 names = collectLStmtsBinders stmts ;
2265 } ;
2266
2267 -- OK, we're ready to typecheck the stmts
2268 traceTc "TcRnDriver.tcGhciStmts: tc stmts" empty ;
2269 ((tc_stmts, ids), lie) <- captureTopConstraints $
2270 tc_io_stmts $ \ _ ->
2271 mapM tcLookupId names ;
2272 -- Look up the names right in the middle,
2273 -- where they will all be in scope
2274
2275 -- Simplify the context
2276 traceTc "TcRnDriver.tcGhciStmts: simplify ctxt" empty ;
2277 const_binds <- checkNoErrs (simplifyInteractive lie) ;
2278 -- checkNoErrs ensures that the plan fails if context redn fails
2279
2280 traceTc "TcRnDriver.tcGhciStmts: done" empty ;
2281 let { -- mk_return builds the expression
2282 -- returnIO @ [()] [coerce () x, .., coerce () z]
2283 --
2284 -- Despite the inconvenience of building the type applications etc,
2285 -- this *has* to be done in type-annotated post-typecheck form
2286 -- because we are going to return a list of *polymorphic* values
2287 -- coerced to type (). If we built a *source* stmt
2288 -- return [coerce x, ..., coerce z]
2289 -- then the type checker would instantiate x..z, and we wouldn't
2290 -- get their *polymorphic* values. (And we'd get ambiguity errs
2291 -- if they were overloaded, since they aren't applied to anything.)
2292 ret_expr = nlHsApp (nlHsTyApp ret_id [ret_ty])
2293 (noLoc $ ExplicitList unitTy Nothing
2294 (map mk_item ids)) ;
2295 mk_item id = let ty_args = [idType id, unitTy] in
2296 nlHsApp (nlHsTyApp unsafeCoerceId
2297 (map getRuntimeRep ty_args ++ ty_args))
2298 (nlHsVar id) ;
2299 stmts = tc_stmts ++ [noLoc (mkLastStmt ret_expr)]
2300 } ;
2301 return (ids, mkHsDictLet (EvBinds const_binds) $
2302 noLoc (HsDo io_ret_ty GhciStmtCtxt (noLoc stmts)))
2303 }
2304
2305 -- | Generate a typed ghciStepIO expression (ghciStep :: Ty a -> IO a)
2306 getGhciStepIO :: TcM (LHsExpr GhcRn)
2307 getGhciStepIO = do
2308 ghciTy <- getGHCiMonad
2309 a_tv <- newName (mkTyVarOccFS (fsLit "a"))
2310 let ghciM = nlHsAppTy (nlHsTyVar ghciTy) (nlHsTyVar a_tv)
2311 ioM = nlHsAppTy (nlHsTyVar ioTyConName) (nlHsTyVar a_tv)
2312
2313 step_ty = noLoc $ HsForAllTy
2314 { hst_bndrs = [noLoc $ UserTyVar noExt (noLoc a_tv)]
2315 , hst_xforall = noExt
2316 , hst_body = nlHsFunTy ghciM ioM }
2317
2318 stepTy :: LHsSigWcType GhcRn
2319 stepTy = mkEmptyWildCardBndrs (mkEmptyImplicitBndrs step_ty)
2320
2321 return (noLoc $ ExprWithTySig noExt (nlHsVar ghciStepIoMName) stepTy)
2322
2323 isGHCiMonad :: HscEnv -> String -> IO (Messages, Maybe Name)
2324 isGHCiMonad hsc_env ty
2325 = runTcInteractive hsc_env $ do
2326 rdrEnv <- getGlobalRdrEnv
2327 let occIO = lookupOccEnv rdrEnv (mkOccName tcName ty)
2328 case occIO of
2329 Just [n] -> do
2330 let name = gre_name n
2331 ghciClass <- tcLookupClass ghciIoClassName
2332 userTyCon <- tcLookupTyCon name
2333 let userTy = mkTyConApp userTyCon []
2334 _ <- tcLookupInstance ghciClass [userTy]
2335 return name
2336
2337 Just _ -> failWithTc $ text "Ambiguous type!"
2338 Nothing -> failWithTc $ text ("Can't find type:" ++ ty)
2339
2340 -- | How should we infer a type? See Note [TcRnExprMode]
2341 data TcRnExprMode = TM_Inst -- ^ Instantiate the type fully (:type)
2342 | TM_NoInst -- ^ Do not instantiate the type (:type +v)
2343 | TM_Default -- ^ Default the type eagerly (:type +d)
2344
2345 -- | tcRnExpr just finds the type of an expression
2346 tcRnExpr :: HscEnv
2347 -> TcRnExprMode
2348 -> LHsExpr GhcPs
2349 -> IO (Messages, Maybe Type)
2350 tcRnExpr hsc_env mode rdr_expr
2351 = runTcInteractive hsc_env $
2352 do {
2353
2354 (rn_expr, _fvs) <- rnLExpr rdr_expr ;
2355 failIfErrsM ;
2356
2357 -- Now typecheck the expression, and generalise its type
2358 -- it might have a rank-2 type (e.g. :t runST)
2359 uniq <- newUnique ;
2360 let { fresh_it = itName uniq (getLoc rdr_expr)
2361 ; orig = lexprCtOrigin rn_expr } ;
2362 (tclvl, lie, res_ty)
2363 <- pushLevelAndCaptureConstraints $
2364 do { (_tc_expr, expr_ty) <- tcInferSigma rn_expr
2365 ; if inst
2366 then snd <$> deeplyInstantiate orig expr_ty
2367 else return expr_ty } ;
2368
2369 -- Generalise
2370 (qtvs, dicts, _, residual, _)
2371 <- simplifyInfer tclvl infer_mode
2372 [] {- No sig vars -}
2373 [(fresh_it, res_ty)]
2374 lie ;
2375
2376 -- Ignore the dictionary bindings
2377 _ <- perhaps_disable_default_warnings $
2378 simplifyInteractive residual ;
2379
2380 let { all_expr_ty = mkInvForAllTys qtvs (mkLamTypes dicts res_ty) } ;
2381 ty <- zonkTcType all_expr_ty ;
2382
2383 -- We normalise type families, so that the type of an expression is the
2384 -- same as of a bound expression (TcBinds.mkInferredPolyId). See Trac
2385 -- #10321 for further discussion.
2386 fam_envs <- tcGetFamInstEnvs ;
2387 -- normaliseType returns a coercion which we discard, so the Role is
2388 -- irrelevant
2389 return (snd (normaliseType fam_envs Nominal ty))
2390 }
2391 where
2392 -- See Note [TcRnExprMode]
2393 (inst, infer_mode, perhaps_disable_default_warnings) = case mode of
2394 TM_Inst -> (True, NoRestrictions, id)
2395 TM_NoInst -> (False, NoRestrictions, id)
2396 TM_Default -> (True, EagerDefaulting, unsetWOptM Opt_WarnTypeDefaults)
2397
2398 --------------------------
2399 tcRnImportDecls :: HscEnv
2400 -> [LImportDecl GhcPs]
2401 -> IO (Messages, Maybe GlobalRdrEnv)
2402 -- Find the new chunk of GlobalRdrEnv created by this list of import
2403 -- decls. In contract tcRnImports *extends* the TcGblEnv.
2404 tcRnImportDecls hsc_env import_decls
2405 = runTcInteractive hsc_env $
2406 do { gbl_env <- updGblEnv zap_rdr_env $
2407 tcRnImports hsc_env import_decls
2408 ; return (tcg_rdr_env gbl_env) }
2409 where
2410 zap_rdr_env gbl_env = gbl_env { tcg_rdr_env = emptyGlobalRdrEnv }
2411
2412 -- tcRnType just finds the kind of a type
2413 tcRnType :: HscEnv
2414 -> Bool -- Normalise the returned type
2415 -> LHsType GhcPs
2416 -> IO (Messages, Maybe (Type, Kind))
2417 tcRnType hsc_env normalise rdr_type
2418 = runTcInteractive hsc_env $
2419 setXOptM LangExt.PolyKinds $ -- See Note [Kind-generalise in tcRnType]
2420 do { (HsWC { hswc_ext = wcs, hswc_body = rn_type }, _fvs)
2421 <- rnHsWcType GHCiCtx (mkHsWildCardBndrs rdr_type)
2422 -- The type can have wild cards, but no implicit
2423 -- generalisation; e.g. :kind (T _)
2424 ; failIfErrsM
2425
2426 -- Now kind-check the type
2427 -- It can have any rank or kind
2428 -- First bring into scope any wildcards
2429 ; traceTc "tcRnType" (vcat [ppr wcs, ppr rn_type])
2430 ; (ty, kind) <- pushTcLevelM_ $
2431 -- must push level to satisfy level precondition of
2432 -- kindGeneralize, below
2433 solveEqualities $
2434 tcWildCardBinders wcs $ \ wcs' ->
2435 do { emitWildCardHoleConstraints wcs'
2436 ; tcLHsTypeUnsaturated rn_type }
2437
2438 -- Do kind generalisation; see Note [Kind-generalise in tcRnType]
2439 ; kind <- zonkTcType kind
2440 ; kvs <- kindGeneralize kind
2441 ; ty <- zonkTcTypeToType ty
2442
2443 -- Do validity checking on type
2444 ; checkValidType (GhciCtxt True) ty
2445
2446 ; ty' <- if normalise
2447 then do { fam_envs <- tcGetFamInstEnvs
2448 ; let (_, ty')
2449 = normaliseType fam_envs Nominal ty
2450 ; return ty' }
2451 else return ty ;
2452
2453 ; return (ty', mkInvForAllTys kvs (tcTypeKind ty')) }
2454
2455 {- Note [TcRnExprMode]
2456 ~~~~~~~~~~~~~~~~~~~~~~
2457 How should we infer a type when a user asks for the type of an expression e
2458 at the GHCi prompt? We offer 3 different possibilities, described below. Each
2459 considers this example, with -fprint-explicit-foralls enabled:
2460
2461 foo :: forall a f b. (Show a, Num b, Foldable f) => a -> f b -> String
2462 :type{,-spec,-def} foo @Int
2463
2464 :type / TM_Inst
2465
2466 In this mode, we report the type that would be inferred if a variable
2467 were assigned to expression e, without applying the monomorphism restriction.
2468 This means we deeply instantiate the type and then regeneralize, as discussed
2469 in #11376.
2470
2471 > :type foo @Int
2472 forall {b} {f :: * -> *}. (Foldable f, Num b) => Int -> f b -> String
2473
2474 Note that the variables and constraints are reordered here, because this
2475 is possible during regeneralization. Also note that the variables are
2476 reported as Inferred instead of Specified.
2477
2478 :type +v / TM_NoInst
2479
2480 This mode is for the benefit of users using TypeApplications. It does no
2481 instantiation whatsoever, sometimes meaning that class constraints are not
2482 solved.
2483
2484 > :type +v foo @Int
2485 forall f b. (Show Int, Num b, Foldable f) => Int -> f b -> String
2486
2487 Note that Show Int is still reported, because the solver never got a chance
2488 to see it.
2489
2490 :type +d / TM_Default
2491
2492 This mode is for the benefit of users who wish to see instantiations of
2493 generalized types, and in particular to instantiate Foldable and Traversable.
2494 In this mode, any type variable that can be defaulted is defaulted. Because
2495 GHCi uses -XExtendedDefaultRules, this means that Foldable and Traversable are
2496 defaulted.
2497
2498 > :type +d foo @Int
2499 Int -> [Integer] -> String
2500
2501 Note that this mode can sometimes lead to a type error, if a type variable is
2502 used with a defaultable class but cannot actually be defaulted:
2503
2504 bar :: (Num a, Monoid a) => a -> a
2505 > :type +d bar
2506 ** error **
2507
2508 The error arises because GHC tries to default a but cannot find a concrete
2509 type in the defaulting list that is both Num and Monoid. (If this list is
2510 modified to include an element that is both Num and Monoid, the defaulting
2511 would succeed, of course.)
2512
2513 Note [Kind-generalise in tcRnType]
2514 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2515 We switch on PolyKinds when kind-checking a user type, so that we will
2516 kind-generalise the type, even when PolyKinds is not otherwise on.
2517 This gives the right default behaviour at the GHCi prompt, where if
2518 you say ":k T", and T has a polymorphic kind, you'd like to see that
2519 polymorphism. Of course. If T isn't kind-polymorphic you won't get
2520 anything unexpected, but the apparent *loss* of polymorphism, for
2521 types that you know are polymorphic, is quite surprising. See Trac
2522 #7688 for a discussion.
2523
2524 Note that the goal is to generalise the *kind of the type*, not
2525 the type itself! Example:
2526 ghci> data SameKind :: k -> k -> Type
2527 ghci> :k SameKind _
2528
2529 We want to get `k -> Type`, not `Any -> Type`, which is what we would
2530 get without kind-generalisation. Note that `:k SameKind` is OK, as
2531 GHC will not instantiate SameKind here, and so we see its full kind
2532 of `forall k. k -> k -> Type`.
2533
2534 ************************************************************************
2535 * *
2536 tcRnDeclsi
2537 * *
2538 ************************************************************************
2539
2540 tcRnDeclsi exists to allow class, data, and other declarations in GHCi.
2541 -}
2542
2543 tcRnDeclsi :: HscEnv
2544 -> [LHsDecl GhcPs]
2545 -> IO (Messages, Maybe TcGblEnv)
2546 tcRnDeclsi hsc_env local_decls
2547 = runTcInteractive hsc_env $
2548 tcRnSrcDecls False local_decls
2549
2550 externaliseAndTidyId :: Module -> Id -> TcM Id
2551 externaliseAndTidyId this_mod id
2552 = do { name' <- externaliseName this_mod (idName id)
2553 ; return (globaliseAndTidyId (setIdName id name')) }
2554
2555
2556 {-
2557 ************************************************************************
2558 * *
2559 More GHCi stuff, to do with browsing and getting info
2560 * *
2561 ************************************************************************
2562 -}
2563
2564 -- | ASSUMES that the module is either in the 'HomePackageTable' or is
2565 -- a package module with an interface on disk. If neither of these is
2566 -- true, then the result will be an error indicating the interface
2567 -- could not be found.
2568 getModuleInterface :: HscEnv -> Module -> IO (Messages, Maybe ModIface)
2569 getModuleInterface hsc_env mod
2570 = runTcInteractive hsc_env $
2571 loadModuleInterface (text "getModuleInterface") mod
2572
2573 tcRnLookupRdrName :: HscEnv -> Located RdrName
2574 -> IO (Messages, Maybe [Name])
2575 -- ^ Find all the Names that this RdrName could mean, in GHCi
2576 tcRnLookupRdrName hsc_env (dL->L loc rdr_name)
2577 = runTcInteractive hsc_env $
2578 setSrcSpan loc $
2579 do { -- If the identifier is a constructor (begins with an
2580 -- upper-case letter), then we need to consider both
2581 -- constructor and type class identifiers.
2582 let rdr_names = dataTcOccs rdr_name
2583 ; names_s <- mapM lookupInfoOccRn rdr_names
2584 ; let names = concat names_s
2585 ; when (null names) (addErrTc (text "Not in scope:" <+> quotes (ppr rdr_name)))
2586 ; return names }
2587
2588 tcRnLookupName :: HscEnv -> Name -> IO (Messages, Maybe TyThing)
2589 tcRnLookupName hsc_env name
2590 = runTcInteractive hsc_env $
2591 tcRnLookupName' name
2592
2593 -- To look up a name we have to look in the local environment (tcl_lcl)
2594 -- as well as the global environment, which is what tcLookup does.
2595 -- But we also want a TyThing, so we have to convert:
2596
2597 tcRnLookupName' :: Name -> TcRn TyThing
2598 tcRnLookupName' name = do
2599 tcthing <- tcLookup name
2600 case tcthing of
2601 AGlobal thing -> return thing
2602 ATcId{tct_id=id} -> return (AnId id)
2603 _ -> panic "tcRnLookupName'"
2604
2605 tcRnGetInfo :: HscEnv
2606 -> Name
2607 -> IO ( Messages
2608 , Maybe (TyThing, Fixity, [ClsInst], [FamInst], SDoc))
2609
2610 -- Used to implement :info in GHCi
2611 --
2612 -- Look up a RdrName and return all the TyThings it might be
2613 -- A capitalised RdrName is given to us in the DataName namespace,
2614 -- but we want to treat it as *both* a data constructor
2615 -- *and* as a type or class constructor;
2616 -- hence the call to dataTcOccs, and we return up to two results
2617 tcRnGetInfo hsc_env name
2618 = runTcInteractive hsc_env $
2619 do { loadUnqualIfaces hsc_env (hsc_IC hsc_env)
2620 -- Load the interface for all unqualified types and classes
2621 -- That way we will find all the instance declarations
2622 -- (Packages have not orphan modules, and we assume that
2623 -- in the home package all relevant modules are loaded.)
2624
2625 ; thing <- tcRnLookupName' name
2626 ; fixity <- lookupFixityRn name
2627 ; (cls_insts, fam_insts) <- lookupInsts thing
2628 ; let info = lookupKnownNameInfo name
2629 ; return (thing, fixity, cls_insts, fam_insts, info) }
2630
2631
2632 -- Lookup all class and family instances for a type constructor.
2633 --
2634 -- This function filters all instances in the type environment, so there
2635 -- is a lot of duplicated work if it is called many times in the same
2636 -- type environment. If this becomes a problem, the NameEnv computed
2637 -- in GHC.getNameToInstancesIndex could be cached in TcM and both functions
2638 -- could be changed to consult that index.
2639 lookupInsts :: TyThing -> TcM ([ClsInst],[FamInst])
2640 lookupInsts (ATyCon tc)
2641 = do { InstEnvs { ie_global = pkg_ie, ie_local = home_ie, ie_visible = vis_mods } <- tcGetInstEnvs
2642 ; (pkg_fie, home_fie) <- tcGetFamInstEnvs
2643 -- Load all instances for all classes that are
2644 -- in the type environment (which are all the ones
2645 -- we've seen in any interface file so far)
2646
2647 -- Return only the instances relevant to the given thing, i.e.
2648 -- the instances whose head contains the thing's name.
2649 ; let cls_insts =
2650 [ ispec -- Search all
2651 | ispec <- instEnvElts home_ie ++ instEnvElts pkg_ie
2652 , instIsVisible vis_mods ispec
2653 , tc_name `elemNameSet` orphNamesOfClsInst ispec ]
2654 ; let fam_insts =
2655 [ fispec
2656 | fispec <- famInstEnvElts home_fie ++ famInstEnvElts pkg_fie
2657 , tc_name `elemNameSet` orphNamesOfFamInst fispec ]
2658 ; return (cls_insts, fam_insts) }
2659 where
2660 tc_name = tyConName tc
2661
2662 lookupInsts _ = return ([],[])
2663
2664 loadUnqualIfaces :: HscEnv -> InteractiveContext -> TcM ()
2665 -- Load the interface for everything that is in scope unqualified
2666 -- This is so that we can accurately report the instances for
2667 -- something
2668 loadUnqualIfaces hsc_env ictxt
2669 = initIfaceTcRn $ do
2670 mapM_ (loadSysInterface doc) (moduleSetElts (mkModuleSet unqual_mods))
2671 where
2672 this_pkg = thisPackage (hsc_dflags hsc_env)
2673
2674 unqual_mods = [ nameModule name
2675 | gre <- globalRdrEnvElts (ic_rn_gbl_env ictxt)
2676 , let name = gre_name gre
2677 , nameIsFromExternalPackage this_pkg name
2678 , isTcOcc (nameOccName name) -- Types and classes only
2679 , unQualOK gre ] -- In scope unqualified
2680 doc = text "Need interface for module whose export(s) are in scope unqualified"
2681
2682
2683
2684 {-
2685 ************************************************************************
2686 * *
2687 Debugging output
2688 This is what happens when you do -ddump-types
2689 * *
2690 ************************************************************************
2691 -}
2692
2693 rnDump :: (Outputable a, Data a) => a -> TcRn ()
2694 -- Dump, with a banner, if -ddump-rn
2695 rnDump rn = do { traceOptTcRn Opt_D_dump_rn (mkDumpDoc "Renamer" (ppr rn)) }
2696
2697 tcDump :: TcGblEnv -> TcRn ()
2698 tcDump env
2699 = do { dflags <- getDynFlags ;
2700
2701 -- Dump short output if -ddump-types or -ddump-tc
2702 when (dopt Opt_D_dump_types dflags || dopt Opt_D_dump_tc dflags)
2703 (traceTcRnForUser Opt_D_dump_types short_dump) ;
2704
2705 -- Dump bindings if -ddump-tc
2706 traceOptTcRn Opt_D_dump_tc (mkDumpDoc "Typechecker" full_dump);
2707
2708 -- Dump bindings as an hsSyn AST if -ddump-tc-ast
2709 traceOptTcRn Opt_D_dump_tc_ast (mkDumpDoc "Typechecker" ast_dump)
2710 }
2711 where
2712 short_dump = pprTcGblEnv env
2713 full_dump = pprLHsBinds (tcg_binds env)
2714 -- NB: foreign x-d's have undefined's in their types;
2715 -- hence can't show the tc_fords
2716 ast_dump = showAstData NoBlankSrcSpan (tcg_binds env)
2717
2718 -- It's unpleasant having both pprModGuts and pprModDetails here
2719 pprTcGblEnv :: TcGblEnv -> SDoc
2720 pprTcGblEnv (TcGblEnv { tcg_type_env = type_env,
2721 tcg_insts = insts,
2722 tcg_fam_insts = fam_insts,
2723 tcg_rules = rules,
2724 tcg_imports = imports })
2725 = getPprDebug $ \debug ->
2726 vcat [ ppr_types debug type_env
2727 , ppr_tycons debug fam_insts type_env
2728 , ppr_datacons debug type_env
2729 , ppr_patsyns type_env
2730 , ppr_insts insts
2731 , ppr_fam_insts fam_insts
2732 , ppr_rules rules
2733 , text "Dependent modules:" <+>
2734 pprUFM (imp_dep_mods imports) (ppr . sort)
2735 , text "Dependent packages:" <+>
2736 ppr (S.toList $ imp_dep_pkgs imports)]
2737 where -- The use of sort is just to reduce unnecessary
2738 -- wobbling in testsuite output
2739
2740 ppr_rules :: [LRuleDecl GhcTc] -> SDoc
2741 ppr_rules rules
2742 = ppUnless (null rules) $
2743 hang (text "RULES")
2744 2 (vcat (map ppr rules))
2745
2746 ppr_types :: Bool -> TypeEnv -> SDoc
2747 ppr_types debug type_env
2748 = ppr_things "TYPE SIGNATURES" ppr_sig
2749 (sortBy (comparing getOccName) ids)
2750 where
2751 ids = [id | id <- typeEnvIds type_env, want_sig id]
2752 want_sig id
2753 | debug = True
2754 | otherwise = hasTopUserName id
2755 && case idDetails id of
2756 VanillaId -> True
2757 RecSelId {} -> True
2758 ClassOpId {} -> True
2759 FCallId {} -> True
2760 _ -> False
2761 -- Data cons (workers and wrappers), pattern synonyms,
2762 -- etc are suppressed (unless -dppr-debug),
2763 -- because they appear elsehwere
2764
2765 ppr_sig id = hang (ppr id <+> dcolon) 2 (ppr (tidyTopType (idType id)))
2766
2767 ppr_tycons :: Bool -> [FamInst] -> TypeEnv -> SDoc
2768 ppr_tycons debug fam_insts type_env
2769 = vcat [ ppr_things "TYPE CONSTRUCTORS" ppr_tc tycons
2770 , ppr_things "COERCION AXIOMS" ppr_ax
2771 (typeEnvCoAxioms type_env) ]
2772 where
2773 fi_tycons = famInstsRepTyCons fam_insts
2774
2775 tycons = sortBy (comparing getOccName) $
2776 [tycon | tycon <- typeEnvTyCons type_env
2777 , want_tycon tycon]
2778 -- Sort by OccName to reduce unnecessary changes
2779 want_tycon tycon | debug = True
2780 | otherwise = isExternalName (tyConName tycon) &&
2781 not (tycon `elem` fi_tycons)
2782 ppr_tc tc
2783 = vcat [ hang (ppr (tyConFlavour tc) <+> ppr tc
2784 <> braces (ppr (tyConArity tc)) <+> dcolon)
2785 2 (ppr (tidyTopType (tyConKind tc)))
2786 , nest 2 $
2787 ppWhen show_roles $
2788 text "roles" <+> (sep (map ppr roles)) ]
2789 where
2790 show_roles = debug || not (all (== boring_role) roles)
2791 roles = tyConRoles tc
2792 boring_role | isClassTyCon tc = Nominal
2793 | otherwise = Representational
2794 -- Matches the choice in IfaceSyn, calls to pprRoles
2795
2796 ppr_ax ax = ppr (coAxiomToIfaceDecl ax)
2797 -- We go via IfaceDecl rather than using pprCoAxiom
2798 -- This way we get the full axiom (both LHS and RHS) with
2799 -- wildcard binders tidied to _1, _2, etc.
2800
2801 ppr_datacons :: Bool -> TypeEnv -> SDoc
2802 ppr_datacons debug type_env
2803 = ppr_things "DATA CONSTRUCTORS" ppr_dc wanted_dcs
2804 -- The filter gets rid of class data constructors
2805 where
2806 ppr_dc dc = ppr dc <+> dcolon <+> ppr (dataConUserType dc)
2807 all_dcs = typeEnvDataCons type_env
2808 wanted_dcs | debug = all_dcs
2809 | otherwise = filterOut is_cls_dc all_dcs
2810 is_cls_dc dc = isClassTyCon (dataConTyCon dc)
2811
2812 ppr_patsyns :: TypeEnv -> SDoc
2813 ppr_patsyns type_env
2814 = ppr_things "PATTERN SYNONYMS" ppr_ps
2815 (typeEnvPatSyns type_env)
2816 where
2817 ppr_ps ps = ppr ps <+> dcolon <+> pprPatSynType ps
2818
2819 ppr_insts :: [ClsInst] -> SDoc
2820 ppr_insts ispecs
2821 = ppr_things "CLASS INSTANCES" pprInstance ispecs
2822
2823 ppr_fam_insts :: [FamInst] -> SDoc
2824 ppr_fam_insts fam_insts
2825 = ppr_things "FAMILY INSTANCES" pprFamInst fam_insts
2826
2827 ppr_things :: String -> (a -> SDoc) -> [a] -> SDoc
2828 ppr_things herald ppr_one things
2829 | null things = empty
2830 | otherwise = text herald $$ nest 2 (vcat (map ppr_one things))
2831
2832 hasTopUserName :: NamedThing x => x -> Bool
2833 -- A top-level thing whose name is not "derived"
2834 -- Thus excluding things like $tcX, from Typeable boilerplate
2835 -- and C:Coll from class-dictionary data constructors
2836 hasTopUserName x
2837 = isExternalName name && not (isDerivedOccName (nameOccName name))
2838 where
2839 name = getName x
2840
2841 {-
2842 ********************************************************************************
2843
2844 Type Checker Plugins
2845
2846 ********************************************************************************
2847 -}
2848
2849 withTcPlugins :: HscEnv -> TcM a -> TcM a
2850 withTcPlugins hsc_env m =
2851 do let plugins = getTcPlugins (hsc_dflags hsc_env)
2852 case plugins of
2853 [] -> m -- Common fast case
2854 _ -> do ev_binds_var <- newTcEvBinds
2855 (solvers,stops) <- unzip `fmap` mapM (startPlugin ev_binds_var) plugins
2856 -- This ensures that tcPluginStop is called even if a type
2857 -- error occurs during compilation (Fix of #10078)
2858 eitherRes <- tryM $ do
2859 updGblEnv (\e -> e { tcg_tc_plugins = solvers }) m
2860 mapM_ (flip runTcPluginM ev_binds_var) stops
2861 case eitherRes of
2862 Left _ -> failM
2863 Right res -> return res
2864 where
2865 startPlugin ev_binds_var (TcPlugin start solve stop) =
2866 do s <- runTcPluginM start ev_binds_var
2867 return (solve s, stop s)
2868
2869 getTcPlugins :: DynFlags -> [TcRnMonad.TcPlugin]
2870 getTcPlugins dflags = catMaybes $ mapPlugins dflags (\p args -> tcPlugin p args)
2871
2872 runRenamerPlugin :: TcGblEnv
2873 -> HsGroup GhcRn
2874 -> TcM (TcGblEnv, HsGroup GhcRn)
2875 runRenamerPlugin gbl_env hs_group = do
2876 dflags <- getDynFlags
2877 withPlugins dflags
2878 (\p opts (e, g) -> ( mark_plugin_unsafe dflags >> renamedResultAction p opts e g))
2879 (gbl_env, hs_group)
2880
2881
2882 -- XXX: should this really be a Maybe X? Check under which circumstances this
2883 -- can become a Nothing and decide whether this should instead throw an
2884 -- exception/signal an error.
2885 type RenamedStuff =
2886 (Maybe (HsGroup GhcRn, [LImportDecl GhcRn], Maybe [(LIE GhcRn, Avails)],
2887 Maybe LHsDocString))
2888
2889 -- | Extract the renamed information from TcGblEnv.
2890 getRenamedStuff :: TcGblEnv -> RenamedStuff
2891 getRenamedStuff tc_result
2892 = fmap (\decls -> ( decls, tcg_rn_imports tc_result
2893 , tcg_rn_exports tc_result, tcg_doc_hdr tc_result ) )
2894 (tcg_rn_decls tc_result)
2895
2896 runTypecheckerPlugin :: ModSummary -> HscEnv -> TcGblEnv -> TcM TcGblEnv
2897 runTypecheckerPlugin sum hsc_env gbl_env = do
2898 let dflags = hsc_dflags hsc_env
2899 withPlugins dflags
2900 (\p opts env -> mark_plugin_unsafe dflags
2901 >> typeCheckResultAction p opts sum env)
2902 gbl_env
2903
2904 mark_plugin_unsafe :: DynFlags -> TcM ()
2905 mark_plugin_unsafe dflags = recordUnsafeInfer pluginUnsafe
2906 where
2907 unsafeText = "Use of plugins makes the module unsafe"
2908 pluginUnsafe = unitBag ( mkPlainWarnMsg dflags noSrcSpan
2909 (Outputable.text unsafeText) )