TcRnDriver.hs 121 KB
Newer Older
1 2 3 4
{-
(c) The University of Glasgow 2006
(c) The GRASP/AQUA Project, Glasgow University, 1992-1998

5
\section[TcRnDriver]{Typechecking a whole module}
6 7

https://ghc.haskell.org/trac/ghc/wiki/Commentary/Compiler/TypeChecker
8
-}
9

10
{-# LANGUAGE CPP #-}
11
{-# LANGUAGE BangPatterns #-}
12 13
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NondecreasingIndentation #-}
Edward Z. Yang's avatar
Edward Z. Yang committed
14 15
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE ScopedTypeVariables #-}
16
{-# LANGUAGE TypeFamilies #-}
17
{-# LANGUAGE FlexibleContexts #-}
18
{-# LANGUAGE ViewPatterns #-}
19

20
module TcRnDriver (
21
        tcRnStmt, tcRnExpr, TcRnExprMode(..), tcRnType,
dterei's avatar
dterei committed
22 23 24 25
        tcRnImportDecls,
        tcRnLookupRdrName,
        getModuleInterface,
        tcRnDeclsi,
dterei's avatar
dterei committed
26
        isGHCiMonad,
27
        runTcInteractive,    -- Used by GHC API clients (Trac #8878)
dterei's avatar
dterei committed
28 29
        tcRnLookupName,
        tcRnGetInfo,
30
        tcRnModule, tcRnModuleTcRnM,
31
        tcTopSrcDecls,
Edward Z. Yang's avatar
Edward Z. Yang committed
32 33 34 35 36 37 38 39 40
        rnTopSrcDecls,
        checkBootDecl, checkHiBootIface',
        findExtraSigImports,
        implicitRequirements,
        checkUnitId,
        mergeSignatures,
        tcRnMergeSignatures,
        instantiateSignature,
        tcRnInstantiateSignature,
duog's avatar
duog committed
41
        loadUnqualIfaces,
Edward Z. Yang's avatar
Edward Z. Yang committed
42 43 44 45
        -- More private...
        badReexportedBootThing,
        checkBootDeclM,
        missingBootThing,
46
        getRenamedStuff, RenamedStuff
47 48
    ) where

49 50
import GhcPrelude

51
import {-# SOURCE #-} TcSplice ( finishTH, runRemoteModFinalizers )
52
import RnSplice ( rnTopSpliceDecls, traceSplice, SpliceInfo(..) )
53 54
import IfaceEnv( externaliseName )
import TcHsType
55
import TcValidity( checkValidType )
56
import TcMatches
57
import Inst( deeplyInstantiate )
58
import TcUnify( checkConstraints )
59 60
import RnTypes
import RnExpr
61 62
import RnUtils ( HsDocContext(..) )
import RnFixity ( lookupFixityRn )
63 64 65
import MkId
import TidyPgm    ( globaliseAndTidyId )
import TysWiredIn ( unitTy, mkListTy )
66
import Plugins
67 68
import DynFlags
import HsSyn
69 70
import IfaceSyn ( ShowSub(..), showToHeader )
import IfaceType( ShowForAllFlag(..) )
Simon Peyton Jones's avatar
Simon Peyton Jones committed
71
import PatSyn( pprPatSynType )
72
import PrelNames
73
import PrelInfo
74 75 76
import RdrName
import TcHsSyn
import TcExpr
77
import TcRnMonad
78
import TcRnExports
79
import TcEvidence
80
import qualified BooleanFormula as BF
81
import PprTyThing( pprTyThingInContext )
Simon Peyton Jones's avatar
Simon Peyton Jones committed
82
import CoreFVs( orphNamesOfFamInst )
83
import FamInst
84
import InstEnv
85 86
import FamInstEnv( FamInst, pprFamInst, famInstsRepTyCons
                 , famInstEnvElts, extendFamInstEnvList, normaliseType )
87
import TcAnnotations
88
import TcBinds
89
import MkIface          ( coAxiomToIfaceDecl )
90
import HeaderInfo       ( mkPrelImports )
91 92 93 94 95 96
import TcDefaults
import TcEnv
import TcRules
import TcForeign
import TcInstDcls
import TcIface
97
import TcMType
98
import TcType
99 100
import TcSimplify
import TcTyClsDecls
101
import TcTypeable ( mkTypeableBinds )
Edward Z. Yang's avatar
Edward Z. Yang committed
102
import TcBackpack
103 104 105 106 107 108
import LoadIface
import RnNames
import RnEnv
import RnSource
import ErrUtils
import Id
109
import IdInfo( IdDetails(..) )
110
import VarEnv
111
import Module
112
import UniqFM
113
import Name
114
import NameEnv
115
import NameSet
116
import Avail
117 118 119
import TyCon
import SrcLoc
import HscTypes
120
import ListSetOps
121
import Outputable
cactus's avatar
cactus committed
122
import ConLike
123 124 125
import DataCon
import Type
import Class
126
import BasicTypes hiding( SuccessFlag(..) )
127
import CoAxiom
128
import Annotations
129
import Data.List ( sortBy, sort )
130
import Data.Ord
131
import FastString
132
import Maybes
133 134
import Util
import Bag
135
import Inst (tcGetInsts)
136
import qualified GHC.LanguageExtensions as LangExt
137
import Data.Data ( Data )
138 139
import HsDumpAst
import qualified Data.Set as S
140

141
import Control.DeepSeq
142
import Control.Monad
143

144
#include "HsVersions.h"
145

146 147 148
{-
************************************************************************
*                                                                      *
dterei's avatar
dterei committed
149
        Typecheck and rename a module
150 151 152
*                                                                      *
************************************************************************
-}
153

154
-- | Top level entry point for typechecker and renamer
dterei's avatar
dterei committed
155
tcRnModule :: HscEnv
156
           -> ModSummary
dterei's avatar
dterei committed
157
           -> Bool              -- True <=> save renamed syntax
158
           -> HsParsedModule
dterei's avatar
dterei committed
159
           -> IO (Messages, Maybe TcGblEnv)
160

161
tcRnModule hsc_env mod_sum save_rn_syntax
162
   parsedModule@HsParsedModule {hpm_module= (dL->L loc this_module)}
163
 | RealSrcSpan real_loc <- loc
164 165 166 167 168
 = withTiming (pure dflags)
              (text "Renamer/typechecker"<+>brackets (ppr this_mod))
              (const ()) $
   initTc hsc_env hsc_src save_rn_syntax this_mod real_loc $
          withTcPlugins hsc_env $
169

170
          tcRnModuleTcRnM hsc_env mod_sum parsedModule pair
dterei's avatar
dterei committed
171

172 173 174 175
  | otherwise
  = return ((emptyBag, unitBag err_msg), Nothing)

  where
176
    hsc_src = ms_hsc_src mod_sum
177
    dflags = hsc_dflags hsc_env
178 179 180 181 182 183 184
    err_msg = mkPlainErrMsg (hsc_dflags hsc_env) loc $
              text "Module does not have a RealSrcSpan:" <+> ppr this_mod

    this_pkg = thisPackage (hsc_dflags hsc_env)

    pair :: (Module, SrcSpan)
    pair@(this_mod,_)
185
      | Just (dL->L mod_loc mod) <- hsmodName this_module
186 187 188 189
      = (mkModule this_pkg mod, mod_loc)

      | otherwise   -- 'module M where' is omitted
      = (mAIN, srcLocSpan (srcSpanStart loc))
dterei's avatar
dterei committed
190

191

192 193


194
tcRnModuleTcRnM :: HscEnv
195
                -> ModSummary
196 197 198
                -> HsParsedModule
                -> (Module, SrcSpan)
                -> TcRn TcGblEnv
199
-- Factored out separately from tcRnModule so that a Core plugin can
200
-- call the type checker directly
201
tcRnModuleTcRnM hsc_env mod_sum
202 203
                (HsParsedModule {
                   hpm_module =
204
                      (dL->L loc (HsModule maybe_mod export_ies
205 206 207 208 209 210
                                       import_decls local_decls mod_deprec
                                       maybe_doc_hdr)),
                   hpm_src_files = src_files
                })
                (this_mod, prel_imp_loc)
 = setSrcSpan loc $
211
   do { let { explicit_mod_hdr = isJust maybe_mod
212 213 214 215 216 217 218 219 220 221 222 223 224 225 226
            ; hsc_src          = ms_hsc_src mod_sum }
      ; -- Load the hi-boot interface for this module, if any
        -- We do this now so that the boot_names can be passed
        -- to tcTyAndClassDecls, because the boot_names are
        -- automatically considered to be loop breakers
        tcg_env <- getGblEnv
      ; boot_info <- tcHiBootIface hsc_src this_mod
      ; setGblEnv (tcg_env { tcg_self_boot = boot_info })
        $ do
        { -- Deal with imports; first add implicit prelude
          implicit_prelude <- xoptM LangExt.ImplicitPrelude
        ; let { prel_imports = mkPrelImports (moduleName this_mod) prel_imp_loc
                               implicit_prelude import_decls }

        ; whenWOptM Opt_WarnImplicitPrelude $
227
             when (notNull prel_imports) $
228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251
                addWarn (Reason Opt_WarnImplicitPrelude) (implicitPreludeWarn)

        ; -- TODO This is a little skeevy; maybe handle a bit more directly
          let { simplifyImport (dL->L _ idecl) =
                  ( fmap sl_fs (ideclPkgQual idecl) , ideclName idecl)
              }
        ; raw_sig_imports <- liftIO
                             $ findExtraSigImports hsc_env hsc_src
                                 (moduleName this_mod)
        ; raw_req_imports <- liftIO
                             $ implicitRequirements hsc_env
                                (map simplifyImport (prel_imports
                                                     ++ import_decls))
        ; let { mkImport (Nothing, dL->L _ mod_name) = noLoc
                $ (simpleImportDecl mod_name)
                  { ideclHiding = Just (False, noLoc [])}
              ; mkImport _ = panic "mkImport" }
        ; let { all_imports = prel_imports ++ import_decls
                       ++ map mkImport (raw_sig_imports ++ raw_req_imports) }
        ; -- OK now finally rename the imports
          tcg_env <- {-# SCC "tcRnImports" #-}
                     tcRnImports hsc_env all_imports

        ; -- If the whole module is warned about or deprecated
252
          -- (via mod_deprec) record that in tcg_warns. If we do thereby add
Gabor Greif's avatar
Gabor Greif committed
253
          -- a WarnAll, it will override any subsequent deprecations added to tcg_warns
254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302
          let { tcg_env1 = case mod_deprec of
                             Just (dL->L _ txt) ->
                               tcg_env {tcg_warns = WarnAll txt}
                             Nothing            -> tcg_env
              }
        ; setGblEnv tcg_env1
          $ do { -- Rename and type check the declarations
                 traceRn "rn1a" empty
               ; tcg_env <- if isHsBootOrSig hsc_src
                            then tcRnHsBootDecls hsc_src local_decls
                            else {-# SCC "tcRnSrcDecls" #-}
                                 tcRnSrcDecls explicit_mod_hdr local_decls
               ; setGblEnv tcg_env
                 $ do { -- Process the export list
                        traceRn "rn4a: before exports" empty
                      ; tcg_env <- tcRnExports explicit_mod_hdr export_ies
                                     tcg_env
                      ; traceRn "rn4b: after exports" empty
                      ; -- Check main is exported(must be after tcRnExports)
                        checkMainExported tcg_env
                      ; -- Compare hi-boot iface (if any) with the real thing
                        -- Must be done after processing the exports
                        tcg_env <- checkHiBootIface tcg_env boot_info
                      ; -- The new type env is already available to stuff
                        -- slurped from interface files, via
                        -- TcEnv.setGlobalTypeEnv. It's important that this
                        -- includes the stuff in checkHiBootIface,
                        -- because the latter might add new bindings for
                        -- boot_dfuns, which may be mentioned in imported
                        -- unfoldings.

                        -- Don't need to rename the Haddock documentation,
                        -- it's not parsed by GHC anymore.
                        tcg_env <- return (tcg_env
                                           { tcg_doc_hdr = maybe_doc_hdr })
                      ; -- Report unused names
                        -- Do this /after/ typeinference, so that when reporting
                        -- a function with no type signature we can give the
                        -- inferred type
                        reportUnusedNames export_ies tcg_env
                      ; -- add extra source files to tcg_dependent_files
                        addDependentFiles src_files
                      ; tcg_env <- runTypecheckerPlugin mod_sum hsc_env tcg_env
                      ; -- Dump output and return
                        tcDump tcg_env
                      ; return tcg_env }
               }
        }
      }
303 304 305

implicitPreludeWarn :: SDoc
implicitPreludeWarn
306
  = text "Module `Prelude' implicitly imported"
307

308 309 310
{-
************************************************************************
*                                                                      *
dterei's avatar
dterei committed
311
                Import declarations
312 313 314
*                                                                      *
************************************************************************
-}
315

316
tcRnImports :: HscEnv -> [LImportDecl GhcPs] -> TcM TcGblEnv
317
tcRnImports hsc_env import_decls
318
  = do  { (rn_imports, rdr_env, imports, hpc_info) <- rnImports import_decls ;
dterei's avatar
dterei committed
319

320
        ; this_mod <- getModule
321
        ; let { dep_mods :: ModuleNameEnv (ModuleName, IsBootInterface)
322
              ; dep_mods = imp_dep_mods imports
dterei's avatar
dterei committed
323 324 325 326

                -- We want instance declarations from all home-package
                -- modules below this one, including boot modules, except
                -- ourselves.  The 'except ourselves' is so that we don't
327 328 329 330
                -- get the instances from this module's hs-boot file.  This
                -- filtering also ensures that we don't see instances from
                -- modules batch (@--make@) compiled before this one, but
                -- which are not below this one.
dterei's avatar
dterei committed
331
              ; want_instances :: ModuleName -> Bool
332
              ; want_instances mod = mod `elemUFM` dep_mods
dterei's avatar
dterei committed
333
                                   && mod /= moduleName this_mod
dterei's avatar
dterei committed
334
              ; (home_insts, home_fam_insts) = hptInstances hsc_env
335
                                                            want_instances
dterei's avatar
dterei committed
336
              } ;
337

dterei's avatar
dterei committed
338
                -- Record boot-file info in the EPS, so that it's
dterei's avatar
dterei committed
339 340
                -- visible to loadHiBootInterface in tcRnSrcDecls,
                -- and any other incrementally-performed imports
341
        ; updateEps_ (\eps -> eps { eps_is_boot = dep_mods }) ;
342

dterei's avatar
dterei committed
343
                -- Update the gbl env
dterei's avatar
dterei committed
344 345
        ; updGblEnv ( \ gbl ->
            gbl {
346
              tcg_rdr_env      = tcg_rdr_env gbl `plusGlobalRdrEnv` rdr_env,
dterei's avatar
dterei committed
347
              tcg_imports      = tcg_imports gbl `plusImportAvails` imports,
348
              tcg_rn_imports   = rn_imports,
dterei's avatar
dterei committed
349
              tcg_inst_env     = extendInstEnvList (tcg_inst_env gbl) home_insts,
dterei's avatar
dterei committed
350
              tcg_fam_inst_env = extendFamInstEnvList (tcg_fam_inst_env gbl)
351
                                                      home_fam_insts,
dterei's avatar
dterei committed
352 353 354
              tcg_hpc          = hpc_info
            }) $ do {

355
        ; traceRn "rn1" (ppr (imp_dep_mods imports))
dterei's avatar
dterei committed
356
                -- Fail if there are any errors so far
dterei's avatar
dterei committed
357
                -- The error printing (if needed) takes advantage
dterei's avatar
dterei committed
358 359 360 361
                -- of the tcg_env we have now set
--      ; traceIf (text "rdr_env: " <+> ppr rdr_env)
        ; failIfErrsM

362 363 364 365 366 367 368 369 370
                -- Load any orphan-module (including orphan family
                -- instance-module) interfaces, so that their rules and
                -- instance decls will be found.  But filter out a
                -- self hs-boot: these instances will be checked when
                -- we define them locally.
                -- (We don't need to load non-orphan family instance
                -- modules until we either try to use the instances they
                -- define, or define our own family instances, at which
                -- point we need to check them for consistency.)
371
        ; loadModuleInterfaces (text "Loading orphan modules")
372
                               (filter (/= this_mod) (imp_orphs imports))
373

374 375
                -- Check type-family consistency between imports.
                -- See Note [The type family instance consistency story]
376
        ; traceRn "rn1: checking family instance consistency {" empty
dterei's avatar
dterei committed
377
        ; let { dir_imp_mods = moduleEnvKeys
dterei's avatar
dterei committed
378
                             . imp_mods
dterei's avatar
dterei committed
379
                             $ imports }
380
        ; checkFamInstConsistency dir_imp_mods
381
        ; traceRn "rn1: } checking family instance consistency" empty
382

383
        ; getGblEnv } }
384

385 386 387
{-
************************************************************************
*                                                                      *
dterei's avatar
dterei committed
388
        Type-checking the top level of a module
389 390 391
*                                                                      *
************************************************************************
-}
392

393
tcRnSrcDecls :: Bool  -- False => no 'module M(..) where' header at all
394
             -> [LHsDecl GhcPs]               -- Declarations
395
             -> TcM TcGblEnv
396
tcRnSrcDecls explicit_mod_hdr decls
397
 = do { -- Do all the declarations
398
      ; (tcg_env, tcl_env, lie) <- tc_rn_src_decls decls
399

400 401 402 403 404 405
        -- Check for the 'main' declaration
        -- Must do this inside the captureTopConstraints
      ; (tcg_env, lie_main) <- setEnvs (tcg_env, tcl_env) $
                               -- always set envs *before* captureTopConstraints
                               captureTopConstraints $
                               checkMain explicit_mod_hdr
406

407
      ; setEnvs (tcg_env, tcl_env) $ do {
408

409
             --         Simplify constraints
dterei's avatar
dterei committed
410
             --
dterei's avatar
dterei committed
411
             -- We do this after checkMain, so that we use the type info
dterei's avatar
dterei committed
412
             -- that checkMain adds
dterei's avatar
dterei committed
413
             --
dterei's avatar
dterei committed
414 415
             -- We do it with both global and local env in scope:
             --  * the global env exposes the instances to simplifyTop
dterei's avatar
dterei committed
416
             --  * the local env exposes the local Ids to simplifyTop,
dterei's avatar
dterei committed
417
             --    so that we get better error messages (monomorphism restriction)
418
      ; new_ev_binds <- {-# SCC "simplifyTop" #-}
419
                        simplifyTop (lie `andWC` lie_main)
420

421 422 423
        -- Emit Typeable bindings
      ; tcg_env <- mkTypeableBinds

424

425
      ; traceTc "Tc9" empty
426

427
      ; failIfErrsM     -- Don't zonk if there have been errors
dterei's avatar
dterei committed
428 429
                        -- It's a waste of time; and we may get debug warnings
                        -- about strangely-typed TyCons!
430
      ; traceTc "Tc10" empty
431

432 433
        -- Zonk the final code.  This must be done last.
        -- Even simplifyTop may do some unification.
434
        -- This pass also warns about missing type signatures
435
      ; (bind_env, ev_binds', binds', fords', imp_specs', rules')
436 437 438 439 440 441 442 443 444
            <- zonkTcGblEnv new_ev_binds tcg_env

        -- Finalizers must run after constraints are simplified, or some types
        -- might not be complete when using reify (see #12777).
        -- and also after we zonk the first time because we run typed splices
        -- in the zonker which gives rise to the finalisers.
      ; (tcg_env_mf, _) <- setGblEnv (clearTcGblEnv tcg_env)
                                     run_th_modfinalizers
      ; finishTH
445
      ; traceTc "Tc11" empty
dterei's avatar
dterei committed
446

447 448 449 450 451 452 453 454 455 456 457 458 459 460 461
      ; -- zonk the new bindings arising from running the finalisers.
        -- This won't give rise to any more finalisers as you can't nest
        -- finalisers inside finalisers.
      ; (bind_env_mf, ev_binds_mf, binds_mf, fords_mf, imp_specs_mf, rules_mf)
            <- zonkTcGblEnv emptyBag tcg_env_mf


      ; let { final_type_env = plusTypeEnv (tcg_type_env tcg_env)
                                (plusTypeEnv bind_env_mf bind_env)
            ; tcg_env' = tcg_env_mf
                          { tcg_binds    = binds' `unionBags` binds_mf,
                            tcg_ev_binds = ev_binds' `unionBags` ev_binds_mf ,
                            tcg_imp_specs = imp_specs' ++ imp_specs_mf ,
                            tcg_rules    = rules' ++ rules_mf ,
                            tcg_fords    = fords' ++ fords_mf } } ;
462

463
      ; setGlobalTypeEnv tcg_env' final_type_env
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 491
zonkTcGblEnv :: Bag EvBind -> TcGblEnv
             -> TcM (TypeEnv, Bag EvBind, LHsBinds GhcTc,
                       [LForeignDecl GhcTc], [LTcSpecPrag], [LRuleDecl GhcTc])
zonkTcGblEnv new_ev_binds tcg_env =
  let TcGblEnv {   tcg_binds     = binds,
                   tcg_ev_binds  = cur_ev_binds,
                   tcg_imp_specs = imp_specs,
                   tcg_rules     = rules,
                   tcg_fords     = fords } = tcg_env

      all_ev_binds = cur_ev_binds `unionBags` new_ev_binds

  in {-# SCC "zonkTopDecls" #-}
      zonkTopDecls all_ev_binds binds rules imp_specs fords


-- | Remove accumulated bindings, rules and so on from TcGblEnv
clearTcGblEnv :: TcGblEnv -> TcGblEnv
clearTcGblEnv tcg_env
  = tcg_env { tcg_binds    = emptyBag,
              tcg_ev_binds = emptyBag ,
              tcg_imp_specs = [],
              tcg_rules    = [],
              tcg_fords    = [] }

492 493 494 495 496 497 498 499 500 501
-- | Runs TH finalizers and renames and typechecks the top-level declarations
-- that they could introduce.
run_th_modfinalizers :: TcM (TcGblEnv, TcLclEnv)
run_th_modfinalizers = do
  th_modfinalizers_var <- fmap tcg_th_modfinalizers getGblEnv
  th_modfinalizers <- readTcRef th_modfinalizers_var
  if null th_modfinalizers
  then getEnvs
  else do
    writeTcRef th_modfinalizers_var []
502 503 504 505
    let run_finalizer (lcl_env, f) =
            setLclEnv lcl_env (runRemoteModFinalizers f)

    (_, lie_th) <- captureTopConstraints $ mapM_ run_finalizer th_modfinalizers
506 507 508 509
      -- Finalizers can add top-level declarations with addTopDecls, so
      -- we have to run tc_rn_src_decls to get them
    (tcg_env, tcl_env, lie_top_decls) <- tc_rn_src_decls []
    setEnvs (tcg_env, tcl_env) $ do
510 511 512 513
      -- Subsequent rounds of finalizers run after any new constraints are
      -- simplified, or some types might not be complete when using reify
      -- (see #12777).
      new_ev_binds <- {-# SCC "simplifyTop2" #-}
514
                      simplifyTop (lie_th `andWC` lie_top_decls)
515
      addTopEvBinds new_ev_binds run_th_modfinalizers
516
        -- addTopDecls can add declarations which add new finalizers.
517

518
tc_rn_src_decls :: [LHsDecl GhcPs]
519
                -> TcM (TcGblEnv, TcLclEnv, WantedConstraints)
dterei's avatar
dterei committed
520
-- Loops around dealing with each top level inter-splice group
521
-- in turn, until it's dealt with the entire module
522
-- Never emits constraints; calls captureTopConstraints internally
523
tc_rn_src_decls ds
524
 = {-# SCC "tc_rn_src_decls" #-}
gmainland's avatar
gmainland committed
525
   do { (first_group, group_tail) <- findSplice ds
dterei's avatar
dterei committed
526
                -- If ds is [] we get ([], Nothing)
dterei's avatar
dterei committed
527

dterei's avatar
dterei committed
528
        -- Deal with decls up to, but not including, the first splice
529
      ; (tcg_env, rn_decls) <- rnTopSrcDecls first_group
dterei's avatar
dterei committed
530
                -- rnTopSrcDecls fails if there are any errors
dterei's avatar
dterei committed
531

532 533
        -- Get TH-generated top-level declarations and make sure they don't
        -- contain any splices since we don't handle that at the moment
534 535
        --
        -- The plumbing here is a bit odd: see Trac #10853
536 537 538 539 540 541 542 543 544
      ; th_topdecls_var <- fmap tcg_th_topdecls getGblEnv
      ; th_ds <- readTcRef th_topdecls_var
      ; writeTcRef th_topdecls_var []

      ; (tcg_env, rn_decls) <-
            if null th_ds
            then return (tcg_env, rn_decls)
            else do { (th_group, th_group_tail) <- findSplice th_ds
                    ; case th_group_tail of
545 546 547 548 549 550 551
                        { Nothing -> return ()
                        ; Just (SpliceDecl _ (dL->L loc _) _, _) ->
                            setSrcSpan loc
                            $ addErr (text
                                ("Declaration splices are not "
                                  ++ "permitted inside top-level "
                                  ++ "declarations added with addTopDecls"))
552
                        ; Just (XSpliceDecl _, _) -> panic "tc_rn_src_decls"
553 554 555 556
                        }
                      -- Rename TH-generated top-level declarations
                    ; (tcg_env, th_rn_decls) <- setGblEnv tcg_env
                        $ rnTopSrcDecls th_group
557

558
                      -- Dump generated top-level declarations
559
                    ; let msg = "top-level declarations added with addTopDecls"
560 561 562 563 564
                    ; traceSplice
                        $ SpliceInfo { spliceDescription = msg
                                     , spliceIsDecl    = True
                                     , spliceSource    = Nothing
                                     , spliceGenerated = ppr th_rn_decls }
565 566 567 568
                    ; return (tcg_env, appendGroups rn_decls th_rn_decls)
                    }

      -- Type check all declarations
569 570 571 572 573 574
      -- NB: set the env **before** captureTopConstraints so that error messages
      -- get reported w.r.t. the right GlobalRdrEnv. It is for this reason that
      -- the captureTopConstraints must go here, not in tcRnSrcDecls.
      ; ((tcg_env, tcl_env), lie1) <- setGblEnv tcg_env $
                                      captureTopConstraints $
                                      tcTopSrcDecls rn_decls
575

dterei's avatar
dterei committed
576
        -- If there is no splice, we're nearly done
gmainland's avatar
gmainland committed
577 578
      ; setEnvs (tcg_env, tcl_env) $
        case group_tail of
579
          { Nothing -> return (tcg_env, tcl_env, lie1)
580

gmainland's avatar
gmainland committed
581
            -- If there's a splice, we must carry on
582
          ; Just (SpliceDecl _ (dL->L loc splice) _, rest_ds) ->
583 584 585
            do { recordTopLevelSpliceLoc loc

                 -- Rename the splice expression, and get its supporting decls
586
               ; (spliced_decls, splice_fvs) <- rnTopSpliceDecls splice
gmainland's avatar
gmainland committed
587 588

                 -- Glue them on the front of the remaining decls and loop
589 590 591 592 593
               ; (tcg_env, tcl_env, lie2) <-
                   setGblEnv (tcg_env `addTcgDUs` usesOnly splice_fvs) $
                   tc_rn_src_decls (spliced_decls ++ rest_ds)

               ; return (tcg_env, tcl_env, lie1 `andWC` lie2)
gmainland's avatar
gmainland committed
594
               }
595
          ; Just (XSpliceDecl _, _) -> panic "tc_rn_src_decls"
gmainland's avatar
gmainland committed
596 597
          }
      }
598

599 600 601
{-
************************************************************************
*                                                                      *
dterei's avatar
dterei committed
602 603
        Compiling hs-boot source files, and
        comparing the hi-boot interface with the real thing
604 605 606
*                                                                      *
************************************************************************
-}
607

608
tcRnHsBootDecls :: HscSource -> [LHsDecl GhcPs] -> TcM TcGblEnv
609
tcRnHsBootDecls hsc_src decls
610
   = do { (first_group, group_tail) <- findSplice decls
611

dterei's avatar
dterei committed
612
                -- Rename the declarations
613 614 615 616 617 618
        ; (tcg_env, HsGroup { hs_tyclds = tycl_decls
                            , hs_derivds = deriv_decls
                            , hs_fords  = for_decls
                            , hs_defds  = def_decls
                            , hs_ruleds = rule_decls
                            , hs_annds  = _
619 620
                            , hs_valds
                                 = XValBindsLR (NValBinds val_binds val_sigs) })
621
              <- rnTopSrcDecls first_group
622 623
        -- The empty list is for extra dependencies coming from .hs-boot files
        -- See Note [Extra dependencies from .hs-boot files] in RnSource
624 625 626
        ; (gbl_env, lie) <- setGblEnv tcg_env $ captureTopConstraints $ do {
              -- NB: setGblEnv **before** captureTopConstraints so that
              -- if the latter reports errors, it knows what's in scope
dterei's avatar
dterei committed
627 628 629

                -- Check for illegal declarations
        ; case group_tail of
630 631
             Just (SpliceDecl _ d _, _) -> badBootDecl hsc_src "splice" d
             Just (XSpliceDecl _, _) -> panic "tcRnHsBootDecls"
dterei's avatar
dterei committed
632
             Nothing                  -> return ()
633 634 635
        ; mapM_ (badBootDecl hsc_src "foreign") for_decls
        ; mapM_ (badBootDecl hsc_src "default") def_decls
        ; mapM_ (badBootDecl hsc_src "rule")    rule_decls
dterei's avatar
dterei committed
636

Gabor Greif's avatar
Gabor Greif committed
637
                -- Typecheck type/class/instance decls
638
        ; traceTc "Tc2 (boot)" empty
dterei's avatar
dterei committed
639
        ; (tcg_env, inst_infos, _deriv_binds)
640
             <- tcTyClsInstDecls tycl_decls deriv_decls val_binds
dterei's avatar
dterei committed
641 642
        ; setGblEnv tcg_env     $ do {

Ben Gamari's avatar
Ben Gamari committed
643 644 645 646
        -- Emit Typeable bindings
        ; tcg_env <- mkTypeableBinds
        ; setGblEnv tcg_env $ do {

dterei's avatar
dterei committed
647
                -- Typecheck value declarations
dterei's avatar
dterei committed
648
        ; traceTc "Tc5" empty
649
        ; val_ids <- tcHsBootSigs val_binds val_sigs
dterei's avatar
dterei committed
650 651 652 653

                -- Wrap up
                -- No simplification or zonking to do
        ; traceTc "Tc7a" empty
dterei's avatar
dterei committed
654 655
        ; gbl_env <- getGblEnv

dterei's avatar
dterei committed
656 657
                -- Make the final type-env
                -- Include the dfun_ids so that their type sigs
dterei's avatar
dterei committed
658
                -- are written into the interface file.
dterei's avatar
dterei committed
659 660
        ; let { type_env0 = tcg_type_env gbl_env
              ; type_env1 = extendTypeEnvWithIds type_env0 val_ids
Edward Z. Yang's avatar
Edward Z. Yang committed
661
              ; type_env2 = extendTypeEnvWithIds type_env1 dfun_ids
dterei's avatar
dterei committed
662 663 664 665
              ; dfun_ids = map iDFunId inst_infos
              }

        ; setGlobalTypeEnv gbl_env type_env2
Ben Gamari's avatar
Ben Gamari committed
666
   }}}
667
   ; traceTc "boot" (ppr lie); return gbl_env }
668

669
badBootDecl :: HscSource -> String -> Located decl -> TcM ()
670
badBootDecl hsc_src what (dL->L loc _)
dterei's avatar
dterei committed
671
  = addErrAt loc (char 'A' <+> text what
672
      <+> text "declaration is not (currently) allowed in a"
673
      <+> (case hsc_src of
674 675
            HsBootFile -> text "hs-boot"
            HsigFile -> text "hsig"
676
            _ -> panic "badBootDecl: should be an hsig or hs-boot file")
677
      <+> text "file")
678

679
{-
680 681
Once we've typechecked the body of the module, we want to compare what
we've found (gathered in a TypeEnv) with the hi-boot details (if any).
682
-}
683

684
checkHiBootIface :: TcGblEnv -> SelfBootInfo -> TcM TcGblEnv
685 686
-- Compare the hi-boot file for this module (if there is one)
-- with the type environment we've just come up with
687 688
-- In the common case where there is no hi-boot file, the list
-- of boot_names is empty.
689

690 691
checkHiBootIface tcg_env boot_info
  | NoSelfBoot <- boot_info  -- Common case
dterei's avatar
dterei committed
692
  = return tcg_env
693

694 695 696 697 698 699 700 701
  | HsBootFile <- tcg_src tcg_env   -- Current module is already a hs-boot file!
  = return tcg_env

  | SelfBoot { sb_mds = boot_details } <- boot_info
  , TcGblEnv { tcg_binds    = binds
             , tcg_insts    = local_insts
             , tcg_type_env = local_type_env
             , tcg_exports  = local_exports } <- tcg_env
702
  = do  { -- This code is tricky, see Note [DFun knot-tying]
703
        ; dfun_prs <- checkHiBootIface' local_insts local_type_env
704
                                        local_exports boot_details
705

706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722
        -- Now add the boot-dfun bindings  $fxblah = $fblah
        -- to (a) the type envt, and (b) the top-level bindings
        ; let boot_dfuns = map fst dfun_prs
              type_env'  = extendTypeEnvWithIds local_type_env boot_dfuns
              dfun_binds = listToBag [ mkVarBind boot_dfun (nlHsVar dfun)
                                     | (boot_dfun, dfun) <- dfun_prs ]
              tcg_env_w_binds
                = tcg_env { tcg_binds = binds `unionBags` dfun_binds }

        ; type_env' `seq`
             -- Why the seq?  Without, we will put a TypeEnv thunk in
             -- tcg_type_env_var.  That thunk will eventually get
             -- forced if we are typechecking interfaces, but that
             -- is no good if we are trying to typecheck the very
             -- DFun we were going to put in.
             -- TODO: Maybe setGlobalTypeEnv should be strict.
          setGlobalTypeEnv tcg_env_w_binds type_env' }
723

724 725
  | otherwise = panic "checkHiBootIface: unreachable code"

726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763
{- Note [DFun impedance matching]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We return a list of "impedance-matching" bindings for the dfuns
defined in the hs-boot file, such as
          $fxEqT = $fEqT
We need these because the module and hi-boot file might differ in
the name it chose for the dfun: the name of a dfun is not
uniquely determined by its type; there might be multiple dfuns
which, individually, would map to the same name (in which case
we have to disambiguate them.)  There's no way for the hi file
to know exactly what disambiguation to use... without looking
at the hi-boot file itself.

In fact, the names will always differ because we always pick names
prefixed with "$fx" for boot dfuns, and "$f" for real dfuns
(so that this impedance matching is always possible).

Note [DFun knot-tying]
~~~~~~~~~~~~~~~~~~~~~~
The 'SelfBootInfo' that is fed into 'checkHiBootIface' comes from
typechecking the hi-boot file that we are presently implementing.
Suppose we are typechecking the module A: when we typecheck the
hi-boot file, whenever we see an identifier A.T, we knot-tie this
identifier to the *local* type environment (via if_rec_types.)  The
contract then is that we don't *look* at 'SelfBootInfo' until we've
finished typechecking the module and updated the type environment with
the new tycons and ids.

This most works well, but there is one problem: DFuns!  We do not want
to look at the mb_insts of the ModDetails in SelfBootInfo, because a
dfun in one of those ClsInsts is gotten (in TcIface.tcIfaceInst) by a
(lazily evaluated) lookup in the if_rec_types.  We could extend the
type env, do a setGloblaTypeEnv etc; but that all seems very indirect.
It is much more directly simply to extract the DFunIds from the
md_types of the SelfBootInfo.

See Trac #4003, #16038 for why we need to take care here.
-}
764

765
checkHiBootIface' :: [ClsInst] -> TypeEnv -> [AvailInfo]
766
                  -> ModDetails -> TcM [(Id, Id)]
767 768 769 770
-- Variant which doesn't require a full TcGblEnv; you could get the
-- local components from another ModDetails.
checkHiBootIface'
        local_insts local_type_env local_exports
771 772 773
        (ModDetails { md_types = boot_type_env
                    , md_fam_insts = boot_fam_insts
                    , md_exports = boot_exports })
dterei's avatar
dterei committed
774
  = do  { traceTc "checkHiBootIface" $ vcat
775
             [ ppr boot_type_env, ppr boot_exports]
776

dterei's avatar
dterei committed
777 778
                -- Check the exports of the boot module, one by one
        ; mapM_ check_export boot_exports
779

dterei's avatar
dterei committed
780 781 782 783
                -- Check for no family instances
        ; unless (null boot_fam_insts) $
            panic ("TcRnDriver.checkHiBootIface: Cannot handle family " ++
                   "instances in boot files yet...")
784
            -- FIXME: Why?  The actual comparison is not hard, but what would
dterei's avatar
dterei committed
785 786
            --        be the equivalent to the dfun bindings returned for class
            --        instances?  We can't easily equate tycons...
787

dterei's avatar
dterei committed
788
                -- Check instance declarations
Gabor Greif's avatar
Gabor Greif committed
789
                -- and generate an impedance-matching binding
790
        ; mb_dfun_prs <- mapM check_cls_inst boot_dfuns
791

792
        ; failIfErrsM
793

794
        ; return (catMaybes mb_dfun_prs) }
795

796
  where
797 798 799 800 801 802
    boot_dfun_names = map idName boot_dfuns
    boot_dfuns      = filter isDFunId $ typeEnvIds boot_type_env
       -- NB: boot_dfuns is /not/ defined thus: map instanceDFunId md_insts
       --     We don't want to look at md_insts!
       --     Why not?  See Note [DFun knot-tying]

dterei's avatar
dterei committed
803
    check_export boot_avail     -- boot_avail is exported by the boot iface
804 805
      | name `elem` boot_dfun_names = return ()
      | isWiredInName name          = return () -- No checking for wired-in names.  In particular,
dterei's avatar
dterei committed
806 807
                                                -- 'error' is handled by a rather gross hack
                                                -- (see comments in GHC.Err.hs-boot)
808

dterei's avatar
dterei committed
809
        -- Check that the actual module exports the same thing
810
      | not (null missing_names)
dterei's avatar
dterei committed
811
      = addErrAt (nameSrcSpan (head missing_names))
812
                 (missingBootThing True (head missing_names) "exported by")
813

dterei's avatar
dterei committed
814 815
        -- If the boot module does not *define* the thing, we are done
        -- (it simply re-exports it, and names match, so nothing further to do)
816
      | isNothing mb_boot_thing = return ()
817

dterei's avatar
dterei committed
818
        -- Check that the actual module also defines the thing, and
dterei's avatar
dterei committed
819
        -- then compare the definitions
820 821
      | Just real_thing <- lookupTypeEnv local_type_env name,
        Just boot_thing <- mb_boot_thing
822
      = checkBootDeclM True boot_thing real_thing
823

824
      | otherwise
825
      = addErrTc (missingBootThing True name "defined in")
826
      where
dterei's avatar
dterei committed
827 828 829 830 831
        name          = availName boot_avail
        mb_boot_thing = lookupTypeEnv boot_type_env name
        missing_names = case lookupNameEnv local_export_env name of
                          Nothing    -> [name]
                          Just avail -> availNames boot_avail `minusList` availNames avail
dterei's avatar
dterei committed
832

833 834
    local_export_env :: NameEnv AvailInfo
    local_export_env = availsToNameEnv local_exports
835

836
    check_cls_inst :: DFunId -> TcM (Maybe (Id, Id))
837 838 839 840
        -- Returns a pair of the boot dfun in terms of the equivalent
        -- real dfun. Delicate (like checkBootDecl) because it depends
        -- on the types lining up precisely even to the ordering of
        -- the type variables in the foralls.
841 842 843 844 845 846 847
    check_cls_inst boot_dfun
      | (real_dfun : _) <- find_real_dfun boot_dfun
      , let local_boot_dfun = Id.mkExportedVanillaId
                                  (idName boot_dfun) (idType real_dfun)
      = return (Just (local_boot_dfun, real_dfun))
          -- Two tricky points here:
          --
848 849 850 851 852 853
          --  * The local_boot_fun should have a Name from the /boot-file/,
          --    but type from the dfun defined in /this module/.
          --    That ensures that the TyCon etc inside the type are
          --    the ones defined in this module, not the ones gotten
          --    from the hi-boot file, which may have a lot less info
          --    (Trac #8743, comment:10).
854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877
          --
          --  * The DFunIds from boot_details are /GlobalIds/, because
          --    they come from typechecking M.hi-boot.
          --    But all bindings in this module should be for /LocalIds/,
          --    otherwise dependency analysis fails (Trac #16038). This
          --    is another reason for using mkExportedVanillaId, rather
          --    that modifying boot_dfun, to make local_boot_fun.

      | otherwise
      = setSrcSpan (getLoc (getName boot_dfun)) $
        do { traceTc "check_cls_inst" $ vcat
                [ text "local_insts"  <+>
                     vcat (map (ppr . idType . instanceDFunId) local_insts)
                , text "boot_dfun_ty" <+> ppr (idType boot_dfun) ]

           ; addErrTc (instMisMatch boot_dfun)
           ; return Nothing }

    find_real_dfun :: DFunId -> [DFunId]
    find_real_dfun boot_dfun
       = [dfun | inst <- local_insts
               , let dfun = instanceDFunId inst
               , idType dfun `eqType` boot_dfun_ty ]
       where
878
          boot_dfun_ty   = idType boot_dfun
879

880

Edward Z. Yang's avatar
Edward Z. Yang committed
881 882
-- In general, to perform these checks we have to
-- compare the TyThing from the .hi-boot file to the TyThing
883 884 885 886 887 888
-- in the current source file.  We must be careful to allow alpha-renaming
-- where appropriate, and also the boot declaration is allowed to omit
-- constructors and class methods.
--
-- See rnfail055 for a good test of this stuff.

889 890 891 892 893
-- | Compares two things for equivalence between boot-file and normal code,
-- reporting an error if they don't match up.
checkBootDeclM :: Bool  -- ^ True <=> an hs-boot file (could also be a sig)
               -> TyThing -> TyThing -> TcM ()
checkBootDeclM is_boot boot_thing real_thing
Edward Z. Yang's avatar
Edward Z. Yang committed
894
  = whenIsJust (checkBootDecl is_boot boot_thing real_thing) $ \ err ->
895
       addErrAt span
896
                (bootMisMatch is_boot err real_thing boot_thing)
897 898 899 900 901 902 903 904 905
  where
    -- Here we use the span of the boot thing or, if it doesn't have a sensible
    -- span, that of the real thing,
    span
      | let span = nameSrcSpan (getName boot_thing)
      , isGoodSrcSpan span
      = span
      | otherwise
      = nameSrcSpan (getName real_thing)
906 907 908 909 910

-- | Compares the two things for equivalence between boot-file and normal
-- code. Returns @Nothing@ on success or @Just "some helpful info for user"@
-- failure. If the difference will be apparent to the user, @Just empty@ is
-- perfectly suitable.
Edward Z. Yang's avatar
Edward Z. Yang committed
911
checkBootDecl :: Bool -> TyThing -> TyThing -> Maybe SDoc
912

Edward Z. Yang's avatar
Edward Z. Yang committed
913
checkBootDecl _ (AnId id1) (AnId id2)
dterei's avatar
dterei committed
914
  = ASSERT(id1 == id2)
915 916
    check (idType id1 `eqType` idType id2)
          (text "The two types are different")
917

Edward Z. Yang's avatar
Edward Z. Yang committed
918 919
checkBootDecl is_boot (ATyCon tc1) (ATyCon tc2)
  = checkBootTyCon is_boot tc1 tc2
920

Edward Z. Yang's avatar
Edward Z. Yang committed
921
checkBootDecl _ (AConLike (RealDataCon dc1)) (AConLike (RealDataCon _))
922 923
  = pprPanic "checkBootDecl" (ppr dc1)

Edward Z. Yang's avatar
Edward Z. Yang committed
924
checkBootDecl _ _ _ = Just empty -- probably shouldn't happen
925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945

-- | Combines two potential error messages
andThenCheck :: Maybe SDoc -> Maybe SDoc -> Maybe SDoc
Nothing `andThenCheck` msg     = msg
msg     `andThenCheck` Nothing = msg
Just d1 `andThenCheck` Just d2 = Just (d1 $$ d2)
infixr 0 `andThenCheck`

-- | If the test in the first parameter is True, succeed with @Nothing@;
-- otherwise, return the provided check
checkUnless :: Bool -> Maybe SDoc -> Maybe SDoc
checkUnless True  _ = Nothing
checkUnless False k = k

-- | Run the check provided for every pair of elements in the lists.
-- The provided SDoc should name the element type, in the plural.
checkListBy :: (a -> a -> Maybe SDoc) -> [a] -> [a] -> SDoc
            -> Maybe SDoc
checkListBy check_fun as bs whats = go [] as bs
  where
    herald = text "The" <+> whats <+> text "do not match"
946

947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963
    go []   [] [] = Nothing
    go docs [] [] = Just (hang (herald <> colon) 2 (vcat $ reverse docs))
    go docs (x:xs) (y:ys) = case check_fun x y of
      Just doc -> go (doc:docs) xs ys
      Nothing  -> go docs       xs ys
    go _    _  _ = Just (hang (herald <> colon)
                            2 (text "There are different numbers of" <+> whats))

-- | If the test in the first parameter is True, succeed with @Nothing@;
-- otherwise, fail with the given SDoc.
check :: Bool -> SDoc -> Maybe SDoc
check True  _   = Nothing
check False doc = Just doc

-- | A more perspicuous name for @Nothing@, for @checkBootDecl@ and friends.
checkSuccess :: Maybe SDoc
checkSuccess = Nothing
964 965

----------------
Edward Z. Yang's avatar
Edward Z. Yang committed
966 967
checkBootTyCon :: Bool -> TyCon -> TyCon -> Maybe SDoc
checkBootTyCon is_boot tc1 tc2
968
  | not (eqType (tyConKind tc1) (tyConKind tc2))
969
  = Just $ text "The types have different kinds"    -- First off, check the kind
970 971 972

  | Just c1 <- tyConClass_maybe tc1
  , Just c2 <- tyConClass_maybe tc2
973
  , let (clas_tvs1, clas_fds1, sc_theta1, _, ats1, op_stuff1)
974
          = classExtraBigSig c1
975
        (clas_tvs2, clas_fds2, sc_theta2, _, ats2, op_stuff2)
976
          = classExtraBigSig c2
977
  , Just env <- eqVarBndrs emptyRnEnv2 clas_tvs1 clas_tvs2
978
  = let
979
       eqSig (id1, def_meth1) (id2, def_meth2)
980 981 982 983 984 985
         = check (name1 == name2)
                 (text "The names" <+> pname1 <+> text "and" <+> pname2 <+>
                  text "are different") `andThenCheck`
           check (eqTypeX env op_ty1 op_ty2)
                 (text "The types of" <+> pname1 <+>
                  text "are different") `andThenCheck`
986 987 988 989 990 991 992
           if is_boot
               then check (eqMaybeBy eqDM def_meth1 def_meth2)
                          (text "The default methods associated with" <+> pname1 <+>
                           text "are different")
               else check (subDM op_ty1 def_meth1 def_meth2)
                          (text "The default methods associated with" <+> pname1 <+>
                           text "are not compatible")
993
         where
994 995 996 997
          name1 = idName id1
          name2 = idName id2
          pname1 = quotes (ppr name1)
          pname2 = quotes (ppr name2)
998 999 1000
          (_, rho_ty1) = splitForAllTys (idType id1)
          op_ty1 = funResultTy rho_ty1
          (_, rho_ty2) = splitForAllTys (idType id2)
1001 1002
          op_ty2 = funResultTy rho_ty2

1003
       eqAT (ATI tc1 def_ats1) (ATI tc2 def_ats2)
Edward Z. Yang's avatar
Edward Z. Yang committed
1004
         = checkBootTyCon is_boot tc1 tc2 `andThenCheck`
1005 1006
           check (eqATDef def_ats1 def_ats2)
                 (text "The associated type defaults differ")
1007

1008 1009 1010 1011
       eqDM (_, VanillaDM)    (_, VanillaDM)    = True
       eqDM (_, GenericDM t1) (_, GenericDM t2) = eqTypeX env t1 t2
       eqDM _ _ = False

1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031
       -- NB: first argument is from hsig, second is from real impl.
       -- Order of pattern matching matters.
       subDM _ Nothing _ = True
       subDM _ _ Nothing = False
       -- If the hsig wrote:
       --
       --   f :: a -> a
       --   default f :: a -> a
       --
       -- this should be validly implementable using an old-fashioned
       -- vanilla default method.
       subDM t1 (Just (_, GenericDM t2)) (Just (_, VanillaDM))
        = eqTypeX env t1 t2
       -- This case can occur when merging signatures
       subDM t1 (Just (_, VanillaDM)) (Just (_, GenericDM t2))
        = eqTypeX env t1 t2
       subDM _ (Just (_, VanillaDM)) (Just (_, VanillaDM)) = True
       subDM _ (Just (_, GenericDM t1)) (Just (_, GenericDM t2))
        = eqTypeX env t1 t2

dreixel's avatar
dreixel committed
1032
       -- Ignore the location of the defaults
1033 1034
       eqATDef Nothing             Nothing             = True
       eqATDef (Just (ty1, _loc1)) (Just (ty2, _loc2)) = eqTypeX env ty1 ty2
1035
       eqATDef _ _ = False
1036

dterei's avatar
dterei committed
1037
       eqFD (as1,bs1) (as2,bs2) =
1038 1039
         eqListBy (eqTypeX env) (mkTyVarTys as1) (mkTyVarTys as2) &&
         eqListBy (eqTypeX env) (mkTyVarTys bs1) (mkTyVarTys bs2)
1040
    in
1041
    checkRoles roles1 roles2 `andThenCheck`
1042 1043 1044
          -- Checks kind of class
    check (eqListBy eqFD clas_fds1 clas_fds2)
          (text "The functional dependencies do not match") `andThenCheck`
1045
    checkUnless (isAbstractTyCon tc1) $
1046
    check (eqListBy (eqTypeX env) sc_theta1 sc_theta2)
1047 1048
          (text "The class constraints do not match") `andThenCheck`
    checkListBy eqSig op_stuff1 op_stuff2 (text "methods") `andThenCheck`
1049 1050 1051
    checkListBy eqAT ats1 ats2 (text "associated types") `andThenCheck`
    check (classMinimalDef c1 `BF.implies` classMinimalDef c2)
        (text "The MINIMAL pragmas are not compatible")
1052

1053 1054
  | Just syn_rhs1 <- synTyConRhs_maybe tc1
  , Just syn_rhs2 <- synTyConRhs_maybe tc2
1055
  , Just env <- eqVarBndrs emptyRnEnv2 (tyConTyVars tc1) (tyConTyVars tc2)
1056
  = ASSERT(tc1 == tc2)
1057
    checkRoles roles1 roles2 `andThenCheck`
1058
    check (eqTypeX env syn_rhs1 syn_rhs2) empty   -- nothing interesting to say
1059
  -- This allows abstract 'data T a' to be implemented using 'type T = ...'
1060
  -- and abstract 'class K a' to be implement using 'type K = ...'
1061 1062 1063
  -- See Note [Synonyms implement abstract data]
  | not is_boot -- don't support for hs-boot yet
  , isAbstractTyCon tc1
1064 1065
  , Just (tvs, ty) <- synTyConDefn_maybe tc2
  , Just (tc2', args) <- tcSplitTyConApp_maybe ty
1066
  = checkSynAbsData tvs ty tc2' args
1067 1068
    -- TODO: When it's a synonym implementing a class, we really
    -- should check if the fundeps are satisfied, but
1069 1070 1071 1072
    -- there is not an obvious way to do this for a constraint synonym.
    -- So for now, let it all through (it won't cause segfaults, anyway).
    -- Tracked at #12704.

1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083
  -- This allows abstract 'data T :: Nat' to be implemented using
  -- 'type T = 42' Since the kinds already match (we have checked this
  -- upfront) all we need to check is that the implementation 'type T
  -- = ...' defined an actual literal.  See #15138 for the case this
  -- handles.
  | not is_boot
  , isAbstractTyCon tc1
  , Just (_,ty2) <- synTyConDefn_maybe tc2
  , isJust (isLitTy ty2)
  = Nothing

1084 1085 1086
  | Just fam_flav1 <- famTyConFlav_maybe tc1
  , Just fam_flav2 <- famTyConFlav_maybe tc2
  = ASSERT(tc1 == tc2)
1087 1088
    let eqFamFlav OpenSynFamilyTyCon   OpenSynFamilyTyCon = True
        eqFamFlav (DataFamilyTyCon {}) (DataFamilyTyCon {}) = True
1089 1090
        -- This case only happens for hsig merging:
        eqFamFlav AbstractClosedSynFamilyTyCon AbstractClosedSynFamilyTyCon = True
1091 1092 1093
        eqFamFlav AbstractClosedSynFamilyTyCon (ClosedSynFamilyTyCon {}) = True
        eqFamFlav (ClosedSynFamilyTyCon {}) AbstractClosedSynFamilyTyCon = True
        eqFamFlav (ClosedSynFamilyTyCon ax1) (ClosedSynFamilyTyCon ax2)
1094
            = eqClosedFamilyAx ax1 ax2
1095
        eqFamFlav (BuiltInSynFamTyCon {}) (BuiltInSynFamTyCon {}) = tc1 == tc2
1096
        eqFamFlav _ _ = False
1097 1098
        injInfo1 = tyConInjectivityInfo tc1
        injInfo2 = tyConInjectivityInfo tc2
1099
    in
Jan Stolarek's avatar
Jan Stolarek committed
1100
    -- check equality of roles, family flavours and injectivity annotations
1101 1102
    -- (NB: Type family roles are always nominal. But the check is
    -- harmless enough.)
1103
    checkRoles roles1 roles2 `andThenCheck`
1104
    check (eqFamFlav fam_flav1 fam_flav2)
Simon Peyton Jones's avatar
Simon Peyton Jones committed
1105
        (whenPprDebug $
1106 1107 1108
            text "Family flavours" <+> ppr fam_flav1 <+> text "and" <+> ppr fam_flav2 <+>
            text "do not match") `andThenCheck`
    check (injInfo1 == injInfo2) (text "Injectivities do not match")
1109 1110

  | isAlgTyCon tc1 && isAlgTyCon tc2
1111
  , Just env <- eqVarBndrs emptyRnEnv2 (tyConTyVars tc1) (tyConTyVars tc2)
1112
  = ASSERT(tc1 == tc2)
1113
    checkRoles roles1 roles2 `andThenCheck`
1114
    check (eqListBy (eqTypeX env)
1115 1116 1117
                     (tyConStupidTheta tc1) (tyConStupidTheta tc2))
          (text "The datatype contexts do not match") `andThenCheck`
    eqAlgRhs tc1 (algTyConRhs tc1) (algTyConRhs tc2)
1118

1119
  | otherwise = Just empty   -- two very different types -- should be obvious
dterei's avatar
dterei committed
1120
  where
1121
    roles1 = tyConRoles tc1 -- the abstract one
1122
    roles2 = tyConRoles tc2
1123 1124 1125
    roles_msg = text "The roles do not match." $$
                (text "Roles on abstract types default to" <+>
                 quotes (text "representational") <+> text "in boot files.")
1126

1127 1128 1129 1130 1131
    roles_subtype_msg = text "The roles are not compatible:" $$
                        text "Main module:" <+> ppr roles2 $$
                        text "Hsig file:" <+> ppr roles1

    checkRoles r1 r2
1132 1133
      | is_boot || isInjectiveTyCon tc1 Representational -- See Note [Role subtyping]
      = check (r1 == r2) roles_msg
1134 1135
      | otherwise = check (r2 `rolesSubtypeOf` r1) roles_subtype_msg

1136 1137
    -- Note [Role subtyping]
    -- ~~~~~~~~~~~~~~~~~~~~~
1138 1139 1140 1141 1142
    -- In the current formulation of roles, role subtyping is only OK if the
    -- "abstract" TyCon was not representationally injective.  Among the most
    -- notable examples of non representationally injective TyCons are abstract
    -- data, which can be implemented via newtypes (which are not
    -- representationally injective).  The key example is
1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154
    -- in this example from #13140:
    --
    --      -- In an hsig file
    --      data T a -- abstract!
    --      type role T nominal
    --
    --      -- Elsewhere
    --      foo :: Coercible (T a) (T b) => a -> b
    --      foo x = x
    --
    -- We must NOT allow foo to typecheck, because if we instantiate
    -- T with a concrete data type with a phantom role would cause
1155 1156 1157
    -- Coercible (T a) (T b) to be provable.  Fortunately, if T is not
    -- representationally injective, we cannot make the inference that a ~N b if
    -- T a ~R T b.
1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186
    --
    -- Unconditional role subtyping would be possible if we setup
    -- an extra set of roles saying when we can project out coercions
    -- (we call these proj-roles); then it would NOT be valid to instantiate T
    -- with a data type at phantom since the proj-role subtyping check
    -- would fail.  See #13140 for more details.
    --
    -- One consequence of this is we get no role subtyping for non-abstract
    -- data types in signatures. Suppose you have:
    --
    --      signature A where
    --          type role T nominal
    --          data T a = MkT
    --
    -- If you write this, we'll treat T as injective, and make inferences
    -- like T a ~R T b ==> a ~N b (mkNthCo).  But if we can
    -- subsequently replace T with one at phantom role, we would then be able to
    -- infer things like T Int ~R T Bool which is bad news.
    --
    -- We could allow role subtyping here if we didn't treat *any* data types
    -- defined in signatures as injective.  But this would be a bit surprising,
    -- replacing a data type in a module with one in a signature could cause
    -- your code to stop typechecking (whereas if you made the type abstract,
    -- it is more understandable that the type checker knows less).
    --
    -- It would have been best if this was purely a question of defaults
    -- (i.e., a user could explicitly ask for one behavior or another) but
    -- the current role system isn't expressive enough to do this.
    -- Having explict proj-roles would solve this problem.
1187

1188
    rolesSubtypeOf [] [] = True
1189