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