TcRnDriver.hs 120 KB
Newer Older
Austin Seipp's avatar
Austin Seipp committed
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
Austin Seipp's avatar
Austin Seipp committed
8
-}
9

10
{-# LANGUAGE CPP #-}
Simon Marlow's avatar
Simon Marlow committed
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,
Adam Gundry's avatar
Adam Gundry committed
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
Simon Marlow's avatar
Simon Marlow committed
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

Simon Marlow's avatar
Simon Marlow committed
141
import Control.DeepSeq
142
import Control.Monad
143

144
#include "HsVersions.h"
145

Austin Seipp's avatar
Austin Seipp committed
146 147 148
{-
************************************************************************
*                                                                      *
dterei's avatar
dterei committed
149
        Typecheck and rename a module
Austin Seipp's avatar
Austin Seipp committed
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

Austin Seipp's avatar
Austin Seipp committed
308 309 310
{-
************************************************************************
*                                                                      *
dterei's avatar
dterei committed
311
                Import declarations
Austin Seipp's avatar
Austin Seipp committed
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

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

Simon Peyton Jones's avatar
Simon Peyton Jones committed
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
Simon Peyton Jones's avatar
Simon Peyton Jones committed
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)
Simon Peyton Jones's avatar
Simon Peyton Jones committed
418
      ; new_ev_binds <- {-# SCC "simplifyTop" #-}
419
                        simplifyTop (lie `andWC` lie_main)
420

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

424 425
        -- Finalizers must run after constraints are simplified, or some types
        -- might not be complete when using reify (see #12777).
426
      ; (tcg_env, tcl_env) <- setGblEnv tcg_env run_th_modfinalizers
427 428 429 430
      ; setEnvs (tcg_env, tcl_env) $ do {

      ; finishTH

Simon Peyton Jones's avatar
Simon Peyton Jones committed
431
      ; traceTc "Tc9" empty
432

Simon Peyton Jones's avatar
Simon Peyton Jones committed
433
      ; failIfErrsM     -- Don't zonk if there have been errors
dterei's avatar
dterei committed
434 435
                        -- It's a waste of time; and we may get debug warnings
                        -- about strangely-typed TyCons!
Matthew Pickering's avatar
Matthew Pickering committed
436
      ; traceTc "Tc10" empty
437

438 439
        -- Zonk the final code.  This must be done last.
        -- Even simplifyTop may do some unification.
440
        -- This pass also warns about missing type signatures
Simon Peyton Jones's avatar
Simon Peyton Jones committed
441
      ; let { TcGblEnv { tcg_type_env  = type_env,
442 443 444 445 446
                         tcg_binds     = binds,
                         tcg_ev_binds  = cur_ev_binds,
                         tcg_imp_specs = imp_specs,
                         tcg_rules     = rules,
                         tcg_fords     = fords } = tcg_env
447
            ; all_ev_binds = cur_ev_binds `unionBags` new_ev_binds } ;
448

449
      ; (bind_env, ev_binds', binds', fords', imp_specs', rules')
450
            <- {-# SCC "zonkTopDecls" #-}
451
               zonkTopDecls all_ev_binds binds rules
452
                            imp_specs fords ;
Matthew Pickering's avatar
Matthew Pickering committed
453
      ; traceTc "Tc11" empty
dterei's avatar
dterei committed
454

niteria's avatar
niteria committed
455
      ; let { final_type_env = plusTypeEnv type_env bind_env
456 457 458
            ; tcg_env' = tcg_env { tcg_binds    = binds',
                                   tcg_ev_binds = ev_binds',
                                   tcg_imp_specs = imp_specs',
dterei's avatar
dterei committed
459
                                   tcg_rules    = rules',
460 461
                                   tcg_fords    = fords' } } ;

Simon Peyton Jones's avatar
Simon Peyton Jones committed
462
      ; setGlobalTypeEnv tcg_env' final_type_env
Austin Seipp's avatar
Austin Seipp committed
463

464
   }
465
   } }
466

467 468 469 470 471 472 473 474 475 476
-- | 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 []
477 478 479 480
    let run_finalizer (lcl_env, f) =
            setLclEnv lcl_env (runRemoteModFinalizers f)

    (_, lie_th) <- captureTopConstraints $ mapM_ run_finalizer th_modfinalizers
481 482 483 484
      -- 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
485 486 487 488
      -- 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" #-}
489
                      simplifyTop (lie_th `andWC` lie_top_decls)
490
      addTopEvBinds new_ev_binds run_th_modfinalizers
491
        -- addTopDecls can add declarations which add new finalizers.
492

493
tc_rn_src_decls :: [LHsDecl GhcPs]
494
                -> TcM (TcGblEnv, TcLclEnv, WantedConstraints)
dterei's avatar
dterei committed
495
-- Loops around dealing with each top level inter-splice group
496
-- in turn, until it's dealt with the entire module
497
-- Never emits constraints; calls captureTopConstraints internally
Simon Peyton Jones's avatar
Simon Peyton Jones committed
498
tc_rn_src_decls ds
499
 = {-# SCC "tc_rn_src_decls" #-}
gmainland's avatar
gmainland committed
500
   do { (first_group, group_tail) <- findSplice ds
dterei's avatar
dterei committed
501
                -- If ds is [] we get ([], Nothing)
dterei's avatar
dterei committed
502

dterei's avatar
dterei committed
503
        -- Deal with decls up to, but not including, the first splice
Simon Peyton Jones's avatar
Simon Peyton Jones committed
504
      ; (tcg_env, rn_decls) <- rnTopSrcDecls first_group
dterei's avatar
dterei committed
505
                -- rnTopSrcDecls fails if there are any errors
dterei's avatar
dterei committed
506

507 508
        -- Get TH-generated top-level declarations and make sure they don't
        -- contain any splices since we don't handle that at the moment
509 510
        --
        -- The plumbing here is a bit odd: see Trac #10853
511 512 513 514 515 516 517 518 519
      ; 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
520 521 522 523 524 525 526
                        { Nothing -> return ()
                        ; Just (SpliceDecl _ (dL->L loc _) _, _) ->
                            setSrcSpan loc
                            $ addErr (text
                                ("Declaration splices are not "
                                  ++ "permitted inside top-level "
                                  ++ "declarations added with addTopDecls"))
527
                        ; Just (XSpliceDecl _, _) -> panic "tc_rn_src_decls"
528 529 530 531
                        }
                      -- Rename TH-generated top-level declarations
                    ; (tcg_env, th_rn_decls) <- setGblEnv tcg_env
                        $ rnTopSrcDecls th_group
532

533
                      -- Dump generated top-level declarations
534
                    ; let msg = "top-level declarations added with addTopDecls"
535 536 537 538 539
                    ; traceSplice
                        $ SpliceInfo { spliceDescription = msg
                                     , spliceIsDecl    = True
                                     , spliceSource    = Nothing
                                     , spliceGenerated = ppr th_rn_decls }
540 541 542 543
                    ; return (tcg_env, appendGroups rn_decls th_rn_decls)
                    }

      -- Type check all declarations
544 545 546 547 548 549
      -- 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
550

dterei's avatar
dterei committed
551
        -- If there is no splice, we're nearly done
gmainland's avatar
gmainland committed
552 553
      ; setEnvs (tcg_env, tcl_env) $
        case group_tail of
554
          { Nothing -> return (tcg_env, tcl_env, lie1)
555

gmainland's avatar
gmainland committed
556
            -- If there's a splice, we must carry on
557
          ; Just (SpliceDecl _ (dL->L loc splice) _, rest_ds) ->
558 559 560
            do { recordTopLevelSpliceLoc loc

                 -- Rename the splice expression, and get its supporting decls
561
               ; (spliced_decls, splice_fvs) <- rnTopSpliceDecls splice
gmainland's avatar
gmainland committed
562 563

                 -- Glue them on the front of the remaining decls and loop
564 565 566 567 568
               ; (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
569
               }
570
          ; Just (XSpliceDecl _, _) -> panic "tc_rn_src_decls"
gmainland's avatar
gmainland committed
571 572
          }
      }
573

Austin Seipp's avatar
Austin Seipp committed
574 575 576
{-
************************************************************************
*                                                                      *
dterei's avatar
dterei committed
577 578
        Compiling hs-boot source files, and
        comparing the hi-boot interface with the real thing
Austin Seipp's avatar
Austin Seipp committed
579 580 581
*                                                                      *
************************************************************************
-}
582

583
tcRnHsBootDecls :: HscSource -> [LHsDecl GhcPs] -> TcM TcGblEnv
584
tcRnHsBootDecls hsc_src decls
585
   = do { (first_group, group_tail) <- findSplice decls
586

dterei's avatar
dterei committed
587
                -- Rename the declarations
588 589 590 591 592 593
        ; (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  = _
594 595
                            , hs_valds
                                 = XValBindsLR (NValBinds val_binds val_sigs) })
596
              <- rnTopSrcDecls first_group
597 598
        -- The empty list is for extra dependencies coming from .hs-boot files
        -- See Note [Extra dependencies from .hs-boot files] in RnSource
599 600 601
        ; (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
602 603 604

                -- Check for illegal declarations
        ; case group_tail of
605 606
             Just (SpliceDecl _ d _, _) -> badBootDecl hsc_src "splice" d
             Just (XSpliceDecl _, _) -> panic "tcRnHsBootDecls"
dterei's avatar
dterei committed
607
             Nothing                  -> return ()
608 609 610
        ; 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
611

Gabor Greif's avatar
Gabor Greif committed
612
                -- Typecheck type/class/instance decls
613
        ; traceTc "Tc2 (boot)" empty
dterei's avatar
dterei committed
614
        ; (tcg_env, inst_infos, _deriv_binds)
615
             <- tcTyClsInstDecls tycl_decls deriv_decls val_binds
dterei's avatar
dterei committed
616 617
        ; setGblEnv tcg_env     $ do {

Ben Gamari's avatar
Ben Gamari committed
618 619 620 621
        -- Emit Typeable bindings
        ; tcg_env <- mkTypeableBinds
        ; setGblEnv tcg_env $ do {

dterei's avatar
dterei committed
622
                -- Typecheck value declarations
dterei's avatar
dterei committed
623
        ; traceTc "Tc5" empty
624
        ; val_ids <- tcHsBootSigs val_binds val_sigs
dterei's avatar
dterei committed
625 626 627 628

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

dterei's avatar
dterei committed
631 632
                -- Make the final type-env
                -- Include the dfun_ids so that their type sigs
dterei's avatar
dterei committed
633
                -- are written into the interface file.
dterei's avatar
dterei committed
634 635
        ; let { type_env0 = tcg_type_env gbl_env
              ; type_env1 = extendTypeEnvWithIds type_env0 val_ids
Edward Z. Yang's avatar
Edward Z. Yang committed
636
              ; type_env2 = extendTypeEnvWithIds type_env1 dfun_ids
dterei's avatar
dterei committed
637 638 639 640
              ; dfun_ids = map iDFunId inst_infos
              }

        ; setGlobalTypeEnv gbl_env type_env2
Ben Gamari's avatar
Ben Gamari committed
641
   }}}
642
   ; traceTc "boot" (ppr lie); return gbl_env }
643

644
badBootDecl :: HscSource -> String -> Located decl -> TcM ()
645
badBootDecl hsc_src what (dL->L loc _)
dterei's avatar
dterei committed
646
  = addErrAt loc (char 'A' <+> text what
647
      <+> text "declaration is not (currently) allowed in a"
648
      <+> (case hsc_src of
649 650
            HsBootFile -> text "hs-boot"
            HsigFile -> text "hsig"
651
            _ -> panic "badBootDecl: should be an hsig or hs-boot file")
652
      <+> text "file")
653

Austin Seipp's avatar
Austin Seipp committed
654
{-
655 656
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).
Austin Seipp's avatar
Austin Seipp committed
657
-}
658

Simon Peyton Jones's avatar
Simon Peyton Jones committed
659
checkHiBootIface :: TcGblEnv -> SelfBootInfo -> TcM TcGblEnv
660 661
-- Compare the hi-boot file for this module (if there is one)
-- with the type environment we've just come up with
662 663
-- In the common case where there is no hi-boot file, the list
-- of boot_names is empty.
664

Simon Peyton Jones's avatar
Simon Peyton Jones committed
665 666
checkHiBootIface tcg_env boot_info
  | NoSelfBoot <- boot_info  -- Common case
dterei's avatar
dterei committed
667
  = return tcg_env
668

Simon Peyton Jones's avatar
Simon Peyton Jones committed
669 670 671 672 673 674 675 676
  | 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
677 678 679 680 681 682 683 684 685 686 687
  = do  { -- This code is tricky, see Note [DFun knot-tying]
        ; let boot_dfuns = filter isDFunId (typeEnvIds (md_types boot_details))
              type_env'  = extendTypeEnvWithIds local_type_env boot_dfuns
          -- 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.
        ; tcg_env <- type_env' `seq` setGlobalTypeEnv tcg_env type_env'
        ; dfun_prs <- checkHiBootIface' local_insts type_env'
688
                                        local_exports boot_details
689
        ; let dfun_binds = listToBag [ mkVarBind boot_dfun (nlHsVar dfun)
690 691
                                     | (boot_dfun, dfun) <- dfun_prs ]

692
        ; return tcg_env { tcg_binds = binds `unionBags` dfun_binds } }
693

Simon Peyton Jones's avatar
Simon Peyton Jones committed
694 695
  | otherwise = panic "checkHiBootIface: unreachable code"

696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731
-- 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!
-- In general, it's not possible to know a priori what an
-- hs-boot file named a DFun (see Note [DFun impedance matching]),
-- so we look at the ClsInsts from the boot file to figure out
-- what DFuns to add to the type environment.  But we're not
-- allowed to poke the DFuns of the ClsInsts in the SelfBootInfo
-- until we've added the DFuns to the type environment.  A
-- Gordian knot!
--
-- We cut the knot by a little trick: we first *unconditionally*
-- add all of the boot-declared DFuns to the type environment
-- (so that knot tying works, see Trac #4003), without the
-- actual bindings for them.  Then, we compute the impedance
-- matching bindings, and add them to the environment.
--
-- There is one subtlety to doing this: we have to get the
-- DFuns from md_types, not md_insts, even though involves
-- filtering a bunch of TyThings we don't care about.  The
-- reason is only the TypeEnv in md_types has the actual
-- Id we want to add to the environment; the DFun fields
-- in md_insts are typechecking thunks that will attempt to
-- go through if_rec_types to lookup the real Id... but
-- that's what we're trying to setup right now.

732
checkHiBootIface' :: [ClsInst] -> TypeEnv -> [AvailInfo]
733
                  -> ModDetails -> TcM [(Id, Id)]
734 735
-- Variant which doesn't require a full TcGblEnv; you could get the
-- local components from another ModDetails.
736
--
737 738
-- Note [DFun impedance matching]
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Gabor Greif's avatar
Gabor Greif committed
739
-- We return a list of "impedance-matching" bindings for the dfuns
740 741 742
-- defined in the hs-boot file, such as
--           $fxEqT = $fEqT
-- We need these because the module and hi-boot file might differ in
743 744 745 746 747 748 749 750 751 752
-- 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).
753 754 755 756 757

checkHiBootIface'
        local_insts local_type_env local_exports
        (ModDetails { md_insts = boot_insts, md_fam_insts = boot_fam_insts,
                      md_types = boot_type_env, md_exports = boot_exports })
dterei's avatar
dterei committed
758
  = do  { traceTc "checkHiBootIface" $ vcat
759
             [ ppr boot_type_env, ppr boot_insts, ppr boot_exports]
760

dterei's avatar
dterei committed
761 762
                -- Check the exports of the boot module, one by one
        ; mapM_ check_export boot_exports
763

dterei's avatar
dterei committed
764 765 766 767
                -- Check for no family instances
        ; unless (null boot_fam_insts) $
            panic ("TcRnDriver.checkHiBootIface: Cannot handle family " ++
                   "instances in boot files yet...")
768
            -- FIXME: Why?  The actual comparison is not hard, but what would
dterei's avatar
dterei committed
769 770
            --        be the equivalent to the dfun bindings returned for class
            --        instances?  We can't easily equate tycons...
771

dterei's avatar
dterei committed
772
                -- Check instance declarations
Gabor Greif's avatar
Gabor Greif committed
773
                -- and generate an impedance-matching binding
dterei's avatar
dterei committed
774
        ; mb_dfun_prs <- mapM check_inst boot_insts
775

776
        ; failIfErrsM
777

778
        ; return (catMaybes mb_dfun_prs) }
779

780
  where
dterei's avatar
dterei committed
781
    check_export boot_avail     -- boot_avail is exported by the boot iface
dterei's avatar
dterei committed
782
      | name `elem` dfun_names = return ()
dterei's avatar
dterei committed
783 784 785
      | isWiredInName name     = return ()      -- No checking for wired-in names.  In particular,
                                                -- 'error' is handled by a rather gross hack
                                                -- (see comments in GHC.Err.hs-boot)
786

dterei's avatar
dterei committed
787
        -- Check that the actual module exports the same thing
788
      | not (null missing_names)
dterei's avatar
dterei committed
789
      = addErrAt (nameSrcSpan (head missing_names))
790
                 (missingBootThing True (head missing_names) "exported by")
791

dterei's avatar
dterei committed
792 793
        -- 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)
794
      | isNothing mb_boot_thing = return ()
795

dterei's avatar
dterei committed
796
        -- Check that the actual module also defines the thing, and
dterei's avatar
dterei committed
797
        -- then compare the definitions
798 799
      | Just real_thing <- lookupTypeEnv local_type_env name,
        Just boot_thing <- mb_boot_thing
800
      = checkBootDeclM True boot_thing real_thing
801

802
      | otherwise
803
      = addErrTc (missingBootThing True name "defined in")
804
      where
dterei's avatar
dterei committed
805 806 807 808 809
        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
810

811 812
    dfun_names = map getName boot_insts

813 814
    local_export_env :: NameEnv AvailInfo
    local_export_env = availsToNameEnv local_exports
815

816
    check_inst :: ClsInst -> TcM (Maybe (Id, Id))
817 818 819 820
        -- 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.
821
    check_inst boot_inst
dterei's avatar
dterei committed
822
        = case [dfun | inst <- local_insts,
dterei's avatar
dterei committed
823
                       let dfun = instanceDFunId inst,
824 825 826 827 828 829
                       idType dfun `eqType` boot_dfun_ty ] of
            [] -> do { traceTc "check_inst" $ vcat
                          [ text "local_insts"  <+> vcat (map (ppr . idType . instanceDFunId) local_insts)
                          , text "boot_inst"    <+> ppr boot_inst
                          , text "boot_dfun_ty" <+> ppr boot_dfun_ty
                          ]
830 831
                     ; addErrTc (instMisMatch True boot_inst)
                     ; return Nothing }
dterei's avatar
dterei committed
832
            (dfun:_) -> return (Just (local_boot_dfun, dfun))
833
                     where
834
                        local_boot_dfun = Id.mkExportedVanillaId boot_dfun_name (idType dfun)
835 836 837 838 839
                           -- Name from the /boot-file/ ClsInst, 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 #T8743, comment:10).
dterei's avatar
dterei committed
840
        where
841 842 843
          boot_dfun      = instanceDFunId boot_inst
          boot_dfun_ty   = idType boot_dfun
          boot_dfun_name = idName boot_dfun
844

Edward Z. Yang's avatar
Edward Z. Yang committed
845 846
-- In general, to perform these checks we have to
-- compare the TyThing from the .hi-boot file to the TyThing
847 848 849 850 851 852
-- 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.

853 854 855 856 857
-- | 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
858
  = whenIsJust (checkBootDecl is_boot boot_thing real_thing) $ \ err ->
859
       addErrAt span
860
                (bootMisMatch is_boot err real_thing boot_thing)
861 862 863 864 865 866 867 868 869
  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)
870 871 872 873 874

-- | 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
875
checkBootDecl :: Bool -> TyThing -> TyThing -> Maybe SDoc
876

Edward Z. Yang's avatar
Edward Z. Yang committed
877
checkBootDecl _ (AnId id1) (AnId id2)
dterei's avatar
dterei committed
878
  = ASSERT(id1 == id2)
879 880
    check (idType id1 `eqType` idType id2)
          (text "The two types are different")
881

Edward Z. Yang's avatar
Edward Z. Yang committed
882 883
checkBootDecl is_boot (ATyCon tc1) (ATyCon tc2)
  = checkBootTyCon is_boot tc1 tc2
884

Edward Z. Yang's avatar
Edward Z. Yang committed
885
checkBootDecl _ (AConLike (RealDataCon dc1)) (AConLike (RealDataCon _))
batterseapower's avatar
batterseapower committed
886 887
  = pprPanic "checkBootDecl" (ppr dc1)

Edward Z. Yang's avatar
Edward Z. Yang committed
888
checkBootDecl _ _ _ = Just empty -- probably shouldn't happen
889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909

-- | 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"
Austin Seipp's avatar
Austin Seipp committed
910

911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927
    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
batterseapower's avatar
batterseapower committed
928 929

----------------
Edward Z. Yang's avatar
Edward Z. Yang committed
930 931
checkBootTyCon :: Bool -> TyCon -> TyCon -> Maybe SDoc
checkBootTyCon is_boot tc1 tc2
932
  | not (eqType (tyConKind tc1) (tyConKind tc2))
933
  = Just $ text "The types have different kinds"    -- First off, check the kind
batterseapower's avatar
batterseapower committed
934 935 936

  | Just c1 <- tyConClass_maybe tc1
  , Just c2 <- tyConClass_maybe tc2
937
  , let (clas_tvs1, clas_fds1, sc_theta1, _, ats1, op_stuff1)
938
          = classExtraBigSig c1
939
        (clas_tvs2, clas_fds2, sc_theta2, _, ats2, op_stuff2)
940
          = classExtraBigSig c2
941
  , Just env <- eqVarBndrs emptyRnEnv2 clas_tvs1 clas_tvs2
942
  = let
943
       eqSig (id1, def_meth1) (id2, def_meth2)
944 945 946 947 948 949
         = 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`
950 951 952 953 954 955 956
           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")
957
         where
958 959 960 961
          name1 = idName id1
          name2 = idName id2
          pname1 = quotes (ppr name1)
          pname2 = quotes (ppr name2)
batterseapower's avatar
batterseapower committed
962 963 964
          (_, rho_ty1) = splitForAllTys (idType id1)
          op_ty1 = funResultTy rho_ty1
          (_, rho_ty2) = splitForAllTys (idType id2)
965 966
          op_ty2 = funResultTy rho_ty2

967
       eqAT (ATI tc1 def_ats1) (ATI tc2 def_ats2)
Edward Z. Yang's avatar
Edward Z. Yang committed
968
         = checkBootTyCon is_boot tc1 tc2 `andThenCheck`
969 970
           check (eqATDef def_ats1 def_ats2)
                 (text "The associated type defaults differ")
971

972 973 974 975
       eqDM (_, VanillaDM)    (_, VanillaDM)    = True
       eqDM (_, GenericDM t1) (_, GenericDM t2) = eqTypeX env t1 t2
       eqDM _ _ = False

976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995
       -- 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
996
       -- Ignore the location of the defaults
997 998
       eqATDef Nothing             Nothing             = True
       eqATDef (Just (ty1, _loc1)) (Just (ty2, _loc2)) = eqTypeX env ty1 ty2