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