Improve error messages for skolems
[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 -- None of the Ids should be of unboxed type, because we
1881 -- cast them all to HValues in the end!
1882 mapM_ bad_unboxed (filter (isUnliftedType . idType) zonked_ids) ;
1883
1884 traceTc "tcs 1" empty ;
1885 this_mod <- getModule ;
1886 global_ids <- mapM (externaliseAndTidyId this_mod) zonked_ids ;
1887 -- Note [Interactively-bound Ids in GHCi] in HscTypes
1888
1889 {- ---------------------------------------------
1890 At one stage I removed any shadowed bindings from the type_env;
1891 they are inaccessible but might, I suppose, cause a space leak if we leave them there.
1892 However, with Template Haskell they aren't necessarily inaccessible. Consider this
1893 GHCi session
1894 Prelude> let f n = n * 2 :: Int
1895 Prelude> fName <- runQ [| f |]
1896 Prelude> $(return $ AppE fName (LitE (IntegerL 7)))
1897 14
1898 Prelude> let f n = n * 3 :: Int
1899 Prelude> $(return $ AppE fName (LitE (IntegerL 7)))
1900 In the last line we use 'fName', which resolves to the *first* 'f'
1901 in scope. If we delete it from the type env, GHCi crashes because
1902 it doesn't expect that.
1903
1904 Hence this code is commented out
1905
1906 -------------------------------------------------- -}
1907
1908 traceOptTcRn Opt_D_dump_tc
1909 (vcat [text "Bound Ids" <+> pprWithCommas ppr global_ids,
1910 text "Typechecked expr" <+> ppr zonked_expr]) ;
1911
1912 return (global_ids, zonked_expr, fix_env)
1913 }
1914 where
1915 bad_unboxed id = addErr (sep [text "GHCi can't bind a variable of unlifted type:",
1916 nest 2 (ppr id <+> dcolon <+> ppr (idType id))])
1917
1918 {-
1919 --------------------------------------------------------------------------
1920 Typechecking Stmts in GHCi
1921
1922 Here is the grand plan, implemented in tcUserStmt
1923
1924 What you type The IO [HValue] that hscStmt returns
1925 ------------- ------------------------------------
1926 let pat = expr ==> let pat = expr in return [coerce HVal x, coerce HVal y, ...]
1927 bindings: [x,y,...]
1928
1929 pat <- expr ==> expr >>= \ pat -> return [coerce HVal x, coerce HVal y, ...]
1930 bindings: [x,y,...]
1931
1932 expr (of IO type) ==> expr >>= \ it -> return [coerce HVal it]
1933 [NB: result not printed] bindings: [it]
1934
1935 expr (of non-IO type, ==> let it = expr in print it >> return [coerce HVal it]
1936 result showable) bindings: [it]
1937
1938 expr (of non-IO type,
1939 result not showable) ==> error
1940 -}
1941
1942 -- | A plan is an attempt to lift some code into the IO monad.
1943 type PlanResult = ([Id], LHsExpr Id)
1944 type Plan = TcM PlanResult
1945
1946 -- | Try the plans in order. If one fails (by raising an exn), try the next.
1947 -- If one succeeds, take it.
1948 runPlans :: [Plan] -> TcM PlanResult
1949 runPlans [] = panic "runPlans"
1950 runPlans [p] = p
1951 runPlans (p:ps) = tryTcLIE_ (runPlans ps) p
1952
1953 -- | Typecheck (and 'lift') a stmt entered by the user in GHCi into the
1954 -- GHCi 'environment'.
1955 --
1956 -- By 'lift' and 'environment we mean that the code is changed to
1957 -- execute properly in an IO monad. See Note [Interactively-bound Ids
1958 -- in GHCi] in HscTypes for more details. We do this lifting by trying
1959 -- different ways ('plans') of lifting the code into the IO monad and
1960 -- type checking each plan until one succeeds.
1961 tcUserStmt :: GhciLStmt RdrName -> TcM (PlanResult, FixityEnv)
1962
1963 -- An expression typed at the prompt is treated very specially
1964 tcUserStmt (L loc (BodyStmt expr _ _ _))
1965 = do { (rn_expr, fvs) <- checkNoErrs (rnLExpr expr)
1966 -- Don't try to typecheck if the renamer fails!
1967 ; ghciStep <- getGhciStepIO
1968 ; uniq <- newUnique
1969 ; interPrintName <- getInteractivePrintName
1970 ; let fresh_it = itName uniq loc
1971 matches = [mkMatch (FunRhs (L loc fresh_it) Prefix) [] rn_expr
1972 (noLoc emptyLocalBinds)]
1973 -- [it = expr]
1974 the_bind = L loc $ (mkTopFunBind FromSource (L loc fresh_it) matches) { bind_fvs = fvs }
1975 -- Care here! In GHCi the expression might have
1976 -- free variables, and they in turn may have free type variables
1977 -- (if we are at a breakpoint, say). We must put those free vars
1978
1979 -- [let it = expr]
1980 let_stmt = L loc $ LetStmt $ noLoc $ HsValBinds $
1981 ValBindsOut [(NonRecursive,unitBag the_bind)] []
1982
1983 -- [it <- e]
1984 bind_stmt = L loc $ BindStmt (L loc (VarPat (L loc fresh_it)))
1985 (nlHsApp ghciStep rn_expr)
1986 (mkRnSyntaxExpr bindIOName)
1987 noSyntaxExpr
1988 PlaceHolder
1989
1990 -- [; print it]
1991 print_it = L loc $ BodyStmt (nlHsApp (nlHsVar interPrintName) (nlHsVar fresh_it))
1992 (mkRnSyntaxExpr thenIOName)
1993 noSyntaxExpr placeHolderType
1994
1995 -- The plans are:
1996 -- A. [it <- e; print it] but not if it::()
1997 -- B. [it <- e]
1998 -- C. [let it = e; print it]
1999 --
2000 -- Ensure that type errors don't get deferred when type checking the
2001 -- naked expression. Deferring type errors here is unhelpful because the
2002 -- expression gets evaluated right away anyway. It also would potentially
2003 -- emit two redundant type-error warnings, one from each plan.
2004 ; plan <- unsetGOptM Opt_DeferTypeErrors $
2005 unsetGOptM Opt_DeferTypedHoles $ runPlans [
2006 -- Plan A
2007 do { stuff@([it_id], _) <- tcGhciStmts [bind_stmt, print_it]
2008 ; it_ty <- zonkTcType (idType it_id)
2009 ; when (isUnitTy $ it_ty) failM
2010 ; return stuff },
2011
2012 -- Plan B; a naked bind statment
2013 tcGhciStmts [bind_stmt],
2014
2015 -- Plan C; check that the let-binding is typeable all by itself.
2016 -- If not, fail; if so, try to print it.
2017 -- The two-step process avoids getting two errors: one from
2018 -- the expression itself, and one from the 'print it' part
2019 -- This two-step story is very clunky, alas
2020 do { _ <- checkNoErrs (tcGhciStmts [let_stmt])
2021 --- checkNoErrs defeats the error recovery of let-bindings
2022 ; tcGhciStmts [let_stmt, print_it] } ]
2023
2024 ; fix_env <- getFixityEnv
2025 ; return (plan, fix_env) }
2026
2027 tcUserStmt rdr_stmt@(L loc _)
2028 = do { (([rn_stmt], fix_env), fvs) <- checkNoErrs $
2029 rnStmts GhciStmtCtxt rnLExpr [rdr_stmt] $ \_ -> do
2030 fix_env <- getFixityEnv
2031 return (fix_env, emptyFVs)
2032 -- Don't try to typecheck if the renamer fails!
2033 ; traceRn "tcRnStmt" (vcat [ppr rdr_stmt, ppr rn_stmt, ppr fvs])
2034 ; rnDump rn_stmt ;
2035
2036 ; ghciStep <- getGhciStepIO
2037 ; let gi_stmt
2038 | (L loc (BindStmt pat expr op1 op2 ty)) <- rn_stmt
2039 = L loc $ BindStmt pat (nlHsApp ghciStep expr) op1 op2 ty
2040 | otherwise = rn_stmt
2041
2042 ; opt_pr_flag <- goptM Opt_PrintBindResult
2043 ; let print_result_plan
2044 | opt_pr_flag -- The flag says "print result"
2045 , [v] <- collectLStmtBinders gi_stmt -- One binder
2046 = [mk_print_result_plan gi_stmt v]
2047 | otherwise = []
2048
2049 -- The plans are:
2050 -- [stmt; print v] if one binder and not v::()
2051 -- [stmt] otherwise
2052 ; plan <- runPlans (print_result_plan ++ [tcGhciStmts [gi_stmt]])
2053 ; return (plan, fix_env) }
2054 where
2055 mk_print_result_plan stmt v
2056 = do { stuff@([v_id], _) <- tcGhciStmts [stmt, print_v]
2057 ; v_ty <- zonkTcType (idType v_id)
2058 ; when (isUnitTy v_ty || not (isTauTy v_ty)) failM
2059 ; return stuff }
2060 where
2061 print_v = L loc $ BodyStmt (nlHsApp (nlHsVar printName) (nlHsVar v))
2062 (mkRnSyntaxExpr thenIOName) noSyntaxExpr
2063 placeHolderType
2064
2065 -- | Typecheck the statements given and then return the results of the
2066 -- statement in the form 'IO [()]'.
2067 tcGhciStmts :: [GhciLStmt Name] -> TcM PlanResult
2068 tcGhciStmts stmts
2069 = do { ioTyCon <- tcLookupTyCon ioTyConName ;
2070 ret_id <- tcLookupId returnIOName ; -- return @ IO
2071 let {
2072 ret_ty = mkListTy unitTy ;
2073 io_ret_ty = mkTyConApp ioTyCon [ret_ty] ;
2074 tc_io_stmts = tcStmtsAndThen GhciStmtCtxt tcDoStmt stmts
2075 (mkCheckExpType io_ret_ty) ;
2076 names = collectLStmtsBinders stmts ;
2077 } ;
2078
2079 -- OK, we're ready to typecheck the stmts
2080 traceTc "TcRnDriver.tcGhciStmts: tc stmts" empty ;
2081 ((tc_stmts, ids), lie) <- captureTopConstraints $
2082 tc_io_stmts $ \ _ ->
2083 mapM tcLookupId names ;
2084 -- Look up the names right in the middle,
2085 -- where they will all be in scope
2086
2087 -- Simplify the context
2088 traceTc "TcRnDriver.tcGhciStmts: simplify ctxt" empty ;
2089 const_binds <- checkNoErrs (simplifyInteractive lie) ;
2090 -- checkNoErrs ensures that the plan fails if context redn fails
2091
2092 traceTc "TcRnDriver.tcGhciStmts: done" empty ;
2093 let { -- mk_return builds the expression
2094 -- returnIO @ [()] [coerce () x, .., coerce () z]
2095 --
2096 -- Despite the inconvenience of building the type applications etc,
2097 -- this *has* to be done in type-annotated post-typecheck form
2098 -- because we are going to return a list of *polymorphic* values
2099 -- coerced to type (). If we built a *source* stmt
2100 -- return [coerce x, ..., coerce z]
2101 -- then the type checker would instantiate x..z, and we wouldn't
2102 -- get their *polymorphic* values. (And we'd get ambiguity errs
2103 -- if they were overloaded, since they aren't applied to anything.)
2104 ret_expr = nlHsApp (nlHsTyApp ret_id [ret_ty])
2105 (noLoc $ ExplicitList unitTy Nothing (map mk_item ids)) ;
2106 mk_item id = let ty_args = [idType id, unitTy] in
2107 nlHsApp (nlHsTyApp unsafeCoerceId
2108 (map (getRuntimeRep "tcGhciStmts") ty_args ++ ty_args))
2109 (nlHsVar id) ;
2110 stmts = tc_stmts ++ [noLoc (mkLastStmt ret_expr)]
2111 } ;
2112 return (ids, mkHsDictLet (EvBinds const_binds) $
2113 noLoc (HsDo GhciStmtCtxt (noLoc stmts) io_ret_ty))
2114 }
2115
2116 -- | Generate a typed ghciStepIO expression (ghciStep :: Ty a -> IO a)
2117 getGhciStepIO :: TcM (LHsExpr Name)
2118 getGhciStepIO = do
2119 ghciTy <- getGHCiMonad
2120 a_tv <- newName (mkTyVarOccFS (fsLit "a"))
2121 let ghciM = nlHsAppTy (nlHsTyVar ghciTy) (nlHsTyVar a_tv)
2122 ioM = nlHsAppTy (nlHsTyVar ioTyConName) (nlHsTyVar a_tv)
2123
2124 step_ty = noLoc $ HsForAllTy { hst_bndrs = [noLoc $ UserTyVar (noLoc a_tv)]
2125 , hst_body = nlHsFunTy ghciM ioM }
2126
2127 stepTy :: LHsSigWcType Name
2128 stepTy = mkEmptyWildCardBndrs (mkEmptyImplicitBndrs step_ty)
2129
2130 return (noLoc $ ExprWithTySig (nlHsVar ghciStepIoMName) stepTy)
2131
2132 isGHCiMonad :: HscEnv -> String -> IO (Messages, Maybe Name)
2133 isGHCiMonad hsc_env ty
2134 = runTcInteractive hsc_env $ do
2135 rdrEnv <- getGlobalRdrEnv
2136 let occIO = lookupOccEnv rdrEnv (mkOccName tcName ty)
2137 case occIO of
2138 Just [n] -> do
2139 let name = gre_name n
2140 ghciClass <- tcLookupClass ghciIoClassName
2141 userTyCon <- tcLookupTyCon name
2142 let userTy = mkTyConApp userTyCon []
2143 _ <- tcLookupInstance ghciClass [userTy]
2144 return name
2145
2146 Just _ -> failWithTc $ text "Ambiguous type!"
2147 Nothing -> failWithTc $ text ("Can't find type:" ++ ty)
2148
2149 -- | How should we infer a type? See Note [TcRnExprMode]
2150 data TcRnExprMode = TM_Inst -- ^ Instantiate the type fully (:type)
2151 | TM_NoInst -- ^ Do not instantiate the type (:type +v)
2152 | TM_Default -- ^ Default the type eagerly (:type +d)
2153
2154 -- | tcRnExpr just finds the type of an expression
2155 tcRnExpr :: HscEnv
2156 -> TcRnExprMode
2157 -> LHsExpr RdrName
2158 -> IO (Messages, Maybe Type)
2159 tcRnExpr hsc_env mode rdr_expr
2160 = runTcInteractive hsc_env $
2161 do {
2162
2163 (rn_expr, _fvs) <- rnLExpr rdr_expr ;
2164 failIfErrsM ;
2165
2166 -- Now typecheck the expression, and generalise its type
2167 -- it might have a rank-2 type (e.g. :t runST)
2168 uniq <- newUnique ;
2169 let { fresh_it = itName uniq (getLoc rdr_expr)
2170 ; orig = lexprCtOrigin rn_expr } ;
2171 (tclvl, lie, res_ty)
2172 <- pushLevelAndCaptureConstraints $
2173 do { (_tc_expr, expr_ty) <- tcInferSigma rn_expr
2174 ; if inst
2175 then snd <$> deeplyInstantiate orig expr_ty
2176 else return expr_ty } ;
2177
2178 -- Generalise
2179 ((qtvs, dicts, _), lie_top) <- captureTopConstraints $
2180 {-# SCC "simplifyInfer" #-}
2181 simplifyInfer tclvl
2182 infer_mode
2183 [] {- No sig vars -}
2184 [(fresh_it, res_ty)]
2185 lie ;
2186
2187 -- Ignore the dictionary bindings
2188 _ <- perhaps_disable_default_warnings $
2189 simplifyInteractive lie_top ;
2190
2191 let { all_expr_ty = mkInvForAllTys qtvs (mkLamTypes dicts res_ty) } ;
2192 ty <- zonkTcType all_expr_ty ;
2193
2194 -- We normalise type families, so that the type of an expression is the
2195 -- same as of a bound expression (TcBinds.mkInferredPolyId). See Trac
2196 -- #10321 for further discussion.
2197 fam_envs <- tcGetFamInstEnvs ;
2198 -- normaliseType returns a coercion which we discard, so the Role is
2199 -- irrelevant
2200 return (snd (normaliseType fam_envs Nominal ty))
2201 }
2202 where
2203 -- See Note [TcRnExprMode]
2204 (inst, infer_mode, perhaps_disable_default_warnings) = case mode of
2205 TM_Inst -> (True, NoRestrictions, id)
2206 TM_NoInst -> (False, NoRestrictions, id)
2207 TM_Default -> (True, EagerDefaulting, unsetWOptM Opt_WarnTypeDefaults)
2208
2209 --------------------------
2210 tcRnImportDecls :: HscEnv
2211 -> [LImportDecl RdrName]
2212 -> IO (Messages, Maybe GlobalRdrEnv)
2213 -- Find the new chunk of GlobalRdrEnv created by this list of import
2214 -- decls. In contract tcRnImports *extends* the TcGblEnv.
2215 tcRnImportDecls hsc_env import_decls
2216 = runTcInteractive hsc_env $
2217 do { gbl_env <- updGblEnv zap_rdr_env $
2218 tcRnImports hsc_env import_decls
2219 ; return (tcg_rdr_env gbl_env) }
2220 where
2221 zap_rdr_env gbl_env = gbl_env { tcg_rdr_env = emptyGlobalRdrEnv }
2222
2223 -- tcRnType just finds the kind of a type
2224 tcRnType :: HscEnv
2225 -> Bool -- Normalise the returned type
2226 -> LHsType RdrName
2227 -> IO (Messages, Maybe (Type, Kind))
2228 tcRnType hsc_env normalise rdr_type
2229 = runTcInteractive hsc_env $
2230 setXOptM LangExt.PolyKinds $ -- See Note [Kind-generalise in tcRnType]
2231 do { (HsWC { hswc_wcs = wcs, hswc_body = rn_type }, _fvs)
2232 <- rnHsWcType GHCiCtx (mkHsWildCardBndrs rdr_type)
2233 -- The type can have wild cards, but no implicit
2234 -- generalisation; e.g. :kind (T _)
2235 ; failIfErrsM
2236
2237 -- Now kind-check the type
2238 -- It can have any rank or kind
2239 -- First bring into scope any wildcards
2240 ; traceTc "tcRnType" (vcat [ppr wcs, ppr rn_type])
2241 ; (ty, kind) <- solveEqualities $
2242 tcWildCardBinders wcs $ \ _ ->
2243 tcLHsType rn_type
2244
2245 -- Do kind generalisation; see Note [Kind-generalise in tcRnType]
2246 ; kvs <- kindGeneralize kind
2247 ; ty <- zonkTcTypeToType emptyZonkEnv ty
2248
2249 ; ty' <- if normalise
2250 then do { fam_envs <- tcGetFamInstEnvs
2251 ; let (_, ty')
2252 = normaliseType fam_envs Nominal ty
2253 ; return ty' }
2254 else return ty ;
2255
2256 ; return (ty', mkInvForAllTys kvs (typeKind ty')) }
2257
2258 {- Note [TcRnExprMode]
2259 ~~~~~~~~~~~~~~~~~~~~~~
2260 How should we infer a type when a user asks for the type of an expression e
2261 at the GHCi prompt? We offer 3 different possibilities, described below. Each
2262 considers this example, with -fprint-explicit-foralls enabled:
2263
2264 foo :: forall a f b. (Show a, Num b, Foldable f) => a -> f b -> String
2265 :type{,-spec,-def} foo @Int
2266
2267 :type / TM_Inst
2268
2269 In this mode, we report the type that would be inferred if a variable
2270 were assigned to expression e, without applying the monomorphism restriction.
2271 This means we deeply instantiate the type and then regeneralize, as discussed
2272 in #11376.
2273
2274 > :type foo @Int
2275 forall {b} {f :: * -> *}. (Foldable f, Num b) => Int -> f b -> String
2276
2277 Note that the variables and constraints are reordered here, because this
2278 is possible during regeneralization. Also note that the variables are
2279 reported as Inferred instead of Specified.
2280
2281 :type +v / TM_NoInst
2282
2283 This mode is for the benefit of users using TypeApplications. It does no
2284 instantiation whatsoever, sometimes meaning that class constraints are not
2285 solved.
2286
2287 > :type +v foo @Int
2288 forall f b. (Show Int, Num b, Foldable f) => Int -> f b -> String
2289
2290 Note that Show Int is still reported, because the solver never got a chance
2291 to see it.
2292
2293 :type +d / TM_Default
2294
2295 This mode is for the benefit of users who wish to see instantiations of
2296 generalized types, and in particular to instantiate Foldable and Traversable.
2297 In this mode, any type variable that can be defaulted is defaulted. Because
2298 GHCi uses -XExtendedDefaultRules, this means that Foldable and Traversable are
2299 defaulted.
2300
2301 > :type +d foo @Int
2302 Int -> [Integer] -> String
2303
2304 Note that this mode can sometimes lead to a type error, if a type variable is
2305 used with a defaultable class but cannot actually be defaulted:
2306
2307 bar :: (Num a, Monoid a) => a -> a
2308 > :type +d bar
2309 ** error **
2310
2311 The error arises because GHC tries to default a but cannot find a concrete
2312 type in the defaulting list that is both Num and Monoid. (If this list is
2313 modified to include an element that is both Num and Monoid, the defaulting
2314 would succeed, of course.)
2315
2316 Note [Kind-generalise in tcRnType]
2317 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2318 We switch on PolyKinds when kind-checking a user type, so that we will
2319 kind-generalise the type, even when PolyKinds is not otherwise on.
2320 This gives the right default behaviour at the GHCi prompt, where if
2321 you say ":k T", and T has a polymorphic kind, you'd like to see that
2322 polymorphism. Of course. If T isn't kind-polymorphic you won't get
2323 anything unexpected, but the apparent *loss* of polymorphism, for
2324 types that you know are polymorphic, is quite surprising. See Trac
2325 #7688 for a discussion.
2326
2327 Note that the goal is to generalise the *kind of the type*, not
2328 the type itself! Example:
2329 ghci> data T m a = MkT (m a) -- T :: forall . (k -> *) -> k -> *
2330 ghci> :k T
2331 We instantiate T to get (T kappa). We do not want to kind-generalise
2332 that to forall k. T k! Rather we want to take its kind
2333 T kappa :: (kappa -> *) -> kappa -> *
2334 and now kind-generalise that kind, to forall k. (k->*) -> k -> *
2335 (It was Trac #10122 that made me realise how wrong the previous
2336 approach was.) -}
2337
2338
2339 {-
2340 ************************************************************************
2341 * *
2342 tcRnDeclsi
2343 * *
2344 ************************************************************************
2345
2346 tcRnDeclsi exists to allow class, data, and other declarations in GHCi.
2347 -}
2348
2349 tcRnDeclsi :: HscEnv
2350 -> [LHsDecl RdrName]
2351 -> IO (Messages, Maybe TcGblEnv)
2352 tcRnDeclsi hsc_env local_decls
2353 = runTcInteractive hsc_env $
2354 tcRnSrcDecls False local_decls
2355
2356 externaliseAndTidyId :: Module -> Id -> TcM Id
2357 externaliseAndTidyId this_mod id
2358 = do { name' <- externaliseName this_mod (idName id)
2359 ; return (globaliseAndTidyId (setIdName id name')) }
2360
2361
2362 {-
2363 ************************************************************************
2364 * *
2365 More GHCi stuff, to do with browsing and getting info
2366 * *
2367 ************************************************************************
2368 -}
2369
2370 -- | ASSUMES that the module is either in the 'HomePackageTable' or is
2371 -- a package module with an interface on disk. If neither of these is
2372 -- true, then the result will be an error indicating the interface
2373 -- could not be found.
2374 getModuleInterface :: HscEnv -> Module -> IO (Messages, Maybe ModIface)
2375 getModuleInterface hsc_env mod
2376 = runTcInteractive hsc_env $
2377 loadModuleInterface (text "getModuleInterface") mod
2378
2379 tcRnLookupRdrName :: HscEnv -> Located RdrName
2380 -> IO (Messages, Maybe [Name])
2381 -- ^ Find all the Names that this RdrName could mean, in GHCi
2382 tcRnLookupRdrName hsc_env (L loc rdr_name)
2383 = runTcInteractive hsc_env $
2384 setSrcSpan loc $
2385 do { -- If the identifier is a constructor (begins with an
2386 -- upper-case letter), then we need to consider both
2387 -- constructor and type class identifiers.
2388 let rdr_names = dataTcOccs rdr_name
2389 ; names_s <- mapM lookupInfoOccRn rdr_names
2390 ; let names = concat names_s
2391 ; when (null names) (addErrTc (text "Not in scope:" <+> quotes (ppr rdr_name)))
2392 ; return names }
2393
2394 tcRnLookupName :: HscEnv -> Name -> IO (Messages, Maybe TyThing)
2395 tcRnLookupName hsc_env name
2396 = runTcInteractive hsc_env $
2397 tcRnLookupName' name
2398
2399 -- To look up a name we have to look in the local environment (tcl_lcl)
2400 -- as well as the global environment, which is what tcLookup does.
2401 -- But we also want a TyThing, so we have to convert:
2402
2403 tcRnLookupName' :: Name -> TcRn TyThing
2404 tcRnLookupName' name = do
2405 tcthing <- tcLookup name
2406 case tcthing of
2407 AGlobal thing -> return thing
2408 ATcId{tct_id=id} -> return (AnId id)
2409 _ -> panic "tcRnLookupName'"
2410
2411 tcRnGetInfo :: HscEnv
2412 -> Name
2413 -> IO (Messages, Maybe (TyThing, Fixity, [ClsInst], [FamInst]))
2414
2415 -- Used to implement :info in GHCi
2416 --
2417 -- Look up a RdrName and return all the TyThings it might be
2418 -- A capitalised RdrName is given to us in the DataName namespace,
2419 -- but we want to treat it as *both* a data constructor
2420 -- *and* as a type or class constructor;
2421 -- hence the call to dataTcOccs, and we return up to two results
2422 tcRnGetInfo hsc_env name
2423 = runTcInteractive hsc_env $
2424 do { loadUnqualIfaces hsc_env (hsc_IC hsc_env)
2425 -- Load the interface for all unqualified types and classes
2426 -- That way we will find all the instance declarations
2427 -- (Packages have not orphan modules, and we assume that
2428 -- in the home package all relevant modules are loaded.)
2429
2430 ; thing <- tcRnLookupName' name
2431 ; fixity <- lookupFixityRn name
2432 ; (cls_insts, fam_insts) <- lookupInsts thing
2433 ; return (thing, fixity, cls_insts, fam_insts) }
2434
2435 lookupInsts :: TyThing -> TcM ([ClsInst],[FamInst])
2436 lookupInsts (ATyCon tc)
2437 = do { InstEnvs { ie_global = pkg_ie, ie_local = home_ie, ie_visible = vis_mods } <- tcGetInstEnvs
2438 ; (pkg_fie, home_fie) <- tcGetFamInstEnvs
2439 -- Load all instances for all classes that are
2440 -- in the type environment (which are all the ones
2441 -- we've seen in any interface file so far)
2442
2443 -- Return only the instances relevant to the given thing, i.e.
2444 -- the instances whose head contains the thing's name.
2445 ; let cls_insts =
2446 [ ispec -- Search all
2447 | ispec <- instEnvElts home_ie ++ instEnvElts pkg_ie
2448 , instIsVisible vis_mods ispec
2449 , tc_name `elemNameSet` orphNamesOfClsInst ispec ]
2450 ; let fam_insts =
2451 [ fispec
2452 | fispec <- famInstEnvElts home_fie ++ famInstEnvElts pkg_fie
2453 , tc_name `elemNameSet` orphNamesOfFamInst fispec ]
2454 ; return (cls_insts, fam_insts) }
2455 where
2456 tc_name = tyConName tc
2457
2458 lookupInsts _ = return ([],[])
2459
2460 loadUnqualIfaces :: HscEnv -> InteractiveContext -> TcM ()
2461 -- Load the interface for everything that is in scope unqualified
2462 -- This is so that we can accurately report the instances for
2463 -- something
2464 loadUnqualIfaces hsc_env ictxt
2465 = initIfaceTcRn $ do
2466 mapM_ (loadSysInterface doc) (moduleSetElts (mkModuleSet unqual_mods))
2467 where
2468 this_pkg = thisPackage (hsc_dflags hsc_env)
2469
2470 unqual_mods = [ nameModule name
2471 | gre <- globalRdrEnvElts (ic_rn_gbl_env ictxt)
2472 , let name = gre_name gre
2473 , nameIsFromExternalPackage this_pkg name
2474 , isTcOcc (nameOccName name) -- Types and classes only
2475 , unQualOK gre ] -- In scope unqualified
2476 doc = text "Need interface for module whose export(s) are in scope unqualified"
2477
2478
2479
2480 {-
2481 ************************************************************************
2482 * *
2483 Degugging output
2484 * *
2485 ************************************************************************
2486 -}
2487
2488 rnDump :: (Outputable a, Data a) => a -> TcRn ()
2489 -- Dump, with a banner, if -ddump-rn
2490 rnDump rn = do { traceOptTcRn Opt_D_dump_rn (mkDumpDoc "Renamer" (ppr rn))
2491 ; traceOptTcRn Opt_D_dump_rn_ast
2492 (mkDumpDoc "Renamer" (text (showAstData NoBlankSrcSpan rn))) }
2493
2494 tcDump :: TcGblEnv -> TcRn ()
2495 tcDump env
2496 = do { dflags <- getDynFlags ;
2497
2498 -- Dump short output if -ddump-types or -ddump-tc
2499 when (dopt Opt_D_dump_types dflags || dopt Opt_D_dump_tc dflags)
2500 (printForUserTcRn short_dump) ;
2501
2502 -- Dump bindings if -ddump-tc
2503 traceOptTcRn Opt_D_dump_tc (mkDumpDoc "Typechecker" full_dump);
2504
2505 -- Dump bindings as an hsSyn AST if -ddump-tc-ast
2506 traceOptTcRn Opt_D_dump_tc_ast (mkDumpDoc "Typechecker" ast_dump)
2507 }
2508 where
2509 short_dump = pprTcGblEnv env
2510 full_dump = pprLHsBinds (tcg_binds env)
2511 -- NB: foreign x-d's have undefined's in their types;
2512 -- hence can't show the tc_fords
2513 ast_dump = text (showAstData NoBlankSrcSpan (tcg_binds env))
2514
2515 -- It's unpleasant having both pprModGuts and pprModDetails here
2516 pprTcGblEnv :: TcGblEnv -> SDoc
2517 pprTcGblEnv (TcGblEnv { tcg_type_env = type_env,
2518 tcg_insts = insts,
2519 tcg_fam_insts = fam_insts,
2520 tcg_rules = rules,
2521 tcg_vects = vects,
2522 tcg_imports = imports })
2523 = vcat [ ppr_types type_env
2524 , ppr_tycons fam_insts type_env
2525 , ppr_insts insts
2526 , ppr_fam_insts fam_insts
2527 , vcat (map ppr rules)
2528 , vcat (map ppr vects)
2529 , text "Dependent modules:" <+>
2530 pprUDFM (imp_dep_mods imports) ppr
2531 , text "Dependent packages:" <+>
2532 ppr (S.toList $ imp_dep_pkgs imports)]
2533 where -- The use of sortBy is just to reduce unnecessary
2534 -- wobbling in testsuite output
2535
2536 ppr_types :: TypeEnv -> SDoc
2537 ppr_types type_env = sdocWithPprDebug $ \dbg ->
2538 let
2539 ids = [id | id <- typeEnvIds type_env, want_sig id]
2540 want_sig id | dbg
2541 = True
2542 | otherwise
2543 = isExternalName (idName id) &&
2544 (not (isDerivedOccName (getOccName id)))
2545 -- Top-level user-defined things have External names.
2546 -- Suppress internally-generated things unless -dppr-debug
2547 in
2548 text "TYPE SIGNATURES" $$ nest 2 (ppr_sigs ids)
2549
2550 ppr_tycons :: [FamInst] -> TypeEnv -> SDoc
2551 ppr_tycons fam_insts type_env = sdocWithPprDebug $ \dbg ->
2552 let
2553 fi_tycons = famInstsRepTyCons fam_insts
2554 tycons = [tycon | tycon <- typeEnvTyCons type_env, want_tycon tycon]
2555 want_tycon tycon | dbg = True
2556 | otherwise = not (isImplicitTyCon tycon) &&
2557 isExternalName (tyConName tycon) &&
2558 not (tycon `elem` fi_tycons)
2559 in
2560 vcat [ text "TYPE CONSTRUCTORS"
2561 , nest 2 (ppr_tydecls tycons)
2562 , text "COERCION AXIOMS"
2563 , nest 2 (vcat (map pprCoAxiom (typeEnvCoAxioms type_env))) ]
2564
2565 ppr_insts :: [ClsInst] -> SDoc
2566 ppr_insts [] = empty
2567 ppr_insts ispecs = text "INSTANCES" $$ nest 2 (pprInstances ispecs)
2568
2569 ppr_fam_insts :: [FamInst] -> SDoc
2570 ppr_fam_insts [] = empty
2571 ppr_fam_insts fam_insts =
2572 text "FAMILY INSTANCES" $$ nest 2 (pprFamInsts fam_insts)
2573
2574 ppr_sigs :: [Var] -> SDoc
2575 ppr_sigs ids
2576 -- Print type signatures; sort by OccName
2577 = vcat (map ppr_sig (sortBy (comparing getOccName) ids))
2578 where
2579 ppr_sig id = hang (ppr id <+> dcolon) 2 (ppr (tidyTopType (idType id)))
2580
2581 ppr_tydecls :: [TyCon] -> SDoc
2582 ppr_tydecls tycons
2583 -- Print type constructor info for debug purposes
2584 -- Sort by OccName to reduce unnecessary changes
2585 = vcat [ ppr (tyThingToIfaceDecl (ATyCon tc))
2586 | tc <- sortBy (comparing getOccName) tycons ]
2587 -- The Outputable instance for IfaceDecl uses
2588 -- showToIface, which is what we want here, whereas
2589 -- pprTyThing uses ShowSome.
2590
2591 {-
2592 ********************************************************************************
2593
2594 Type Checker Plugins
2595
2596 ********************************************************************************
2597 -}
2598
2599 withTcPlugins :: HscEnv -> TcM a -> TcM a
2600 withTcPlugins hsc_env m =
2601 do plugins <- liftIO (loadTcPlugins hsc_env)
2602 case plugins of
2603 [] -> m -- Common fast case
2604 _ -> do ev_binds_var <- newTcEvBinds
2605 (solvers,stops) <- unzip `fmap` mapM (startPlugin ev_binds_var) plugins
2606 -- This ensures that tcPluginStop is called even if a type
2607 -- error occurs during compilation (Fix of #10078)
2608 eitherRes <- tryM $ do
2609 updGblEnv (\e -> e { tcg_tc_plugins = solvers }) m
2610 mapM_ (flip runTcPluginM ev_binds_var) stops
2611 case eitherRes of
2612 Left _ -> failM
2613 Right res -> return res
2614 where
2615 startPlugin ev_binds_var (TcPlugin start solve stop) =
2616 do s <- runTcPluginM start ev_binds_var
2617 return (solve s, stop s)
2618
2619 loadTcPlugins :: HscEnv -> IO [TcPlugin]
2620 #ifndef GHCI
2621 loadTcPlugins _ = return []
2622 #else
2623 loadTcPlugins hsc_env =
2624 do named_plugins <- loadPlugins hsc_env
2625 return $ catMaybes $ map load_plugin named_plugins
2626 where
2627 load_plugin (_, plug, opts) = tcPlugin plug opts
2628 #endif