Export.hs 33 KB
Newer Older
1
{-# LANGUAGE NamedFieldPuns #-}
2
{-# LANGUAGE FlexibleContexts #-}
3 4
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE OverloadedStrings #-}
5
{-# LANGUAGE TypeFamilies #-}
6 7
{-# LANGUAGE ViewPatterns #-}

Sylvain Henry's avatar
Sylvain Henry committed
8
module GHC.Tc.Gen.Export (tcRnExports, exports_from_avail) where
9

10
import GHC.Prelude
11

Sylvain Henry's avatar
Sylvain Henry committed
12
import GHC.Hs
Sylvain Henry's avatar
Sylvain Henry committed
13
import GHC.Builtin.Names
Sylvain Henry's avatar
Sylvain Henry committed
14
import GHC.Types.Name.Reader
Sylvain Henry's avatar
Sylvain Henry committed
15 16 17
import GHC.Tc.Utils.Monad
import GHC.Tc.Utils.Env
import GHC.Tc.Utils.TcType
18 19 20
import GHC.Rename.Names
import GHC.Rename.Env
import GHC.Rename.Unbound ( reportUnboundName )
21
import GHC.Utils.Error
Sylvain Henry's avatar
Sylvain Henry committed
22 23
import GHC.Types.Id
import GHC.Types.Id.Info
Sylvain Henry's avatar
Sylvain Henry committed
24
import GHC.Unit.Module
Sylvain Henry's avatar
Sylvain Henry committed
25 26 27 28
import GHC.Types.Name
import GHC.Types.Name.Env
import GHC.Types.Name.Set
import GHC.Types.Avail
Sylvain Henry's avatar
Sylvain Henry committed
29
import GHC.Core.TyCon
Sylvain Henry's avatar
Sylvain Henry committed
30
import GHC.Types.SrcLoc as SrcLoc
Sylvain Henry's avatar
Sylvain Henry committed
31
import GHC.Driver.Types
32
import GHC.Utils.Outputable
33
import GHC.Utils.Panic
Sylvain Henry's avatar
Sylvain Henry committed
34 35 36
import GHC.Core.ConLike
import GHC.Core.DataCon
import GHC.Core.PatSyn
37
import GHC.Data.Maybe
Sylvain Henry's avatar
Sylvain Henry committed
38
import GHC.Types.Unique.Set
39 40
import GHC.Utils.Misc (capitalise)
import GHC.Data.FastString (fsLit)
41 42

import Control.Monad
Sylvain Henry's avatar
Sylvain Henry committed
43
import GHC.Driver.Session
Sylvain Henry's avatar
Sylvain Henry committed
44 45
import GHC.Parser.PostProcess ( setRdrNameSpace )
import Data.Either            ( partitionEithers )
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67

{-
************************************************************************
*                                                                      *
\subsection{Export list processing}
*                                                                      *
************************************************************************

Processing the export list.

You might think that we should record things that appear in the export
list as ``occurrences'' (using @addOccurrenceName@), but you'd be
wrong.  We do check (here) that they are in scope, but there is no
need to slurp in their actual declaration (which is what
@addOccurrenceName@ forces).

Indeed, doing so would big trouble when compiling @PrelBase@, because
it re-exports @GHC@, which includes @takeMVar#@, whose type includes
@ConcBase.StateAndSynchVar#@, and so on...

Note [Exports of data families]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
68
Suppose you see (#5306)
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
        module M where
          import X( F )
          data instance F Int = FInt
What does M export?  AvailTC F [FInt]
                  or AvailTC F [F,FInt]?
The former is strictly right because F isn't defined in this module.
But then you can never do an explicit import of M, thus
    import M( F( FInt ) )
because F isn't exported by M.  Nor can you import FInt alone from here
    import M( FInt )
because we don't have syntax to support that.  (It looks like an import of
the type FInt.)

At one point I implemented a compromise:
  * When constructing exports with no export list, or with module M(
    module M ), we add the parent to the exports as well.
  * But not when you see module M( f ), even if f is a
    class method with a parent.
  * Nor when you see module M( module N ), with N /= M.

But the compromise seemed too much of a hack, so we backed it out.
You just have to use an explicit export list:
    module M( F(..) ) where ...
92 93 94

Note [Avails of associated data families]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
95
Suppose you have (#16077)
96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126

    {-# LANGUAGE TypeFamilies #-}
    module A (module A) where

    class    C a  where { data T a }
    instance C () where { data T () = D }

Because @A@ is exported explicitly, GHC tries to produce an export list
from the @GlobalRdrEnv@. In this case, it pulls out the following:

    [ C defined at A.hs:4:1
    , T parent:C defined at A.hs:4:23
    , D parent:T defined at A.hs:5:35 ]

If map these directly into avails, (via 'availFromGRE'), we get
@[C{C;}, C{T;}, T{D;}]@, which eventually gets merged into @[C{C, T;}, T{D;}]@.
That's not right, because @T{D;}@ violates the AvailTC invariant: @T@ is
exported, but it isn't the first entry in the avail!

We work around this issue by expanding GREs where the parent and child
are both type constructors into two GRES.

    T parent:C defined at A.hs:4:23

      =>

    [ T parent:C defined at A.hs:4:23
    , T defined at A.hs:4:23 ]

Then, we get  @[C{C;}, C{T;}, T{T;}, T{D;}]@, which eventually gets merged
into @[C{C, T;}, T{T, D;}]@ (which satsifies the AvailTC invariant).
127 128 129 130 131 132
-}

data ExportAccum        -- The type of the accumulating parameter of
                        -- the main worker function in rnExports
     = ExportAccum
        ExportOccMap           --  Tracks exported occurrence names
133
        (UniqSet ModuleName)   --  Tracks (re-)exported module names
134 135

emptyExportAccum :: ExportAccum
136 137 138 139 140 141 142
emptyExportAccum = ExportAccum emptyOccEnv emptyUniqSet

accumExports :: (ExportAccum -> x -> TcRn (Maybe (ExportAccum, y)))
             -> [x]
             -> TcRn [y]
accumExports f = fmap (catMaybes . snd) . mapAccumLM f' emptyExportAccum
  where f' acc x = do
143
          m <- attemptM (f acc x)
144
          pure $ case m of
145 146
            Just (Just (acc', y)) -> (acc', Just y)
            _                     -> (acc, Nothing)
147

148
type ExportOccMap = OccEnv (Name, IE GhcPs)
149 150 151 152 153 154
        -- Tracks what a particular exported OccName
        --   in an export list refers to, and which item
        --   it came from.  It's illegal to export two distinct things
        --   that have the same occurrence name

tcRnExports :: Bool       -- False => no 'module M(..) where' header at all
155
          -> Maybe (Located [LIE GhcPs]) -- Nothing => no explicit export list
156 157 158 159 160 161 162 163 164 165
          -> TcGblEnv
          -> RnM TcGblEnv

        -- Complains if two distinct exports have same OccName
        -- Warns about identical exports.
        -- Complains about exports items not in scope

tcRnExports explicit_mod exports
          tcg_env@TcGblEnv { tcg_mod     = this_mod,
                              tcg_rdr_env = rdr_env,
166 167
                              tcg_imports = imports,
                              tcg_src     = hsc_src }
168 169 170 171 172 173
 = unsetWOptM Opt_WarnWarningsDeprecations $
       -- Do not report deprecations arising from the export
       -- list, to avoid bleating about re-exporting a deprecated
       -- thing (especially via 'module Foo' export item)
   do   {
        ; dflags <- getDynFlags
174
        ; let is_main_mod = mainModIs dflags == this_mod
chessai's avatar
chessai committed
175
        ; let default_main = case mainFunIs dflags of
176 177 178
                 Just main_fun
                     | is_main_mod -> mkUnqual varName (fsLit main_fun)
                 _                 -> main_RDR_Unqual
179 180 181 182
        ; has_main <- (not . null) <$> lookupInfoOccRn default_main -- #17832
        -- If a module has no explicit header, and it has one or more main
        -- functions in scope, then add a header like
        -- "module Main(main) where ..."                               #13839
183
        -- See Note [Modules without a module header]
184 185
        ; let real_exports
                 | explicit_mod = exports
186
                 | has_main
187
                          = Just (noLoc [noLoc (IEVar noExtField
chessai's avatar
chessai committed
188
                                     (noLoc (IEName $ noLoc default_main)))])
189 190
                        -- ToDo: the 'noLoc' here is unhelpful if 'main'
                        --       turns out to be out of scope
191
                 | otherwise = Nothing
192

193
        ; let do_it = exports_from_avail real_exports rdr_env imports this_mod
194
        ; (rn_exports, final_avails)
195
            <- if hsc_src == HsigFile
196
                then do (mb_r, msgs) <- tryTc do_it
197 198 199
                        case mb_r of
                            Just r  -> return r
                            Nothing -> addMessages msgs >> failM
Matthew Pickering's avatar
Matthew Pickering committed
200
                else checkNoErrs do_it
201
        ; let final_ns     = availsToNameSetWithSelectors final_avails
202

203
        ; traceRn "rnExports: Exports:" (ppr final_avails)
204 205 206 207 208 209 210 211 212 213 214

        ; let new_tcg_env =
                  tcg_env { tcg_exports    = final_avails,
                             tcg_rn_exports = case tcg_rn_exports tcg_env of
                                                Nothing -> Nothing
                                                Just _  -> rn_exports,
                            tcg_dus = tcg_dus tcg_env `plusDU`
                                      usesOnly final_ns }
        ; failIfErrsM
        ; return new_tcg_env }

215
exports_from_avail :: Maybe (Located [LIE GhcPs])
216
                         -- ^ 'Nothing' means no explicit export list
217 218
                   -> GlobalRdrEnv
                   -> ImportAvails
219 220 221
                         -- ^ Imported modules; this is used to test if a
                         -- @module Foo@ export is valid (it's not valid
                         -- if we didn't import @Foo@!)
222
                   -> Module
alexbiehl's avatar
alexbiehl committed
223 224 225 226 227
                   -> RnM (Maybe [(LIE GhcRn, Avails)], Avails)
                         -- (Nothing, _) <=> no explicit export list
                         -- if explicit export list is present it contains
                         -- each renamed export item together with its exported
                         -- names.
228 229 230 231 232

exports_from_avail Nothing rdr_env _imports _this_mod
   -- The same as (module M) where M is the current module name,
   -- so that's how we handle it, except we also export the data family
   -- when a data instance is exported.
233 234 235 236 237 238 239 240 241
  = do {
    ; warnMissingExportList <- woptM Opt_WarnMissingExportList
    ; warnIfFlag Opt_WarnMissingExportList
        warnMissingExportList
        (missingModuleExportWarn $ moduleName _this_mod)
    ; let avails =
            map fix_faminst . gresToAvailInfo
              . filter isLocalGRE . globalRdrEnvElts $ rdr_env
    ; return (Nothing, avails) }
242 243 244 245 246 247
  where
    -- #11164: when we define a data instance
    -- but not data family, re-export the family
    -- Even though we don't check whether this is actually a data family
    -- only data families can locally define subordinate things (`ns` here)
    -- without locally defining (and instead importing) the parent (`n`)
248 249 250 251 252 253
    fix_faminst (AvailTC n ns flds) =
      let new_ns =
            case ns of
              [] -> [n]
              (p:_) -> if p == n then ns else n:ns
      in AvailTC n new_ns flds
254 255 256 257

    fix_faminst avail = avail


258
exports_from_avail (Just (L _ rdr_items)) rdr_env imports this_mod
259
  = do ie_avails <- accumExports do_litem rdr_items
260
       let final_exports = nubAvails (concatMap snd ie_avails) -- Combine families
alexbiehl's avatar
alexbiehl committed
261
       return (Just ie_avails, final_exports)
262
  where
263 264
    do_litem :: ExportAccum -> LIE GhcPs
             -> RnM (Maybe (ExportAccum, (LIE GhcRn, Avails)))
265 266 267 268 269 270
    do_litem acc lie = setSrcSpan (getLoc lie) (exports_from_item acc lie)

    -- Maps a parent to its in-scope children
    kids_env :: NameEnv [GlobalRdrElt]
    kids_env = mkChildEnv (globalRdrEnvElts rdr_env)

271 272
    -- See Note [Avails of associated data families]
    expand_tyty_gre :: GlobalRdrElt -> [GlobalRdrElt]
273
    expand_tyty_gre (gre@GRE { gre_name = me, gre_par = ParentIs p })
274 275
      | isTyConName p, isTyConName me = [gre, gre{ gre_par = NoParent }]
    expand_tyty_gre gre = [gre]
276 277

    imported_modules = [ imv_name imv
278 279
                       | xs <- moduleEnvElts $ imp_mods imports
                       , imv <- importedByUser xs ]
280

281 282 283
    exports_from_item :: ExportAccum -> LIE GhcPs
                      -> RnM (Maybe (ExportAccum, (LIE GhcRn, Avails)))
    exports_from_item (ExportAccum occs earlier_mods)
284
                      (L loc ie@(IEModuleContents _ lmod@(L _ mod)))
285
        | mod `elementOfUniqSet` earlier_mods    -- Duplicate export of M
286 287
        = do { warnIfFlag Opt_WarnDuplicateExports True
                          (dupModuleExport mod) ;
288
               return Nothing }
289 290 291 292 293

        | otherwise
        = do { let { exportValid = (mod `elem` imported_modules)
                                || (moduleName this_mod == mod)
                   ; gre_prs     = pickGREsModExp mod (globalRdrEnvElts rdr_env)
294 295 296
                   ; new_exports = [ availFromGRE gre'
                                   | (gre, _) <- gre_prs
                                   , gre' <- expand_tyty_gre gre ]
297
                   ; all_gres    = foldr (\(gre1,gre2) gres -> gre1 : gre2 : gres) [] gre_prs
298
                   ; mods        = addOneToUniqSet earlier_mods mod
299
                   }
300 301

             ; checkErr exportValid (moduleNotImported mod)
302 303 304
             ; warnIfFlag Opt_WarnDodgyExports
                          (exportValid && null gre_prs)
                          (nullModuleExport mod)
305

306
             ; traceRn "efa" (ppr mod $$ ppr all_gres)
307 308
             ; addUsedGREs all_gres

309
             ; occs' <- check_occs ie occs new_exports
310 311 312 313 314 315
                      -- This check_occs not only finds conflicts
                      -- between this item and others, but also
                      -- internally within this item.  That is, if
                      -- 'M.x' is in scope in several ways, we'll have
                      -- several members of mod_avails with the same
                      -- OccName.
316 317
             ; traceRn "export_mod"
                       (vcat [ ppr mod
318 319
                             , ppr new_exports ])

320
             ; return (Just ( ExportAccum occs' mods
321
                            , ( L loc (IEModuleContents noExtField lmod)
322
                              , new_exports))) }
alexbiehl's avatar
alexbiehl committed
323

324
    exports_from_item acc@(ExportAccum occs mods) (L loc ie)
Vladislav Zavialov's avatar
Vladislav Zavialov committed
325 326
        | Just new_ie <- lookup_doc_ie ie
        = return (Just (acc, (L loc new_ie, [])))
327 328

        | otherwise
329
        = do (new_ie, avail) <- lookup_ie ie
330
             if isUnboundName (ieName new_ie)
331
                  then return Nothing    -- Avoid error cascade
332 333
                  else do

334
                    occs' <- check_occs ie occs [avail]
335

336
                    return (Just ( ExportAccum occs' mods
337
                                 , (L loc new_ie, [avail])))
338 339

    -------------
340
    lookup_ie :: IE GhcPs -> RnM (IE GhcRn, AvailInfo)
341
    lookup_ie (IEVar _ (L l rdr))
342
        = do (name, avail) <- lookupGreAvailRn $ ieWrappedName rdr
343
             return (IEVar noExtField (L l (replaceWrappedName rdr name)), avail)
344

345
    lookup_ie (IEThingAbs _ (L l rdr))
346
        = do (name, avail) <- lookupGreAvailRn $ ieWrappedName rdr
347
             return (IEThingAbs noExtField (L l (replaceWrappedName rdr name))
348
                    , avail)
349

350
    lookup_ie ie@(IEThingAll _ n')
351
        = do
352
            (n, avail, flds) <- lookup_ie_all ie n'
353
            let name = unLoc n
354
            return (IEThingAll noExtField (replaceLWrappedName n' (unLoc n))
355
                   , AvailTC name (name:avail) flds)
356 357


358
    lookup_ie ie@(IEThingWith _ l wc sub_rdrs _)
359 360 361 362 363 364 365 366
        = do
            (lname, subs, avails, flds)
              <- addExportErrCtxt ie $ lookup_ie_with l sub_rdrs
            (_, all_avail, all_flds) <-
              case wc of
                NoIEWildcard -> return (lname, [], [])
                IEWildcard _ -> lookup_ie_all ie l
            let name = unLoc lname
367
            return (IEThingWith noExtField (replaceLWrappedName l name) wc subs
368
                                (flds ++ (map noLoc all_flds)),
369
                    AvailTC name (name : avails ++ all_avail)
370
                                 (map unLoc flds ++ all_flds))
371 372 373 374


    lookup_ie _ = panic "lookup_ie"    -- Other cases covered earlier

375

376
    lookup_ie_with :: LIEWrappedName RdrName -> [LIEWrappedName RdrName]
377 378
                   -> RnM (Located Name, [LIEWrappedName Name], [Name],
                           [Located FieldLabel])
379
    lookup_ie_with (L l rdr) sub_rdrs
380
        = do name <- lookupGlobalOccRn $ ieWrappedName rdr
381
             (non_flds, flds) <- lookupChildrenExport name sub_rdrs
382
             if isUnboundName name
383 384
                then return (L l name, [], [name], [])
                else return (L l name, non_flds
385 386 387
                            , map (ieWrappedName . unLoc) non_flds
                            , flds)

388
    lookup_ie_all :: IE GhcPs -> LIEWrappedName RdrName
389
                  -> RnM (Located Name, [Name], [FieldLabel])
390
    lookup_ie_all ie (L l rdr) =
391
          do name <- lookupGlobalOccRn $ ieWrappedName rdr
392 393
             let gres = findChildren kids_env name
                 (non_flds, flds) = classifyGREs gres
394
             addUsedKids (ieWrappedName rdr) gres
395 396 397 398 399 400 401 402 403
             warnDodgyExports <- woptM Opt_WarnDodgyExports
             when (null gres) $
                  if isTyConName name
                  then when warnDodgyExports $
                           addWarn (Reason Opt_WarnDodgyExports)
                                   (dodgyExportWarn name)
                  else -- This occurs when you export T(..), but
                       -- only import T abstractly, or T is a synonym.
                       addErr (exportItemErr ie)
404
             return (L l name, non_flds, flds)
405 406

    -------------
Vladislav Zavialov's avatar
Vladislav Zavialov committed
407 408 409 410 411
    lookup_doc_ie :: IE GhcPs -> Maybe (IE GhcRn)
    lookup_doc_ie (IEGroup _ lev doc) = Just (IEGroup noExtField lev doc)
    lookup_doc_ie (IEDoc _ doc)       = Just (IEDoc noExtField doc)
    lookup_doc_ie (IEDocNamed _ str)  = Just (IEDocNamed noExtField str)
    lookup_doc_ie _ = Nothing
412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432

    -- In an export item M.T(A,B,C), we want to treat the uses of
    -- A,B,C as if they were M.A, M.B, M.C
    -- Happily pickGREs does just the right thing
    addUsedKids :: RdrName -> [GlobalRdrElt] -> RnM ()
    addUsedKids parent_rdr kid_gres = addUsedGREs (pickGREs parent_rdr kid_gres)

classifyGREs :: [GlobalRdrElt] -> ([Name], [FieldLabel])
classifyGREs = partitionEithers . map classifyGRE

classifyGRE :: GlobalRdrElt -> Either Name FieldLabel
classifyGRE gre = case gre_par gre of
  FldParent _ Nothing -> Right (FieldLabel (occNameFS (nameOccName n)) False n)
  FldParent _ (Just lbl) -> Right (FieldLabel lbl True n)
  _                      -> Left  n
  where
    n = gre_name gre

-- Renaming and typechecking of exports happens after everything else has
-- been typechecked.

433 434 435 436 437 438 439 440 441 442 443 444 445
{-
Note [Modules without a module header]
--------------------------------------------------

The Haskell 2010 report says in section 5.1:

>> An abbreviated form of module, consisting only of the module body, is
>> permitted. If this is used, the header is assumed to be
>> ‘module Main(main) where’.

For modules without a module header, this is implemented the
following way:

446 447 448
If the module has a main function in scope:
   Then create a module header and export the main function,
   as if a module header like ‘module Main(main) where...’ would exist.
449 450 451 452
   This has the effect to mark the main function and all top level
   functions called directly or indirectly via main as 'used',
   and later on, unused top-level functions can be reported correctly.
   There is no distinction between GHC and GHCi.
453 454
If the module has several main functions in scope:
   Then generate a header as above. The ambiguity is reported later in
Sylvain Henry's avatar
Sylvain Henry committed
455
   module  `GHC.Tc.Module` function `check_main`.
456 457 458 459
If the module has NO main function:
   Then export all top-level functions. This marks all top level
   functions as 'used'.
   In GHCi this has the effect, that we don't get any 'non-used' warnings.
Sylvain Henry's avatar
Sylvain Henry committed
460 461
   In GHC, however, the 'has-main-module' check in GHC.Tc.Module.checkMain
   fires, and we get the error:
462 463
      The IO action ‘main’ is not defined in module ‘Main’
-}
464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490


-- Renaming exports lists is a minefield. Five different things can appear in
-- children export lists ( T(A, B, C) ).
-- 1. Record selectors
-- 2. Type constructors
-- 3. Data constructors
-- 4. Pattern Synonyms
-- 5. Pattern Synonym Selectors
--
-- However, things get put into weird name spaces.
-- 1. Some type constructors are parsed as variables (-.->) for example.
-- 2. All data constructors are parsed as type constructors
-- 3. When there is ambiguity, we default type constructors to data
-- constructors and require the explicit `type` keyword for type
-- constructors.
--
-- This function first establishes the possible namespaces that an
-- identifier might be in (`choosePossibleNameSpaces`).
--
-- Then for each namespace in turn, tries to find the correct identifier
-- there returning the first positive result or the first terminating
-- error.
--



491 492
lookupChildrenExport :: Name -> [LIEWrappedName RdrName]
                     -> RnM ([LIEWrappedName Name], [Located FieldLabel])
493
lookupChildrenExport spec_parent rdr_items =
494 495 496 497 498 499 500 501 502 503 504 505 506
  do
    xs <- mapAndReportM doOne rdr_items
    return $ partitionEithers xs
    where
        -- Pick out the possible namespaces in order of priority
        -- This is a consequence of how the parser parses all
        -- data constructors as type constructors.
        choosePossibleNamespaces :: NameSpace -> [NameSpace]
        choosePossibleNamespaces ns
          | ns == varName = [varName, tcName]
          | ns == tcName  = [dataName, tcName]
          | otherwise = [ns]
        -- Process an individual child
507 508
        doOne :: LIEWrappedName RdrName
              -> RnM (Either (LIEWrappedName Name) (Located FieldLabel))
509 510
        doOne n = do

511
          let bareName = (ieWrappedName . unLoc) n
Matthew Pickering's avatar
Matthew Pickering committed
512
              lkup v = lookupSubBndrOcc_helper False True
513
                        spec_parent (setRdrNameSpace bareName v)
514

515 516
          name <-  combineChildLookupResult $ map lkup $
                   choosePossibleNamespaces (rdrNameSpace bareName)
Matthew Pickering's avatar
Matthew Pickering committed
517
          traceRn "lookupChildrenExport" (ppr name)
518 519 520 521 522 523 524
          -- Default to data constructors for slightly better error
          -- messages
          let unboundName :: RdrName
              unboundName = if rdrNameSpace bareName == varName
                                then bareName
                                else setRdrNameSpace bareName dataName

525
          case name of
526 527
            NameNotFound -> do { ub <- reportUnboundName unboundName
                               ; let l = getLoc n
528 529
                               ; return (Left (L l (IEName (L l ub))))}
            FoundFL fls -> return $ Right (L (getLoc n) fls)
530
            FoundName par name -> do { checkPatSynParent spec_parent par name
531 532
                                     ; return
                                       $ Left (replaceLWrappedName n name) }
533
            IncorrectParent p g td gs -> failWithDcErr p g td gs
534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581


-- Note: [Typing Pattern Synonym Exports]
-- It proved quite a challenge to precisely specify which pattern synonyms
-- should be allowed to be bundled with which type constructors.
-- In the end it was decided to be quite liberal in what we allow. Below is
-- how Simon described the implementation.
--
-- "Personally I think we should Keep It Simple.  All this talk of
--  satisfiability makes me shiver.  I suggest this: allow T( P ) in all
--   situations except where `P`'s type is ''visibly incompatible'' with
--   `T`.
--
--    What does "visibly incompatible" mean?  `P` is visibly incompatible
--    with
--     `T` if
--       * `P`'s type is of form `... -> S t1 t2`
--       * `S` is a data/newtype constructor distinct from `T`
--
--  Nothing harmful happens if we allow `P` to be exported with
--  a type it can't possibly be useful for, but specifying a tighter
--  relationship is very awkward as you have discovered."
--
-- Note that this allows *any* pattern synonym to be bundled with any
-- datatype type constructor. For example, the following pattern `P` can be
-- bundled with any type.
--
-- ```
-- pattern P :: (A ~ f) => f
-- ```
--
-- So we provide basic type checking in order to help the user out, most
-- pattern synonyms are defined with definite type constructors, but don't
-- actually prevent a library author completely confusing their users if
-- they want to.
--
-- So, we check for exactly four things
-- 1. The name arises from a pattern synonym definition. (Either a pattern
--    synonym constructor or a pattern synonym selector)
-- 2. The pattern synonym is only bundled with a datatype or newtype.
-- 3. Check that the head of the result type constructor is an actual type
--    constructor and not a type variable. (See above example)
-- 4. Is so, check that this type constructor is the same as the parent
--    type constructor.
--
--
-- Note: [Types of TyCon]
--
Krzysztof Gogolewski's avatar
Krzysztof Gogolewski committed
582
-- This check appears to be overly complicated, Richard asked why it
583 584 585 586 587 588 589 590 591
-- is not simply just `isAlgTyCon`. The answer for this is that
-- a classTyCon is also an `AlgTyCon` which we explicitly want to disallow.
-- (It is either a newtype or data depending on the number of methods)
--

-- | Given a resolved name in the children export list and a parent. Decide
-- whether we are allowed to export the child with the parent.
-- Invariant: gre_par == NoParent
-- See note [Typing Pattern Synonym Exports]
592 593 594 595 596 597 598 599 600 601 602 603 604 605
checkPatSynParent :: Name    -- ^ Alleged parent type constructor
                             -- User wrote T( P, Q )
                  -> Parent  -- The parent of P we discovered
                  -> Name    -- ^ Either a
                             --   a) Pattern Synonym Constructor
                             --   b) A pattern synonym selector
                  -> TcM ()  -- Fails if wrong parent
checkPatSynParent _ (ParentIs {}) _
  = return ()

checkPatSynParent _ (FldParent {}) _
  = return ()

checkPatSynParent parent NoParent mpat_syn
Matthew Pickering's avatar
Matthew Pickering committed
606
  | isUnboundName parent -- Avoid an error cascade
607 608 609 610 611 612 613 614 615 616 617
  = return ()

  | otherwise
  = do { parent_ty_con <- tcLookupTyCon parent
       ; mpat_syn_thing <- tcLookupGlobal mpat_syn

        -- 1. Check that the Id was actually from a thing associated with patsyns
       ; case mpat_syn_thing of
            AnId i | isId i
                   , RecSelId { sel_tycon = RecSelPatSyn p } <- idDetails i
                   -> handle_pat_syn (selErr i) parent_ty_con p
618

619 620 621 622 623
            AConLike (PatSynCon p) -> handle_pat_syn (psErr p) parent_ty_con p

            _ -> failWithDcErr parent mpat_syn (ppr mpat_syn) [] }
  where
    psErr  = exportErrCtxt "pattern synonym"
624 625 626
    selErr = exportErrCtxt "pattern synonym record selector"

    assocClassErr :: SDoc
627
    assocClassErr = text "Pattern synonyms can be bundled only with datatypes."
628

629 630 631 632 633 634
    handle_pat_syn :: SDoc
                   -> TyCon      -- ^ Parent TyCon
                   -> PatSyn     -- ^ Corresponding bundled PatSyn
                                 --   and pretty printed origin
                   -> TcM ()
    handle_pat_syn doc ty_con pat_syn
635 636

      -- 2. See note [Types of TyCon]
637 638 639
      | not $ isTyConWithSrcDataCons ty_con
      = addErrCtxt doc $ failWithTc assocClassErr

640
      -- 3. Is the head a type variable?
641 642
      | Nothing <- mtycon
      = return ()
643
      -- 4. Ok. Check they are actually the same type constructor.
644 645 646 647

      | Just p_ty_con <- mtycon, p_ty_con /= ty_con
      = addErrCtxt doc $ failWithTc typeMismatchError

648
      -- 5. We passed!
649 650
      | otherwise
      = return ()
651 652

      where
653
        expected_res_ty = mkTyConApp ty_con (mkTyVarTys (tyConTyVars ty_con))
654 655 656 657 658 659 660 661 662 663 664 665
        (_, _, _, _, _, res_ty) = patSynSig pat_syn
        mtycon = fst <$> tcSplitTyConApp_maybe res_ty
        typeMismatchError :: SDoc
        typeMismatchError =
          text "Pattern synonyms can only be bundled with matching type constructors"
              $$ text "Couldn't match expected type of"
              <+> quotes (ppr expected_res_ty)
              <+> text "with actual type of"
              <+> quotes (ppr res_ty)


{-===========================================================================-}
666
check_occs :: IE GhcPs -> ExportOccMap -> [AvailInfo]
667
           -> RnM ExportOccMap
668
check_occs ie occs avails
669 670
  -- 'names' and 'fls' are the entities specified by 'ie'
  = foldlM check occs names_with_occs
671
  where
672 673
    -- Each Name specified by 'ie', paired with the OccName used to
    -- refer to it in the GlobalRdrEnv
Sylvain Henry's avatar
Sylvain Henry committed
674
    -- (see Note [Representing fields in AvailInfo] in GHC.Types.Avail).
675 676 677 678
    --
    -- We check for export clashes using the selector Name, but need
    -- the field label OccName for presenting error messages.
    names_with_occs = availsNamesWithOccs avails
679 680

    check occs (name, occ)
681 682 683 684 685 686 687
      = case lookupOccEnv occs name_occ of
          Nothing -> return (extendOccEnv occs name_occ (name, ie))

          Just (name', ie')
            | name == name'   -- Duplicate export
            -- But we don't want to warn if the same thing is exported
            -- by two different module exports. See ticket #4478.
688 689
            -> do { warnIfFlag Opt_WarnDuplicateExports
                               (not (dupExport_ok name ie ie'))
690
                               (dupExportWarn occ ie ie')
691 692 693 694
                  ; return occs }

            | otherwise    -- Same occ name but different names: an error
            ->  do { global_env <- getGlobalRdrEnv ;
695
                     addErr (exportClashErr global_env occ name' name ie' ie) ;
696 697 698 699 700
                     return occs }
      where
        name_occ = nameOccName name


701
dupExport_ok :: Name -> IE GhcPs -> IE GhcPs -> Bool
702 703 704 705 706 707 708 709 710 711 712 713 714 715
-- The Name is exported by both IEs. Is that ok?
-- "No"  iff the name is mentioned explicitly in both IEs
--        or one of the IEs mentions the name *alone*
-- "Yes" otherwise
--
-- Examples of "no":  module M( f, f )
--                    module M( fmap, Functor(..) )
--                    module M( module Data.List, head )
--
-- Example of "yes"
--    module M( module A, module B ) where
--        import A( f )
--        import B( f )
--
716
-- Example of "yes" (#2436)
717 718 719 720
--    module M( C(..), T(..) ) where
--         class C a where { data T a }
--         instance C Int where { data T Int = TInt }
--
721
-- Example of "yes" (#2436)
722 723 724 725 726 727 728 729 730 731
--    module Foo ( T ) where
--      data family T a
--    module Bar ( T(..), module Foo ) where
--        import Foo
--        data instance T Int = TInt

dupExport_ok n ie1 ie2
  = not (  single ie1 || single ie2
        || (explicit_in ie1 && explicit_in ie2) )
  where
732 733
    explicit_in (IEModuleContents {}) = False                   -- module M
    explicit_in (IEThingAll _ r)
734
      = nameOccName n == rdrNameOcc (ieWrappedName $ unLoc r)  -- T(..)
735 736 737 738 739 740 741 742 743 744 745 746 747 748 749
    explicit_in _              = True

    single IEVar {}      = True
    single IEThingAbs {} = True
    single _               = False


dupModuleExport :: ModuleName -> SDoc
dupModuleExport mod
  = hsep [text "Duplicate",
          quotes (text "Module" <+> ppr mod),
          text "in export list"]

moduleNotImported :: ModuleName -> SDoc
moduleNotImported mod
750 751 752
  = hsep [text "The export item",
          quotes (text "module" <+> ppr mod),
          text "is not imported"]
753 754 755

nullModuleExport :: ModuleName -> SDoc
nullModuleExport mod
756 757 758
  = hsep [text "The export item",
          quotes (text "module" <+> ppr mod),
          text "exports nothing"]
759

760 761
missingModuleExportWarn :: ModuleName -> SDoc
missingModuleExportWarn mod
762 763 764
  = hsep [text "The export item",
          quotes (text "module" <+> ppr mod),
          text "is missing an export list"]
765

766 767

dodgyExportWarn :: Name -> SDoc
768 769
dodgyExportWarn item
  = dodgyMsg (text "export") item (dodgyMsgInsert item :: IE GhcRn)
770 771 772 773 774 775

exportErrCtxt :: Outputable o => String -> o -> SDoc
exportErrCtxt herald exp =
  text "In the" <+> text (herald ++ ":") <+> ppr exp


776
addExportErrCtxt :: (OutputableBndrId p)
777
                 => IE (GhcPass p) -> TcM a -> TcM a
778 779 780 781
addExportErrCtxt ie = addErrCtxt exportCtxt
  where
    exportCtxt = text "In the export:" <+> ppr ie

782
exportItemErr :: IE GhcPs -> SDoc
783 784 785 786 787
exportItemErr export_item
  = sep [ text "The export item" <+> quotes (ppr export_item),
          text "attempts to export constructors or class methods that are not visible here" ]


788
dupExportWarn :: OccName -> IE GhcPs -> IE GhcPs -> SDoc
789 790 791 792 793
dupExportWarn occ_name ie1 ie2
  = hsep [quotes (ppr occ_name),
          text "is exported by", quotes (ppr ie1),
          text "and",            quotes (ppr ie2)]

Matthew Pickering's avatar
Matthew Pickering committed
794
dcErrMsg :: Name -> String -> SDoc -> [SDoc] -> SDoc
795 796 797
dcErrMsg ty_con what_is thing parents =
          text "The type constructor" <+> quotes (ppr ty_con)
                <+> text "is not the parent of the" <+> text what_is
Matthew Pickering's avatar
Matthew Pickering committed
798
                <+> quotes thing <> char '.'
799 800 801 802 803 804 805
                $$ text (capitalise what_is)
                <> text "s can only be exported with their parent type constructor."
                $$ (case parents of
                      [] -> empty
                      [_] -> text "Parent:"
                      _  -> text "Parents:") <+> fsep (punctuate comma parents)

806 807
failWithDcErr :: Name -> Name -> SDoc -> [Name] -> TcM a
failWithDcErr parent thing thing_doc parents = do
808
  ty_thing <- tcLookupGlobal thing
809 810
  failWithTc $ dcErrMsg parent (tyThingCategory' ty_thing)
                        thing_doc (map ppr parents)
811 812 813 814 815 816 817
  where
    tyThingCategory' :: TyThing -> String
    tyThingCategory' (AnId i)
      | isRecordSelector i = "record selector"
    tyThingCategory' i = tyThingCategory i


818 819 820
exportClashErr :: GlobalRdrEnv -> OccName
               -> Name -> Name
               -> IE GhcPs -> IE GhcPs
821
               -> MsgDoc
822
exportClashErr global_env occ name1 name2 ie1 ie2
823 824 825 826 827
  = vcat [ text "Conflicting exports for" <+> quotes (ppr occ) <> colon
         , ppr_export ie1' name1'
         , ppr_export ie2' name2' ]
  where
    ppr_export ie name = nest 3 (hang (quotes (ppr ie) <+> text "exports" <+>
828
                                       quotes (ppr_name name))
829 830
                                    2 (pprNameProvenance (get_gre name)))

831 832 833 834 835 836
    -- DuplicateRecordFields means that nameOccName might be a mangled
    -- $sel-prefixed thing, in which case show the correct OccName alone
    ppr_name name
      | nameOccName name == occ = ppr name
      | otherwise               = ppr occ

837 838
    -- get_gre finds a GRE for the Name, so that we can show its provenance
    get_gre name
839 840
        = fromMaybe (pprPanic "exportClashErr" (ppr name))
                    (lookupGRE_Name_OccName global_env name occ)
841
    get_loc name = greSrcSpan (get_gre name)
842 843 844 845 846
    (name1', ie1', name2', ie2') =
      case SrcLoc.leftmost_smallest (get_loc name1) (get_loc name2) of
        LT -> (name1, ie1, name2, ie2)
        GT -> (name2, ie2, name1, ie1)
        EQ -> panic "exportClashErr: clashing exports have idential location"