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