Disable PVP warnings temporarily.
[ghc.git] / compiler / typecheck / TcBackpack.hs
1 {-# LANGUAGE CPP #-}
2 {-# LANGUAGE LambdaCase #-}
3 {-# LANGUAGE NondecreasingIndentation #-}
4 {-# LANGUAGE GeneralizedNewtypeDeriving #-}
5 {-# LANGUAGE ScopedTypeVariables #-}
6 module TcBackpack (
7 findExtraSigImports',
8 findExtraSigImports,
9 implicitRequirements',
10 implicitRequirements,
11 checkUnitId,
12 tcRnCheckUnitId,
13 tcRnMergeSignatures,
14 mergeSignatures,
15 tcRnInstantiateSignature,
16 instantiateSignature,
17 ) where
18
19 import BasicTypes (defaultFixity)
20 import Packages
21 import TcRnExports
22 import DynFlags
23 import HsSyn
24 import RdrName
25 import TcRnMonad
26 import TcTyDecls
27 import InstEnv
28 import FamInstEnv
29 import Inst
30 import TcIface
31 import TcMType
32 import TcType
33 import TcSimplify
34 import LoadIface
35 import RnNames
36 import ErrUtils
37 import Id
38 import Module
39 import Name
40 import NameEnv
41 import NameSet
42 import Avail
43 import SrcLoc
44 import HscTypes
45 import Outputable
46 import Type
47 import FastString
48 import RnEnv
49 import Maybes
50 import TcEnv
51 import Var
52 import IfaceSyn
53 import PrelNames
54 import qualified Data.Map as Map
55
56 import Finder
57 import UniqDSet
58 import NameShape
59 import TcErrors
60 import TcUnify
61 import RnModIface
62 import Util
63
64 import Control.Monad
65 import Data.List (find, foldl')
66
67 import {-# SOURCE #-} TcRnDriver
68
69 #include "HsVersions.h"
70
71 fixityMisMatch :: TyThing -> Fixity -> Fixity -> SDoc
72 fixityMisMatch real_thing real_fixity sig_fixity =
73 vcat [ppr real_thing <+> text "has conflicting fixities in the module",
74 text "and its hsig file",
75 text "Main module:" <+> ppr_fix real_fixity,
76 text "Hsig file:" <+> ppr_fix sig_fixity]
77 where
78 ppr_fix f =
79 ppr f <+>
80 (if f == defaultFixity
81 then parens (text "default")
82 else empty)
83
84 checkHsigDeclM :: ModIface -> TyThing -> TyThing -> TcRn ()
85 checkHsigDeclM sig_iface sig_thing real_thing = do
86 let name = getName real_thing
87 -- TODO: Distinguish between signature merging and signature
88 -- implementation cases.
89 checkBootDeclM False sig_thing real_thing
90 real_fixity <- lookupFixityRn name
91 let sig_fixity = case mi_fix_fn sig_iface (occName name) of
92 Nothing -> defaultFixity
93 Just f -> f
94 when (real_fixity /= sig_fixity) $
95 addErrAt (nameSrcSpan name)
96 (fixityMisMatch real_thing real_fixity sig_fixity)
97
98 -- | Given a 'ModDetails' of an instantiated signature (note that the
99 -- 'ModDetails' must be knot-tied consistently with the actual implementation)
100 -- and a 'GlobalRdrEnv' constructed from the implementor of this interface,
101 -- verify that the actual implementation actually matches the original
102 -- interface.
103 --
104 -- Note that it is already assumed that the implementation *exports*
105 -- a sufficient set of entities, since otherwise the renaming and then
106 -- typechecking of the signature 'ModIface' would have failed.
107 checkHsigIface :: TcGblEnv -> GlobalRdrEnv -> ModIface -> ModDetails -> TcRn ()
108 checkHsigIface tcg_env gr sig_iface
109 ModDetails { md_insts = sig_insts, md_fam_insts = sig_fam_insts,
110 md_types = sig_type_env, md_exports = sig_exports } = do
111 traceTc "checkHsigIface" $ vcat
112 [ ppr sig_type_env, ppr sig_insts, ppr sig_exports ]
113 mapM_ check_export (map availName sig_exports)
114 unless (null sig_fam_insts) $
115 panic ("TcRnDriver.checkHsigIface: Cannot handle family " ++
116 "instances in hsig files yet...")
117 -- Delete instances so we don't look them up when
118 -- checking instance satisfiability
119 -- TODO: this should not be necessary
120 tcg_env <- getGblEnv
121 setGblEnv tcg_env { tcg_inst_env = emptyInstEnv,
122 tcg_fam_inst_env = emptyFamInstEnv,
123 tcg_insts = [],
124 tcg_fam_insts = [] } $ do
125 mapM_ check_inst sig_insts
126 failIfErrsM
127 where
128 -- NB: the Names in sig_type_env are bogus. Let's say we have H.hsig
129 -- in package p that defines T; and we implement with himpl:H. Then the
130 -- Name is p[himpl:H]:H.T, NOT himplH:H.T. That's OK but we just
131 -- have to look up the right name.
132 sig_type_occ_env = mkOccEnv
133 . map (\t -> (nameOccName (getName t), t))
134 $ nameEnvElts sig_type_env
135 dfun_names = map getName sig_insts
136 check_export name
137 -- Skip instances, we'll check them later
138 -- TODO: Actually this should never happen, because DFuns are
139 -- never exported...
140 | name `elem` dfun_names = return ()
141 -- See if we can find the type directly in the hsig ModDetails
142 -- TODO: need to special case wired in names
143 | Just sig_thing <- lookupOccEnv sig_type_occ_env (nameOccName name) = do
144 -- NB: We use tcLookupImported_maybe because we want to EXCLUDE
145 -- tcg_env (TODO: but maybe this isn't relevant anymore).
146 r <- tcLookupImported_maybe name
147 case r of
148 Failed err -> addErr err
149 Succeeded real_thing -> checkHsigDeclM sig_iface sig_thing real_thing
150
151 -- The hsig did NOT define this function; that means it must
152 -- be a reexport. In this case, make sure the 'Name' of the
153 -- reexport matches the 'Name exported here.
154 | [GRE { gre_name = name' }] <- lookupGlobalRdrEnv gr (nameOccName name) =
155 when (name /= name') $ do
156 -- See Note [Error reporting bad reexport]
157 -- TODO: Actually this error swizzle doesn't work
158 let p (L _ ie) = name `elem` ieNames ie
159 loc = case tcg_rn_exports tcg_env of
160 Just es | Just e <- find p es
161 -- TODO: maybe we can be a little more
162 -- precise here and use the Located
163 -- info for the *specific* name we matched.
164 -> getLoc e
165 _ -> nameSrcSpan name
166 dflags <- getDynFlags
167 addErrAt loc
168 (badReexportedBootThing dflags False name name')
169 -- This should actually never happen, but whatever...
170 | otherwise =
171 addErrAt (nameSrcSpan name)
172 (missingBootThing False name "exported by")
173
174 -- Note [Error reporting bad reexport]
175 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
176 -- NB: You want to be a bit careful about what location you report on reexports.
177 -- If the name was declared in the hsig file, 'nameSrcSpan name' is indeed the
178 -- correct source location. However, if it was *reexported*, obviously the name
179 -- is not going to have the right location. In this case, we need to grovel in
180 -- tcg_rn_exports to figure out where the reexport came from.
181
182
183
184 -- | Checks if a 'ClsInst' is "defined". In general, for hsig files we can't
185 -- assume that the implementing file actually implemented the instances (they
186 -- may be reexported from elsewhere). Where should we look for the instances?
187 -- We do the same as we would otherwise: consult the EPS. This isn't perfect
188 -- (we might conclude the module exports an instance when it doesn't, see
189 -- #9422), but we will never refuse to compile something.
190 check_inst :: ClsInst -> TcM ()
191 check_inst sig_inst = do
192 -- TODO: This could be very well generalized to support instance
193 -- declarations in boot files.
194 tcg_env <- getGblEnv
195 -- NB: Have to tug on the interface, not necessarily
196 -- tugged... but it didn't work?
197 mapM_ tcLookupImported_maybe (nameSetElemsStable (orphNamesOfClsInst sig_inst))
198 -- Based off of 'simplifyDeriv'
199 let ty = idType (instanceDFunId sig_inst)
200 skol_info = InstSkol
201 -- Based off of tcSplitDFunTy
202 (tvs, theta, pred) =
203 case tcSplitForAllTys ty of { (tvs, rho) ->
204 case splitFunTys rho of { (theta, pred) ->
205 (tvs, theta, pred) }}
206 origin = InstProvidedOrigin (tcg_semantic_mod tcg_env) sig_inst
207 (skol_subst, tvs_skols) <- tcInstSkolTyVars tvs -- Skolemize
208 (cts, tclvl) <- pushTcLevelM $ do
209 wanted <- newWanted origin
210 (Just TypeLevel)
211 (substTy skol_subst pred)
212 givens <- forM theta $ \given -> do
213 loc <- getCtLocM origin (Just TypeLevel)
214 let given_pred = substTy skol_subst given
215 new_ev <- newEvVar given_pred
216 return CtGiven { ctev_pred = given_pred
217 -- Doesn't matter, make something up
218 , ctev_evar = new_ev
219 , ctev_loc = loc
220 }
221 return $ wanted : givens
222 unsolved <- simplifyWantedsTcM cts
223
224 (implic, _) <- buildImplicationFor tclvl skol_info tvs_skols [] unsolved
225 reportAllUnsolved (mkImplicWC implic)
226
227 -- | Return this list of requirement interfaces that need to be merged
228 -- to form @mod_name@, or @[]@ if this is not a requirement.
229 requirementMerges :: DynFlags -> ModuleName -> [IndefModule]
230 requirementMerges dflags mod_name =
231 fromMaybe [] (Map.lookup mod_name (requirementContext (pkgState dflags)))
232
233 -- | For a module @modname@ of type 'HscSource', determine the list
234 -- of extra "imports" of other requirements which should be considered part of
235 -- the import of the requirement, because it transitively depends on those
236 -- requirements by imports of modules from other packages. The situation
237 -- is something like this:
238 --
239 -- unit p where
240 -- signature A
241 -- signature B
242 -- import A
243 --
244 -- unit q where
245 -- dependency p[A=<A>,B=<B>]
246 -- signature A
247 -- signature B
248 --
249 -- Although q's B does not directly import A, we still have to make sure we
250 -- process A first, because the merging process will cause B to indirectly
251 -- import A. This function finds the TRANSITIVE closure of all such imports
252 -- we need to make.
253 findExtraSigImports' :: HscEnv
254 -> HscSource
255 -> ModuleName
256 -> IO (UniqDSet ModuleName)
257 findExtraSigImports' hsc_env HsigFile modname =
258 fmap unionManyUniqDSets (forM reqs $ \(IndefModule iuid mod_name) ->
259 (initIfaceLoad hsc_env
260 . withException
261 $ moduleFreeHolesPrecise (text "findExtraSigImports")
262 (mkModule (IndefiniteUnitId iuid) mod_name)))
263 where
264 reqs = requirementMerges (hsc_dflags hsc_env) modname
265
266 findExtraSigImports' _ _ _ = return emptyUniqDSet
267
268 -- | 'findExtraSigImports', but in a convenient form for "GhcMake" and
269 -- "TcRnDriver".
270 findExtraSigImports :: HscEnv -> HscSource -> ModuleName
271 -> IO [(Maybe FastString, Located ModuleName)]
272 findExtraSigImports hsc_env hsc_src modname = do
273 extra_requirements <- findExtraSigImports' hsc_env hsc_src modname
274 return [ (Nothing, noLoc mod_name)
275 | mod_name <- uniqDSetToList extra_requirements ]
276
277 -- A version of 'implicitRequirements'' which is more friendly
278 -- for "GhcMake" and "TcRnDriver".
279 implicitRequirements :: HscEnv
280 -> [(Maybe FastString, Located ModuleName)]
281 -> IO [(Maybe FastString, Located ModuleName)]
282 implicitRequirements hsc_env normal_imports
283 = do mns <- implicitRequirements' hsc_env normal_imports
284 return [ (Nothing, noLoc mn) | mn <- mns ]
285
286 -- Given a list of 'import M' statements in a module, figure out
287 -- any extra implicit requirement imports they may have. For
288 -- example, if they 'import M' and M resolves to p[A=<B>], then
289 -- they actually also import the local requirement B.
290 implicitRequirements' :: HscEnv
291 -> [(Maybe FastString, Located ModuleName)]
292 -> IO [ModuleName]
293 implicitRequirements' hsc_env normal_imports
294 = fmap concat $
295 forM normal_imports $ \(mb_pkg, L _ imp) -> do
296 found <- findImportedModule hsc_env imp mb_pkg
297 case found of
298 Found _ mod | thisPackage dflags /= moduleUnitId mod ->
299 return (uniqDSetToList (moduleFreeHoles mod))
300 _ -> return []
301 where dflags = hsc_dflags hsc_env
302
303 -- | Given a 'UnitId', make sure it is well typed. This is because
304 -- unit IDs come from Cabal, which does not know if things are well-typed or
305 -- not; a component may have been filled with implementations for the holes
306 -- that don't actually fulfill the requirements.
307 --
308 -- INVARIANT: the UnitId is NOT a InstalledUnitId
309 checkUnitId :: UnitId -> TcM ()
310 checkUnitId uid = do
311 case splitUnitIdInsts uid of
312 (_, Just indef) ->
313 let insts = indefUnitIdInsts indef in
314 forM_ insts $ \(mod_name, mod) ->
315 -- NB: direct hole instantiations are well-typed by construction
316 -- (because we FORCE things to be merged in), so don't check them
317 when (not (isHoleModule mod)) $ do
318 checkUnitId (moduleUnitId mod)
319 _ <- mod `checkImplements` IndefModule indef mod_name
320 return ()
321 _ -> return () -- if it's hashed, must be well-typed
322
323 -- | Top-level driver for signature instantiation (run when compiling
324 -- an @hsig@ file.)
325 tcRnCheckUnitId ::
326 HscEnv -> UnitId ->
327 IO (Messages, Maybe ())
328 tcRnCheckUnitId hsc_env uid =
329 withTiming (pure dflags)
330 (text "Check unit id" <+> ppr uid)
331 (const ()) $
332 initTc hsc_env
333 HsigFile -- bogus
334 False
335 mAIN -- bogus
336 (realSrcLocSpan (mkRealSrcLoc (fsLit loc_str) 0 0)) -- bogus
337 $ checkUnitId uid
338 where
339 dflags = hsc_dflags hsc_env
340 loc_str = "Command line argument: -unit-id " ++ showSDoc dflags (ppr uid)
341
342 -- TODO: Maybe lcl_iface0 should be pre-renamed to the right thing? Unclear...
343
344 -- | Top-level driver for signature merging (run after typechecking
345 -- an @hsig@ file).
346 tcRnMergeSignatures :: HscEnv -> RealSrcSpan -> HsParsedModule -> ModIface
347 -> IO (Messages, Maybe TcGblEnv)
348 tcRnMergeSignatures hsc_env real_loc hsmod iface =
349 withTiming (pure dflags)
350 (text "Signature merging" <+> brackets (ppr this_mod))
351 (const ()) $
352 initTc hsc_env HsigFile False this_mod real_loc $
353 mergeSignatures hsmod iface
354 where
355 dflags = hsc_dflags hsc_env
356 this_mod = mi_module iface
357
358 thinModIface :: [AvailInfo] -> ModIface -> ModIface
359 thinModIface avails iface =
360 iface {
361 mi_exports = avails,
362 -- mi_fixities = ...,
363 -- mi_warns = ...,
364 -- mi_anns = ...,
365 -- TODO: The use of nameOccName here is a bit dodgy, because
366 -- perhaps there might be two IfaceTopBndr that are the same
367 -- OccName but different Name. Requires better understanding
368 -- of invariants here.
369 mi_decls = exported_decls ++ non_exported_decls ++ dfun_decls
370 -- mi_insts = ...,
371 -- mi_fam_insts = ...,
372 }
373 where
374 decl_pred occs decl = nameOccName (ifName decl) `elemOccSet` occs
375 filter_decls occs = filter (decl_pred occs . snd) (mi_decls iface)
376
377 exported_occs = mkOccSet [ occName n
378 | a <- avails
379 , n <- availNames a ]
380 exported_decls = filter_decls exported_occs
381
382 non_exported_occs = mkOccSet [ occName n
383 | (_, d) <- exported_decls
384 , n <- ifaceDeclNeverExportedRefs d ]
385 non_exported_decls = filter_decls non_exported_occs
386
387 dfun_pred IfaceId{ ifIdDetails = IfDFunId } = True
388 dfun_pred _ = False
389 dfun_decls = filter (dfun_pred . snd) (mi_decls iface)
390
391 -- | The list of 'Name's of *non-exported* 'IfaceDecl's which this
392 -- 'IfaceDecl' may refer to. A non-exported 'IfaceDecl' should be kept
393 -- after thinning if an *exported* 'IfaceDecl' (or 'mi_insts', perhaps)
394 -- refers to it; we can't decide to keep it by looking at the exports
395 -- of a module after thinning. Keep this synchronized with
396 -- 'rnIfaceDecl'.
397 ifaceDeclNeverExportedRefs :: IfaceDecl -> [Name]
398 ifaceDeclNeverExportedRefs d@IfaceFamily{} =
399 case ifFamFlav d of
400 IfaceClosedSynFamilyTyCon (Just (n, _))
401 -> [n]
402 _ -> []
403 ifaceDeclNeverExportedRefs _ = []
404
405
406 -- Note [Blank hsigs for all requirements]
407 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
408 -- One invariant that a client of GHC must uphold is that there
409 -- must be an hsig file for every requirement (according to
410 -- @-this-unit-id@); this ensures that for every interface
411 -- file (hi), there is a source file (hsig), which helps grease
412 -- the wheels of recompilation avoidance which assumes that
413 -- source files always exist.
414
415 {-
416 inheritedSigPvpWarning :: WarningTxt
417 inheritedSigPvpWarning =
418 WarningTxt (noLoc NoSourceText) [noLoc (StringLiteral NoSourceText (fsLit msg))]
419 where
420 msg = "Inherited requirements from non-signature libraries (libraries " ++
421 "with modules) should not be used, as this mode of use is not " ++
422 "compatible with PVP-style version bounds. Instead, copy the " ++
423 "declaration to the local hsig file or move the signature to a " ++
424 "library of its own and add that library as a dependency."
425 -}
426
427 -- Note [Handling never-exported TyThings under Backpack]
428 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
429 -- DEFINITION: A "never-exported TyThing" is a TyThing whose 'Name' will
430 -- never be mentioned in the export list of a module (mi_avails).
431 -- Unlike implicit TyThings (Note [Implicit TyThings]), non-exported
432 -- TyThings DO have a standalone IfaceDecl declaration in their
433 -- interface file.
434 --
435 -- Originally, Backpack was designed under the assumption that anything
436 -- you could declare in a module could also be exported; thus, merging
437 -- the export lists of two signatures is just merging the declarations
438 -- of two signatures writ small. Of course, in GHC Haskell, there are a
439 -- few important things which are not explicitly exported but still can
440 -- be used: in particular, dictionary functions for instances and
441 -- coercion axioms for type families also count.
442 --
443 -- When handling these non-exported things, there two primary things
444 -- we need to watch out for:
445 --
446 -- * Signature matching/merging is done by comparing each
447 -- of the exported entities of a signature and a module. These exported
448 -- entities may refer to non-exported TyThings which must be tested for
449 -- consistency. For example, an instance (ClsInst) will refer to a
450 -- non-exported DFunId. In this case, 'checkBootDeclM' directly compares the
451 -- embedded 'DFunId' in 'is_dfun'.
452 --
453 -- For this to work at all, we must ensure that pointers in 'is_dfun' refer
454 -- to DISTINCT 'DFunId's, even though the 'Name's (may) be the same.
455 -- Unfortunately, this is the OPPOSITE of how we treat most other references
456 -- to 'Name's, so this case needs to be handled specially.
457 --
458 -- The details are in the documentation for 'typecheckIfacesForMerging'.
459 -- and the Note [Resolving never-exported Names in TcIface].
460 --
461 -- * When we rename modules and signatures, we use the export lists to
462 -- decide how the declarations should be renamed. However, this
463 -- means we don't get any guidance for how to rename non-exported
464 -- entities. Fortunately, we only need to rename these entities
465 -- *consistently*, so that 'typecheckIfacesForMerging' can wire them
466 -- up as needed.
467 --
468 -- The details are in Note [rnIfaceNeverExported] in 'RnModIface'.
469 --
470 -- The root cause for all of these complications is the fact that these
471 -- logically "implicit" entities are defined indirectly in an interface
472 -- file. #13151 gives a proposal to make these *truly* implicit.
473
474 merge_msg :: ModuleName -> [IndefModule] -> SDoc
475 merge_msg mod_name [] =
476 text "while checking the local signature" <+> ppr mod_name <+>
477 text "for consistency"
478 merge_msg mod_name reqs =
479 hang (text "while merging the signatures from" <> colon)
480 2 (vcat [ bullet <+> ppr req | req <- reqs ] $$
481 bullet <+> text "...and the local signature for" <+> ppr mod_name)
482
483 -- | Given a local 'ModIface', merge all inherited requirements
484 -- from 'requirementMerges' into this signature, producing
485 -- a final 'TcGblEnv' that matches the local signature and
486 -- all required signatures.
487 mergeSignatures :: HsParsedModule -> ModIface -> TcRn TcGblEnv
488 mergeSignatures hsmod lcl_iface0 = do
489 -- The lcl_iface0 is the ModIface for the local hsig
490 -- file, which is guaranteed to exist, see
491 -- Note [Blank hsigs for all requirements]
492 hsc_env <- getTopEnv
493 dflags <- getDynFlags
494 tcg_env <- getGblEnv
495 let outer_mod = tcg_mod tcg_env
496 inner_mod = tcg_semantic_mod tcg_env
497 mb_exports = hsmodExports (unLoc (hpm_module hsmod))
498 mod_name = moduleName (tcg_mod tcg_env)
499
500 -- STEP 1: Figure out all of the external signature interfaces
501 -- we are going to merge in.
502 let reqs = requirementMerges dflags mod_name
503
504 addErrCtxt (merge_msg mod_name reqs) $ do
505
506 -- STEP 2: Read in the RAW forms of all of these interfaces
507 ireq_ifaces0 <- forM reqs $ \(IndefModule iuid mod_name) ->
508 fmap fst
509 . withException
510 . flip (findAndReadIface (text "mergeSignatures")) False
511 $ fst (splitModuleInsts (mkModule (IndefiniteUnitId iuid) mod_name))
512
513 -- STEP 3: Get the unrenamed exports of all these interfaces,
514 -- thin it according to the export list, and do shaping on them.
515 let extend_ns nsubst as = liftIO $ extendNameShape hsc_env nsubst as
516 -- This function gets run on every inherited interface, and
517 -- it's responsible for:
518 --
519 -- 1. Merging the exports of the interface into @nsubst@,
520 -- 2. Adding these exports to the "OK to import" set (@oks@)
521 -- if they came from a package with no exposed modules
522 -- (this means we won't report a PVP error in this case), and
523 -- 3. Thinning the interface according to an explicit export
524 -- list.
525 --
526 gen_subst (nsubst,oks,ifaces) (imod@(IndefModule iuid _), ireq_iface) = do
527 let insts = indefUnitIdInsts iuid
528 as1 <- tcRnModExports insts ireq_iface
529 let inst_uid = fst (splitUnitIdInsts (IndefiniteUnitId iuid))
530 pkg = getInstalledPackageDetails dflags inst_uid
531 rdr_env = mkGlobalRdrEnv (gresFromAvails Nothing as1)
532 (thinned_iface, as2) <- case mb_exports of
533 Just (L loc _)
534 | null (exposedModules pkg) -> setSrcSpan loc $ do
535 -- Suppress missing errors; we'll pick em up
536 -- when we test exports on the final thing
537 (msgs, mb_r) <- tryTc $
538 setGblEnv tcg_env {
539 tcg_rdr_env = rdr_env
540 } $ exports_from_avail mb_exports rdr_env
541 (tcg_imports tcg_env) (tcg_semantic_mod tcg_env)
542 case mb_r of
543 Just (_, as2) -> return (thinModIface as2 ireq_iface, as2)
544 Nothing -> addMessages msgs >> failM
545 _ -> return (ireq_iface, as1)
546 let oks' | null (exposedModules pkg)
547 = extendOccSetList oks (exportOccs as2)
548 | otherwise
549 = oks
550 mb_r <- extend_ns nsubst as2
551 case mb_r of
552 Left err -> failWithTc err
553 Right nsubst' -> return (nsubst',oks',(imod, thinned_iface):ifaces)
554 nsubst0 = mkNameShape (moduleName inner_mod) (mi_exports lcl_iface0)
555 ok_to_use0 = mkOccSet (exportOccs (mi_exports lcl_iface0))
556 -- Process each interface, getting the thinned interfaces as well as
557 -- the final, full set of exports @nsubst@ and the exports which are
558 -- "ok to use" (we won't attach 'inheritedSigPvpWarning' to them.)
559 (nsubst, ok_to_use, rev_thinned_ifaces)
560 <- foldM gen_subst (nsubst0, ok_to_use0, []) (zip reqs ireq_ifaces0)
561 let thinned_ifaces = reverse rev_thinned_ifaces
562 exports = nameShapeExports nsubst
563 rdr_env = mkGlobalRdrEnv (gresFromAvails Nothing exports)
564 _warn_occs = filter (not . (`elemOccSet` ok_to_use)) (exportOccs exports)
565 warns = NoWarnings
566 {-
567 -- TODO: Warnings are transitive, but this is not what we want here:
568 -- if a module reexports an entity from a signature, that should be OK.
569 -- Not supported in current warning framework
570 warns | null warn_occs = NoWarnings
571 | otherwise = WarnSome $ map (\o -> (o, inheritedSigPvpWarning)) warn_occs
572 -}
573 setGblEnv tcg_env {
574 tcg_rdr_env = rdr_env,
575 tcg_exports = exports,
576 tcg_dus = usesOnly (availsToNameSetWithSelectors exports),
577 tcg_warns = warns
578 } $ do
579 tcg_env <- getGblEnv
580
581 -- Make sure we didn't refer to anything that doesn't actually exist
582 (mb_lies, _) <- exports_from_avail mb_exports rdr_env
583 (tcg_imports tcg_env) (tcg_semantic_mod tcg_env)
584
585 -- If you tried to explicitly export an identifier that has a warning
586 -- attached to it, that's probably a mistake. Warn about it.
587 case mb_lies of
588 Nothing -> return ()
589 Just lies ->
590 forM_ (concatMap (\(L loc x) -> map (L loc) (ieNames x)) lies) $ \(L loc n) ->
591 setSrcSpan loc $
592 unless (nameOccName n `elemOccSet` ok_to_use) $
593 addWarn NoReason $ vcat [
594 text "Exported identifier" <+> quotes (ppr n) <+> text "will cause warnings if used.",
595 parens (text "To suppress this warning, remove" <+> quotes (ppr n) <+> text "from the export list of this signature.")
596 ]
597
598 failIfErrsM
599
600 -- STEP 4: Rename the interfaces
601 ext_ifaces <- forM thinned_ifaces $ \((IndefModule iuid _), ireq_iface) ->
602 tcRnModIface (indefUnitIdInsts iuid) (Just nsubst) ireq_iface
603 lcl_iface <- tcRnModIface (thisUnitIdInsts dflags) (Just nsubst) lcl_iface0
604 let ifaces = lcl_iface : ext_ifaces
605
606 -- STEP 4.1: Merge fixities (we'll verify shortly) tcg_fix_env
607 let fix_env = mkNameEnv [ (gre_name rdr_elt, FixItem occ f)
608 | (occ, f) <- concatMap mi_fixities ifaces
609 , rdr_elt <- lookupGlobalRdrEnv rdr_env occ ]
610
611 -- STEP 5: Typecheck the interfaces
612 let type_env_var = tcg_type_env_var tcg_env
613
614 -- typecheckIfacesForMerging does two things:
615 -- 1. It merges the all of the ifaces together, and typechecks the
616 -- result to type_env.
617 -- 2. It typechecks each iface individually, but with their 'Name's
618 -- resolving to the merged type_env from (1).
619 -- See typecheckIfacesForMerging for more details.
620 (type_env, detailss) <- initIfaceTcRn $
621 typecheckIfacesForMerging inner_mod ifaces type_env_var
622 let infos = zip ifaces detailss
623
624 -- Test for cycles
625 checkSynCycles (thisPackage dflags) (typeEnvTyCons type_env) []
626
627 -- NB on type_env: it contains NO dfuns. DFuns are recorded inside
628 -- detailss, and given a Name that doesn't correspond to anything real. See
629 -- also Note [Signature merging DFuns]
630
631 -- Add the merged type_env to TcGblEnv, so that it gets serialized
632 -- out when we finally write out the interface.
633 --
634 -- NB: Why do we set tcg_tcs/tcg_patsyns/tcg_type_env directly,
635 -- rather than use tcExtendGlobalEnv (the normal method to add newly
636 -- defined types to TcGblEnv?) tcExtendGlobalEnv adds these
637 -- TyThings to 'tcg_type_env_var', which is consulted when
638 -- we read in interfaces to tie the knot. But *these TyThings themselves
639 -- come from interface*, so that would result in deadlock. Don't
640 -- update it!
641 setGblEnv tcg_env {
642 tcg_tcs = typeEnvTyCons type_env,
643 tcg_patsyns = typeEnvPatSyns type_env,
644 tcg_type_env = type_env,
645 tcg_fix_env = fix_env
646 } $ do
647 tcg_env <- getGblEnv
648
649 -- STEP 6: Check for compatibility/merge things
650 tcg_env <- (\x -> foldM x tcg_env infos)
651 $ \tcg_env (iface, details) -> do
652
653 let check_export name
654 | Just sig_thing <- lookupTypeEnv (md_types details) name
655 = case lookupTypeEnv type_env (getName sig_thing) of
656 Just thing -> checkHsigDeclM iface sig_thing thing
657 Nothing -> panic "mergeSignatures: check_export"
658 -- Oops! We're looking for this export but it's
659 -- not actually in the type environment of the signature's
660 -- ModDetails.
661 --
662 -- NB: This case happens because the we're iterating
663 -- over the union of all exports, so some interfaces
664 -- won't have everything. Note that md_exports is nonsense
665 -- (it's the same as exports); maybe we should fix this
666 -- eventually.
667 | otherwise
668 = return ()
669 mapM_ check_export (map availName exports)
670
671 -- Note [Signature merging instances]
672 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
673 -- Merge instances into the global environment. The algorithm here is
674 -- dumb and simple: if an instance has exactly the same DFun type
675 -- (tested by 'memberInstEnv') as an existing instance, we drop it;
676 -- otherwise, we add it even, even if this would cause overlap.
677 --
678 -- Why don't we deduplicate instances with identical heads? There's no
679 -- good choice if they have premises:
680 --
681 -- instance K1 a => K (T a)
682 -- instance K2 a => K (T a)
683 --
684 -- Why not eagerly error in this case? The overlapping head does not
685 -- necessarily mean that the instances are unimplementable: in fact,
686 -- they may be implemented without overlap (if, for example, the
687 -- implementing module has 'instance K (T a)'; both are implemented in
688 -- this case.) The implements test just checks that the wanteds are
689 -- derivable assuming the givens.
690 --
691 -- Still, overlapping instances with hypotheses like above are going
692 -- to be a bad deal, because instance resolution when we're typechecking
693 -- against the merged signature is going to have a bad time when
694 -- there are overlapping heads like this: we never backtrack, so it
695 -- may be difficult to see that a wanted is derivable. For now,
696 -- we hope that we get lucky / the overlapping instances never
697 -- get used, but it is not a very good situation to be in.
698 --
699 let merge_inst (insts, inst_env) inst
700 | memberInstEnv inst_env inst -- test DFun Type equality
701 = (insts, inst_env)
702 | otherwise
703 -- NB: is_dfun_name inst is still nonsense here,
704 -- see Note [Signature merging DFuns]
705 = (inst:insts, extendInstEnv inst_env inst)
706 (insts, inst_env) = foldl' merge_inst
707 (tcg_insts tcg_env, tcg_inst_env tcg_env)
708 (md_insts details)
709 -- This is a HACK to prevent calculateAvails from including imp_mod
710 -- in the listing. We don't want it because a module is NOT
711 -- supposed to include itself in its dep_orphs/dep_finsts. See #13214
712 iface' = iface { mi_orphan = False, mi_finsts = False }
713 avails = plusImportAvails (tcg_imports tcg_env)
714 (calculateAvails dflags iface' False False)
715 return tcg_env {
716 tcg_inst_env = inst_env,
717 tcg_insts = insts,
718 tcg_imports = avails,
719 tcg_merged =
720 if outer_mod == mi_module iface
721 -- Don't add ourselves!
722 then tcg_merged tcg_env
723 else (mi_module iface, mi_mod_hash iface) : tcg_merged tcg_env
724 }
725
726 -- Note [Signature merging DFuns]
727 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
728 -- Once we know all of instances which will be defined by this merged
729 -- signature, we go through each of the DFuns and rename them with a fresh,
730 -- new, unique DFun Name, and add these DFuns to tcg_type_env (thus fixing
731 -- up the "bogus" names that were setup in 'typecheckIfacesForMerging'.
732 --
733 -- We can't do this fixup earlier, because we need a way to identify each
734 -- source DFun (from each of the signatures we are merging in) so that
735 -- when we have a ClsInst, we can pull up the correct DFun to check if
736 -- the types match.
737 --
738 -- See also Note [rnIfaceNeverExported] in RnModIface
739 dfun_insts <- forM (tcg_insts tcg_env) $ \inst -> do
740 n <- newDFunName (is_cls inst) (is_tys inst) (nameSrcSpan (is_dfun_name inst))
741 let dfun = setVarName (is_dfun inst) n
742 return (dfun, inst { is_dfun_name = n, is_dfun = dfun })
743 tcg_env <- return tcg_env {
744 tcg_insts = map snd dfun_insts,
745 tcg_type_env = extendTypeEnvWithIds (tcg_type_env tcg_env) (map fst dfun_insts)
746 }
747
748 return tcg_env
749
750 -- | Top-level driver for signature instantiation (run when compiling
751 -- an @hsig@ file.)
752 tcRnInstantiateSignature ::
753 HscEnv -> Module -> RealSrcSpan ->
754 IO (Messages, Maybe TcGblEnv)
755 tcRnInstantiateSignature hsc_env this_mod real_loc =
756 withTiming (pure dflags)
757 (text "Signature instantiation"<+>brackets (ppr this_mod))
758 (const ()) $
759 initTc hsc_env HsigFile False this_mod real_loc $ instantiateSignature
760 where
761 dflags = hsc_dflags hsc_env
762
763 exportOccs :: [AvailInfo] -> [OccName]
764 exportOccs = concatMap (map occName . availNames)
765
766 impl_msg :: Module -> IndefModule -> SDoc
767 impl_msg impl_mod (IndefModule req_uid req_mod_name) =
768 text "while checking that" <+> ppr impl_mod <+>
769 text "implements signature" <+> ppr req_mod_name <+>
770 text "in" <+> ppr req_uid
771
772 -- | Check if module implements a signature. (The signature is
773 -- always un-hashed, which is why its components are specified
774 -- explicitly.)
775 checkImplements :: Module -> IndefModule -> TcRn TcGblEnv
776 checkImplements impl_mod req_mod@(IndefModule uid mod_name) =
777 addErrCtxt (impl_msg impl_mod req_mod) $ do
778 let insts = indefUnitIdInsts uid
779
780 -- STEP 1: Load the implementing interface, and make a RdrEnv
781 -- for its exports. Also, add its 'ImportAvails' to 'tcg_imports',
782 -- so that we treat all orphan instances it provides as visible
783 -- when we verify that all instances are checked (see #12945), and so that
784 -- when we eventually write out the interface we record appropriate
785 -- dependency information.
786 impl_iface <- initIfaceTcRn $
787 loadSysInterface (text "checkImplements 1") impl_mod
788 let impl_gr = mkGlobalRdrEnv
789 (gresFromAvails Nothing (mi_exports impl_iface))
790 nsubst = mkNameShape (moduleName impl_mod) (mi_exports impl_iface)
791
792 -- Load all the orphans, so the subsequent 'checkHsigIface' sees
793 -- all the instances it needs to
794 loadModuleInterfaces (text "Loading orphan modules (from implementor of hsig)")
795 (dep_orphs (mi_deps impl_iface))
796
797 dflags <- getDynFlags
798 let avails = calculateAvails dflags
799 impl_iface False{- safe -} False{- boot -}
800 fix_env = mkNameEnv [ (gre_name rdr_elt, FixItem occ f)
801 | (occ, f) <- mi_fixities impl_iface
802 , rdr_elt <- lookupGlobalRdrEnv impl_gr occ ]
803 updGblEnv (\tcg_env -> tcg_env {
804 -- Setting tcg_rdr_env to treat all exported entities from
805 -- the implementing module as in scope improves error messages,
806 -- as it reduces the amount of qualification we need. Unfortunately,
807 -- we still end up qualifying references to external modules
808 -- (see bkpfail07 for an example); we'd need to record more
809 -- information in ModIface to solve this.
810 tcg_rdr_env = tcg_rdr_env tcg_env `plusGlobalRdrEnv` impl_gr,
811 tcg_imports = tcg_imports tcg_env `plusImportAvails` avails,
812 -- This is here so that when we call 'lookupFixityRn' for something
813 -- directly implemented by the module, we grab the right thing
814 tcg_fix_env = fix_env
815 }) $ do
816
817 -- STEP 2: Load the *unrenamed, uninstantiated* interface for
818 -- the ORIGINAL signature. We are going to eventually rename it,
819 -- but we must proceed slowly, because it is NOT known if the
820 -- instantiation is correct.
821 let isig_mod = fst (splitModuleInsts (mkModule (IndefiniteUnitId uid) mod_name))
822 mb_isig_iface <- findAndReadIface (text "checkImplements 2") isig_mod False
823 isig_iface <- case mb_isig_iface of
824 Succeeded (iface, _) -> return iface
825 Failed err -> failWithTc $
826 hang (text "Could not find hi interface for signature" <+>
827 quotes (ppr isig_mod) <> colon) 4 err
828
829 -- STEP 3: Check that the implementing interface exports everything
830 -- we need. (Notice we IGNORE the Modules in the AvailInfos.)
831 forM_ (exportOccs (mi_exports isig_iface)) $ \occ ->
832 case lookupGlobalRdrEnv impl_gr occ of
833 [] -> addErr $ quotes (ppr occ)
834 <+> text "is exported by the hsig file, but not"
835 <+> text "exported by the implementing module"
836 <+> quotes (ppr impl_mod)
837 _ -> return ()
838 failIfErrsM
839
840 -- STEP 4: Now that the export is complete, rename the interface...
841 sig_iface <- tcRnModIface insts (Just nsubst) isig_iface
842
843 -- STEP 5: ...and typecheck it. (Note that in both cases, the nsubst
844 -- lets us determine how top-level identifiers should be handled.)
845 sig_details <- initIfaceTcRn $ typecheckIfaceForInstantiate nsubst sig_iface
846
847 -- STEP 6: Check that it's sufficient
848 tcg_env <- getGblEnv
849 checkHsigIface tcg_env impl_gr sig_iface sig_details
850
851 -- STEP 7: Return the updated 'TcGblEnv' with the signature exports,
852 -- so we write them out.
853 return tcg_env {
854 tcg_exports = mi_exports sig_iface
855 }
856
857 -- | Given 'tcg_mod', instantiate a 'ModIface' from the indefinite
858 -- library to use the actual implementations of the relevant entities,
859 -- checking that the implementation matches the signature.
860 instantiateSignature :: TcRn TcGblEnv
861 instantiateSignature = do
862 tcg_env <- getGblEnv
863 dflags <- getDynFlags
864 let outer_mod = tcg_mod tcg_env
865 inner_mod = tcg_semantic_mod tcg_env
866 -- TODO: setup the local RdrEnv so the error messages look a little better.
867 -- But this information isn't stored anywhere. Should we RETYPECHECK
868 -- the local one just to get the information? Hmm...
869 MASSERT( moduleUnitId outer_mod == thisPackage dflags )
870 inner_mod `checkImplements`
871 IndefModule
872 (newIndefUnitId (thisComponentId dflags)
873 (thisUnitIdInsts dflags))
874 (moduleName outer_mod)