45c25e4942b81f0e87ea24b3a375abeb9538e424
[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[TcMovectle]{Typechecking a whole module}
6
7 https://ghc.haskell.org/trac/ghc/wiki/Commentary/Compiler/TypeChecker
8 -}
9
10 {-# LANGUAGE CPP, NondecreasingIndentation #-}
11
12 module TcRnDriver (
13 #ifdef GHCI
14 tcRnStmt, tcRnExpr, tcRnType,
15 tcRnImportDecls,
16 tcRnLookupRdrName,
17 getModuleInterface,
18 tcRnDeclsi,
19 isGHCiMonad,
20 runTcInteractive, -- Used by GHC API clients (Trac #8878)
21 #endif
22 tcRnLookupName,
23 tcRnGetInfo,
24 tcRnModule, tcRnModuleTcRnM,
25 tcTopSrcDecls,
26 ) where
27
28 #ifdef GHCI
29 import {-# SOURCE #-} TcSplice ( runQuasi )
30 import RnSplice ( rnTopSpliceDecls, traceSplice, SpliceInfo(..) )
31 import IfaceEnv( externaliseName )
32 import TcType ( isUnitTy, isTauTy )
33 import TcHsType
34 import TcMatches
35 import RnTypes
36 import RnExpr
37 import MkId
38 import TidyPgm ( globaliseAndTidyId )
39 import TysWiredIn ( unitTy, mkListTy )
40 import DynamicLoading ( loadPlugins )
41 import Plugins ( tcPlugin )
42 #endif
43
44 import DynFlags
45 import StaticFlags
46 import HsSyn
47 import PrelNames
48 import RdrName
49 import TcHsSyn
50 import TcExpr
51 import TcRnMonad
52 import TcEvidence
53 import PprTyThing( pprTyThing )
54 import Coercion( pprCoAxiom )
55 import FamInst
56 import InstEnv
57 import FamInstEnv
58 import TcAnnotations
59 import TcBinds
60 import HeaderInfo ( mkPrelImports )
61 import TcDefaults
62 import TcEnv
63 import TcRules
64 import TcForeign
65 import TcInstDcls
66 import TcIface
67 import TcMType
68 import MkIface
69 import TcSimplify
70 import TcTyClsDecls
71 import LoadIface
72 import TidyPgm ( mkBootModDetailsTc )
73 import RnNames
74 import RnEnv
75 import RnSource
76 import ErrUtils
77 import Id
78 import IdInfo( IdDetails( VanillaId ) )
79 import VarEnv
80 import Module
81 import UniqFM
82 import Name
83 import NameEnv
84 import NameSet
85 import Avail
86 import TyCon
87 import SrcLoc
88 import HscTypes
89 import ListSetOps
90 import Outputable
91 import ConLike
92 import DataCon
93 import Type
94 import Class
95 import BasicTypes hiding( SuccessFlag(..) )
96 import CoAxiom
97 import Annotations
98 import Data.List ( sortBy )
99 import Data.Ord
100 import FastString
101 import Maybes
102 import Util
103 import Bag
104
105 import Control.Monad
106
107 #include "HsVersions.h"
108
109 {-
110 ************************************************************************
111 * *
112 Typecheck and rename a module
113 * *
114 ************************************************************************
115 -}
116
117 -- | Top level entry point for typechecker and renamer
118 tcRnModule :: HscEnv
119 -> HscSource
120 -> Bool -- True <=> save renamed syntax
121 -> HsParsedModule
122 -> IO (Messages, Maybe TcGblEnv)
123
124 tcRnModule hsc_env hsc_src save_rn_syntax
125 parsedModule@HsParsedModule {hpm_module=L loc this_module}
126 | RealSrcSpan real_loc <- loc
127 = do { showPass (hsc_dflags hsc_env) "Renamer/typechecker" ;
128
129 ; initTc hsc_env hsc_src save_rn_syntax this_mod real_loc $
130 withTcPlugins hsc_env $
131 tcRnModuleTcRnM hsc_env hsc_src parsedModule pair }
132
133 | otherwise
134 = return ((emptyBag, unitBag err_msg), Nothing)
135
136 where
137 err_msg = mkPlainErrMsg (hsc_dflags hsc_env) loc $
138 text "Module does not have a RealSrcSpan:" <+> ppr this_mod
139
140 this_pkg = thisPackage (hsc_dflags hsc_env)
141
142 pair :: (Module, SrcSpan)
143 pair@(this_mod,_)
144 | Just (L mod_loc mod) <- hsmodName this_module
145 = (mkModule this_pkg mod, mod_loc)
146
147 | otherwise -- 'module M where' is omitted
148 = (mAIN, srcLocSpan (srcSpanStart loc))
149
150
151 -- To be called at the beginning of renaming hsig files.
152 -- If we're processing a signature, load up the RdrEnv
153 -- specified by sig-of so that
154 -- when we process top-level bindings, we pull in the right
155 -- original names. We also need to add in dependencies from
156 -- the implementation (orphans, family instances, packages),
157 -- similar to how rnImportDecl handles things.
158 -- ToDo: Handle SafeHaskell
159 tcRnSignature :: DynFlags -> HscSource -> TcRn TcGblEnv
160 tcRnSignature dflags hsc_src
161 = do { tcg_env <- getGblEnv ;
162 case tcg_sig_of tcg_env of {
163 Just sof
164 | hsc_src /= HsBootFile -> do
165 { modname <- fmap moduleName getModule
166 ; addErr (text "Found -sig-of entry for" <+> ppr modname
167 <+> text "which is not hs-boot." $$
168 text "Try removing" <+> ppr modname <+>
169 text "from -sig-of")
170 ; return tcg_env
171 }
172 | otherwise -> do
173 { sig_iface <- initIfaceTcRn $ loadSysInterface (text "sig-of") sof
174 ; let { gr = mkGlobalRdrEnv
175 (gresFromAvails Nothing (mi_exports sig_iface))
176 ; avails = calculateAvails dflags
177 sig_iface False{- safe -} False{- boot -} }
178 ; return (tcg_env
179 { tcg_impl_rdr_env = Just gr
180 , tcg_imports = tcg_imports tcg_env `plusImportAvails` avails
181 })
182 } ;
183 Nothing -> return tcg_env
184 }
185 }
186
187 checkHsigIface :: HscEnv -> TcGblEnv -> TcRn ()
188 checkHsigIface hsc_env tcg_env
189 = case tcg_impl_rdr_env tcg_env of
190 Just gr -> do { sig_details <- liftIO $ mkBootModDetailsTc hsc_env tcg_env
191 ; checkHsigIface' gr sig_details
192 }
193 Nothing -> return ()
194
195 checkHsigIface' :: GlobalRdrEnv -> ModDetails -> TcRn ()
196 checkHsigIface' gr
197 ModDetails { md_insts = sig_insts, md_fam_insts = sig_fam_insts,
198 md_types = sig_type_env, md_exports = sig_exports}
199 = do { traceTc "checkHsigIface" $ vcat
200 [ ppr sig_type_env, ppr sig_insts, ppr sig_exports ]
201 ; mapM_ check_export sig_exports
202 ; unless (null sig_fam_insts) $
203 panic ("TcRnDriver.checkHsigIface: Cannot handle family " ++
204 "instances in hsig files yet...")
205 ; mapM_ check_inst sig_insts
206 ; failIfErrsM
207 }
208 where
209 check_export sig_avail
210 -- Skip instances, we'll check them later
211 | name `elem` dfun_names = return ()
212 | otherwise = do
213 { -- Lookup local environment only (don't want to accidentally pick
214 -- up the backing copy.) We consult tcg_type_env because we want
215 -- to pick up wired in names too (which get dropped by the iface
216 -- creation process); it's OK for a signature file to mention
217 -- a wired in name.
218 env <- getGblEnv
219 ; case lookupNameEnv (tcg_type_env env) name of
220 Nothing
221 -- All this means is no local definition is available: but we
222 -- could have created the export this way:
223 --
224 -- module ASig(f) where
225 -- import B(f)
226 --
227 -- In this case, we have to just lookup the identifier in
228 -- the backing implementation and make sure it matches.
229 | [GRE { gre_name = name' }]
230 <- lookupGlobalRdrEnv gr (nameOccName name)
231 , name == name' -> return ()
232 -- TODO: Possibly give a different error if the identifier
233 -- is exported, but it's a different original name
234 | otherwise -> addErrAt (nameSrcSpan name)
235 (missingBootThing False name "exported by")
236 Just sig_thing -> do {
237 -- We use tcLookupImported_maybe because we want to EXCLUDE
238 -- tcg_env.
239 ; r <- tcLookupImported_maybe name
240 ; case r of
241 Failed err -> addErr err
242 Succeeded real_thing -> checkBootDeclM False sig_thing real_thing
243 }}
244 where
245 name = availName sig_avail
246
247 dfun_names = map getName sig_insts
248
249 -- In general, for hsig files we can't assume that the implementing
250 -- file actually implemented the instances (they may be reexported
251 -- from elsewhere). Where should we look for the instances? We do
252 -- the same as we would otherwise: consult the EPS. This isn't
253 -- perfect (we might conclude the module exports an instance
254 -- when it doesn't, see #9422), but we will never refuse to compile
255 -- something
256 check_inst :: ClsInst -> TcM ()
257 check_inst sig_inst
258 = do eps <- getEps
259 when (not (memberInstEnv (eps_inst_env eps) sig_inst)) $
260 addErrTc (instMisMatch False sig_inst)
261
262 tcRnModuleTcRnM :: HscEnv
263 -> HscSource
264 -> HsParsedModule
265 -> (Module, SrcSpan)
266 -> TcRn TcGblEnv
267 -- Factored out separately from tcRnModule so that a Core plugin can
268 -- call the type checker directly
269 tcRnModuleTcRnM hsc_env hsc_src
270 (HsParsedModule {
271 hpm_module =
272 (L loc (HsModule maybe_mod export_ies
273 import_decls local_decls mod_deprec
274 maybe_doc_hdr)),
275 hpm_src_files = src_files
276 })
277 (this_mod, prel_imp_loc)
278 = setSrcSpan loc $
279 do { let { dflags = hsc_dflags hsc_env
280 ; explicit_mod_hdr = isJust maybe_mod } ;
281
282 tcg_env <- tcRnSignature dflags hsc_src ;
283 setGblEnv tcg_env $ do {
284
285 -- Load the hi-boot interface for this module, if any
286 -- We do this now so that the boot_names can be passed
287 -- to tcTyAndClassDecls, because the boot_names are
288 -- automatically considered to be loop breakers
289 --
290 -- Do this *after* tcRnImports, so that we know whether
291 -- a module that we import imports us; and hence whether to
292 -- look for a hi-boot file
293 boot_info <- tcHiBootIface hsc_src this_mod ;
294 setGblEnv (tcg_env { tcg_self_boot = boot_info }) $ do {
295
296 -- Deal with imports; first add implicit prelude
297 implicit_prelude <- xoptM Opt_ImplicitPrelude;
298 let { prel_imports = mkPrelImports (moduleName this_mod) prel_imp_loc
299 implicit_prelude import_decls } ;
300
301 whenWOptM Opt_WarnImplicitPrelude $
302 when (notNull prel_imports) $ addWarn (implicitPreludeWarn) ;
303
304 tcg_env <- {-# SCC "tcRnImports" #-}
305 tcRnImports hsc_env (prel_imports ++ import_decls) ;
306
307 -- If the whole module is warned about or deprecated
308 -- (via mod_deprec) record that in tcg_warns. If we do thereby add
309 -- a WarnAll, it will override any subseqent depracations added to tcg_warns
310 let { tcg_env1 = case mod_deprec of
311 Just (L _ txt) -> tcg_env { tcg_warns = WarnAll txt }
312 Nothing -> tcg_env
313 } ;
314
315 setGblEnv tcg_env1 $ do {
316
317 -- Rename and type check the declarations
318 traceRn (text "rn1a") ;
319 tcg_env <- if isHsBoot hsc_src then
320 tcRnHsBootDecls hsc_src local_decls
321 else
322 {-# SCC "tcRnSrcDecls" #-}
323 tcRnSrcDecls explicit_mod_hdr export_ies local_decls ;
324 setGblEnv tcg_env $ do {
325
326 -- Process the export list
327 traceRn (text "rn4a: before exports");
328 tcg_env <- rnExports explicit_mod_hdr export_ies tcg_env ;
329 traceRn (text "rn4b: after exports") ;
330
331 -- Check that main is exported (must be after rnExports)
332 checkMainExported tcg_env ;
333
334 -- Compare the hi-boot iface (if any) with the real thing
335 -- Must be done after processing the exports
336 tcg_env <- checkHiBootIface tcg_env boot_info ;
337
338 -- Compare the hsig tcg_env with the real thing
339 checkHsigIface hsc_env tcg_env ;
340
341 -- Nub out type class instances now that we've checked them,
342 -- if we're compiling an hsig with sig-of.
343 -- See Note [Signature files and type class instances]
344 tcg_env <- (case tcg_sig_of tcg_env of
345 Just _ -> return tcg_env {
346 tcg_inst_env = emptyInstEnv,
347 tcg_fam_inst_env = emptyFamInstEnv,
348 tcg_insts = [],
349 tcg_fam_insts = []
350 }
351 Nothing -> return tcg_env) ;
352
353 -- The new type env is already available to stuff slurped from
354 -- interface files, via TcEnv.updateGlobalTypeEnv
355 -- It's important that this includes the stuff in checkHiBootIface,
356 -- because the latter might add new bindings for boot_dfuns,
357 -- which may be mentioned in imported unfoldings
358
359 -- Don't need to rename the Haddock documentation,
360 -- it's not parsed by GHC anymore.
361 tcg_env <- return (tcg_env { tcg_doc_hdr = maybe_doc_hdr }) ;
362
363 -- Report unused names
364 reportUnusedNames export_ies tcg_env ;
365
366 -- add extra source files to tcg_dependent_files
367 addDependentFiles src_files ;
368
369 -- Dump output and return
370 tcDump tcg_env ;
371 return tcg_env
372 }}}}}
373
374 implicitPreludeWarn :: SDoc
375 implicitPreludeWarn
376 = ptext (sLit "Module `Prelude' implicitly imported")
377
378 {-
379 ************************************************************************
380 * *
381 Import declarations
382 * *
383 ************************************************************************
384 -}
385
386 tcRnImports :: HscEnv -> [LImportDecl RdrName] -> TcM TcGblEnv
387 tcRnImports hsc_env import_decls
388 = do { (rn_imports, rdr_env, imports, hpc_info) <- rnImports import_decls ;
389
390 ; this_mod <- getModule
391 ; let { dep_mods :: ModuleNameEnv (ModuleName, IsBootInterface)
392 ; dep_mods = imp_dep_mods imports
393
394 -- We want instance declarations from all home-package
395 -- modules below this one, including boot modules, except
396 -- ourselves. The 'except ourselves' is so that we don't
397 -- get the instances from this module's hs-boot file. This
398 -- filtering also ensures that we don't see instances from
399 -- modules batch (@--make@) compiled before this one, but
400 -- which are not below this one.
401 ; want_instances :: ModuleName -> Bool
402 ; want_instances mod = mod `elemUFM` dep_mods
403 && mod /= moduleName this_mod
404 ; (home_insts, home_fam_insts) = hptInstances hsc_env
405 want_instances
406 } ;
407
408 -- Record boot-file info in the EPS, so that it's
409 -- visible to loadHiBootInterface in tcRnSrcDecls,
410 -- and any other incrementally-performed imports
411 ; updateEps_ (\eps -> eps { eps_is_boot = dep_mods }) ;
412
413 -- Update the gbl env
414 ; updGblEnv ( \ gbl ->
415 gbl {
416 tcg_rdr_env = tcg_rdr_env gbl `plusGlobalRdrEnv` rdr_env,
417 tcg_imports = tcg_imports gbl `plusImportAvails` imports,
418 tcg_rn_imports = rn_imports,
419 tcg_inst_env = extendInstEnvList (tcg_inst_env gbl) home_insts,
420 tcg_fam_inst_env = extendFamInstEnvList (tcg_fam_inst_env gbl)
421 home_fam_insts,
422 tcg_hpc = hpc_info
423 }) $ do {
424
425 ; traceRn (text "rn1" <+> ppr (imp_dep_mods imports))
426 -- Fail if there are any errors so far
427 -- The error printing (if needed) takes advantage
428 -- of the tcg_env we have now set
429 -- ; traceIf (text "rdr_env: " <+> ppr rdr_env)
430 ; failIfErrsM
431
432 -- Load any orphan-module and family instance-module
433 -- interfaces, so that their rules and instance decls will be
434 -- found. But filter out a self hs-boot: these instances
435 -- will be checked when we define them locally.
436 ; loadModuleInterfaces (ptext (sLit "Loading orphan modules"))
437 (filter (/= this_mod) (imp_orphs imports))
438
439 -- Check type-family consistency
440 ; traceRn (text "rn1: checking family instance consistency")
441 ; let { dir_imp_mods = moduleEnvKeys
442 . imp_mods
443 $ imports }
444 ; checkFamInstConsistency (imp_finsts imports) dir_imp_mods ;
445
446 ; getGblEnv } }
447
448 {-
449 ************************************************************************
450 * *
451 Type-checking the top level of a module
452 * *
453 ************************************************************************
454 -}
455
456 tcRnSrcDecls :: Bool -- False => no 'module M(..) where' header at all
457 -> Maybe (Located [LIE RdrName]) -- Exports
458 -> [LHsDecl RdrName] -- Declarations
459 -> TcM TcGblEnv
460 -- Returns the variables free in the decls
461 -- Reason: solely to report unused imports and bindings
462 tcRnSrcDecls explicit_mod_hdr exports decls
463 = do { -- Do all the declarations
464 ((tcg_env, tcl_env), lie) <- captureConstraints $
465 do { (tcg_env, tcl_env) <- tc_rn_src_decls decls ;
466 ; tcg_env <- setEnvs (tcg_env, tcl_env) $
467 checkMain explicit_mod_hdr
468 ; return (tcg_env, tcl_env) }
469 ; setEnvs (tcg_env, tcl_env) $ do {
470
471 #ifdef GHCI
472 -- Run all module finalizers
473 let th_modfinalizers_var = tcg_th_modfinalizers tcg_env
474 ; modfinalizers <- readTcRef th_modfinalizers_var
475 ; writeTcRef th_modfinalizers_var []
476 ; mapM_ runQuasi modfinalizers
477 #endif /* GHCI */
478
479 -- wanted constraints from static forms
480 ; stWC <- tcg_static_wc <$> getGblEnv >>= readTcRef
481
482 -- Finish simplifying class constraints
483 --
484 -- simplifyTop deals with constant or ambiguous InstIds.
485 -- How could there be ambiguous ones? They can only arise if a
486 -- top-level decl falls under the monomorphism restriction
487 -- and no subsequent decl instantiates its type.
488 --
489 -- We do this after checkMain, so that we use the type info
490 -- that checkMain adds
491 --
492 -- We do it with both global and local env in scope:
493 -- * the global env exposes the instances to simplifyTop
494 -- * the local env exposes the local Ids to simplifyTop,
495 -- so that we get better error messages (monomorphism restriction)
496 ; new_ev_binds <- {-# SCC "simplifyTop" #-}
497 simplifyTop (andWC stWC lie)
498 ; traceTc "Tc9" empty
499
500 ; failIfErrsM -- Don't zonk if there have been errors
501 -- It's a waste of time; and we may get debug warnings
502 -- about strangely-typed TyCons!
503 ; traceTc "Tc10" empty
504
505 -- Zonk the final code. This must be done last.
506 -- Even simplifyTop may do some unification.
507 -- This pass also warns about missing type signatures
508 ; let { TcGblEnv { tcg_type_env = type_env,
509 tcg_binds = binds,
510 tcg_sigs = sig_ns,
511 tcg_ev_binds = cur_ev_binds,
512 tcg_imp_specs = imp_specs,
513 tcg_rules = rules,
514 tcg_vects = vects,
515 tcg_fords = fords } = tcg_env
516 ; all_ev_binds = cur_ev_binds `unionBags` new_ev_binds } ;
517
518 ; (bind_ids, ev_binds', binds', fords', imp_specs', rules', vects')
519 <- {-# SCC "zonkTopDecls" #-}
520 zonkTopDecls all_ev_binds binds exports sig_ns rules vects
521 imp_specs fords ;
522 ; traceTc "Tc11" empty
523
524 ; let { final_type_env = extendTypeEnvWithIds type_env bind_ids
525 ; tcg_env' = tcg_env { tcg_binds = binds',
526 tcg_ev_binds = ev_binds',
527 tcg_imp_specs = imp_specs',
528 tcg_rules = rules',
529 tcg_vects = vects',
530 tcg_fords = fords' } } ;
531
532 ; setGlobalTypeEnv tcg_env' final_type_env
533
534 } }
535
536 tc_rn_src_decls :: [LHsDecl RdrName]
537 -> TcM (TcGblEnv, TcLclEnv)
538 -- Loops around dealing with each top level inter-splice group
539 -- in turn, until it's dealt with the entire module
540 tc_rn_src_decls ds
541 = {-# SCC "tc_rn_src_decls" #-}
542 do { (first_group, group_tail) <- findSplice ds
543 -- If ds is [] we get ([], Nothing)
544
545 -- Deal with decls up to, but not including, the first splice
546 ; (tcg_env, rn_decls) <- rnTopSrcDecls first_group
547 -- rnTopSrcDecls fails if there are any errors
548
549 #ifdef GHCI
550 -- Get TH-generated top-level declarations and make sure they don't
551 -- contain any splices since we don't handle that at the moment
552 ; th_topdecls_var <- fmap tcg_th_topdecls getGblEnv
553 ; th_ds <- readTcRef th_topdecls_var
554 ; writeTcRef th_topdecls_var []
555
556 ; (tcg_env, rn_decls) <-
557 if null th_ds
558 then return (tcg_env, rn_decls)
559 else do { (th_group, th_group_tail) <- findSplice th_ds
560 ; case th_group_tail of
561 { Nothing -> return () ;
562 ; Just (SpliceDecl (L loc _) _, _)
563 -> setSrcSpan loc $
564 addErr (ptext (sLit "Declaration splices are not permitted inside top-level declarations added with addTopDecls"))
565 } ;
566
567 -- Rename TH-generated top-level declarations
568 ; (tcg_env, th_rn_decls) <- setGblEnv tcg_env $
569 rnTopSrcDecls th_group
570
571 -- Dump generated top-level declarations
572 ; let msg = "top-level declarations added with addTopDecls"
573 ; traceSplice $ SpliceInfo { spliceDescription = msg
574 , spliceIsDecl = True
575 , spliceSource = Nothing
576 , spliceGenerated = ppr th_rn_decls }
577
578 ; return (tcg_env, appendGroups rn_decls th_rn_decls)
579 }
580 #endif /* GHCI */
581
582 -- Type check all declarations
583 ; (tcg_env, tcl_env) <- setGblEnv tcg_env $
584 tcTopSrcDecls rn_decls
585
586 -- If there is no splice, we're nearly done
587 ; setEnvs (tcg_env, tcl_env) $
588 case group_tail of
589 { Nothing -> return (tcg_env, tcl_env)
590
591 #ifndef GHCI
592 -- There shouldn't be a splice
593 ; Just (SpliceDecl {}, _) ->
594 failWithTc (text "Can't do a top-level splice; need a bootstrapped compiler")
595 }
596 #else
597 -- If there's a splice, we must carry on
598 ; Just (SpliceDecl (L _ splice) _, rest_ds) ->
599 do { -- Rename the splice expression, and get its supporting decls
600 (spliced_decls, splice_fvs) <- checkNoErrs (rnTopSpliceDecls splice)
601
602 -- Glue them on the front of the remaining decls and loop
603 ; setGblEnv (tcg_env `addTcgDUs` usesOnly splice_fvs) $
604 tc_rn_src_decls (spliced_decls ++ rest_ds)
605 }
606 }
607 #endif /* GHCI */
608 }
609
610 {-
611 ************************************************************************
612 * *
613 Compiling hs-boot source files, and
614 comparing the hi-boot interface with the real thing
615 * *
616 ************************************************************************
617 -}
618
619 tcRnHsBootDecls :: HscSource -> [LHsDecl RdrName] -> TcM TcGblEnv
620 tcRnHsBootDecls hsc_src decls
621 = do { (first_group, group_tail) <- findSplice decls
622
623 -- Rename the declarations
624 ; (tcg_env, HsGroup {
625 hs_tyclds = tycl_decls,
626 hs_instds = inst_decls,
627 hs_derivds = deriv_decls,
628 hs_fords = for_decls,
629 hs_defds = def_decls,
630 hs_ruleds = rule_decls,
631 hs_vects = vect_decls,
632 hs_annds = _,
633 hs_valds = val_binds }) <- rnTopSrcDecls first_group
634 -- The empty list is for extra dependencies coming from .hs-boot files
635 -- See Note [Extra dependencies from .hs-boot files] in RnSource
636 ; (gbl_env, lie) <- captureConstraints $ setGblEnv tcg_env $ do {
637
638
639 -- Check for illegal declarations
640 ; case group_tail of
641 Just (SpliceDecl d _, _) -> badBootDecl hsc_src "splice" d
642 Nothing -> return ()
643 ; mapM_ (badBootDecl hsc_src "foreign") for_decls
644 ; mapM_ (badBootDecl hsc_src "default") def_decls
645 ; mapM_ (badBootDecl hsc_src "rule") rule_decls
646 ; mapM_ (badBootDecl hsc_src "vect") vect_decls
647
648 -- Typecheck type/class/isntance decls
649 ; traceTc "Tc2 (boot)" empty
650 ; (tcg_env, inst_infos, _deriv_binds)
651 <- tcTyClsInstDecls tycl_decls inst_decls deriv_decls
652 ; setGblEnv tcg_env $ do {
653
654 -- Typecheck value declarations
655 ; traceTc "Tc5" empty
656 ; val_ids <- tcHsBootSigs val_binds
657
658 -- Wrap up
659 -- No simplification or zonking to do
660 ; traceTc "Tc7a" empty
661 ; gbl_env <- getGblEnv
662
663 -- Make the final type-env
664 -- Include the dfun_ids so that their type sigs
665 -- are written into the interface file.
666 ; let { type_env0 = tcg_type_env gbl_env
667 ; type_env1 = extendTypeEnvWithIds type_env0 val_ids
668 -- Don't add the dictionaries for non-recursive case, we don't
669 -- actually want to /define/ the instance, just an export list
670 ; type_env2 | Just _ <- tcg_impl_rdr_env gbl_env = type_env1
671 | otherwise = extendTypeEnvWithIds type_env1 dfun_ids
672 ; dfun_ids = map iDFunId inst_infos
673 }
674
675 ; setGlobalTypeEnv gbl_env type_env2
676 }}
677 ; traceTc "boot" (ppr lie); return gbl_env }
678
679 badBootDecl :: HscSource -> String -> Located decl -> TcM ()
680 badBootDecl _hsc_src what (L loc _)
681 = addErrAt loc (char 'A' <+> text what
682 <+> text "declaration is not (currently) allowed in a hs-boot file")
683
684 {-
685 Once we've typechecked the body of the module, we want to compare what
686 we've found (gathered in a TypeEnv) with the hi-boot details (if any).
687 -}
688
689 checkHiBootIface :: TcGblEnv -> SelfBootInfo -> TcM TcGblEnv
690 -- Compare the hi-boot file for this module (if there is one)
691 -- with the type environment we've just come up with
692 -- In the common case where there is no hi-boot file, the list
693 -- of boot_names is empty.
694
695 checkHiBootIface tcg_env boot_info
696 | NoSelfBoot <- boot_info -- Common case
697 = return tcg_env
698
699 | HsBootFile <- tcg_src tcg_env -- Current module is already a hs-boot file!
700 = return tcg_env
701
702 | SelfBoot { sb_mds = boot_details } <- boot_info
703 , TcGblEnv { tcg_binds = binds
704 , tcg_insts = local_insts
705 , tcg_type_env = local_type_env
706 , tcg_exports = local_exports } <- tcg_env
707 = do { dfun_prs <- checkHiBootIface' local_insts local_type_env
708 local_exports boot_details
709 ; let boot_dfuns = map fst dfun_prs
710 dfun_binds = listToBag [ mkVarBind boot_dfun (nlHsVar dfun)
711 | (boot_dfun, dfun) <- dfun_prs ]
712 type_env' = extendTypeEnvWithIds local_type_env boot_dfuns
713 tcg_env' = tcg_env { tcg_binds = binds `unionBags` dfun_binds }
714
715 ; setGlobalTypeEnv tcg_env' type_env' }
716 -- Update the global type env *including* the knot-tied one
717 -- so that if the source module reads in an interface unfolding
718 -- mentioning one of the dfuns from the boot module, then it
719 -- can "see" that boot dfun. See Trac #4003
720
721 | otherwise = panic "checkHiBootIface: unreachable code"
722
723 checkHiBootIface' :: [ClsInst] -> TypeEnv -> [AvailInfo]
724 -> ModDetails -> TcM [(Id, Id)]
725 -- Variant which doesn't require a full TcGblEnv; you could get the
726 -- local components from another ModDetails.
727 --
728 -- We return a list of "impedance-matching" bindings for the dfuns
729 -- defined in the hs-boot file, such as
730 -- $fxEqT = $fEqT
731 -- We need these because the module and hi-boot file might differ in
732 -- the name it chose for the dfun.
733
734 checkHiBootIface'
735 local_insts local_type_env local_exports
736 (ModDetails { md_insts = boot_insts, md_fam_insts = boot_fam_insts,
737 md_types = boot_type_env, md_exports = boot_exports })
738 = do { traceTc "checkHiBootIface" $ vcat
739 [ ppr boot_type_env, ppr boot_insts, ppr boot_exports]
740
741 -- Check the exports of the boot module, one by one
742 ; mapM_ check_export boot_exports
743
744 -- Check for no family instances
745 ; unless (null boot_fam_insts) $
746 panic ("TcRnDriver.checkHiBootIface: Cannot handle family " ++
747 "instances in boot files yet...")
748 -- FIXME: Why? The actual comparison is not hard, but what would
749 -- be the equivalent to the dfun bindings returned for class
750 -- instances? We can't easily equate tycons...
751
752 -- Check instance declarations
753 -- and generate an impedance-matching binding
754 ; mb_dfun_prs <- mapM check_inst boot_insts
755
756 ; failIfErrsM
757
758 ; return (catMaybes mb_dfun_prs) }
759
760 where
761 check_export boot_avail -- boot_avail is exported by the boot iface
762 | name `elem` dfun_names = return ()
763 | isWiredInName name = return () -- No checking for wired-in names. In particular,
764 -- 'error' is handled by a rather gross hack
765 -- (see comments in GHC.Err.hs-boot)
766
767 -- Check that the actual module exports the same thing
768 | not (null missing_names)
769 = addErrAt (nameSrcSpan (head missing_names))
770 (missingBootThing True (head missing_names) "exported by")
771
772 -- If the boot module does not *define* the thing, we are done
773 -- (it simply re-exports it, and names match, so nothing further to do)
774 | isNothing mb_boot_thing = return ()
775
776 -- Check that the actual module also defines the thing, and
777 -- then compare the definitions
778 | Just real_thing <- lookupTypeEnv local_type_env name,
779 Just boot_thing <- mb_boot_thing
780 = checkBootDeclM True boot_thing real_thing
781
782 | otherwise
783 = addErrTc (missingBootThing True name "defined in")
784 where
785 name = availName boot_avail
786 mb_boot_thing = lookupTypeEnv boot_type_env name
787 missing_names = case lookupNameEnv local_export_env name of
788 Nothing -> [name]
789 Just avail -> availNames boot_avail `minusList` availNames avail
790
791 dfun_names = map getName boot_insts
792
793 local_export_env :: NameEnv AvailInfo
794 local_export_env = availsToNameEnv local_exports
795
796 check_inst :: ClsInst -> TcM (Maybe (Id, Id))
797 -- Returns a pair of the boot dfun in terms of the equivalent real dfun
798 check_inst boot_inst
799 = case [dfun | inst <- local_insts,
800 let dfun = instanceDFunId inst,
801 idType dfun `eqType` boot_dfun_ty ] of
802 [] -> do { traceTc "check_inst" $ vcat
803 [ text "local_insts" <+> vcat (map (ppr . idType . instanceDFunId) local_insts)
804 , text "boot_inst" <+> ppr boot_inst
805 , text "boot_dfun_ty" <+> ppr boot_dfun_ty
806 ]
807 ; addErrTc (instMisMatch True boot_inst); return Nothing }
808 (dfun:_) -> return (Just (local_boot_dfun, dfun))
809 where
810 local_boot_dfun = Id.mkExportedLocalId VanillaId boot_dfun_name (idType dfun)
811 -- Name from the /boot-file/ ClsInst, but type from the dfun
812 -- defined in /this module/. That ensures that the TyCon etc
813 -- inside the type are the ones defined in this module, not
814 -- the ones gotten from the hi-boot file, which may have
815 -- a lot less info (Trac #T8743, comment:10).
816 where
817 boot_dfun = instanceDFunId boot_inst
818 boot_dfun_ty = idType boot_dfun
819 boot_dfun_name = idName boot_dfun
820
821 -- This has to compare the TyThing from the .hi-boot file to the TyThing
822 -- in the current source file. We must be careful to allow alpha-renaming
823 -- where appropriate, and also the boot declaration is allowed to omit
824 -- constructors and class methods.
825 --
826 -- See rnfail055 for a good test of this stuff.
827
828 -- | Compares two things for equivalence between boot-file and normal code,
829 -- reporting an error if they don't match up.
830 checkBootDeclM :: Bool -- ^ True <=> an hs-boot file (could also be a sig)
831 -> TyThing -> TyThing -> TcM ()
832 checkBootDeclM is_boot boot_thing real_thing
833 = whenIsJust (checkBootDecl boot_thing real_thing) $ \ err ->
834 addErrAt (nameSrcSpan (getName boot_thing))
835 (bootMisMatch is_boot err real_thing boot_thing)
836
837 -- | Compares the two things for equivalence between boot-file and normal
838 -- code. Returns @Nothing@ on success or @Just "some helpful info for user"@
839 -- failure. If the difference will be apparent to the user, @Just empty@ is
840 -- perfectly suitable.
841 checkBootDecl :: TyThing -> TyThing -> Maybe SDoc
842
843 checkBootDecl (AnId id1) (AnId id2)
844 = ASSERT(id1 == id2)
845 check (idType id1 `eqType` idType id2)
846 (text "The two types are different")
847
848 checkBootDecl (ATyCon tc1) (ATyCon tc2)
849 = checkBootTyCon tc1 tc2
850
851 checkBootDecl (AConLike (RealDataCon dc1)) (AConLike (RealDataCon _))
852 = pprPanic "checkBootDecl" (ppr dc1)
853
854 checkBootDecl _ _ = Just empty -- probably shouldn't happen
855
856 -- | Combines two potential error messages
857 andThenCheck :: Maybe SDoc -> Maybe SDoc -> Maybe SDoc
858 Nothing `andThenCheck` msg = msg
859 msg `andThenCheck` Nothing = msg
860 Just d1 `andThenCheck` Just d2 = Just (d1 $$ d2)
861 infixr 0 `andThenCheck`
862
863 -- | If the test in the first parameter is True, succeed with @Nothing@;
864 -- otherwise, return the provided check
865 checkUnless :: Bool -> Maybe SDoc -> Maybe SDoc
866 checkUnless True _ = Nothing
867 checkUnless False k = k
868
869 -- | Run the check provided for every pair of elements in the lists.
870 -- The provided SDoc should name the element type, in the plural.
871 checkListBy :: (a -> a -> Maybe SDoc) -> [a] -> [a] -> SDoc
872 -> Maybe SDoc
873 checkListBy check_fun as bs whats = go [] as bs
874 where
875 herald = text "The" <+> whats <+> text "do not match"
876
877 go [] [] [] = Nothing
878 go docs [] [] = Just (hang (herald <> colon) 2 (vcat $ reverse docs))
879 go docs (x:xs) (y:ys) = case check_fun x y of
880 Just doc -> go (doc:docs) xs ys
881 Nothing -> go docs xs ys
882 go _ _ _ = Just (hang (herald <> colon)
883 2 (text "There are different numbers of" <+> whats))
884
885 -- | If the test in the first parameter is True, succeed with @Nothing@;
886 -- otherwise, fail with the given SDoc.
887 check :: Bool -> SDoc -> Maybe SDoc
888 check True _ = Nothing
889 check False doc = Just doc
890
891 -- | A more perspicuous name for @Nothing@, for @checkBootDecl@ and friends.
892 checkSuccess :: Maybe SDoc
893 checkSuccess = Nothing
894
895 ----------------
896 checkBootTyCon :: TyCon -> TyCon -> Maybe SDoc
897 checkBootTyCon tc1 tc2
898 | not (eqKind (tyConKind tc1) (tyConKind tc2))
899 = Just $ text "The types have different kinds" -- First off, check the kind
900
901 | Just c1 <- tyConClass_maybe tc1
902 , Just c2 <- tyConClass_maybe tc2
903 , let (clas_tvs1, clas_fds1, sc_theta1, _, ats1, op_stuff1)
904 = classExtraBigSig c1
905 (clas_tvs2, clas_fds2, sc_theta2, _, ats2, op_stuff2)
906 = classExtraBigSig c2
907 , Just env <- eqTyVarBndrs emptyRnEnv2 clas_tvs1 clas_tvs2
908 = let
909 eqSig (id1, def_meth1) (id2, def_meth2)
910 = check (name1 == name2)
911 (text "The names" <+> pname1 <+> text "and" <+> pname2 <+>
912 text "are different") `andThenCheck`
913 check (eqTypeX env op_ty1 op_ty2)
914 (text "The types of" <+> pname1 <+>
915 text "are different") `andThenCheck`
916 check (def_meth1 == def_meth2)
917 (text "The default methods associated with" <+> pname1 <+>
918 text "are different")
919 where
920 name1 = idName id1
921 name2 = idName id2
922 pname1 = quotes (ppr name1)
923 pname2 = quotes (ppr name2)
924 (_, rho_ty1) = splitForAllTys (idType id1)
925 op_ty1 = funResultTy rho_ty1
926 (_, rho_ty2) = splitForAllTys (idType id2)
927 op_ty2 = funResultTy rho_ty2
928
929 eqAT (ATI tc1 def_ats1) (ATI tc2 def_ats2)
930 = checkBootTyCon tc1 tc2 `andThenCheck`
931 check (eqATDef def_ats1 def_ats2)
932 (text "The associated type defaults differ")
933
934 -- Ignore the location of the defaults
935 eqATDef Nothing Nothing = True
936 eqATDef (Just (ty1, _loc1)) (Just (ty2, _loc2)) = eqTypeX env ty1 ty2
937 eqATDef _ _ = False
938
939 eqFD (as1,bs1) (as2,bs2) =
940 eqListBy (eqTypeX env) (mkTyVarTys as1) (mkTyVarTys as2) &&
941 eqListBy (eqTypeX env) (mkTyVarTys bs1) (mkTyVarTys bs2)
942 in
943 check (roles1 == roles2) roles_msg `andThenCheck`
944 -- Checks kind of class
945 check (eqListBy eqFD clas_fds1 clas_fds2)
946 (text "The functional dependencies do not match") `andThenCheck`
947 checkUnless (null sc_theta1 && null op_stuff1 && null ats1) $
948 -- Above tests for an "abstract" class
949 check (eqListBy (eqPredX env) sc_theta1 sc_theta2)
950 (text "The class constraints do not match") `andThenCheck`
951 checkListBy eqSig op_stuff1 op_stuff2 (text "methods") `andThenCheck`
952 checkListBy eqAT ats1 ats2 (text "associated types")
953
954 | Just syn_rhs1 <- synTyConRhs_maybe tc1
955 , Just syn_rhs2 <- synTyConRhs_maybe tc2
956 , Just env <- eqTyVarBndrs emptyRnEnv2 (tyConTyVars tc1) (tyConTyVars tc2)
957 = ASSERT(tc1 == tc2)
958 check (roles1 == roles2) roles_msg `andThenCheck`
959 check (eqTypeX env syn_rhs1 syn_rhs2) empty -- nothing interesting to say
960
961 | Just fam_flav1 <- famTyConFlav_maybe tc1
962 , Just fam_flav2 <- famTyConFlav_maybe tc2
963 = ASSERT(tc1 == tc2)
964 let eqFamFlav OpenSynFamilyTyCon OpenSynFamilyTyCon = True
965 eqFamFlav AbstractClosedSynFamilyTyCon (ClosedSynFamilyTyCon {}) = True
966 eqFamFlav (ClosedSynFamilyTyCon {}) AbstractClosedSynFamilyTyCon = True
967 eqFamFlav (ClosedSynFamilyTyCon ax1) (ClosedSynFamilyTyCon ax2)
968 = eqClosedFamilyAx ax1 ax2
969 eqFamFlav (BuiltInSynFamTyCon _) (BuiltInSynFamTyCon _) = tc1 == tc2
970 eqFamFlav _ _ = False
971 injInfo1 = familyTyConInjectivityInfo tc1
972 injInfo2 = familyTyConInjectivityInfo tc2
973 in
974 -- check equality of roles, family flavours and injectivity annotations
975 check (roles1 == roles2) roles_msg `andThenCheck`
976 check (eqFamFlav fam_flav1 fam_flav2) empty `andThenCheck`
977 check (injInfo1 == injInfo2) empty
978
979 | isAlgTyCon tc1 && isAlgTyCon tc2
980 , Just env <- eqTyVarBndrs emptyRnEnv2 (tyConTyVars tc1) (tyConTyVars tc2)
981 = ASSERT(tc1 == tc2)
982 check (roles1 == roles2) roles_msg `andThenCheck`
983 check (eqListBy (eqPredX env)
984 (tyConStupidTheta tc1) (tyConStupidTheta tc2))
985 (text "The datatype contexts do not match") `andThenCheck`
986 eqAlgRhs tc1 (algTyConRhs tc1) (algTyConRhs tc2)
987
988 | otherwise = Just empty -- two very different types -- should be obvious
989 where
990 roles1 = tyConRoles tc1
991 roles2 = tyConRoles tc2
992 roles_msg = text "The roles do not match." $$
993 (text "Roles on abstract types default to" <+>
994 quotes (text "representational") <+> text "in boot files.")
995
996 eqAlgRhs tc (AbstractTyCon dis1) rhs2
997 | dis1 = check (isGenInjAlgRhs rhs2) --Check compatibility
998 (text "The natures of the declarations for" <+>
999 quotes (ppr tc) <+> text "are different")
1000 | otherwise = checkSuccess
1001 eqAlgRhs _ DataFamilyTyCon{} DataFamilyTyCon{} = checkSuccess
1002 eqAlgRhs _ tc1@DataTyCon{} tc2@DataTyCon{} =
1003 checkListBy eqCon (data_cons tc1) (data_cons tc2) (text "constructors")
1004 eqAlgRhs _ tc1@NewTyCon{} tc2@NewTyCon{} =
1005 eqCon (data_con tc1) (data_con tc2)
1006 eqAlgRhs _ _ _ = Just (text "Cannot match a" <+> quotes (text "data") <+>
1007 text "definition with a" <+> quotes (text "newtype") <+>
1008 text "definition")
1009
1010 eqCon c1 c2
1011 = check (name1 == name2)
1012 (text "The names" <+> pname1 <+> text "and" <+> pname2 <+>
1013 text "differ") `andThenCheck`
1014 check (dataConIsInfix c1 == dataConIsInfix c2)
1015 (text "The fixities of" <+> pname1 <+>
1016 text "differ") `andThenCheck`
1017 check (eqListBy eqHsBang (dataConImplBangs c1) (dataConImplBangs c2))
1018 (text "The strictness annotations for" <+> pname1 <+>
1019 text "differ") `andThenCheck`
1020 check (map flSelector (dataConFieldLabels c1) == map flSelector (dataConFieldLabels c2))
1021 (text "The record label lists for" <+> pname1 <+>
1022 text "differ") `andThenCheck`
1023 check (eqType (dataConUserType c1) (dataConUserType c2))
1024 (text "The types for" <+> pname1 <+> text "differ")
1025 where
1026 name1 = dataConName c1
1027 name2 = dataConName c2
1028 pname1 = quotes (ppr name1)
1029 pname2 = quotes (ppr name2)
1030
1031 eqClosedFamilyAx Nothing Nothing = True
1032 eqClosedFamilyAx Nothing (Just _) = False
1033 eqClosedFamilyAx (Just _) Nothing = False
1034 eqClosedFamilyAx (Just (CoAxiom { co_ax_branches = branches1 }))
1035 (Just (CoAxiom { co_ax_branches = branches2 }))
1036 = numBranches branches1 == numBranches branches2
1037 && (and $ zipWith eqClosedFamilyBranch branch_list1 branch_list2)
1038 where
1039 branch_list1 = fromBranches branches1
1040 branch_list2 = fromBranches branches2
1041
1042 eqClosedFamilyBranch (CoAxBranch { cab_tvs = tvs1, cab_lhs = lhs1, cab_rhs = rhs1 })
1043 (CoAxBranch { cab_tvs = tvs2, cab_lhs = lhs2, cab_rhs = rhs2 })
1044 | Just env <- eqTyVarBndrs emptyRnEnv2 tvs1 tvs2
1045 = eqListBy (eqTypeX env) lhs1 lhs2 &&
1046 eqTypeX env rhs1 rhs2
1047
1048 | otherwise = False
1049
1050 emptyRnEnv2 :: RnEnv2
1051 emptyRnEnv2 = mkRnEnv2 emptyInScopeSet
1052
1053 ----------------
1054 missingBootThing :: Bool -> Name -> String -> SDoc
1055 missingBootThing is_boot name what
1056 = quotes (ppr name) <+> ptext (sLit "is exported by the")
1057 <+> (if is_boot then ptext (sLit "hs-boot") else ptext (sLit "signature"))
1058 <+> ptext (sLit "file, but not")
1059 <+> text what <+> ptext (sLit "the module")
1060
1061 bootMisMatch :: Bool -> SDoc -> TyThing -> TyThing -> SDoc
1062 bootMisMatch is_boot extra_info real_thing boot_thing
1063 = vcat [ppr real_thing <+>
1064 ptext (sLit "has conflicting definitions in the module"),
1065 ptext (sLit "and its") <+>
1066 (if is_boot then ptext (sLit "hs-boot file")
1067 else ptext (sLit "signature file")),
1068 ptext (sLit "Main module:") <+> PprTyThing.pprTyThing real_thing,
1069 (if is_boot
1070 then ptext (sLit "Boot file: ")
1071 else ptext (sLit "Signature file: "))
1072 <+> PprTyThing.pprTyThing boot_thing,
1073 extra_info]
1074
1075 instMisMatch :: Bool -> ClsInst -> SDoc
1076 instMisMatch is_boot inst
1077 = hang (ppr inst)
1078 2 (ptext (sLit "is defined in the") <+>
1079 (if is_boot then ptext (sLit "hs-boot") else ptext (sLit "signature"))
1080 <+> ptext (sLit "file, but not in the module itself"))
1081
1082 {-
1083 ************************************************************************
1084 * *
1085 Type-checking the top level of a module (continued)
1086 * *
1087 ************************************************************************
1088 -}
1089
1090 rnTopSrcDecls :: HsGroup RdrName -> TcM (TcGblEnv, HsGroup Name)
1091 -- Fails if there are any errors
1092 rnTopSrcDecls group
1093 = do { -- Rename the source decls
1094 traceRn (text "rn12") ;
1095 (tcg_env, rn_decls) <- checkNoErrs $ rnSrcDecls group ;
1096 traceRn (text "rn13") ;
1097
1098 -- save the renamed syntax, if we want it
1099 let { tcg_env'
1100 | Just grp <- tcg_rn_decls tcg_env
1101 = tcg_env{ tcg_rn_decls = Just (appendGroups grp rn_decls) }
1102 | otherwise
1103 = tcg_env };
1104
1105 -- Dump trace of renaming part
1106 rnDump (ppr rn_decls) ;
1107 return (tcg_env', rn_decls)
1108 }
1109
1110 tcTopSrcDecls :: HsGroup Name -> TcM (TcGblEnv, TcLclEnv)
1111 tcTopSrcDecls (HsGroup { hs_tyclds = tycl_decls,
1112 hs_instds = inst_decls,
1113 hs_derivds = deriv_decls,
1114 hs_fords = foreign_decls,
1115 hs_defds = default_decls,
1116 hs_annds = annotation_decls,
1117 hs_ruleds = rule_decls,
1118 hs_vects = vect_decls,
1119 hs_valds = val_binds })
1120 = do { -- Type-check the type and class decls, and all imported decls
1121 -- The latter come in via tycl_decls
1122 traceTc "Tc2 (src)" empty ;
1123
1124 -- Source-language instances, including derivings,
1125 -- and import the supporting declarations
1126 traceTc "Tc3" empty ;
1127 (tcg_env, inst_infos, deriv_binds)
1128 <- tcTyClsInstDecls tycl_decls inst_decls deriv_decls ;
1129 setGblEnv tcg_env $ do {
1130
1131 -- Generate Applicative/Monad proposal (AMP) warnings
1132 traceTc "Tc3b" empty ;
1133
1134 -- Foreign import declarations next.
1135 traceTc "Tc4" empty ;
1136 (fi_ids, fi_decls, fi_gres) <- tcForeignImports foreign_decls ;
1137 tcExtendGlobalValEnv fi_ids $ do {
1138
1139 -- Default declarations
1140 traceTc "Tc4a" empty ;
1141 default_tys <- tcDefaults default_decls ;
1142 updGblEnv (\gbl -> gbl { tcg_default = default_tys }) $ do {
1143
1144 -- Now GHC-generated derived bindings, generics, and selectors
1145 -- Do not generate warnings from compiler-generated code;
1146 -- hence the use of discardWarnings
1147 tc_envs <- discardWarnings (tcTopBinds deriv_binds) ;
1148 setEnvs tc_envs $ do {
1149
1150 -- Value declarations next
1151 traceTc "Tc5" empty ;
1152 tc_envs@(tcg_env, tcl_env) <- tcTopBinds val_binds;
1153 setEnvs tc_envs $ do { -- Environment doesn't change now
1154
1155 -- Second pass over class and instance declarations,
1156 -- now using the kind-checked decls
1157 traceTc "Tc6" empty ;
1158 inst_binds <- tcInstDecls2 (tyClGroupConcat tycl_decls) inst_infos ;
1159
1160 -- Foreign exports
1161 traceTc "Tc7" empty ;
1162 (foe_binds, foe_decls, foe_gres) <- tcForeignExports foreign_decls ;
1163
1164 -- Annotations
1165 annotations <- tcAnnotations annotation_decls ;
1166
1167 -- Rules
1168 rules <- tcRules rule_decls ;
1169
1170 -- Vectorisation declarations
1171 vects <- tcVectDecls vect_decls ;
1172
1173 -- Wrap up
1174 traceTc "Tc7a" empty ;
1175 let { all_binds = inst_binds `unionBags`
1176 foe_binds
1177
1178 ; fo_gres = fi_gres `unionBags` foe_gres
1179 ; fo_fvs = foldrBag (\gre fvs -> fvs `addOneFV` gre_name gre)
1180 emptyFVs fo_gres
1181 ; fo_rdr_names :: [RdrName]
1182 ; fo_rdr_names = foldrBag gre_to_rdr_name [] fo_gres
1183
1184 ; sig_names = mkNameSet (collectHsValBinders val_binds)
1185 `minusNameSet` getTypeSigNames val_binds
1186
1187 -- Extend the GblEnv with the (as yet un-zonked)
1188 -- bindings, rules, foreign decls
1189 ; tcg_env' = tcg_env { tcg_binds = tcg_binds tcg_env `unionBags` all_binds
1190 , tcg_sigs = tcg_sigs tcg_env `unionNameSet` sig_names
1191 , tcg_rules = tcg_rules tcg_env
1192 ++ flattenRuleDecls rules
1193 , tcg_vects = tcg_vects tcg_env ++ vects
1194 , tcg_anns = tcg_anns tcg_env ++ annotations
1195 , tcg_ann_env = extendAnnEnvList (tcg_ann_env tcg_env) annotations
1196 , tcg_fords = tcg_fords tcg_env ++ foe_decls ++ fi_decls
1197 , tcg_dus = tcg_dus tcg_env `plusDU` usesOnly fo_fvs } } ;
1198 -- tcg_dus: see Note [Newtype constructor usage in foreign declarations]
1199
1200 addUsedRdrNames fo_rdr_names ;
1201 return (tcg_env', tcl_env)
1202 }}}}}}
1203 where
1204 gre_to_rdr_name :: GlobalRdrElt -> [RdrName] -> [RdrName]
1205 -- For *imported* newtype data constructors, we want to
1206 -- make sure that at least one of the imports for them is used
1207 -- See Note [Newtype constructor usage in foreign declarations]
1208 gre_to_rdr_name gre rdrs
1209 | isLocalGRE gre = rdrs
1210 | otherwise = greUsedRdrName gre : rdrs
1211
1212 ---------------------------
1213 tcTyClsInstDecls :: [TyClGroup Name]
1214 -> [LInstDecl Name]
1215 -> [LDerivDecl Name]
1216 -> TcM (TcGblEnv, -- The full inst env
1217 [InstInfo Name], -- Source-code instance decls to process;
1218 -- contains all dfuns for this module
1219 HsValBinds Name) -- Supporting bindings for derived instances
1220
1221 tcTyClsInstDecls tycl_decls inst_decls deriv_decls
1222 = tcExtendKindEnv2 [ (con, APromotionErr FamDataConPE)
1223 | lid <- inst_decls, con <- get_cons lid ] $
1224 -- Note [AFamDataCon: not promoting data family constructors]
1225 do { tcg_env <- tcTyAndClassDecls tycl_decls ;
1226 ; setGblEnv tcg_env $
1227 tcInstDecls1 tycl_decls inst_decls deriv_decls }
1228 where
1229 -- get_cons extracts the *constructor* bindings of the declaration
1230 get_cons :: LInstDecl Name -> [Name]
1231 get_cons (L _ (TyFamInstD {})) = []
1232 get_cons (L _ (DataFamInstD { dfid_inst = fid })) = get_fi_cons fid
1233 get_cons (L _ (ClsInstD { cid_inst = ClsInstDecl { cid_datafam_insts = fids } }))
1234 = concatMap (get_fi_cons . unLoc) fids
1235
1236 get_fi_cons :: DataFamInstDecl Name -> [Name]
1237 get_fi_cons (DataFamInstDecl { dfid_defn = HsDataDefn { dd_cons = cons } })
1238 = map unLoc $ concatMap (con_names . unLoc) cons
1239
1240 {-
1241 Note [AFamDataCon: not promoting data family constructors]
1242 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1243 Consider
1244 data family T a
1245 data instance T Int = MkT
1246 data Proxy (a :: k)
1247 data S = MkS (Proxy 'MkT)
1248
1249 Is it ok to use the promoted data family instance constructor 'MkT' in
1250 the data declaration for S? No, we don't allow this. It *might* make
1251 sense, but at least it would mean that we'd have to interleave
1252 typechecking instances and data types, whereas at present we do data
1253 types *then* instances.
1254
1255 So to check for this we put in the TcLclEnv a binding for all the family
1256 constructors, bound to AFamDataCon, so that if we trip over 'MkT' when
1257 type checking 'S' we'll produce a decent error message.
1258
1259
1260 ************************************************************************
1261 * *
1262 Checking for 'main'
1263 * *
1264 ************************************************************************
1265 -}
1266
1267 checkMain :: Bool -- False => no 'module M(..) where' header at all
1268 -> TcM TcGblEnv
1269 -- If we are in module Main, check that 'main' is defined.
1270 checkMain explicit_mod_hdr
1271 = do { dflags <- getDynFlags
1272 ; tcg_env <- getGblEnv
1273 ; check_main dflags tcg_env explicit_mod_hdr }
1274
1275 check_main :: DynFlags -> TcGblEnv -> Bool -> TcM TcGblEnv
1276 check_main dflags tcg_env explicit_mod_hdr
1277 | mod /= main_mod
1278 = traceTc "checkMain not" (ppr main_mod <+> ppr mod) >>
1279 return tcg_env
1280
1281 | otherwise
1282 = do { mb_main <- lookupGlobalOccRn_maybe main_fn
1283 -- Check that 'main' is in scope
1284 -- It might be imported from another module!
1285 ; case mb_main of {
1286 Nothing -> do { traceTc "checkMain fail" (ppr main_mod <+> ppr main_fn)
1287 ; complain_no_main
1288 ; return tcg_env } ;
1289 Just main_name -> do
1290
1291 { traceTc "checkMain found" (ppr main_mod <+> ppr main_fn)
1292 ; let loc = srcLocSpan (getSrcLoc main_name)
1293 ; ioTyCon <- tcLookupTyCon ioTyConName
1294 ; res_ty <- newFlexiTyVarTy liftedTypeKind
1295 ; main_expr
1296 <- addErrCtxt mainCtxt $
1297 tcMonoExpr (L loc (HsVar main_name)) (mkTyConApp ioTyCon [res_ty])
1298
1299 -- See Note [Root-main Id]
1300 -- Construct the binding
1301 -- :Main.main :: IO res_ty = runMainIO res_ty main
1302 ; run_main_id <- tcLookupId runMainIOName
1303 ; let { root_main_name = mkExternalName rootMainKey rOOT_MAIN
1304 (mkVarOccFS (fsLit "main"))
1305 (getSrcSpan main_name)
1306 ; root_main_id = Id.mkExportedLocalId VanillaId root_main_name
1307 (mkTyConApp ioTyCon [res_ty])
1308 ; co = mkWpTyApps [res_ty]
1309 ; rhs = nlHsApp (mkLHsWrap co (nlHsVar run_main_id)) main_expr
1310 ; main_bind = mkVarBind root_main_id rhs }
1311
1312 ; return (tcg_env { tcg_main = Just main_name,
1313 tcg_binds = tcg_binds tcg_env
1314 `snocBag` main_bind,
1315 tcg_dus = tcg_dus tcg_env
1316 `plusDU` usesOnly (unitFV main_name)
1317 -- Record the use of 'main', so that we don't
1318 -- complain about it being defined but not used
1319 })
1320 }}}
1321 where
1322 mod = tcg_mod tcg_env
1323 main_mod = mainModIs dflags
1324 main_fn = getMainFun dflags
1325 interactive = ghcLink dflags == LinkInMemory
1326
1327 complain_no_main = checkTc (interactive && not explicit_mod_hdr) noMainMsg
1328 -- In interactive mode, without an explicit module header, don't
1329 -- worry about the absence of 'main'.
1330 -- In other modes, fail altogether, so that we don't go on
1331 -- and complain a second time when processing the export list.
1332
1333 mainCtxt = ptext (sLit "When checking the type of the") <+> pp_main_fn
1334 noMainMsg = ptext (sLit "The") <+> pp_main_fn
1335 <+> ptext (sLit "is not defined in module") <+> quotes (ppr main_mod)
1336 pp_main_fn = ppMainFn main_fn
1337
1338 -- | Get the unqualified name of the function to use as the \"main\" for the main module.
1339 -- Either returns the default name or the one configured on the command line with -main-is
1340 getMainFun :: DynFlags -> RdrName
1341 getMainFun dflags = case mainFunIs dflags of
1342 Just fn -> mkRdrUnqual (mkVarOccFS (mkFastString fn))
1343 Nothing -> main_RDR_Unqual
1344
1345 -- If we are in module Main, check that 'main' is exported.
1346 checkMainExported :: TcGblEnv -> TcM ()
1347 checkMainExported tcg_env
1348 = case tcg_main tcg_env of
1349 Nothing -> return () -- not the main module
1350 Just main_name ->
1351 do { dflags <- getDynFlags
1352 ; let main_mod = mainModIs dflags
1353 ; checkTc (main_name `elem` concatMap availNames (tcg_exports tcg_env)) $
1354 ptext (sLit "The") <+> ppMainFn (nameRdrName main_name) <+>
1355 ptext (sLit "is not exported by module") <+> quotes (ppr main_mod) }
1356
1357 ppMainFn :: RdrName -> SDoc
1358 ppMainFn main_fn
1359 | rdrNameOcc main_fn == mainOcc
1360 = ptext (sLit "IO action") <+> quotes (ppr main_fn)
1361 | otherwise
1362 = ptext (sLit "main IO action") <+> quotes (ppr main_fn)
1363
1364 mainOcc :: OccName
1365 mainOcc = mkVarOccFS (fsLit "main")
1366
1367 {-
1368 Note [Root-main Id]
1369 ~~~~~~~~~~~~~~~~~~~
1370 The function that the RTS invokes is always :Main.main, which we call
1371 root_main_id. (Because GHC allows the user to have a module not
1372 called Main as the main module, we can't rely on the main function
1373 being called "Main.main". That's why root_main_id has a fixed module
1374 ":Main".)
1375
1376 This is unusual: it's a LocalId whose Name has a Module from another
1377 module. Tiresomely, we must filter it out again in MkIface, les we
1378 get two defns for 'main' in the interface file!
1379
1380
1381 *********************************************************
1382 * *
1383 GHCi stuff
1384 * *
1385 *********************************************************
1386 -}
1387
1388 runTcInteractive :: HscEnv -> TcRn a -> IO (Messages, Maybe a)
1389 -- Initialise the tcg_inst_env with instances from all home modules.
1390 -- This mimics the more selective call to hptInstances in tcRnImports
1391 runTcInteractive hsc_env thing_inside
1392 = initTcInteractive hsc_env $ withTcPlugins hsc_env $
1393 do { traceTc "setInteractiveContext" $
1394 vcat [ text "ic_tythings:" <+> vcat (map ppr (ic_tythings icxt))
1395 , text "ic_insts:" <+> vcat (map (pprBndr LetBind . instanceDFunId) ic_insts)
1396 , text "ic_rn_gbl_env (LocalDef)" <+>
1397 vcat (map ppr [ local_gres | gres <- occEnvElts (ic_rn_gbl_env icxt)
1398 , let local_gres = filter isLocalGRE gres
1399 , not (null local_gres) ]) ]
1400 ; let getOrphans m = fmap (\iface -> mi_module iface
1401 : dep_orphs (mi_deps iface))
1402 (loadSrcInterface (text "runTcInteractive") m
1403 False Nothing)
1404 ; orphs <- fmap concat . forM (ic_imports icxt) $ \i ->
1405 case i of
1406 IIModule n -> getOrphans n
1407 IIDecl i -> getOrphans (unLoc (ideclName i))
1408 ; let imports = emptyImportAvails {
1409 imp_orphs = orphs
1410 }
1411 ; (gbl_env, lcl_env) <- getEnvs
1412 ; let gbl_env' = gbl_env {
1413 tcg_rdr_env = ic_rn_gbl_env icxt
1414 , tcg_type_env = type_env
1415 , tcg_inst_env = extendInstEnvList
1416 (extendInstEnvList (tcg_inst_env gbl_env) ic_insts)
1417 home_insts
1418 , tcg_fam_inst_env = extendFamInstEnvList
1419 (extendFamInstEnvList (tcg_fam_inst_env gbl_env)
1420 ic_finsts)
1421 home_fam_insts
1422 , tcg_field_env = mkNameEnv con_fields
1423 -- setting tcg_field_env is necessary
1424 -- to make RecordWildCards work (test: ghci049)
1425 , tcg_fix_env = ic_fix_env icxt
1426 , tcg_default = ic_default icxt
1427 -- must calculate imp_orphs of the ImportAvails
1428 -- so that instance visibility is done correctly
1429 , tcg_imports = imports
1430 }
1431
1432 ; lcl_env' <- tcExtendLocalTypeEnv lcl_env lcl_ids
1433 ; setEnvs (gbl_env', lcl_env') thing_inside }
1434 where
1435 (home_insts, home_fam_insts) = hptInstances hsc_env (\_ -> True)
1436
1437 icxt = hsc_IC hsc_env
1438 (ic_insts, ic_finsts) = ic_instances icxt
1439 (lcl_ids, top_ty_things) = partitionWith is_closed (ic_tythings icxt)
1440
1441 is_closed :: TyThing -> Either (Name, TcTyThing) TyThing
1442 -- Put Ids with free type variables (always RuntimeUnks)
1443 -- in the *local* type environment
1444 -- See Note [Initialising the type environment for GHCi]
1445 is_closed thing
1446 | AnId id <- thing
1447 , NotTopLevel <- isClosedLetBndr id
1448 = Left (idName id, ATcId { tct_id = id, tct_closed = NotTopLevel })
1449 | otherwise
1450 = Right thing
1451
1452 type_env1 = mkTypeEnvWithImplicits top_ty_things
1453 type_env = extendTypeEnvWithIds type_env1 (map instanceDFunId ic_insts)
1454 -- Putting the dfuns in the type_env
1455 -- is just to keep Core Lint happy
1456
1457 con_fields = [ (dataConName c, dataConFieldLabels c)
1458 | ATyCon t <- top_ty_things
1459 , c <- tyConDataCons t ]
1460
1461
1462 {- Note [Initialising the type environment for GHCi]
1463 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1464 Most of the the Ids in ic_things, defined by the user in 'let' stmts,
1465 have closed types. E.g.
1466 ghci> let foo x y = x && not y
1467
1468 However the GHCi debugger creates top-level bindings for Ids whose
1469 types have free RuntimeUnk skolem variables, standing for unknown
1470 types. If we don't register these free TyVars as global TyVars then
1471 the typechecker will try to quantify over them and fall over in
1472 zonkQuantifiedTyVar. so we must add any free TyVars to the
1473 typechecker's global TyVar set. That is most conveniently by using
1474 tcExtendLocalTypeEnv, which automatically extends the global TyVar
1475 set.
1476
1477 We do this by splitting out the Ids with open types, using 'is_closed'
1478 to do the partition. The top-level things go in the global TypeEnv;
1479 the open, NotTopLevel, Ids, with free RuntimeUnk tyvars, go in the
1480 local TypeEnv.
1481
1482 Note that we don't extend the local RdrEnv (tcl_rdr); all the in-scope
1483 things are already in the interactive context's GlobalRdrEnv.
1484 Extending the local RdrEnv isn't terrible, but it means there is an
1485 entry for the same Name in both global and local RdrEnvs, and that
1486 lead to duplicate "perhaps you meant..." suggestions (e.g. T5564).
1487
1488 We don't bother with the tcl_th_bndrs environment either.
1489 -}
1490
1491 #ifdef GHCI
1492 -- | The returned [Id] is the list of new Ids bound by this statement. It can
1493 -- be used to extend the InteractiveContext via extendInteractiveContext.
1494 --
1495 -- The returned TypecheckedHsExpr is of type IO [ () ], a list of the bound
1496 -- values, coerced to ().
1497 tcRnStmt :: HscEnv -> GhciLStmt RdrName
1498 -> IO (Messages, Maybe ([Id], LHsExpr Id, FixityEnv))
1499 tcRnStmt hsc_env rdr_stmt
1500 = runTcInteractive hsc_env $ do {
1501
1502 -- The real work is done here
1503 ((bound_ids, tc_expr), fix_env) <- tcUserStmt rdr_stmt ;
1504 zonked_expr <- zonkTopLExpr tc_expr ;
1505 zonked_ids <- zonkTopBndrs bound_ids ;
1506
1507 -- None of the Ids should be of unboxed type, because we
1508 -- cast them all to HValues in the end!
1509 mapM_ bad_unboxed (filter (isUnLiftedType . idType) zonked_ids) ;
1510
1511 traceTc "tcs 1" empty ;
1512 this_mod <- getModule ;
1513 global_ids <- mapM (externaliseAndTidyId this_mod) zonked_ids ;
1514 -- Note [Interactively-bound Ids in GHCi] in HscTypes
1515
1516 {- ---------------------------------------------
1517 At one stage I removed any shadowed bindings from the type_env;
1518 they are inaccessible but might, I suppose, cause a space leak if we leave them there.
1519 However, with Template Haskell they aren't necessarily inaccessible. Consider this
1520 GHCi session
1521 Prelude> let f n = n * 2 :: Int
1522 Prelude> fName <- runQ [| f |]
1523 Prelude> $(return $ AppE fName (LitE (IntegerL 7)))
1524 14
1525 Prelude> let f n = n * 3 :: Int
1526 Prelude> $(return $ AppE fName (LitE (IntegerL 7)))
1527 In the last line we use 'fName', which resolves to the *first* 'f'
1528 in scope. If we delete it from the type env, GHCi crashes because
1529 it doesn't expect that.
1530
1531 Hence this code is commented out
1532
1533 -------------------------------------------------- -}
1534
1535 traceOptTcRn Opt_D_dump_tc
1536 (vcat [text "Bound Ids" <+> pprWithCommas ppr global_ids,
1537 text "Typechecked expr" <+> ppr zonked_expr]) ;
1538
1539 return (global_ids, zonked_expr, fix_env)
1540 }
1541 where
1542 bad_unboxed id = addErr (sep [ptext (sLit "GHCi can't bind a variable of unlifted type:"),
1543 nest 2 (ppr id <+> dcolon <+> ppr (idType id))])
1544
1545 {-
1546 --------------------------------------------------------------------------
1547 Typechecking Stmts in GHCi
1548
1549 Here is the grand plan, implemented in tcUserStmt
1550
1551 What you type The IO [HValue] that hscStmt returns
1552 ------------- ------------------------------------
1553 let pat = expr ==> let pat = expr in return [coerce HVal x, coerce HVal y, ...]
1554 bindings: [x,y,...]
1555
1556 pat <- expr ==> expr >>= \ pat -> return [coerce HVal x, coerce HVal y, ...]
1557 bindings: [x,y,...]
1558
1559 expr (of IO type) ==> expr >>= \ it -> return [coerce HVal it]
1560 [NB: result not printed] bindings: [it]
1561
1562 expr (of non-IO type, ==> let it = expr in print it >> return [coerce HVal it]
1563 result showable) bindings: [it]
1564
1565 expr (of non-IO type,
1566 result not showable) ==> error
1567 -}
1568
1569 -- | A plan is an attempt to lift some code into the IO monad.
1570 type PlanResult = ([Id], LHsExpr Id)
1571 type Plan = TcM PlanResult
1572
1573 -- | Try the plans in order. If one fails (by raising an exn), try the next.
1574 -- If one succeeds, take it.
1575 runPlans :: [Plan] -> TcM PlanResult
1576 runPlans [] = panic "runPlans"
1577 runPlans [p] = p
1578 runPlans (p:ps) = tryTcLIE_ (runPlans ps) p
1579
1580 -- | Typecheck (and 'lift') a stmt entered by the user in GHCi into the
1581 -- GHCi 'environment'.
1582 --
1583 -- By 'lift' and 'environment we mean that the code is changed to
1584 -- execute properly in an IO monad. See Note [Interactively-bound Ids
1585 -- in GHCi] in HscTypes for more details. We do this lifting by trying
1586 -- different ways ('plans') of lifting the code into the IO monad and
1587 -- type checking each plan until one succeeds.
1588 tcUserStmt :: GhciLStmt RdrName -> TcM (PlanResult, FixityEnv)
1589
1590 -- An expression typed at the prompt is treated very specially
1591 tcUserStmt (L loc (BodyStmt expr _ _ _))
1592 = do { (rn_expr, fvs) <- checkNoErrs (rnLExpr expr)
1593 -- Don't try to typecheck if the renamer fails!
1594 ; ghciStep <- getGhciStepIO
1595 ; uniq <- newUnique
1596 ; interPrintName <- getInteractivePrintName
1597 ; let fresh_it = itName uniq loc
1598 matches = [mkMatch [] rn_expr emptyLocalBinds]
1599 -- [it = expr]
1600 the_bind = L loc $ (mkTopFunBind FromSource (L loc fresh_it) matches) { bind_fvs = fvs }
1601 -- Care here! In GHCi the expression might have
1602 -- free variables, and they in turn may have free type variables
1603 -- (if we are at a breakpoint, say). We must put those free vars
1604
1605 -- [let it = expr]
1606 let_stmt = L loc $ LetStmt $ HsValBinds $
1607 ValBindsOut [(NonRecursive,unitBag the_bind)] []
1608
1609 -- [it <- e]
1610 bind_stmt = L loc $ BindStmt (L loc (VarPat fresh_it))
1611 (nlHsApp ghciStep rn_expr)
1612 (HsVar bindIOName) noSyntaxExpr
1613
1614 -- [; print it]
1615 print_it = L loc $ BodyStmt (nlHsApp (nlHsVar interPrintName) (nlHsVar fresh_it))
1616 (HsVar thenIOName) noSyntaxExpr placeHolderType
1617
1618 -- The plans are:
1619 -- A. [it <- e; print it] but not if it::()
1620 -- B. [it <- e]
1621 -- C. [let it = e; print it]
1622 --
1623 -- Ensure that type errors don't get deferred when type checking the
1624 -- naked expression. Deferring type errors here is unhelpful because the
1625 -- expression gets evaluated right away anyway. It also would potentially
1626 -- emit two redundant type-error warnings, one from each plan.
1627 ; plan <- unsetGOptM Opt_DeferTypeErrors $ runPlans [
1628 -- Plan A
1629 do { stuff@([it_id], _) <- tcGhciStmts [bind_stmt, print_it]
1630 ; it_ty <- zonkTcType (idType it_id)
1631 ; when (isUnitTy $ it_ty) failM
1632 ; return stuff },
1633
1634 -- Plan B; a naked bind statment
1635 tcGhciStmts [bind_stmt],
1636
1637 -- Plan C; check that the let-binding is typeable all by itself.
1638 -- If not, fail; if so, try to print it.
1639 -- The two-step process avoids getting two errors: one from
1640 -- the expression itself, and one from the 'print it' part
1641 -- This two-step story is very clunky, alas
1642 do { _ <- checkNoErrs (tcGhciStmts [let_stmt])
1643 --- checkNoErrs defeats the error recovery of let-bindings
1644 ; tcGhciStmts [let_stmt, print_it] } ]
1645
1646 ; fix_env <- getFixityEnv
1647 ; return (plan, fix_env) }
1648
1649 tcUserStmt rdr_stmt@(L loc _)
1650 = do { (([rn_stmt], fix_env), fvs) <- checkNoErrs $
1651 rnStmts GhciStmtCtxt rnLExpr [rdr_stmt] $ \_ -> do
1652 fix_env <- getFixityEnv
1653 return (fix_env, emptyFVs)
1654 -- Don't try to typecheck if the renamer fails!
1655 ; traceRn (text "tcRnStmt" <+> vcat [ppr rdr_stmt, ppr rn_stmt, ppr fvs])
1656 ; rnDump (ppr rn_stmt) ;
1657
1658 ; ghciStep <- getGhciStepIO
1659 ; let gi_stmt
1660 | (L loc (BindStmt pat expr op1 op2)) <- rn_stmt
1661 = L loc $ BindStmt pat (nlHsApp ghciStep expr) op1 op2
1662 | otherwise = rn_stmt
1663
1664 ; opt_pr_flag <- goptM Opt_PrintBindResult
1665 ; let print_result_plan
1666 | opt_pr_flag -- The flag says "print result"
1667 , [v] <- collectLStmtBinders gi_stmt -- One binder
1668 = [mk_print_result_plan gi_stmt v]
1669 | otherwise = []
1670
1671 -- The plans are:
1672 -- [stmt; print v] if one binder and not v::()
1673 -- [stmt] otherwise
1674 ; plan <- runPlans (print_result_plan ++ [tcGhciStmts [gi_stmt]])
1675 ; return (plan, fix_env) }
1676 where
1677 mk_print_result_plan stmt v
1678 = do { stuff@([v_id], _) <- tcGhciStmts [stmt, print_v]
1679 ; v_ty <- zonkTcType (idType v_id)
1680 ; when (isUnitTy v_ty || not (isTauTy v_ty)) failM
1681 ; return stuff }
1682 where
1683 print_v = L loc $ BodyStmt (nlHsApp (nlHsVar printName) (nlHsVar v))
1684 (HsVar thenIOName) noSyntaxExpr
1685 placeHolderType
1686
1687 -- | Typecheck the statements given and then return the results of the
1688 -- statement in the form 'IO [()]'.
1689 tcGhciStmts :: [GhciLStmt Name] -> TcM PlanResult
1690 tcGhciStmts stmts
1691 = do { ioTyCon <- tcLookupTyCon ioTyConName ;
1692 ret_id <- tcLookupId returnIOName ; -- return @ IO
1693 let {
1694 ret_ty = mkListTy unitTy ;
1695 io_ret_ty = mkTyConApp ioTyCon [ret_ty] ;
1696 tc_io_stmts = tcStmtsAndThen GhciStmtCtxt tcDoStmt stmts io_ret_ty ;
1697 names = collectLStmtsBinders stmts ;
1698 } ;
1699
1700 -- OK, we're ready to typecheck the stmts
1701 traceTc "TcRnDriver.tcGhciStmts: tc stmts" empty ;
1702 ((tc_stmts, ids), lie) <- captureConstraints $
1703 tc_io_stmts $ \ _ ->
1704 mapM tcLookupId names ;
1705 -- Look up the names right in the middle,
1706 -- where they will all be in scope
1707
1708 -- wanted constraints from static forms
1709 stWC <- tcg_static_wc <$> getGblEnv >>= readTcRef ;
1710
1711 -- Simplify the context
1712 traceTc "TcRnDriver.tcGhciStmts: simplify ctxt" empty ;
1713 const_binds <- checkNoErrs (simplifyInteractive (andWC stWC lie)) ;
1714 -- checkNoErrs ensures that the plan fails if context redn fails
1715
1716 traceTc "TcRnDriver.tcGhciStmts: done" empty ;
1717 let { -- mk_return builds the expression
1718 -- returnIO @ [()] [coerce () x, .., coerce () z]
1719 --
1720 -- Despite the inconvenience of building the type applications etc,
1721 -- this *has* to be done in type-annotated post-typecheck form
1722 -- because we are going to return a list of *polymorphic* values
1723 -- coerced to type (). If we built a *source* stmt
1724 -- return [coerce x, ..., coerce z]
1725 -- then the type checker would instantiate x..z, and we wouldn't
1726 -- get their *polymorphic* values. (And we'd get ambiguity errs
1727 -- if they were overloaded, since they aren't applied to anything.)
1728 ret_expr = nlHsApp (nlHsTyApp ret_id [ret_ty])
1729 (noLoc $ ExplicitList unitTy Nothing (map mk_item ids)) ;
1730 mk_item id = nlHsApp (nlHsTyApp unsafeCoerceId [idType id, unitTy])
1731 (nlHsVar id) ;
1732 stmts = tc_stmts ++ [noLoc (mkLastStmt ret_expr)]
1733 } ;
1734 return (ids, mkHsDictLet (EvBinds const_binds) $
1735 noLoc (HsDo GhciStmtCtxt stmts io_ret_ty))
1736 }
1737
1738 -- | Generate a typed ghciStepIO expression (ghciStep :: Ty a -> IO a)
1739 getGhciStepIO :: TcM (LHsExpr Name)
1740 getGhciStepIO = do
1741 ghciTy <- getGHCiMonad
1742 fresh_a <- newUnique
1743 loc <- getSrcSpanM
1744 let a_tv = mkInternalName fresh_a (mkTyVarOccFS (fsLit "a")) loc
1745 ghciM = nlHsAppTy (nlHsTyVar ghciTy) (nlHsTyVar a_tv)
1746 ioM = nlHsAppTy (nlHsTyVar ioTyConName) (nlHsTyVar a_tv)
1747
1748 stepTy :: LHsType Name -- Renamed, so needs all binders in place
1749 stepTy = noLoc $ HsForAllTy Implicit Nothing
1750 (HsQTvs { hsq_tvs = [noLoc (UserTyVar a_tv)]
1751 , hsq_kvs = [] })
1752 (noLoc [])
1753 (nlHsFunTy ghciM ioM)
1754 step = noLoc $ ExprWithTySig (nlHsVar ghciStepIoMName) stepTy []
1755 return step
1756
1757 isGHCiMonad :: HscEnv -> String -> IO (Messages, Maybe Name)
1758 isGHCiMonad hsc_env ty
1759 = runTcInteractive hsc_env $ do
1760 rdrEnv <- getGlobalRdrEnv
1761 let occIO = lookupOccEnv rdrEnv (mkOccName tcName ty)
1762 case occIO of
1763 Just [n] -> do
1764 let name = gre_name n
1765 ghciClass <- tcLookupClass ghciIoClassName
1766 userTyCon <- tcLookupTyCon name
1767 let userTy = mkTyConApp userTyCon []
1768 _ <- tcLookupInstance ghciClass [userTy]
1769 return name
1770
1771 Just _ -> failWithTc $ text "Ambigous type!"
1772 Nothing -> failWithTc $ text ("Can't find type:" ++ ty)
1773
1774 -- tcRnExpr just finds the type of an expression
1775
1776 tcRnExpr :: HscEnv
1777 -> LHsExpr RdrName
1778 -> IO (Messages, Maybe Type)
1779 -- Type checks the expression and returns its most general type
1780 tcRnExpr hsc_env rdr_expr
1781 = runTcInteractive hsc_env $
1782 do {
1783
1784 (rn_expr, _fvs) <- rnLExpr rdr_expr ;
1785 failIfErrsM ;
1786
1787 -- Now typecheck the expression, and generalise its type
1788 -- it might have a rank-2 type (e.g. :t runST)
1789 uniq <- newUnique ;
1790 let { fresh_it = itName uniq (getLoc rdr_expr) } ;
1791 ((_tc_expr, res_ty), tclvl, lie) <- pushLevelAndCaptureConstraints $
1792 tcInferRho rn_expr ;
1793 ((qtvs, dicts, _), lie_top) <- captureConstraints $
1794 {-# SCC "simplifyInfer" #-}
1795 simplifyInfer tclvl
1796 False {- No MR for now -}
1797 [] {- No sig vars -}
1798 [(fresh_it, res_ty)]
1799 lie ;
1800 -- Wanted constraints from static forms
1801 stWC <- tcg_static_wc <$> getGblEnv >>= readTcRef ;
1802
1803 -- Ignore the dictionary bindings
1804 _ <- simplifyInteractive (andWC stWC lie_top) ;
1805
1806 let { all_expr_ty = mkForAllTys qtvs (mkPiTypes dicts res_ty) } ;
1807 ty <- zonkTcType all_expr_ty ;
1808
1809 -- We normalise type families, so that the type of an expression is the
1810 -- same as of a bound expression (TcBinds.mkInferredPolyId). See Trac
1811 -- #10321 for further discussion.
1812 fam_envs <- tcGetFamInstEnvs ;
1813 -- normaliseType returns a coercion which we discard, so the Role is
1814 -- irrelevant
1815 return (snd (normaliseType fam_envs Nominal ty))
1816 }
1817
1818 --------------------------
1819 tcRnImportDecls :: HscEnv
1820 -> [LImportDecl RdrName]
1821 -> IO (Messages, Maybe GlobalRdrEnv)
1822 -- Find the new chunk of GlobalRdrEnv created by this list of import
1823 -- decls. In contract tcRnImports *extends* the TcGblEnv.
1824 tcRnImportDecls hsc_env import_decls
1825 = runTcInteractive hsc_env $
1826 do { gbl_env <- updGblEnv zap_rdr_env $
1827 tcRnImports hsc_env import_decls
1828 ; return (tcg_rdr_env gbl_env) }
1829 where
1830 zap_rdr_env gbl_env = gbl_env { tcg_rdr_env = emptyGlobalRdrEnv }
1831
1832 -- tcRnType just finds the kind of a type
1833
1834 tcRnType :: HscEnv
1835 -> Bool -- Normalise the returned type
1836 -> LHsType RdrName
1837 -> IO (Messages, Maybe (Type, Kind))
1838 tcRnType hsc_env normalise rdr_type
1839 = runTcInteractive hsc_env $
1840 setXOptM Opt_PolyKinds $ -- See Note [Kind-generalise in tcRnType]
1841 do { (rn_type, _fvs, wcs) <- rnLHsTypeWithWildCards GHCiCtx rdr_type
1842 ; failIfErrsM
1843
1844 -- Now kind-check the type
1845 -- It can have any rank or kind
1846 ; (ty, kind) <- tcWildcardBinders wcs $ \_ ->
1847 tcLHsType rn_type
1848
1849 -- Do kind generalisation; see Note [Kind-generalise in tcRnType]
1850 ; kvs <- zonkTcTypeAndFV kind
1851 ; kvs <- kindGeneralize kvs
1852 ; ty <- zonkTcTypeToType emptyZonkEnv ty
1853
1854 ; ty' <- if normalise
1855 then do { fam_envs <- tcGetFamInstEnvs
1856 ; return (snd (normaliseType fam_envs Nominal ty)) }
1857 -- normaliseType returns a coercion
1858 -- which we discard, so the Role is irrelevant
1859 else return ty ;
1860
1861 ; return (ty', mkForAllTys kvs (typeKind ty')) }
1862
1863 {- Note [Kind-generalise in tcRnType]
1864 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1865 We switch on PolyKinds when kind-checking a user type, so that we will
1866 kind-generalise the type, even when PolyKinds is not otherwise on.
1867 This gives the right default behaviour at the GHCi prompt, where if
1868 you say ":k T", and T has a polymorphic kind, you'd like to see that
1869 polymorphism. Of course. If T isn't kind-polymorphic you won't get
1870 anything unexpected, but the apparent *loss* of polymorphism, for
1871 types that you know are polymorphic, is quite surprising. See Trac
1872 #7688 for a discussion.
1873
1874 Note that the goal is to generalise the *kind of the type*, not
1875 the type itself! Example:
1876 ghci> data T m a = MkT (m a) -- T :: forall . (k -> *) -> k -> *
1877 ghci> :k T
1878 We instantiate T to get (T kappa). We do not want to kind-generalise
1879 that to forall k. T k! Rather we want to take its kind
1880 T kappa :: (kappa -> *) -> kappa -> *
1881 and now kind-generalise that kind, to forall k. (k->*) -> k -> *
1882 (It was Trac #10122 that made me realise how wrong the previous
1883 approach was.) -}
1884
1885
1886 {-
1887 ************************************************************************
1888 * *
1889 tcRnDeclsi
1890 * *
1891 ************************************************************************
1892
1893 tcRnDeclsi exists to allow class, data, and other declarations in GHCi.
1894 -}
1895
1896 tcRnDeclsi :: HscEnv
1897 -> [LHsDecl RdrName]
1898 -> IO (Messages, Maybe TcGblEnv)
1899 tcRnDeclsi hsc_env local_decls
1900 = runTcInteractive hsc_env $
1901 tcRnSrcDecls False Nothing local_decls
1902
1903 externaliseAndTidyId :: Module -> Id -> TcM Id
1904 externaliseAndTidyId this_mod id
1905 = do { name' <- externaliseName this_mod (idName id)
1906 ; return (globaliseAndTidyId (setIdName id name')) }
1907
1908 #endif /* GHCi */
1909
1910 {-
1911 ************************************************************************
1912 * *
1913 More GHCi stuff, to do with browsing and getting info
1914 * *
1915 ************************************************************************
1916 -}
1917
1918 #ifdef GHCI
1919 -- | ASSUMES that the module is either in the 'HomePackageTable' or is
1920 -- a package module with an interface on disk. If neither of these is
1921 -- true, then the result will be an error indicating the interface
1922 -- could not be found.
1923 getModuleInterface :: HscEnv -> Module -> IO (Messages, Maybe ModIface)
1924 getModuleInterface hsc_env mod
1925 = runTcInteractive hsc_env $
1926 loadModuleInterface (ptext (sLit "getModuleInterface")) mod
1927
1928 tcRnLookupRdrName :: HscEnv -> Located RdrName
1929 -> IO (Messages, Maybe [Name])
1930 -- ^ Find all the Names that this RdrName could mean, in GHCi
1931 tcRnLookupRdrName hsc_env (L loc rdr_name)
1932 = runTcInteractive hsc_env $
1933 setSrcSpan loc $
1934 do { -- If the identifier is a constructor (begins with an
1935 -- upper-case letter), then we need to consider both
1936 -- constructor and type class identifiers.
1937 let rdr_names = dataTcOccs rdr_name
1938 ; names_s <- mapM lookupInfoOccRn rdr_names
1939 ; let names = concat names_s
1940 ; when (null names) (addErrTc (ptext (sLit "Not in scope:") <+> quotes (ppr rdr_name)))
1941 ; return names }
1942 #endif
1943
1944 tcRnLookupName :: HscEnv -> Name -> IO (Messages, Maybe TyThing)
1945 tcRnLookupName hsc_env name
1946 = runTcInteractive hsc_env $
1947 tcRnLookupName' name
1948
1949 -- To look up a name we have to look in the local environment (tcl_lcl)
1950 -- as well as the global environment, which is what tcLookup does.
1951 -- But we also want a TyThing, so we have to convert:
1952
1953 tcRnLookupName' :: Name -> TcRn TyThing
1954 tcRnLookupName' name = do
1955 tcthing <- tcLookup name
1956 case tcthing of
1957 AGlobal thing -> return thing
1958 ATcId{tct_id=id} -> return (AnId id)
1959 _ -> panic "tcRnLookupName'"
1960
1961 tcRnGetInfo :: HscEnv
1962 -> Name
1963 -> IO (Messages, Maybe (TyThing, Fixity, [ClsInst], [FamInst]))
1964
1965 -- Used to implement :info in GHCi
1966 --
1967 -- Look up a RdrName and return all the TyThings it might be
1968 -- A capitalised RdrName is given to us in the DataName namespace,
1969 -- but we want to treat it as *both* a data constructor
1970 -- *and* as a type or class constructor;
1971 -- hence the call to dataTcOccs, and we return up to two results
1972 tcRnGetInfo hsc_env name
1973 = runTcInteractive hsc_env $
1974 do { loadUnqualIfaces hsc_env (hsc_IC hsc_env)
1975 -- Load the interface for all unqualified types and classes
1976 -- That way we will find all the instance declarations
1977 -- (Packages have not orphan modules, and we assume that
1978 -- in the home package all relevant modules are loaded.)
1979
1980 ; thing <- tcRnLookupName' name
1981 ; fixity <- lookupFixityRn name
1982 ; (cls_insts, fam_insts) <- lookupInsts thing
1983 ; return (thing, fixity, cls_insts, fam_insts) }
1984
1985 lookupInsts :: TyThing -> TcM ([ClsInst],[FamInst])
1986 lookupInsts (ATyCon tc)
1987 = do { InstEnvs { ie_global = pkg_ie, ie_local = home_ie, ie_visible = vis_mods } <- tcGetInstEnvs
1988 ; (pkg_fie, home_fie) <- tcGetFamInstEnvs
1989 -- Load all instances for all classes that are
1990 -- in the type environment (which are all the ones
1991 -- we've seen in any interface file so far)
1992
1993 -- Return only the instances relevant to the given thing, i.e.
1994 -- the instances whose head contains the thing's name.
1995 ; let cls_insts =
1996 [ ispec -- Search all
1997 | ispec <- instEnvElts home_ie ++ instEnvElts pkg_ie
1998 , instIsVisible vis_mods ispec
1999 , tc_name `elemNameSet` orphNamesOfClsInst ispec ]
2000 ; let fam_insts =
2001 [ fispec
2002 | fispec <- famInstEnvElts home_fie ++ famInstEnvElts pkg_fie
2003 , tc_name `elemNameSet` orphNamesOfFamInst fispec ]
2004 ; return (cls_insts, fam_insts) }
2005 where
2006 tc_name = tyConName tc
2007
2008 lookupInsts _ = return ([],[])
2009
2010 loadUnqualIfaces :: HscEnv -> InteractiveContext -> TcM ()
2011 -- Load the interface for everything that is in scope unqualified
2012 -- This is so that we can accurately report the instances for
2013 -- something
2014 loadUnqualIfaces hsc_env ictxt
2015 = initIfaceTcRn $ do
2016 mapM_ (loadSysInterface doc) (moduleSetElts (mkModuleSet unqual_mods))
2017 where
2018 this_pkg = thisPackage (hsc_dflags hsc_env)
2019
2020 unqual_mods = [ nameModule name
2021 | gre <- globalRdrEnvElts (ic_rn_gbl_env ictxt)
2022 , let name = gre_name gre
2023 , nameIsFromExternalPackage this_pkg name
2024 , isTcOcc (nameOccName name) -- Types and classes only
2025 , unQualOK gre ] -- In scope unqualified
2026 doc = ptext (sLit "Need interface for module whose export(s) are in scope unqualified")
2027
2028
2029 {-
2030 ************************************************************************
2031 * *
2032 Degugging output
2033 * *
2034 ************************************************************************
2035 -}
2036
2037 rnDump :: SDoc -> TcRn ()
2038 -- Dump, with a banner, if -ddump-rn
2039 rnDump doc = do { traceOptTcRn Opt_D_dump_rn (mkDumpDoc "Renamer" doc) }
2040
2041 tcDump :: TcGblEnv -> TcRn ()
2042 tcDump env
2043 = do { dflags <- getDynFlags ;
2044
2045 -- Dump short output if -ddump-types or -ddump-tc
2046 when (dopt Opt_D_dump_types dflags || dopt Opt_D_dump_tc dflags)
2047 (printForUserTcRn short_dump) ;
2048
2049 -- Dump bindings if -ddump-tc
2050 traceOptTcRn Opt_D_dump_tc (mkDumpDoc "Typechecker" full_dump)
2051 }
2052 where
2053 short_dump = pprTcGblEnv env
2054 full_dump = pprLHsBinds (tcg_binds env)
2055 -- NB: foreign x-d's have undefined's in their types;
2056 -- hence can't show the tc_fords
2057
2058 -- It's unpleasant having both pprModGuts and pprModDetails here
2059 pprTcGblEnv :: TcGblEnv -> SDoc
2060 pprTcGblEnv (TcGblEnv { tcg_type_env = type_env,
2061 tcg_insts = insts,
2062 tcg_fam_insts = fam_insts,
2063 tcg_rules = rules,
2064 tcg_vects = vects,
2065 tcg_imports = imports })
2066 = vcat [ ppr_types insts type_env
2067 , ppr_tycons fam_insts type_env
2068 , ppr_insts insts
2069 , ppr_fam_insts fam_insts
2070 , vcat (map ppr rules)
2071 , vcat (map ppr vects)
2072 , ptext (sLit "Dependent modules:") <+>
2073 ppr (sortBy cmp_mp $ eltsUFM (imp_dep_mods imports))
2074 , ptext (sLit "Dependent packages:") <+>
2075 ppr (sortBy stableUnitIdCmp $ imp_dep_pkgs imports)]
2076 where -- The two uses of sortBy are just to reduce unnecessary
2077 -- wobbling in testsuite output
2078 cmp_mp (mod_name1, is_boot1) (mod_name2, is_boot2)
2079 = (mod_name1 `stableModuleNameCmp` mod_name2)
2080 `thenCmp`
2081 (is_boot1 `compare` is_boot2)
2082
2083 ppr_types :: [ClsInst] -> TypeEnv -> SDoc
2084 ppr_types insts type_env
2085 = text "TYPE SIGNATURES" $$ nest 2 (ppr_sigs ids)
2086 where
2087 dfun_ids = map instanceDFunId insts
2088 ids = [id | id <- typeEnvIds type_env, want_sig id]
2089 want_sig id | opt_PprStyle_Debug = True
2090 | otherwise = isLocalId id &&
2091 isExternalName (idName id) &&
2092 not (id `elem` dfun_ids)
2093 -- isLocalId ignores data constructors, records selectors etc.
2094 -- The isExternalName ignores local dictionary and method bindings
2095 -- that the type checker has invented. Top-level user-defined things
2096 -- have External names.
2097
2098 ppr_tycons :: [FamInst] -> TypeEnv -> SDoc
2099 ppr_tycons fam_insts type_env
2100 = vcat [ text "TYPE CONSTRUCTORS"
2101 , nest 2 (ppr_tydecls tycons)
2102 , text "COERCION AXIOMS"
2103 , nest 2 (vcat (map pprCoAxiom (typeEnvCoAxioms type_env))) ]
2104 where
2105 fi_tycons = famInstsRepTyCons fam_insts
2106 tycons = [tycon | tycon <- typeEnvTyCons type_env, want_tycon tycon]
2107 want_tycon tycon | opt_PprStyle_Debug = True
2108 | otherwise = not (isImplicitTyCon tycon) &&
2109 isExternalName (tyConName tycon) &&
2110 not (tycon `elem` fi_tycons)
2111
2112 ppr_insts :: [ClsInst] -> SDoc
2113 ppr_insts [] = empty
2114 ppr_insts ispecs = text "INSTANCES" $$ nest 2 (pprInstances ispecs)
2115
2116 ppr_fam_insts :: [FamInst] -> SDoc
2117 ppr_fam_insts [] = empty
2118 ppr_fam_insts fam_insts =
2119 text "FAMILY INSTANCES" $$ nest 2 (pprFamInsts fam_insts)
2120
2121 ppr_sigs :: [Var] -> SDoc
2122 ppr_sigs ids
2123 -- Print type signatures; sort by OccName
2124 = vcat (map ppr_sig (sortBy (comparing getOccName) ids))
2125 where
2126 ppr_sig id = hang (ppr id <+> dcolon) 2 (ppr (tidyTopType (idType id)))
2127
2128 ppr_tydecls :: [TyCon] -> SDoc
2129 ppr_tydecls tycons
2130 -- Print type constructor info; sort by OccName
2131 = vcat (map ppr_tycon (sortBy (comparing getOccName) tycons))
2132 where
2133 ppr_tycon tycon = vcat [ ppr (tyThingToIfaceDecl (ATyCon tycon)) ]
2134
2135 {-
2136 ********************************************************************************
2137
2138 Type Checker Plugins
2139
2140 ********************************************************************************
2141 -}
2142
2143 withTcPlugins :: HscEnv -> TcM a -> TcM a
2144 withTcPlugins hsc_env m =
2145 do plugins <- liftIO (loadTcPlugins hsc_env)
2146 case plugins of
2147 [] -> m -- Common fast case
2148 _ -> do (solvers,stops) <- unzip `fmap` mapM startPlugin plugins
2149 -- This ensures that tcPluginStop is called even if a type
2150 -- error occurs during compilation (Fix of #10078)
2151 eitherRes <- tryM $ do
2152 updGblEnv (\e -> e { tcg_tc_plugins = solvers }) m
2153 mapM_ (flip runTcPluginM Nothing) stops
2154 case eitherRes of
2155 Left _ -> failM
2156 Right res -> return res
2157 where
2158 startPlugin (TcPlugin start solve stop) =
2159 do s <- runTcPluginM start Nothing
2160 return (solve s, stop s)
2161
2162 loadTcPlugins :: HscEnv -> IO [TcPlugin]
2163 #ifndef GHCI
2164 loadTcPlugins _ = return []
2165 #else
2166 loadTcPlugins hsc_env =
2167 do named_plugins <- loadPlugins hsc_env
2168 return $ catMaybes $ map load_plugin named_plugins
2169 where
2170 load_plugin (_, plug, opts) = tcPlugin plug opts
2171 #endif