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