diff options
author | Simon Peyton Jones <simonpj@microsoft.com> | 2016-06-11 23:49:27 +0100 |
---|---|---|
committer | Simon Peyton Jones <simonpj@microsoft.com> | 2016-06-13 10:57:03 +0100 |
commit | 15b9bf4ba4ab47e6809bf2b3b36ec16e502aea72 (patch) | |
tree | e2e7336c63e9b7130ba70f3551ff290d4a25184b /compiler | |
parent | d25cb61a1c2a135a2564143a332f8b2962f134bc (diff) | |
download | haskell-15b9bf4ba4ab47e6809bf2b3b36ec16e502aea72.tar.gz |
Improve typechecking of let-bindings
This major commit was initially triggered by #11339, but it spiraled
into a major review of the way in which type signatures for bindings
are handled, especially partial type signatures. On the way I fixed a
number of other bugs, namely
#12069
#12033
#11700
#11339
#11670
The main change is that I completely reorganised the way in which type
signatures in bindings are handled. The new story is in TcSigs
Note [Overview of type signatures]. Some specific:
* Changes in the data types for signatures in TcRnTypes:
TcIdSigInfo and new TcIdSigInst
* New module TcSigs deals with typechecking type signatures
and pragmas. It contains code mostly moved from TcBinds,
which is already too big
* HsTypes: I swapped the nesting of HsWildCardBndrs
and HsImplicitBndsrs, so that the wildcards are on the
oustide not the insidde in a LHsSigWcType. This is just
a matter of convenient, nothing deep.
There are a host of other changes as knock-on effects, and
it all took FAR longer than I anticipated :-). But it is
a significant improvement, I think.
Lots of error messages changed slightly, some just variants but
some modest improvements.
New tests
* typecheck/should_compile
* SigTyVars: a scoped-tyvar test
* ExPat, ExPatFail: existential pattern bindings
* T12069
* T11700
* T11339
* partial-sigs/should_compile
* T12033
* T11339a
* T11670
One thing to check:
* Small change to output from ghc-api/landmines.
Need to check with Alan Zimmerman
Diffstat (limited to 'compiler')
25 files changed, 1793 insertions, 1596 deletions
diff --git a/compiler/deSugar/DsMeta.hs b/compiler/deSugar/DsMeta.hs index 91489b7bc7..9e13b8665c 100644 --- a/compiler/deSugar/DsMeta.hs +++ b/compiler/deSugar/DsMeta.hs @@ -189,8 +189,8 @@ hsSigTvBinders binds -- here 'k' scopes too get_scoped_tvs (L _ (TypeSig _ sig)) | HsIB { hsib_vars = implicit_vars - , hsib_body = sig1 } <- sig - , (explicit_vars, _) <- splitLHsForAllTy (hswc_body sig1) + , hsib_body = hs_ty } <- hswc_body sig + , (explicit_vars, _) <- splitLHsForAllTy hs_ty = implicit_vars ++ map hsLTyVarName explicit_vars get_scoped_tvs _ = [] @@ -567,7 +567,7 @@ repRuleD (L loc (HsRule n act bndrs lhs _ rhs _)) ruleBndrNames :: LRuleBndr Name -> [Name] ruleBndrNames (L _ (RuleBndr n)) = [unLoc n] ruleBndrNames (L _ (RuleBndrSig n sig)) - | HsIB { hsib_vars = vars } <- sig + | HsWC { hswc_body = HsIB { hsib_vars = vars }} <- sig = unLoc n : vars repRuleBndr :: LRuleBndr Name -> DsM (Core TH.RuleBndrQ) @@ -735,8 +735,8 @@ rep_wc_ty_sig :: Name -> SrcSpan -> LHsSigWcType Name -> Located Name -- We must special-case the top-level explicit for-all of a TypeSig -- See Note [Scoped type variables in bindings] rep_wc_ty_sig mk_sig loc sig_ty nm - | HsIB { hsib_vars = implicit_tvs, hsib_body = sig1 } <- sig_ty - , (explicit_tvs, ctxt, ty) <- splitLHsSigmaTy (hswc_body sig1) + | HsIB { hsib_vars = implicit_tvs, hsib_body = hs_ty } <- hswc_body sig_ty + , (explicit_tvs, ctxt, ty) <- splitLHsSigmaTy hs_ty = do { nm1 <- lookupLOcc nm ; let rep_in_scope_tv tv = do { name <- lookupBinder (hsLTyVarName tv) ; repTyVarBndrWithKind tv name } @@ -917,8 +917,8 @@ repHsPatSynSigType (HsIB { hsib_vars = implicit_tvs (univs, reqs, exis, provs, ty) = splitLHsPatSynTy body repHsSigWcType :: LHsSigWcType Name -> DsM (Core TH.TypeQ) -repHsSigWcType ib_ty@(HsIB { hsib_body = sig1 }) - = repHsSigType (ib_ty { hsib_body = hswc_body sig1 }) +repHsSigWcType (HsWC { hswc_body = sig1 }) + = repHsSigType sig1 -- yield the representation of a list of types repLTys :: [LHsType Name] -> DsM [Core TH.TypeQ] diff --git a/compiler/deSugar/DsMonad.hs b/compiler/deSugar/DsMonad.hs index 69aa0f9648..0320cdf3a2 100644 --- a/compiler/deSugar/DsMonad.hs +++ b/compiler/deSugar/DsMonad.hs @@ -15,7 +15,6 @@ module DsMonad ( foldlM, foldrM, whenGOptM, unsetGOptM, unsetWOptM, Applicative(..),(<$>), - newLocalName, duplicateLocalDs, newSysLocalDs, newSysLocalsDs, newUniqueId, newFailLocalDs, newPredVarDs, getSrcSpanDs, putSrcSpanDs, diff --git a/compiler/ghc.cabal.in b/compiler/ghc.cabal.in index 24764933c9..cfe350fa8f 100644 --- a/compiler/ghc.cabal.in +++ b/compiler/ghc.cabal.in @@ -399,6 +399,7 @@ Library TcAnnotations TcArrows TcBinds + TcSigs TcClassDcl TcDefaults TcDeriv diff --git a/compiler/hsSyn/HsTypes.hs b/compiler/hsSyn/HsTypes.hs index e5f0f9cde5..a0676c98d6 100644 --- a/compiler/hsSyn/HsTypes.hs +++ b/compiler/hsSyn/HsTypes.hs @@ -288,16 +288,12 @@ data HsWildCardBndrs name thing -- See Note [The wildcard story for types] = HsWC { hswc_wcs :: PostRn name [Name] -- Wild cards, both named and anonymous + -- after the renamer - , hswc_ctx :: Maybe SrcSpan - -- Indicates whether hswc_body has an - -- extra-constraint wildcard, and if so where - -- e.g. (Eq a, _) => a -> a - -- NB: the wildcard stays in HsQualTy inside the type! - -- So for pretty printing purposes you can ignore - -- hswc_ctx - - , hswc_body :: thing -- Main payload (type or list of types) + , hswc_body :: thing + -- Main payload (type or list of types) + -- If there is an extra-constraints wildcard, + -- it's still there in the hsc_body. } deriving instance (Data name, Data thing, Data (PostRn name [Name])) @@ -308,7 +304,7 @@ deriving instance (Data name, Data thing, Data (PostRn name [Name])) type LHsSigType name = HsImplicitBndrs name (LHsType name) -- Implicit only type LHsWcType name = HsWildCardBndrs name (LHsType name) -- Wildcard only -type LHsSigWcType name = HsImplicitBndrs name (LHsWcType name) -- Both +type LHsSigWcType name = HsWildCardBndrs name (LHsSigType name) -- Both -- See Note [Representing type signatures] @@ -319,11 +315,11 @@ hsSigType :: LHsSigType name -> LHsType name hsSigType = hsImplicitBody hsSigWcType :: LHsSigWcType name -> LHsType name -hsSigWcType sig_ty = hswc_body (hsib_body sig_ty) +hsSigWcType sig_ty = hsib_body (hswc_body sig_ty) dropWildCards :: LHsSigWcType name -> LHsSigType name -- Drop the wildcard part of a LHsSigWcType -dropWildCards sig_ty = sig_ty { hsib_body = hsSigWcType sig_ty } +dropWildCards sig_ty = hswc_body sig_ty {- Note [Representing type signatures] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -351,8 +347,7 @@ mkHsImplicitBndrs x = HsIB { hsib_body = x mkHsWildCardBndrs :: thing -> HsWildCardBndrs RdrName thing mkHsWildCardBndrs x = HsWC { hswc_body = x - , hswc_wcs = PlaceHolder - , hswc_ctx = Nothing } + , hswc_wcs = PlaceHolder } -- Add empty binders. This is a bit suspicious; what if -- the wrapped thing had free type variables? @@ -362,8 +357,7 @@ mkEmptyImplicitBndrs x = HsIB { hsib_body = x mkEmptyWildCardBndrs :: thing -> HsWildCardBndrs Name thing mkEmptyWildCardBndrs x = HsWC { hswc_body = x - , hswc_wcs = [] - , hswc_ctx = Nothing } + , hswc_wcs = [] } -------------------------------------------------- @@ -789,8 +783,8 @@ hsWcScopedTvs :: LHsSigWcType Name -> [Name] -- - the named wildcars; see Note [Scoping of named wildcards] -- because they scope in the same way hsWcScopedTvs sig_ty - | HsIB { hsib_vars = vars, hsib_body = sig_ty1 } <- sig_ty - , HsWC { hswc_wcs = nwcs, hswc_body = sig_ty2 } <- sig_ty1 + | HsWC { hswc_wcs = nwcs, hswc_body = sig_ty1 } <- sig_ty + , HsIB { hsib_vars = vars, hsib_body = sig_ty2 } <- sig_ty1 = case sig_ty2 of L _ (HsForAllTy { hst_bndrs = tvs }) -> vars ++ nwcs ++ map hsLTyVarName tvs @@ -1237,10 +1231,10 @@ ppr_mono_ty _ (HsPArrTy ty) = paBrackets (ppr_mono_lty TopPrec ty) ppr_mono_ty prec (HsIParamTy n ty) = maybeParen prec FunPrec (ppr n <+> dcolon <+> ppr_mono_lty TopPrec ty) ppr_mono_ty _ (HsSpliceTy s _) = pprSplice s ppr_mono_ty _ (HsCoreTy ty) = ppr ty -ppr_mono_ty _ (HsExplicitListTy _ tys) = quote $ brackets (interpp'SP tys) +ppr_mono_ty _ (HsExplicitListTy _ tys) = quote $ brackets (interpp'SP tys) ppr_mono_ty _ (HsExplicitTupleTy _ tys) = quote $ parens (interpp'SP tys) ppr_mono_ty _ (HsTyLit t) = ppr_tylit t -ppr_mono_ty _ (HsWildCardTy (AnonWildCard _)) = char '_' +ppr_mono_ty _ (HsWildCardTy {}) = char '_' ppr_mono_ty ctxt_prec (HsEqTy ty1 ty2) = maybeParen ctxt_prec TyOpPrec $ diff --git a/compiler/hsSyn/HsUtils.hs b/compiler/hsSyn/HsUtils.hs index 43d60a3667..23c8d911ad 100644 --- a/compiler/hsSyn/HsUtils.hs +++ b/compiler/hsSyn/HsUtils.hs @@ -564,7 +564,7 @@ mkLHsSigType :: LHsType RdrName -> LHsSigType RdrName mkLHsSigType ty = mkHsImplicitBndrs ty mkLHsSigWcType :: LHsType RdrName -> LHsSigWcType RdrName -mkLHsSigWcType ty = mkHsImplicitBndrs (mkHsWildCardBndrs ty) +mkLHsSigWcType ty = mkHsWildCardBndrs (mkHsImplicitBndrs ty) mkClassOpSigs :: [LSig RdrName] -> [LSig RdrName] -- Convert TypeSig to ClassOpSig diff --git a/compiler/rename/RnTypes.hs b/compiler/rename/RnTypes.hs index 08c157163f..d8a58777f9 100644 --- a/compiler/rename/RnTypes.hs +++ b/compiler/rename/RnTypes.hs @@ -103,100 +103,95 @@ rn_hs_sig_wc_type :: Bool -- see rnImplicitBndrs -> RnM (a, FreeVars) -- rn_hs_sig_wc_type is used for source-language type signatures rn_hs_sig_wc_type no_implicit_if_forall ctxt - (HsIB { hsib_body = wc_ty }) thing_inside - = do { let hs_ty = hswc_body wc_ty - ; free_vars <- extractFilteredRdrTyVars hs_ty - ; (free_vars', nwc_rdrs) <- partition_nwcs free_vars - ; rnImplicitBndrs no_implicit_if_forall free_vars' hs_ty $ \ vars -> - do { rn_hs_wc_type ctxt wc_ty nwc_rdrs $ \ wc_ty' -> - thing_inside (HsIB { hsib_vars = vars - , hsib_body = wc_ty' }) } } + (HsWC { hswc_body = HsIB { hsib_body = hs_ty }}) + thing_inside + = do { free_vars <- extractFilteredRdrTyVars hs_ty + ; (tv_rdrs, nwc_rdrs) <- partition_nwcs free_vars + ; rnImplicitBndrs no_implicit_if_forall tv_rdrs hs_ty $ \ vars -> + do { (wcs, hs_ty', fvs1) <- rnWcBody ctxt nwc_rdrs hs_ty + ; let sig_ty' = HsWC { hswc_wcs = wcs, hswc_body = ib_ty' } + ib_ty' = HsIB { hsib_vars = vars, hsib_body = hs_ty' } + ; (res, fvs2) <- thing_inside sig_ty' + ; return (res, fvs1 `plusFV` fvs2) } } rnHsWcType :: HsDocContext -> LHsWcType RdrName -> RnM (LHsWcType Name, FreeVars) -rnHsWcType ctxt wc_ty@(HsWC { hswc_body = hs_ty }) +rnHsWcType ctxt (HsWC { hswc_body = hs_ty }) = do { free_vars <- extractFilteredRdrTyVars hs_ty ; (_, nwc_rdrs) <- partition_nwcs free_vars - ; rn_hs_wc_type ctxt wc_ty nwc_rdrs $ \ wc_ty' -> - return (wc_ty', emptyFVs) } - --- | Renames a type with wild card binders. --- Expects a list of names of type variables that should be replaced with --- named wild cards. (See Note [Renaming named wild cards]) --- Although the parser does not create named wild cards, it is possible to find --- them in declaration splices, so the function tries to collect them. -rn_hs_wc_type :: HsDocContext -> LHsWcType RdrName - -> [Located RdrName] -- Named wildcards - -> (LHsWcType Name -> RnM (a, FreeVars)) - -> RnM (a, FreeVars) -rn_hs_wc_type ctxt (HsWC { hswc_body = hs_ty }) nwc_rdrs thing_inside + ; (wcs, hs_ty', fvs) <- rnWcBody ctxt nwc_rdrs hs_ty + ; let sig_ty' = HsWC { hswc_wcs = wcs, hswc_body = hs_ty' } + ; return (sig_ty', fvs) } + +rnWcBody :: HsDocContext -> [Located RdrName] -> LHsType RdrName + -> RnM ([Name], LHsType Name, FreeVars) +rnWcBody ctxt nwc_rdrs hs_ty = do { nwcs <- mapM newLocalBndrRn nwc_rdrs - ; bindLocalNamesFV nwcs $ - do { let env = RTKE { rtke_level = TypeLevel + ; let env = RTKE { rtke_level = TypeLevel , rtke_what = RnTypeBody , rtke_nwcs = mkNameSet nwcs , rtke_ctxt = ctxt } - ; (wc_ty, fvs1) <- rnWcSigTy env hs_ty - ; let wc_ty' :: HsWildCardBndrs Name (LHsType Name) - wc_ty' = wc_ty { hswc_wcs = nwcs ++ hswc_wcs wc_ty } - ; (res, fvs2) <- thing_inside wc_ty' - ; return (res, fvs1 `plusFV` fvs2) } } + ; (hs_ty', fvs) <- bindLocalNamesFV nwcs $ + rn_lty env hs_ty + ; let awcs = collectAnonWildCards hs_ty' + ; return (nwcs ++ awcs, hs_ty', fvs) } + where + rn_lty env (L loc hs_ty) + = setSrcSpan loc $ + do { (hs_ty', fvs) <- rn_ty env hs_ty + ; return (L loc hs_ty', fvs) } + + rn_ty :: RnTyKiEnv -> HsType RdrName -> RnM (HsType Name, FreeVars) + -- A lot of faff just to allow the extra-constraints wildcard to appear + rn_ty env hs_ty@(HsForAllTy { hst_bndrs = tvs, hst_body = hs_body }) + = bindLHsTyVarBndrs (rtke_ctxt env) (Just $ inTypeDoc hs_ty) + Nothing [] tvs $ \ _ tvs' _ _ -> + do { (hs_body', fvs) <- rn_lty env hs_body + ; return (HsForAllTy { hst_bndrs = tvs', hst_body = hs_body' }, fvs) } + + rn_ty env (HsQualTy { hst_ctxt = L cx hs_ctxt, hst_body = hs_ty }) + | Just (hs_ctxt1, hs_ctxt_last) <- snocView hs_ctxt + , L lx (HsWildCardTy wc) <- ignoreParens hs_ctxt_last + = do { (hs_ctxt1', fvs1) <- mapFvRn (rn_top_constraint env) hs_ctxt1 + ; wc' <- setSrcSpan lx $ + do { checkExtraConstraintWildCard env wc + ; rnAnonWildCard wc } + ; let hs_ctxt' = hs_ctxt1' ++ [L lx (HsWildCardTy wc')] + ; (hs_ty', fvs2) <- rnLHsTyKi env hs_ty + ; return (HsQualTy { hst_ctxt = L cx hs_ctxt', hst_body = hs_ty' } + , fvs1 `plusFV` fvs2) } + + | otherwise + = do { (hs_ctxt', fvs1) <- mapFvRn (rn_top_constraint env) hs_ctxt + ; (hs_ty', fvs2) <- rnLHsTyKi env hs_ty + ; return (HsQualTy { hst_ctxt = L cx hs_ctxt', hst_body = hs_ty' } + , fvs1 `plusFV` fvs2) } + + rn_ty env hs_ty = rnHsTyKi env hs_ty + + rn_top_constraint env = rnLHsTyKi (env { rtke_what = RnTopConstraint }) -rnWcSigTy :: RnTyKiEnv -> LHsType RdrName - -> RnM (LHsWcType Name, FreeVars) --- ^ Renames just the top level of a type signature --- It's exactly like rnHsTyKi, except that it uses rnWcSigContext --- on a qualified type, and return info on any extra-constraints --- wildcard. Some code duplication, but no big deal. -rnWcSigTy env (L loc hs_ty@(HsForAllTy { hst_bndrs = tvs, hst_body = hs_tau })) - = bindLHsTyVarBndrs (rtke_ctxt env) (Just $ inTypeDoc hs_ty) - Nothing [] tvs $ \ _ tvs' _ _ -> - do { (hs_tau', fvs) <- rnWcSigTy env hs_tau - ; let hs_ty' = HsForAllTy { hst_bndrs = tvs', hst_body = hswc_body hs_tau' } - awcs_bndrs = collectAnonWildCardsBndrs tvs' - ; return ( hs_tau' { hswc_wcs = hswc_wcs hs_tau' ++ awcs_bndrs - , hswc_body = L loc hs_ty' }, fvs) } - -rnWcSigTy env (L loc (HsQualTy { hst_ctxt = hs_ctxt, hst_body = tau })) - = do { (hs_ctxt', fvs1) <- rnWcSigContext env hs_ctxt - ; (tau', fvs2) <- rnLHsTyKi env tau - ; let awcs_tau = collectAnonWildCards tau' - hs_ty' = HsQualTy { hst_ctxt = hswc_body hs_ctxt' - , hst_body = tau' } - ; return ( HsWC { hswc_wcs = hswc_wcs hs_ctxt' ++ awcs_tau - , hswc_ctx = hswc_ctx hs_ctxt' - , hswc_body = L loc hs_ty' } - , fvs1 `plusFV` fvs2) } -rnWcSigTy env hs_ty - = do { (hs_ty', fvs) <- rnLHsTyKi env hs_ty - ; return (HsWC { hswc_wcs = collectAnonWildCards hs_ty' - , hswc_ctx = Nothing - , hswc_body = hs_ty' } - , fvs) } - -rnWcSigContext :: RnTyKiEnv -> LHsContext RdrName - -> RnM (HsWildCardBndrs Name (LHsContext Name), FreeVars) -rnWcSigContext env (L loc hs_ctxt) - | Just (hs_ctxt1, hs_ctxt_last) <- snocView hs_ctxt - , L lx (HsWildCardTy wc) <- ignoreParens hs_ctxt_last - = do { (hs_ctxt1', fvs) <- mapFvRn rn_top_constraint hs_ctxt1 - ; setSrcSpan lx $ checkExtraConstraintWildCard env wc - ; wc' <- rnAnonWildCard wc - ; let hs_ctxt' = hs_ctxt1' ++ [L lx (HsWildCardTy wc')] - awcs = concatMap collectAnonWildCards hs_ctxt1' - -- NB: *not* including the extra-constraint wildcard - ; return ( HsWC { hswc_wcs = awcs - , hswc_ctx = Just lx - , hswc_body = L loc hs_ctxt' } - , fvs ) } - | otherwise - = do { (hs_ctxt', fvs) <- mapFvRn rn_top_constraint hs_ctxt - ; return (HsWC { hswc_wcs = concatMap collectAnonWildCards hs_ctxt' - , hswc_ctx = Nothing - , hswc_body = L loc hs_ctxt' }, fvs) } +checkExtraConstraintWildCard :: RnTyKiEnv -> HsWildCardInfo RdrName + -> RnM () +-- Rename the extra-constraint spot in a type signature +-- (blah, _) => type +-- Check that extra-constraints are allowed at all, and +-- if so that it's an anonymous wildcard +checkExtraConstraintWildCard env wc + = checkWildCard env mb_bad where - rn_top_constraint = rnLHsTyKi (env { rtke_what = RnTopConstraint }) + mb_bad | not (extraConstraintWildCardsAllowed env) + = Just (text "Extra-constraint wildcard" <+> quotes (ppr wc) + <+> text "not allowed") + | otherwise + = Nothing +extraConstraintWildCardsAllowed :: RnTyKiEnv -> Bool +extraConstraintWildCardsAllowed env + = case rtke_ctxt env of + TypeSigCtx {} -> True + ExprWithTySigCtx {} -> True + _ -> False -- | Finds free type and kind variables in a type, -- without duplicates, and @@ -736,27 +731,6 @@ checkNamedWildCard env name RnConstraint -> Just constraint_msg constraint_msg = notAllowed (ppr name) <+> text "in a constraint" -checkExtraConstraintWildCard :: RnTyKiEnv -> HsWildCardInfo RdrName - -> RnM () --- Rename the extra-constraint spot in a type signature --- (blah, _) => type --- Check that extra-constraints are allowed at all, and --- if so that it's an anonymous wildcard -checkExtraConstraintWildCard env wc - = checkWildCard env mb_bad - where - mb_bad | not (extraConstraintWildCardsAllowed env) - = Just (text "Extra-constraint wildcard" <+> quotes (ppr wc) - <+> text "not allowed") - | otherwise - = Nothing - -extraConstraintWildCardsAllowed :: RnTyKiEnv -> Bool -extraConstraintWildCardsAllowed env - = case rtke_ctxt env of - TypeSigCtx {} -> True - _ -> False - wildCardsAllowed :: RnTyKiEnv -> Bool -- ^ In what contexts are wildcards permitted wildCardsAllowed env @@ -1052,7 +1026,9 @@ collectAnonWildCards lty = go lty HsRecTy flds -> gos $ map (cd_fld_type . unLoc) flds HsExplicitListTy _ tys -> gos tys HsExplicitTupleTy _ tys -> gos tys - HsForAllTy { hst_body = ty } -> go ty + HsForAllTy { hst_bndrs = bndrs + , hst_body = ty } -> collectAnonWildCardsBndrs bndrs + `mappend` go ty HsQualTy { hst_ctxt = L _ ctxt , hst_body = ty } -> gos ctxt `mappend` go ty -- HsQuasiQuoteTy, HsSpliceTy, HsCoreTy, HsTyLit diff --git a/compiler/typecheck/TcBinds.hs b/compiler/typecheck/TcBinds.hs index 8cfd5551ca..10d5901b19 100644 --- a/compiler/typecheck/TcBinds.hs +++ b/compiler/typecheck/TcBinds.hs @@ -10,21 +10,18 @@ module TcBinds ( tcLocalBinds, tcTopBinds, tcRecSelBinds, tcValBinds, tcHsBootSigs, tcPolyCheck, - tcSpecPrags, tcSpecWrapper, tcVectDecls, addTypecheckedBinds, - TcSigInfo(..), TcSigFun, - TcPragEnv, mkPragEnv, - tcUserTypeSig, instTcTySig, chooseInferredQuantifiers, - instTcTySigFromId, tcExtendTyVarEnvFromSig, - badBootDeclErr) where + chooseInferredQuantifiers, + badBootDeclErr ) where import {-# SOURCE #-} TcMatches ( tcGRHSsPat, tcMatchesFun ) import {-# SOURCE #-} TcExpr ( tcMonoExpr ) import {-# SOURCE #-} TcPatSyn ( tcInferPatSynDecl, tcCheckPatSynDecl - , tcPatSynBuilderBind, tcPatSynSig ) + , tcPatSynBuilderBind ) import DynFlags import HsSyn import HscTypes( isHsBootOrSig ) +import TcSigs import TcRnMonad import TcEnv import TcUnify @@ -33,12 +30,13 @@ import TcEvidence import TcHsType import TcPat import TcMType -import Inst( topInstantiate, deeplyInstantiate ) +import Inst( deeplyInstantiate ) import FamInstEnv( normaliseType ) import FamInst( tcGetFamInstEnvs ) import TyCon import TcType import TysPrim +import TysWiredIn( cTupleTyConName ) import Id import Var import VarSet @@ -57,7 +55,7 @@ import Util import BasicTypes import Outputable import Type(mkStrLitTy, tidyOpenType) -import PrelNames( mkUnboundName, gHC_PRIM, ipClassName ) +import PrelNames( gHC_PRIM, ipClassName ) import TcValidity (checkValidType) import UniqFM import qualified GHC.LanguageExtensions as LangExt @@ -360,7 +358,7 @@ tcValBinds top_lvl binds sigs thing_inside { (binds', (extra_binds', thing)) <- tcBindGroups top_lvl sig_fn prag_fn binds $ do { thing <- thing_inside -- See Note [Pattern synonym builders don't yield dependencies] - ; patsyn_builders <- mapM (tcPatSynBuilderBind sig_fn) patsyns + ; patsyn_builders <- mapM tcPatSynBuilderBind patsyns ; let extra_binds = [ (NonRecursive, builder) | builder <- patsyn_builders ] ; return (extra_binds, thing) } ; return (binds' ++ extra_binds', thing) }} @@ -550,7 +548,7 @@ tcPolyBinds top_lvl sig_fn prag_fn rec_group rec_tc closed bind_list ; result@(tc_binds, poly_ids) <- case plan of NoGen -> tcPolyNoGen rec_tc prag_fn sig_fn bind_list InferGen mn -> tcPolyInfer rec_tc prag_fn sig_fn mn bind_list - CheckGen lbind sig -> tcPolyCheck rec_tc prag_fn sig lbind + CheckGen lbind sig -> tcPolyCheck prag_fn sig lbind -- Check whether strict bindings are ok -- These must be non-recursive etc, and are not generalised @@ -568,7 +566,32 @@ tcPolyBinds top_lvl sig_fn prag_fn rec_group rec_tc closed bind_list -- may no longer be adjacent; so find the narrowest -- span that includes them all ------------------- +-------------- +-- If typechecking the binds fails, then return with each +-- signature-less binder given type (forall a.a), to minimise +-- subsequent error messages +recoveryCode :: [Name] -> TcSigFun -> TcM (LHsBinds TcId, [Id]) +recoveryCode binder_names sig_fn + = do { traceTc "tcBindsWithSigs: error recovery" (ppr binder_names) + ; let poly_ids = map mk_dummy binder_names + ; return (emptyBag, poly_ids) } + where + mk_dummy name + | Just sig <- sig_fn name + , Just poly_id <- completeSigPolyId_maybe sig + = poly_id + | otherwise + = mkLocalId name forall_a_a + +forall_a_a :: TcType +forall_a_a = mkSpecForAllTys [runtimeRep1TyVar, openAlphaTyVar] openAlphaTy + +{- ********************************************************************* +* * + tcPolyNoGen +* * +********************************************************************* -} + tcPolyNoGen -- No generalisation whatsoever :: RecFlag -- Whether it's recursive after breaking -- dependencies based on type signatures @@ -594,57 +617,87 @@ tcPolyNoGen rec_tc prag_fn tc_sig_fn bind_list -- Indeed that is why we call it here! -- So we can safely ignore _specs ------------------- -tcPolyCheck :: RecFlag -- Whether it's recursive after breaking - -- dependencies based on type signatures - -> TcPragEnv - -> TcIdSigInfo - -> LHsBind Name + +{- ********************************************************************* +* * + tcPolyCheck +* * +********************************************************************* -} + +tcPolyCheck :: TcPragEnv + -> TcIdSigInfo -- Must be a complete signature + -> LHsBind Name -- Must be a FunBind -> TcM (LHsBinds TcId, [TcId]) -- There is just one binding, --- it binds a single variable, +-- it is a Funbind -- it has a complete type signature, -tcPolyCheck rec_tc prag_fn - sig@(TISI { sig_bndr = CompleteSig poly_id - , sig_skols = skol_prs - , sig_theta = theta - , sig_tau = tau - , sig_ctxt = ctxt - , sig_loc = loc }) - bind - = do { ev_vars <- newEvVars theta - ; let skol_info = SigSkol ctxt (mkPhiTy theta tau) - prag_sigs = lookupPragEnv prag_fn name - skol_tvs = map snd skol_prs - -- Find the location of the original source type sig, if - -- there is was one. This will appear in messages like - -- "type variable x is bound by .. at <loc>" - name = idName poly_id - ; (ev_binds, (binds', _)) - <- setSrcSpan loc $ - checkConstraints skol_info skol_tvs ev_vars $ - tcMonoBinds rec_tc (\_ -> Just (TcIdSig sig)) LetLclBndr [bind] - +tcPolyCheck prag_fn + (CompleteSig { sig_bndr = poly_id + , sig_ctxt = ctxt + , sig_loc = sig_loc }) + (L loc (FunBind { fun_id = L nm_loc name + , fun_matches = matches })) + = setSrcSpan sig_loc $ + do { traceTc "tcPolyCheck" (ppr poly_id $$ ppr sig_loc) + ; (tv_prs, theta, tau) <- tcInstType (tcInstSigTyVars sig_loc) poly_id + -- See Note [Instantiate sig with fresh variables] + + ; mono_name <- newNameAt (nameOccName name) nm_loc + ; ev_vars <- newEvVars theta + ; let mono_id = mkLocalId mono_name tau + skol_info = SigSkol ctxt (mkPhiTy theta tau) + skol_tvs = map snd tv_prs + + ; (ev_binds, (co_fn, matches')) + <- checkConstraints skol_info skol_tvs ev_vars $ + tcExtendIdBndrs [TcIdBndr mono_id NotTopLevel] $ + tcExtendTyVarEnv2 tv_prs $ + setSrcSpan loc $ + tcMatchesFun (L nm_loc mono_name) matches (mkCheckExpType tau) + + ; let prag_sigs = lookupPragEnv prag_fn name ; spec_prags <- tcSpecPrags poly_id prag_sigs ; poly_id <- addInlinePrags poly_id prag_sigs - ; let bind' = case bagToList binds' of - [b] -> b - _ -> pprPanic "tcPolyCheck" (ppr binds') + ; let bind' = FunBind { fun_id = L nm_loc mono_id + , fun_matches = matches' + , fun_co_fn = co_fn + , bind_fvs = placeHolderNamesTc + , fun_tick = [] } + abs_bind = L loc $ AbsBindsSig - { abs_tvs = skol_tvs - , abs_ev_vars = ev_vars - , abs_sig_export = poly_id - , abs_sig_prags = SpecPrags spec_prags + { abs_sig_export = poly_id + , abs_tvs = skol_tvs + , abs_ev_vars = ev_vars + , abs_sig_prags = SpecPrags spec_prags , abs_sig_ev_bind = ev_binds - , abs_sig_bind = bind' } + , abs_sig_bind = L loc bind' } ; return (unitBag abs_bind, [poly_id]) } -tcPolyCheck _rec_tc _prag_fn sig _bind - = pprPanic "tcPolyCheck" (ppr sig) +tcPolyCheck _prag_fn sig bind + = pprPanic "tcPolyCheck" (ppr sig $$ ppr bind) + +{- Note [Instantiate sig with fresh variables] +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +It's vital to instantiate a type signature with fresh variables. +For example: + type T = forall a. [a] -> [a] + f :: T; + f = g where { g :: T; g = <rhs> } + + We must not use the same 'a' from the defn of T at both places!! +(Instantiation is only necessary because of type synonyms. Otherwise, +it's all cool; each signature has distinct type variables from the renamer.) +-} + + +{- ********************************************************************* +* * + tcPolyInfer +* * +********************************************************************* -} ------------------- tcPolyInfer :: RecFlag -- Whether it's recursive after breaking -- dependencies based on type signatures @@ -661,6 +714,8 @@ tcPolyInfer rec_tc prag_fn tc_sig_fn mono bind_list | info <- mono_infos ] sigs = [ sig | MBI { mbi_sig = Just sig } <- mono_infos ] + ; mapM_ (checkOverloadedSig mono) sigs + ; traceTc "simplifyInfer call" (ppr tclvl $$ ppr name_taus $$ ppr wanted) ; (qtvs, givens, ev_binds) <- simplifyInfer tclvl mono sigs name_taus wanted @@ -713,11 +768,11 @@ mkExport prag_fn qtvs theta -- See Note [Impedence matching] -- NB: we have already done checkValidType, including an ambiguity check, -- on the type; either when we checked the sig or in mkInferredPolyId - ; let sel_poly_ty = mkInvSigmaTy qtvs theta mono_ty - -- this type is just going into tcSubType, so Inv vs. Spec doesn't - -- matter + ; let poly_ty = idType poly_id + sel_poly_ty = mkInvSigmaTy qtvs theta mono_ty + -- This type is just going into tcSubType, + -- so Inv vs. Spec doesn't matter - poly_ty = idType poly_id ; wrap <- if sel_poly_ty `eqType` poly_ty -- NB: eqType ignores visibility then return idHsWrapper -- Fast path; also avoids complaint when we infer -- an ambiguouse type and have AllowAmbiguousType @@ -739,11 +794,11 @@ mkExport prag_fn qtvs theta sig_ctxt = InfSigCtxt poly_name mkInferredPolyId :: [TyVar] -> TcThetaType - -> Name -> Maybe TcIdSigInfo -> TcType + -> Name -> Maybe TcIdSigInst -> TcType -> TcM TcId -mkInferredPolyId qtvs inferred_theta poly_name mb_sig mono_ty - | Just sig <- mb_sig - , Just poly_id <- completeIdSigPolyId_maybe sig +mkInferredPolyId qtvs inferred_theta poly_name mb_sig_inst mono_ty + | Just (TISI { sig_inst_sig = sig }) <- mb_sig_inst + , CompleteSig { sig_bndr = poly_id } <- sig = return poly_id | otherwise -- Either no type sig or partial type sig @@ -763,7 +818,7 @@ mkInferredPolyId qtvs inferred_theta poly_name mb_sig mono_ty -- it in the call to tcSubType below ; (binders, theta') <- chooseInferredQuantifiers inferred_theta - (tyCoVarsOfType mono_ty') qtvs mb_sig + (tyCoVarsOfType mono_ty') qtvs mb_sig_inst ; let inferred_poly_ty = mkForAllTys binders (mkPhiTy theta' mono_ty') @@ -779,7 +834,7 @@ mkInferredPolyId qtvs inferred_theta poly_name mb_sig mono_ty chooseInferredQuantifiers :: TcThetaType -- inferred -> TcTyVarSet -- tvs free in tau type -> [TcTyVar] -- inferred quantified tvs - -> Maybe TcIdSigInfo + -> Maybe TcIdSigInst -> TcM ([TcTyBinder], TcThetaType) chooseInferredQuantifiers inferred_theta tau_tvs qtvs Nothing = -- No type signature (partial or complete) for this binder, @@ -792,20 +847,18 @@ chooseInferredQuantifiers inferred_theta tau_tvs qtvs Nothing ; return (binders, my_theta) } chooseInferredQuantifiers inferred_theta tau_tvs qtvs - (Just (TISI { sig_bndr = bndr_info -- Always PartialSig - , sig_ctxt = ctxt - , sig_theta = annotated_theta - , sig_skols = annotated_tvs })) - | PartialSig { sig_cts = extra } <- bndr_info - , Nothing <- extra + (Just (TISI { sig_inst_sig = sig -- Always PartialSig + , sig_inst_wcx = wcx + , sig_inst_theta = annotated_theta + , sig_inst_skols = annotated_tvs })) + | Nothing <- wcx = do { annotated_theta <- zonkTcTypes annotated_theta ; let free_tvs = closeOverKinds (tyCoVarsOfTypes annotated_theta `unionVarSet` tau_tvs) - ; traceTc "ciq" (vcat [ ppr bndr_info, ppr annotated_theta, ppr free_tvs]) + ; traceTc "ciq" (vcat [ ppr sig, ppr annotated_theta, ppr free_tvs]) ; return (mk_binders free_tvs, annotated_theta) } - | PartialSig { sig_cts = extra, sig_hs_ty = hs_ty } <- bndr_info - , Just loc <- extra + | Just wc_var <- wcx = do { annotated_theta <- zonkTcTypes annotated_theta ; let free_tvs = closeOverKinds (tyCoVarsOfTypes annotated_theta `unionVarSet` tau_tvs) @@ -818,32 +871,19 @@ chooseInferredQuantifiers inferred_theta tau_tvs qtvs inferred_diff = [ pred | pred <- my_theta , all (not . (`eqType` pred)) annotated_theta ] - ; partial_sigs <- xoptM LangExt.PartialTypeSignatures - ; warn_partial_sigs <- woptM Opt_WarnPartialTypeSignatures - ; msg <- mkLongErrAt loc (mk_msg inferred_diff partial_sigs hs_ty) empty + ; ctuple <- mk_ctuple inferred_diff + ; writeMetaTyVar wc_var ctuple ; traceTc "completeTheta" $ - vcat [ ppr bndr_info + vcat [ ppr sig , ppr annotated_theta, ppr inferred_theta , ppr inferred_diff ] - ; case partial_sigs of - True | warn_partial_sigs -> - reportWarning (Reason Opt_WarnPartialTypeSignatures) msg - | otherwise -> return () - False -> reportError msg ; return (mk_binders free_tvs, my_theta) } | otherwise -- A complete type signature is dealt with in mkInferredPolyId - = pprPanic "chooseInferredQuantifiers" (ppr bndr_info) + = pprPanic "chooseInferredQuantifiers" (ppr sig) where - pts_hint = text "To use the inferred type, enable PartialTypeSignatures" - mk_msg inferred_diff suppress_hint hs_ty - = vcat [ hang ((text "Found constraint wildcard") <+> quotes (char '_')) - 2 (text "standing for") <+> quotes (pprTheta inferred_diff) - , if suppress_hint then empty else pts_hint - , pprSigCtxt ctxt (ppr hs_ty) ] - spec_tv_set = mkVarSet $ map snd annotated_tvs mk_binders free_tvs = [ mkNamedBinder vis tv @@ -853,6 +893,10 @@ chooseInferredQuantifiers inferred_theta tau_tvs qtvs | otherwise = Invisible ] -- Pulling from qtvs maintains original order + mk_ctuple [pred] = return pred + mk_ctuple preds = do { tc <- tcLookupTyCon (cTupleTyConName (length preds)) + ; return (mkTyConApp tc preds) } + mk_impedence_match_msg :: MonoBindInfo -> TcType -> TcType -> TidyEnv -> TcM (TidyEnv, SDoc) @@ -882,7 +926,7 @@ mk_inf_msg poly_name poly_ty tidy_env -- | Warn the user about polymorphic local binders that lack type signatures. -localSigWarn :: WarningFlag -> Id -> Maybe TcIdSigInfo -> TcM () +localSigWarn :: WarningFlag -> Id -> Maybe TcIdSigInst -> TcM () localSigWarn flag id mb_sig | Just _ <- mb_sig = return () | not (isSigmaTy (idType id)) = return () @@ -898,13 +942,32 @@ warnMissingSignatures flag msg id where mk_msg ty = sep [ msg, nest 2 $ pprPrefixName (idName id) <+> dcolon <+> ppr ty ] -{- -Note [Partial type signatures and generalisation] -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -When we have a partial type signature, like +checkOverloadedSig :: Bool -> TcIdSigInst -> TcM () +-- Example: +-- f :: Eq a => a -> a +-- K f = e +-- The MR applies, but the signature is overloaded, and it's +-- best to complain about this directly +-- c.f Trac #11339 +checkOverloadedSig monomorphism_restriction_applies sig + | not (null (sig_inst_theta sig)) + , monomorphism_restriction_applies + , let orig_sig = sig_inst_sig sig + = setSrcSpan (sig_loc orig_sig) $ + failWith $ + hang (text "Illegal overloaded signature conflicts with monomorphism restriction") + 2 (ppr orig_sig) + | otherwise + = return () + +{- Note [Partial type signatures and generalisation] +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +If /any/ of the signatures in the gropu is a partial type signature f :: _ -> Int then we *always* use the InferGen plan, and hence tcPolyInfer. -We do this even for a local binding with -XMonoLocalBinds. +We do this even for a local binding with -XMonoLocalBinds, when +we normally use NoGen. + Reasons: * The TcSigInfo for 'f' has a unification variable for the '_', whose TcLevel is one level deeper than the current level. @@ -922,6 +985,14 @@ It might be possible to fix these difficulties somehow, but there doesn't seem much point. Indeed, adding a partial type signature is a way to get per-binding inferred generalisation. +We apply the MR if /all/ of the partial signatures lack a context. +In particular (Trac #11016): + f2 :: (?loc :: Int) => _ + f2 = ?loc +It's stupid to apply the MR here. This test includes an extra-constraints +wildcard; that is, we don't apply the MR if you write + f3 :: _ => blah + Note [Validity of inferred types] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We need to check inferred type for validity, in case it uses language @@ -976,282 +1047,6 @@ It also cleverly does an ambiguity check; for example, rejecting where F is a non-injective type function. -} --------------- --- If typechecking the binds fails, then return with each --- signature-less binder given type (forall a.a), to minimise --- subsequent error messages -recoveryCode :: [Name] -> TcSigFun -> TcM (LHsBinds TcId, [Id]) -recoveryCode binder_names sig_fn - = do { traceTc "tcBindsWithSigs: error recovery" (ppr binder_names) - ; let poly_ids = map mk_dummy binder_names - ; return (emptyBag, poly_ids) } - where - mk_dummy name - | Just sig <- sig_fn name - , Just poly_id <- completeSigPolyId_maybe sig - = poly_id - | otherwise - = mkLocalId name forall_a_a - -forall_a_a :: TcType -forall_a_a = mkSpecForAllTys [runtimeRep1TyVar, openAlphaTyVar] openAlphaTy - -{- ********************************************************************* -* * - Pragmas, including SPECIALISE -* * -************************************************************************ - -Note [Handling SPECIALISE pragmas] -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -The basic idea is this: - - foo :: Num a => a -> b -> a - {-# SPECIALISE foo :: Int -> b -> Int #-} - -We check that - (forall a b. Num a => a -> b -> a) - is more polymorphic than - forall b. Int -> b -> Int -(for which we could use tcSubType, but see below), generating a HsWrapper -to connect the two, something like - wrap = /\b. <hole> Int b dNumInt -This wrapper is put in the TcSpecPrag, in the ABExport record of -the AbsBinds. - - - f :: (Eq a, Ix b) => a -> b -> Bool - {-# SPECIALISE f :: (Ix p, Ix q) => Int -> (p,q) -> Bool #-} - f = <poly_rhs> - -From this the typechecker generates - - AbsBinds [ab] [d1,d2] [([ab], f, f_mono, prags)] binds - - SpecPrag (wrap_fn :: forall a b. (Eq a, Ix b) => XXX - -> forall p q. (Ix p, Ix q) => XXX[ Int/a, (p,q)/b ]) - -From these we generate: - - Rule: forall p, q, (dp:Ix p), (dq:Ix q). - f Int (p,q) dInt ($dfInPair dp dq) = f_spec p q dp dq - - Spec bind: f_spec = wrap_fn <poly_rhs> - -Note that - - * The LHS of the rule may mention dictionary *expressions* (eg - $dfIxPair dp dq), and that is essential because the dp, dq are - needed on the RHS. - - * The RHS of f_spec, <poly_rhs> has a *copy* of 'binds', so that it - can fully specialise it. - - - -From the TcSpecPrag, in DsBinds we generate a binding for f_spec and a RULE: - - f_spec :: Int -> b -> Int - f_spec = wrap<f rhs> - - RULE: forall b (d:Num b). f b d = f_spec b - -The RULE is generated by taking apart the HsWrapper, which is a little -delicate, but works. - -Some wrinkles - -1. We don't use full-on tcSubType, because that does co and contra - variance and that in turn will generate too complex a LHS for the - RULE. So we use a single invocation of skolemise / - topInstantiate in tcSpecWrapper. (Actually I think that even - the "deeply" stuff may be too much, because it introduces lambdas, - though I think it can be made to work without too much trouble.) - -2. We need to take care with type families (Trac #5821). Consider - type instance F Int = Bool - f :: Num a => a -> F a - {-# SPECIALISE foo :: Int -> Bool #-} - - We *could* try to generate an f_spec with precisely the declared type: - f_spec :: Int -> Bool - f_spec = <f rhs> Int dNumInt |> co - - RULE: forall d. f Int d = f_spec |> sym co - - but the 'co' and 'sym co' are (a) playing no useful role, and (b) are - hard to generate. At all costs we must avoid this: - RULE: forall d. f Int d |> co = f_spec - because the LHS will never match (indeed it's rejected in - decomposeRuleLhs). - - So we simply do this: - - Generate a constraint to check that the specialised type (after - skolemiseation) is equal to the instantiated function type. - - But *discard* the evidence (coercion) for that constraint, - so that we ultimately generate the simpler code - f_spec :: Int -> F Int - f_spec = <f rhs> Int dNumInt - - RULE: forall d. f Int d = f_spec - You can see this discarding happening in - -3. Note that the HsWrapper can transform *any* function with the right - type prefix - forall ab. (Eq a, Ix b) => XXX - regardless of XXX. It's sort of polymorphic in XXX. This is - useful: we use the same wrapper to transform each of the class ops, as - well as the dict. That's what goes on in TcInstDcls.mk_meth_spec_prags --} - -mkPragEnv :: [LSig Name] -> LHsBinds Name -> TcPragEnv -mkPragEnv sigs binds - = foldl extendPragEnv emptyNameEnv prs - where - prs = mapMaybe get_sig sigs - - get_sig :: LSig Name -> Maybe (Name, LSig Name) - get_sig (L l (SpecSig lnm@(L _ nm) ty inl)) = Just (nm, L l $ SpecSig lnm ty (add_arity nm inl)) - get_sig (L l (InlineSig lnm@(L _ nm) inl)) = Just (nm, L l $ InlineSig lnm (add_arity nm inl)) - get_sig _ = Nothing - - add_arity n inl_prag -- Adjust inl_sat field to match visible arity of function - | Inline <- inl_inline inl_prag - -- add arity only for real INLINE pragmas, not INLINABLE - = case lookupNameEnv ar_env n of - Just ar -> inl_prag { inl_sat = Just ar } - Nothing -> WARN( True, text "mkPragEnv no arity" <+> ppr n ) - -- There really should be a binding for every INLINE pragma - inl_prag - | otherwise - = inl_prag - - -- ar_env maps a local to the arity of its definition - ar_env :: NameEnv Arity - ar_env = foldrBag lhsBindArity emptyNameEnv binds - -extendPragEnv :: TcPragEnv -> (Name, LSig Name) -> TcPragEnv -extendPragEnv prag_fn (n, sig) = extendNameEnv_Acc (:) singleton prag_fn n sig - -lhsBindArity :: LHsBind Name -> NameEnv Arity -> NameEnv Arity -lhsBindArity (L _ (FunBind { fun_id = id, fun_matches = ms })) env - = extendNameEnv env (unLoc id) (matchGroupArity ms) -lhsBindArity _ env = env -- PatBind/VarBind - ------------------- -tcSpecPrags :: Id -> [LSig Name] - -> TcM [LTcSpecPrag] --- Add INLINE and SPECIALSE pragmas --- INLINE prags are added to the (polymorphic) Id directly --- SPECIALISE prags are passed to the desugarer via TcSpecPrags --- Pre-condition: the poly_id is zonked --- Reason: required by tcSubExp -tcSpecPrags poly_id prag_sigs - = do { traceTc "tcSpecPrags" (ppr poly_id <+> ppr spec_sigs) - ; unless (null bad_sigs) warn_discarded_sigs - ; pss <- mapAndRecoverM (wrapLocM (tcSpecPrag poly_id)) spec_sigs - ; return $ concatMap (\(L l ps) -> map (L l) ps) pss } - where - spec_sigs = filter isSpecLSig prag_sigs - bad_sigs = filter is_bad_sig prag_sigs - is_bad_sig s = not (isSpecLSig s || isInlineLSig s) - - warn_discarded_sigs - = addWarnTc NoReason - (hang (text "Discarding unexpected pragmas for" <+> ppr poly_id) - 2 (vcat (map (ppr . getLoc) bad_sigs))) - --------------- -tcSpecPrag :: TcId -> Sig Name -> TcM [TcSpecPrag] -tcSpecPrag poly_id prag@(SpecSig fun_name hs_tys inl) --- See Note [Handling SPECIALISE pragmas] --- --- The Name fun_name in the SpecSig may not be the same as that of the poly_id --- Example: SPECIALISE for a class method: the Name in the SpecSig is --- for the selector Id, but the poly_id is something like $cop --- However we want to use fun_name in the error message, since that is --- what the user wrote (Trac #8537) - = addErrCtxt (spec_ctxt prag) $ - do { warnIf NoReason (not (isOverloadedTy poly_ty || isInlinePragma inl)) - (text "SPECIALISE pragma for non-overloaded function" - <+> quotes (ppr fun_name)) - -- Note [SPECIALISE pragmas] - ; spec_prags <- mapM tc_one hs_tys - ; traceTc "tcSpecPrag" (ppr poly_id $$ nest 2 (vcat (map ppr spec_prags))) - ; return spec_prags } - where - name = idName poly_id - poly_ty = idType poly_id - spec_ctxt prag = hang (text "In the SPECIALISE pragma") 2 (ppr prag) - - tc_one hs_ty - = do { spec_ty <- tcHsSigType (FunSigCtxt name False) hs_ty - ; wrap <- tcSpecWrapper (FunSigCtxt name True) poly_ty spec_ty - ; return (SpecPrag poly_id wrap inl) } - -tcSpecPrag _ prag = pprPanic "tcSpecPrag" (ppr prag) - --------------- -tcSpecWrapper :: UserTypeCtxt -> TcType -> TcType -> TcM HsWrapper --- A simpler variant of tcSubType, used for SPECIALISE pragmas --- See Note [Handling SPECIALISE pragmas], wrinkle 1 -tcSpecWrapper ctxt poly_ty spec_ty - = do { (sk_wrap, inst_wrap) - <- tcSkolemise ctxt spec_ty $ \ _ spec_tau -> - do { (inst_wrap, tau) <- topInstantiate orig poly_ty - ; _ <- unifyType noThing spec_tau tau - -- Deliberately ignore the evidence - -- See Note [Handling SPECIALISE pragmas], - -- wrinkle (2) - ; return inst_wrap } - ; return (sk_wrap <.> inst_wrap) } - where - orig = SpecPragOrigin ctxt - --------------- -tcImpPrags :: [LSig Name] -> TcM [LTcSpecPrag] --- SPECIALISE pragmas for imported things -tcImpPrags prags - = do { this_mod <- getModule - ; dflags <- getDynFlags - ; if (not_specialising dflags) then - return [] - else do - { pss <- mapAndRecoverM (wrapLocM tcImpSpec) - [L loc (name,prag) - | (L loc prag@(SpecSig (L _ name) _ _)) <- prags - , not (nameIsLocalOrFrom this_mod name) ] - ; return $ concatMap (\(L l ps) -> map (L l) ps) pss } } - where - -- Ignore SPECIALISE pragmas for imported things - -- when we aren't specialising, or when we aren't generating - -- code. The latter happens when Haddocking the base library; - -- we don't wnat complaints about lack of INLINABLE pragmas - not_specialising dflags - | not (gopt Opt_Specialise dflags) = True - | otherwise = case hscTarget dflags of - HscNothing -> True - HscInterpreted -> True - _other -> False - -tcImpSpec :: (Name, Sig Name) -> TcM [TcSpecPrag] -tcImpSpec (name, prag) - = do { id <- tcLookupId name - ; unless (isAnyInlinePragma (idInlinePragma id)) - (addWarnTc NoReason (impSpecErr name)) - ; tcSpecPrag id prag } - -impSpecErr :: Name -> SDoc -impSpecErr name - = hang (text "You cannot SPECIALISE" <+> quotes (ppr name)) - 2 (vcat [ text "because its definition has no INLINE/INLINABLE pragma" - , parens $ sep - [ text "or its defining module" <+> quotes (ppr mod) - , text "was compiled without -O"]]) - where - mod = nameModule name - - {- ********************************************************************* * * Vectorisation @@ -1288,32 +1083,6 @@ tcVect (HsVect s name rhs) ; return $ HsVect s var (L rhs_loc (HsVar (L lv rhs_id))) } -{- OLD CODE: - -- turn the vectorisation declaration into a single non-recursive binding - ; let bind = L loc $ mkTopFunBind name [mkSimpleMatch [] rhs] - sigFun = const Nothing - pragFun = emptyPragEnv - - -- perform type inference (including generalisation) - ; (binds, [id'], _) <- tcPolyInfer False True sigFun pragFun NonRecursive [bind] - - ; traceTc "tcVect inferred type" $ ppr (varType id') - ; traceTc "tcVect bindings" $ ppr binds - - -- add all bindings, including the type variable and dictionary bindings produced by type - -- generalisation to the right-hand side of the vectorisation declaration - ; let [AbsBinds tvs evs _ evBinds actualBinds] = (map unLoc . bagToList) binds - ; let [bind'] = bagToList actualBinds - MatchGroup - [L _ (Match _ _ (GRHSs [L _ (GRHS _ rhs')] _))] - _ = (fun_matches . unLoc) bind' - rhsWrapped = mkHsLams tvs evs (mkHsDictLet evBinds rhs') - - -- We return the type-checked 'Id', to propagate the inferred signature - -- to the vectoriser - see "Note [Typechecked vectorisation pragmas]" in HsDecls - ; return $ HsVect (L loc id') (Just rhsWrapped) - } - -} tcVect (HsNoVect s name) = addErrCtxt (vectCtxt name) $ do { var <- wrapLocM tcLookupId name @@ -1439,6 +1208,10 @@ We do not need to do this * for FunBinds where we have a signature, bucause we aren't doing inference -} +data MonoBindInfo = MBI { mbi_poly_name :: Name + , mbi_sig :: Maybe TcIdSigInst + , mbi_mono_id :: TcId } + tcMonoBinds :: RecFlag -- Whether the binding is recursive for typechecking purposes -- i.e. the binders are mentioned in their RHSs, and -- we are not rescued by a type signature @@ -1473,7 +1246,7 @@ tcMonoBinds is_rec sig_fn no_gen ; (inst_wrap, rhs_ty) <- addErrCtxtM (instErrCtxt name rhs_ty) $ deeplyInstantiate orig rhs_ty - ; mono_id <- newNoSigLetBndr no_gen name rhs_ty + ; mono_id <- newLetBndr no_gen name rhs_ty ; return (unitBag $ L b_loc $ FunBind { fun_id = L nm_loc mono_id, fun_matches = matches', bind_fvs = fvs, @@ -1505,15 +1278,6 @@ tcMonoBinds _ sig_fn no_gen binds ; return (listToBag binds', mono_infos) } -emitWildCardHoles :: MonoBindInfo -> TcM () -emitWildCardHoles (MBI { mbi_sig = Just sig }) - | TISI { sig_bndr = bndr, sig_ctxt = ctxt } <- sig - , PartialSig { sig_wcs = wc_prs, sig_hs_ty = hs_ty } <- bndr - = addErrCtxt (pprSigCtxt ctxt (ppr hs_ty)) $ - emitWildCardHoleConstraints wc_prs -emitWildCardHoles _ - = return () - ------------------------ -- tcLhs typechecks the LHS of the bindings, to construct the environment in which -- we typecheck the RHSs. Basically what we are doing is this: for each binder: @@ -1534,76 +1298,109 @@ data TcMonoBind -- Half completed; LHS done, RHS not done = TcFunBind MonoBindInfo SrcSpan (MatchGroup Name (LHsExpr Name)) | TcPatBind [MonoBindInfo] (LPat TcId) (GRHSs Name (LHsExpr Name)) TcSigmaType -data MonoBindInfo = MBI { mbi_poly_name :: Name - , mbi_sig :: Maybe TcIdSigInfo - , mbi_mono_id :: TcId } - tcLhs :: TcSigFun -> LetBndrSpec -> HsBind Name -> TcM TcMonoBind tcLhs sig_fn no_gen (FunBind { fun_id = L nm_loc name, fun_matches = matches }) - | Just (TcIdSig sig) <- sig_fn name - , TISI { sig_tau = tau } <- sig - = ASSERT2( case no_gen of { LetLclBndr -> True; LetGblBndr {} -> False } - , ppr name ) - -- { f :: ty; f x = e } is always done via CheckGen (full signature) - -- or InferGen (partial signature) - -- see Note [Partial type signatures and generalisation] - -- Both InferGen and CheckGen gives rise to LetLclBndr - do { mono_name <- newLocalName name - ; let mono_id = mkLocalIdOrCoVar mono_name tau - ; return (TcFunBind (MBI { mbi_poly_name = name - , mbi_sig = Just sig - , mbi_mono_id = mono_id }) - nm_loc matches) } - - | otherwise - = do { mono_ty <- newOpenFlexiTyVarTy - ; mono_id <- newNoSigLetBndr no_gen name mono_ty - ; return (TcFunBind (MBI { mbi_poly_name = name - , mbi_sig = Nothing - , mbi_mono_id = mono_id }) - nm_loc matches) } + = do { mono_info <- tcLhsId sig_fn no_gen name + ; return (TcFunBind mono_info nm_loc matches) } tcLhs sig_fn no_gen (PatBind { pat_lhs = pat, pat_rhs = grhss }) - = do { let tc_pat exp_ty = tcLetPat sig_fn no_gen pat exp_ty $ - mapM lookup_info (collectPatBinders pat) - - -- After typechecking the pattern, look up the binder - -- names, which the pattern has brought into scope. - lookup_info :: Name -> TcM MonoBindInfo - lookup_info name - = do { mono_id <- tcLookupId name - ; let mb_sig = case sig_fn name of - Just (TcIdSig sig) -> Just sig - _ -> Nothing - ; return (MBI { mbi_poly_name = name - , mbi_sig = mb_sig - , mbi_mono_id = mono_id }) } - - ; ((pat', infos), pat_ty) <- addErrCtxt (patMonoBindsCtxt pat grhss) $ - tcInfer tc_pat - - ; return (TcPatBind infos pat' grhss pat_ty) } + = do { let bndr_names = collectPatBinders pat + ; mbis <- mapM (tcLhsId sig_fn no_gen) bndr_names + -- See Note [Existentials in pattern bindings] + + ; let inst_sig_fun = lookupNameEnv $ mkNameEnv $ + bndr_names `zip` map mbi_mono_id mbis + + ; traceTc "tcLhs" (vcat [ ppr id <+> dcolon <+> ppr (idType id) + | mbi <- mbis, let id = mbi_mono_id mbi ] + $$ ppr no_gen) + + ; ((pat', _), pat_ty) <- addErrCtxt (patMonoBindsCtxt pat grhss) $ + tcInfer $ \ exp_ty -> + tcLetPat inst_sig_fun pat exp_ty $ + return () -- mapM (lookup_info inst_sig_fun) bndr_names + + ; return (TcPatBind mbis pat' grhss pat_ty) } tcLhs _ _ other_bind = pprPanic "tcLhs" (ppr other_bind) -- AbsBind, VarBind impossible ------------------- +data LetBndrSpec + = LetLclBndr -- We are going to generalise, and wrap in an AbsBinds + -- so clone a fresh binder for the local monomorphic Id + + | LetGblBndr TcPragEnv -- Generalisation plan is NoGen, so there isn't going + -- to be an AbsBinds; So we must bind the global version + -- of the binder right away. + -- And here is the inline-pragma information + +instance Outputable LetBndrSpec where + ppr LetLclBndr = text "LetLclBndr" + ppr (LetGblBndr {}) = text "LetGblBndr" + +tcLhsId :: TcSigFun -> LetBndrSpec -> Name -> TcM MonoBindInfo +tcLhsId sig_fn no_gen name + | Just (TcIdSig sig) <- sig_fn name + = -- A partial type signature on a FunBind, in a mixed group + -- e.g. f :: _ -> _ + -- f x = ...g... + -- Just g = ...f... + -- Hence always typechecked with InferGen; hence LetLclBndr + -- + -- A compelete type sig on a FunBind is checked with CheckGen + -- and does not go via tcLhsId + do { inst_sig <- tcInstSig sig + ; the_id <- newSigLetBndr no_gen name inst_sig + ; return (MBI { mbi_poly_name = name + , mbi_sig = Just inst_sig + , mbi_mono_id = the_id }) } + + | otherwise + = -- No type signature, plan InferGen (LetLclBndr) or NoGen (LetGblBndr) + do { mono_ty <- newOpenFlexiTyVarTy + ; mono_id <- newLetBndr no_gen name mono_ty + ; return (MBI { mbi_poly_name = name + , mbi_sig = Nothing + , mbi_mono_id = mono_id }) } + +------------ +newSigLetBndr :: LetBndrSpec -> Name -> TcIdSigInst -> TcM TcId +newSigLetBndr (LetGblBndr prags) name (TISI { sig_inst_sig = id_sig }) + | CompleteSig { sig_bndr = poly_id } <- id_sig + = addInlinePrags poly_id (lookupPragEnv prags name) +newSigLetBndr no_gen name (TISI { sig_inst_tau = tau }) + = newLetBndr no_gen name tau + +newLetBndr :: LetBndrSpec -> Name -> TcType -> TcM TcId +-- In the polymorphic case when we are going to generalise +-- (plan InferGen, no_gen = LetLclBndr), generate a "monomorphic version" +-- of the Id; the original name will be bound to the polymorphic version +-- by the AbsBinds +-- In the monomorphic case when we are not going to generalise +-- (plan NoGen, no_gen = LetGblBndr) there is no AbsBinds, +-- and we use the original name directly +newLetBndr LetLclBndr name ty + = do { mono_name <- cloneLocalName name + ; return (mkLocalId mono_name ty) } +newLetBndr (LetGblBndr prags) name ty + = addInlinePrags (mkLocalId name ty) (lookupPragEnv prags name) + +------------------- tcRhs :: TcMonoBind -> TcM (HsBind TcId) tcRhs (TcFunBind info@(MBI { mbi_sig = mb_sig, mbi_mono_id = mono_id }) loc matches) = tcExtendIdBinderStackForRhs [info] $ tcExtendTyVarEnvForRhs mb_sig $ do { traceTc "tcRhs: fun bind" (ppr mono_id $$ ppr (idType mono_id)) - ; (co_fn, matches') <- tcMatchesFun (noLoc $ idName mono_id) + ; (co_fn, matches') <- tcMatchesFun (L loc (idName mono_id)) matches (mkCheckExpType $ idType mono_id) - ; emitWildCardHoles info ; return ( FunBind { fun_id = L loc mono_id , fun_matches = matches' , fun_co_fn = co_fn , bind_fvs = placeHolderNamesTc , fun_tick = [] } ) } --- TODO: emit Hole Constraints for wildcards tcRhs (TcPatBind infos pat' grhss pat_ty) = -- When we are doing pattern bindings we *don't* bring any scoped -- type variables into scope unlike function bindings @@ -1613,26 +1410,23 @@ tcRhs (TcPatBind infos pat' grhss pat_ty) do { traceTc "tcRhs: pat bind" (ppr pat' $$ ppr pat_ty) ; grhss' <- addErrCtxt (patMonoBindsCtxt pat' grhss) $ tcGRHSsPat grhss pat_ty - ; mapM_ emitWildCardHoles infos ; return ( PatBind { pat_lhs = pat', pat_rhs = grhss' , pat_rhs_ty = pat_ty , bind_fvs = placeHolderNamesTc , pat_ticks = ([],[]) } )} -tcExtendTyVarEnvForRhs :: Maybe TcIdSigInfo -> TcM a -> TcM a +tcExtendTyVarEnvForRhs :: Maybe TcIdSigInst -> TcM a -> TcM a tcExtendTyVarEnvForRhs Nothing thing_inside = thing_inside tcExtendTyVarEnvForRhs (Just sig) thing_inside = tcExtendTyVarEnvFromSig sig thing_inside -tcExtendTyVarEnvFromSig :: TcIdSigInfo -> TcM a -> TcM a -tcExtendTyVarEnvFromSig sig thing_inside - | TISI { sig_bndr = s_bndr, sig_skols = skol_prs } <- sig - = tcExtendTyVarEnv2 skol_prs $ - case s_bndr of - CompleteSig {} -> thing_inside - PartialSig { sig_wcs = wc_prs } -- Extend the env ad emit the holes - -> tcExtendTyVarEnv2 wc_prs thing_inside +tcExtendTyVarEnvFromSig :: TcIdSigInst -> TcM a -> TcM a +tcExtendTyVarEnvFromSig sig_inst thing_inside + | TISI { sig_inst_skols = skol_prs, sig_inst_wcs = wcs } <- sig_inst + = tcExtendTyVarEnv2 wcs $ + tcExtendTyVarEnv2 skol_prs $ + thing_inside tcExtendIdBinderStackForRhs :: [MonoBindInfo] -> TcM a -> TcM a -- Extend the TcIdBinderStack for the RHS of the binding, with @@ -1657,243 +1451,72 @@ getMonoBindInfo :: [Located TcMonoBind] -> [MonoBindInfo] getMonoBindInfo tc_binds = foldr (get_info . unLoc) [] tc_binds where - get_info (TcFunBind info _ _) rest = info : rest + get_info (TcFunBind info _ _) rest = info : rest get_info (TcPatBind infos _ _ _) rest = infos ++ rest -{- -************************************************************************ -* * - Signatures -* * -************************************************************************ +{- Note [Existentials in pattern bindings] +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +Consider (typecheck/should_compile/ExPat): + data T where + MkT :: Integral a => a -> Int -> T -Type signatures are tricky. See Note [Signature skolems] in TcType - -@tcSigs@ checks the signatures for validity, and returns a list of -{\em freshly-instantiated} signatures. That is, the types are already -split up, and have fresh type variables installed. All non-type-signature -"RenamedSigs" are ignored. - -The @TcSigInfo@ contains @TcTypes@ because they are unified with -the variable's type, and after that checked to see whether they've -been instantiated. - -Note [Scoped tyvars] -~~~~~~~~~~~~~~~~~~~~ -The -XScopedTypeVariables flag brings lexically-scoped type variables -into scope for any explicitly forall-quantified type variables: - f :: forall a. a -> a - f x = e -Then 'a' is in scope inside 'e'. - -However, we do *not* support this - - For pattern bindings e.g - f :: forall a. a->a - (f,g) = e - -Note [Signature skolems] -~~~~~~~~~~~~~~~~~~~~~~~~ -When instantiating a type signature, we do so with either skolems or -SigTv meta-type variables depending on the use_skols boolean. This -variable is set True when we are typechecking a single function -binding; and False for pattern bindings and a group of several -function bindings. - -Reason: in the latter cases, the "skolems" can be unified together, - so they aren't properly rigid in the type-refinement sense. -NB: unless we are doing H98, each function with a sig will be done - separately, even if it's mutually recursive, so use_skols will be True - - -Note [Only scoped tyvars are in the TyVarEnv] -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -We are careful to keep only the *lexically scoped* type variables in -the type environment. Why? After all, the renamer has ensured -that only legal occurrences occur, so we could put all type variables -into the type env. - -But we want to check that two distinct lexically scoped type variables -do not map to the same internal type variable. So we need to know which -the lexically-scoped ones are... and at the moment we do that by putting -only the lexically scoped ones into the environment. - -Note [Instantiate sig with fresh variables] -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -It's vital to instantiate a type signature with fresh variables. -For example: - type T = forall a. [a] -> [a] - f :: T; - f = g where { g :: T; g = <rhs> } +and suppose t :: T. Which of these pattern bindings are ok? - We must not use the same 'a' from the defn of T at both places!! -(Instantiation is only necessary because of type synonyms. Otherwise, -it's all cool; each signature has distinct type variables from the renamer.) + E1. let { MkT p _ = t } in <body> -Note [Fail eagerly on bad signatures] -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -If a type signaure is wrong, fail immediately: + E2. let { MkT _ q = t } in <body> - * the type sigs may bind type variables, so proceeding without them - can lead to a cascade of errors + E3. let { MkT (toInteger -> r) _ = t } in <body> - * the type signature might be ambiguous, in which case checking - the code against the signature will give a very similar error - to the ambiguity error. +Well (E1) is clearly wrong becuase the existential 'a' escapes. +What type could 'p' possibly have? -ToDo: this means we fall over if any type sig -is wrong (eg at the top level of the module), -which is over-conservative --} +But (E2) is fine, despite the existential pattern, because +q::Int, and nothing escapes. + +Even (E3) is fine. The existential pattern binds a dictionary +for (Integral a) which the view pattern can use to convert the +a-valued field to an Integer, so r :: Integer. + +An easy way to see all three is to imagine the desugaring. +For (2) it would look like + let q = case t of MkT _ q' -> q' + in <body> + +We typecheck pattern bindings as follows: + 1. In tcLhs we bind q'::alpha, for each varibable q bound by the + pattern, where q' is a fresh name, and alpha is a fresh + unification variable; it will be the monomorphic verion of q that + we later generalise + + It's very important that these fresh unification variables + alpha are born here, not deep under implications as would happen + if we allocated them when we encountered q during tcPat. + + 2. Still in tcLhs, we build a little environment mappting "q" -> + q':alpha, and pass that to tcLetPet. + + 3. Then tcLhs invokes tcLetPat to typecheck the patter as usual: + - When tcLetPat finds an existential constructor, it binds fresh + type variables and dictionaries as usual, and emits an + implication constraint. + + - When tcLetPat finds a variable (TcPat.tcPatBndr) it looks it up + in the little environment, which should always succeed. And + uses tcSubTypeET to connect the type of that variable with the + expected type of the pattern. + +And that's it! The implication constraints check for the skolem +escape. It's quite simple and neat, and more exressive than before +e.g. GHC 8.0 rejects (E2) and (E3). + + +************************************************************************ +* * + Generalisation +* * +********************************************************************* -} -tcTySigs :: [LSig Name] -> TcM ([TcId], TcSigFun) -tcTySigs hs_sigs - = checkNoErrs $ -- See Note [Fail eagerly on bad signatures] - do { ty_sigs_s <- mapAndRecoverM tcTySig hs_sigs - ; let ty_sigs = concat ty_sigs_s - poly_ids = mapMaybe completeSigPolyId_maybe ty_sigs - -- The returned [TcId] are the ones for which we have - -- a complete type signature. - -- See Note [Complete and partial type signatures] - env = mkNameEnv [(tcSigInfoName sig, sig) | sig <- ty_sigs] - ; return (poly_ids, lookupNameEnv env) } - -tcTySig :: LSig Name -> TcM [TcSigInfo] -tcTySig (L _ (IdSig id)) - = do { sig <- instTcTySigFromId id - ; return [TcIdSig sig] } - -tcTySig (L loc (TypeSig names sig_ty)) - = setSrcSpan loc $ - do { sigs <- sequence [ tcUserTypeSig sig_ty (Just name) - | L _ name <- names ] - ; return (map TcIdSig sigs) } - -tcTySig (L loc (PatSynSig (L _ name) sig_ty)) - = setSrcSpan loc $ - do { tpsi <- tcPatSynSig name sig_ty - ; return [TcPatSynSig tpsi] } - -tcTySig _ = return [] - -isCompleteHsSig :: LHsSigWcType Name -> Bool --- ^ If there are no wildcards, return a LHsSigType -isCompleteHsSig sig_ty - | HsWC { hswc_wcs = wcs, hswc_ctx = extra } <- hsib_body sig_ty - , null wcs - , Nothing <- extra - = True - | otherwise - = False - -tcUserTypeSig :: LHsSigWcType Name -> Maybe Name -> TcM TcIdSigInfo --- Just n => Function type signatre name :: type --- Nothing => Expression type signature <expr> :: type -tcUserTypeSig hs_sig_ty mb_name - | isCompleteHsSig hs_sig_ty - = pushTcLevelM_ $ -- When instantiating the signature, do so "one level in" - -- so that they can be unified under the forall - do { sigma_ty <- tcHsSigWcType ctxt_F hs_sig_ty - ; (inst_tvs, theta, tau) <- tcInstType tcInstSigTyVars sigma_ty - ; loc <- getSrcSpanM - ; return $ - TISI { sig_bndr = CompleteSig (mkLocalId name sigma_ty) - , sig_skols = findScopedTyVars sigma_ty inst_tvs - , sig_theta = theta - , sig_tau = tau - , sig_ctxt = ctxt_T - , sig_loc = loc } } - - -- Partial sig with wildcards - | HsIB { hsib_vars = vars, hsib_body = wc_ty } <- hs_sig_ty - , HsWC { hswc_wcs = wcs, hswc_ctx = extra, hswc_body = hs_ty } <- wc_ty - , (hs_tvs, L _ hs_ctxt, hs_tau) <- splitLHsSigmaTy hs_ty - = do { (vars1, (wcs, tvs2, theta, tau)) - <- pushTcLevelM_ $ - -- When instantiating the signature, do so "one level in" - -- so that they can be unified under the forall - solveEqualities $ - tcImplicitTKBndrs vars $ - tcWildCardBinders wcs $ \ wcs -> - tcExplicitTKBndrs hs_tvs $ \ tvs2 -> - do { -- Instantiate the type-class context; but if there - -- is an extra-constraints wildcard, just discard it here - traceTc "tcPartial" (ppr name $$ ppr vars $$ ppr wcs) - ; theta <- mapM tcLHsPredType $ - case extra of - Nothing -> hs_ctxt - Just _ -> dropTail 1 hs_ctxt - - ; tau <- tcHsOpenType hs_tau - - -- zonking is necessary to establish type representation - -- invariants - ; theta <- zonkTcTypes theta - ; tau <- zonkTcType tau - - ; let bound_tvs - = unionVarSets [ allBoundVariabless theta - , allBoundVariables tau - , mkVarSet (map snd wcs) ] - ; return ((wcs, tvs2, theta, tau), bound_tvs) } - - -- NB: checkValidType on the final inferred type will - -- be done later by checkInferredPolyId - ; loc <- getSrcSpanM - ; return $ - TISI { sig_bndr = PartialSig { sig_name = name, sig_hs_ty = hs_ty - , sig_cts = extra, sig_wcs = wcs } - , sig_skols = [ (tyVarName tv, tv) | tv <- vars1 ++ tvs2 ] - , sig_theta = theta - , sig_tau = tau - , sig_ctxt = ctxt_F - , sig_loc = loc } } - where - name = case mb_name of - Just n -> n - Nothing -> mkUnboundName (mkVarOcc "<expression>") - ctxt_F = case mb_name of - Just n -> FunSigCtxt n False - Nothing -> ExprSigCtxt - ctxt_T = case mb_name of - Just n -> FunSigCtxt n True - Nothing -> ExprSigCtxt - -instTcTySigFromId :: Id -> TcM TcIdSigInfo --- Used for instance methods and record selectors -instTcTySigFromId id - = do { let name = idName id - loc = getSrcSpan name - ; (tvs, theta, tau) <- tcInstType (tcInstSigTyVarsLoc loc) - (idType id) - ; return $ TISI { sig_bndr = CompleteSig id - , sig_skols = [(tyVarName tv, tv) | tv <- tvs] - -- These are freshly instantiated, so although - -- we put them in the type envt, doing so has - -- no effect - , sig_theta = theta - , sig_tau = tau - , sig_ctxt = FunSigCtxt name False - -- False: do not report redundant constraints - -- The user has no control over the signature! - , sig_loc = loc } } - -instTcTySig :: UserTypeCtxt - -> LHsSigType Name -- Used to get the scoped type variables - -> TcType - -> Name -- Name of the function - -> TcM TcIdSigInfo -instTcTySig ctxt hs_ty sigma_ty name - = do { (inst_tvs, theta, tau) <- tcInstType tcInstSigTyVars sigma_ty - ; return (TISI { sig_bndr = CompleteSig (mkLocalIdOrCoVar name sigma_ty) - , sig_skols = findScopedTyVars sigma_ty inst_tvs - , sig_theta = theta - , sig_tau = tau - , sig_ctxt = ctxt - , sig_loc = getLoc (hsSigType hs_ty) - -- SrcSpan from the signature - }) } - -------------------------------- data GeneralisationPlan = NoGen -- No generalisation, no AbsBinds @@ -1916,28 +1539,26 @@ decideGeneralisationPlan :: DynFlags -> [LHsBind Name] -> IsGroupClosed -> TcSigFun -> GeneralisationPlan decideGeneralisationPlan dflags lbinds closed sig_fn - | unlifted_pat_binds = NoGen - | Just bind_sig <- one_funbind_with_sig = sig_plan bind_sig - | mono_local_binds closed = NoGen - | otherwise = InferGen mono_restriction + | unlifted_pat_binds = NoGen + | has_partial_sigs = InferGen (and partial_sig_mrs) + | Just (bind, sig) <- one_funbind_with_sig = CheckGen bind sig + | mono_local_binds closed = NoGen + | otherwise = InferGen mono_restriction where binds = map unLoc lbinds - sig_plan :: (LHsBind Name, TcIdSigInfo) -> GeneralisationPlan + partial_sig_mrs :: [Bool] + -- One for each parital signature (so empty => no partial sigs) + -- The Bool is True if the signature has no constraint context + -- so we should apply the MR -- See Note [Partial type signatures and generalisation] - -- We use InferGen False to say "do inference, but do not apply - -- the MR". It's stupid to apply the MR when we are given a - -- signature! C.f Trac #11016, function f2 - sig_plan (lbind, sig@(TISI { sig_bndr = s_bndr, sig_theta = theta })) - = case s_bndr of - CompleteSig {} -> CheckGen lbind sig - PartialSig { sig_cts = extra_constraints } - | Nothing <- extra_constraints - , [] <- theta - -> InferGen True -- No signature constraints: apply the MR - | otherwise - -> InferGen False -- Don't apply the MR + partial_sig_mrs + = [ null theta + | TcIdSig (PartialSig { psig_hs_ty = hs_ty }) + <- mapMaybe sig_fn (collectHsBindListBinders lbinds) + , let (_, L _ theta, _) = splitLHsSigmaTy (hsSigWcType hs_ty) ] + has_partial_sigs = not (null partial_sig_mrs) unlifted_pat_binds = any isUnliftedHsBind binds -- Unlifted patterns (unboxed tuple) must not -- be polymorphic, because we are going to force them @@ -1949,8 +1570,6 @@ decideGeneralisationPlan dflags lbinds closed sig_fn mono_local_binds ClosedGroup = False mono_local_binds _ = xopt LangExt.MonoLocalBinds dflags - no_sig n = noCompleteSig (sig_fn n) - -- With OutsideIn, all nested bindings are monomorphic -- except a single function binding with a signature one_funbind_with_sig @@ -1974,6 +1593,8 @@ decideGeneralisationPlan dflags lbinds closed sig_fn -- No args => like a pattern binding -- Some args => a function binding + no_sig n = noCompleteSig (sig_fn n) + isClosedBndrGroup :: Bag (LHsBind Name) -> TcM IsGroupClosed isClosedBndrGroup binds = do type_env <- getLclTypeEnv diff --git a/compiler/typecheck/TcClassDcl.hs b/compiler/typecheck/TcClassDcl.hs index 48b0e56baf..d0978fb5d4 100644 --- a/compiler/typecheck/TcClassDcl.hs +++ b/compiler/typecheck/TcClassDcl.hs @@ -20,8 +20,8 @@ module TcClassDcl ( tcClassSigs, tcClassDecl2, import HsSyn import TcEnv -import TcPat( addInlinePrags, lookupPragEnv, emptyPragEnv ) -import TcEvidence( idHsWrapper ) +import TcSigs +import TcEvidence ( idHsWrapper ) import TcBinds import TcUnify import TcHsType @@ -152,10 +152,10 @@ tcClassSigs clas sigs def_methods tcClassDecl2 :: LTyClDecl Name -- The class declaration -> TcM (LHsBinds Id) -tcClassDecl2 (L loc (ClassDecl {tcdLName = class_name, tcdSigs = sigs, +tcClassDecl2 (L _ (ClassDecl {tcdLName = class_name, tcdSigs = sigs, tcdMeths = default_binds})) = recoverM (return emptyLHsBinds) $ - setSrcSpan loc $ + setSrcSpan (getLoc class_name) $ do { clas <- tcLookupLocatedClass class_name -- We make a separate binding for each default method. @@ -203,7 +203,7 @@ tcDefMeth clas tyvars this_dict binds_in hs_sig_fn prag_fn = do { -- First look up the default method -- It should be there! global_dm_id <- tcLookupId dm_name ; global_dm_id <- addInlinePrags global_dm_id prags - ; local_dm_name <- setSrcSpan bndr_loc (newLocalName sel_name) + ; local_dm_name <- newNameAt (getOccName sel_name) bndr_loc -- Base the local_dm_name on the selector name, because -- type errors from tcInstanceMethodBody come from here @@ -241,26 +241,27 @@ tcDefMeth clas tyvars this_dict binds_in hs_sig_fn prag_fn ctxt = FunSigCtxt sel_name warn_redundant - ; local_dm_sig <- instTcTySig ctxt hs_ty local_dm_ty local_dm_name - ; (ev_binds, (tc_bind, _)) + ; let local_dm_id = mkLocalId local_dm_name local_dm_ty + local_dm_sig = CompleteSig { sig_bndr = local_dm_id + , sig_ctxt = ctxt + , sig_loc = getLoc (hsSigType hs_ty) } + + ; (ev_binds, (tc_bind, _)) <- checkConstraints (ClsSkol clas) tyvars [this_dict] $ - tcPolyCheck NonRecursive no_prag_fn local_dm_sig + tcPolyCheck no_prag_fn local_dm_sig (L bind_loc lm_bind) - ; let export = ABE { abe_poly = global_dm_id - -- We have created a complete type signature in - -- instTcTySig, hence it is safe to call - -- completeSigPolyId - , abe_mono = completeIdSigPolyId local_dm_sig - , abe_wrap = idHsWrapper - , abe_prags = IsDefaultMethod } - full_bind = AbsBinds { abs_tvs = tyvars - , abs_ev_vars = [this_dict] - , abs_exports = [export] - , abs_ev_binds = [ev_binds] - , abs_binds = tc_bind } - - ; return (unitBag (L bind_loc full_bind)) } + ; let export = ABE { abe_poly = global_dm_id + , abe_mono = local_dm_id + , abe_wrap = idHsWrapper + , abe_prags = IsDefaultMethod } + full_bind = AbsBinds { abs_tvs = tyvars + , abs_ev_vars = [this_dict] + , abs_exports = [export] + , abs_ev_binds = [ev_binds] + , abs_binds = tc_bind } + + ; return (unitBag (L bind_loc full_bind)) } | otherwise = pprPanic "tcDefMeth" (ppr sel_id) where diff --git a/compiler/typecheck/TcEnv.hs b/compiler/typecheck/TcEnv.hs index 525e834393..be301f3ba1 100644 --- a/compiler/typecheck/TcEnv.hs +++ b/compiler/typecheck/TcEnv.hs @@ -60,7 +60,7 @@ module TcEnv( topIdLvl, isBrackStage, -- New Ids - newLocalName, newDFunName, newDFunName', newFamInstTyConName, + newDFunName, newDFunName', newFamInstTyConName, newFamInstAxiomName, mkStableIdFromString, mkStableIdFromName, mkWrapperName diff --git a/compiler/typecheck/TcErrors.hs b/compiler/typecheck/TcErrors.hs index e7fb82757b..d5b003b3c5 100644 --- a/compiler/typecheck/TcErrors.hs +++ b/compiler/typecheck/TcErrors.hs @@ -1545,7 +1545,7 @@ suggestAddSig ctxt ty1 ty2 inferred_bndrs = nub (get_inf ty1 ++ get_inf ty2) get_inf ty | Just tv <- tcGetTyVar_maybe ty , isSkolemTyVar tv - , (_, InferSkol prs) <- getSkolemInfo (cec_encl ctxt) tv + , InferSkol prs <- ic_info (getSkolemInfo (cec_encl ctxt) tv) = map fst prs | otherwise = [] @@ -2477,17 +2477,18 @@ mkAmbigMsg prepend_msg ct pprSkol :: [Implication] -> TcTyVar -> SDoc pprSkol implics tv - | (skol_tvs, skol_info) <- getSkolemInfo implics tv = case skol_info of - UnkSkol -> pp_tv <+> text "is an unknown type variable" + UnkSkol -> quotes (ppr tv) <+> text "is an unknown type variable" SigSkol ctxt ty -> ppr_rigid (pprSigSkolInfo ctxt (mkSpecForAllTys skol_tvs ty)) _ -> ppr_rigid (pprSkolInfo skol_info) where - pp_tv = quotes (ppr tv) - ppr_rigid pp_info = hang (pp_tv <+> text "is a rigid type variable bound by") - 2 (sep [ pp_info - , text "at" <+> ppr (getSrcLoc tv) ]) + Implic { ic_skols = skol_tvs, ic_info = skol_info } + = getSkolemInfo implics tv + ppr_rigid pp_info + = hang (quotes (ppr tv) <+> text "is a rigid type variable bound by") + 2 (sep [ pp_info + , text "at" <+> ppr (getSrcSpan tv) ]) getAmbigTkvs :: Ct -> ([Var],[Var]) getAmbigTkvs ct @@ -2497,15 +2498,14 @@ getAmbigTkvs ct ambig_tkvs = filter isAmbiguousTyVar tkvs dep_tkv_set = tyCoVarsOfTypes (map tyVarKind tkvs) -getSkolemInfo :: [Implication] -> TcTyVar -> ([TcTyVar], SkolemInfo) +getSkolemInfo :: [Implication] -> TcTyVar -> Implication -- Get the skolem info for a type variable -- from the implication constraint that binds it getSkolemInfo [] tv = pprPanic "No skolem info:" (ppr tv) getSkolemInfo (implic:implics) tv - | let skols = ic_skols implic - , tv `elem` ic_skols implic = (skols, ic_info implic) + | tv `elem` ic_skols implic = implic | otherwise = getSkolemInfo implics tv ----------------------- diff --git a/compiler/typecheck/TcExpr.hs b/compiler/typecheck/TcExpr.hs index f078ba4da8..816fd9b031 100644 --- a/compiler/typecheck/TcExpr.hs +++ b/compiler/typecheck/TcExpr.hs @@ -27,8 +27,8 @@ import TcRnMonad import TcUnify import BasicTypes import Inst -import TcBinds ( chooseInferredQuantifiers, tcLocalBinds - , tcUserTypeSig, tcExtendTyVarEnvFromSig ) +import TcBinds ( chooseInferredQuantifiers, tcLocalBinds ) +import TcSigs ( tcUserTypeSig, tcInstSig ) import TcSimplify ( simplifyInfer ) import FamInst ( tcGetFamInstEnvs, tcLookupDataFamInst ) import FamInstEnv ( FamInstEnvs ) @@ -256,8 +256,9 @@ tcExpr e@(HsLamCase matches) res_ty match_ctxt = MC { mc_what = CaseAlt, mc_body = tcBody } tcExpr e@(ExprWithTySig expr sig_ty) res_ty - = do { sig_info <- checkNoErrs $ -- Avoid error cascade - tcUserTypeSig sig_ty Nothing + = do { let loc = getLoc (hsSigWcType sig_ty) + ; sig_info <- checkNoErrs $ -- Avoid error cascade + tcUserTypeSig loc sig_ty Nothing ; (expr', poly_ty) <- tcExprSig expr sig_info ; let expr'' = ExprWithTySigOut expr' sig_ty ; tcWrapResult e expr'' poly_ty res_ty } @@ -880,12 +881,13 @@ tcExpr expr@(RecordUpd { rupd_expr = record_expr, rupd_flds = rbnds }) res_ty ; (result_subst, con1_tvs') <- newMetaTyVars con1_tvs ; let result_inst_tys = mkTyVarTys con1_tvs' + init_subst = mkEmptyTCvSubst (getTCvInScope result_subst) - ; (scrut_subst, scrut_inst_tys) <- mapAccumLM mk_inst_ty emptyTCvSubst + ; (scrut_subst, scrut_inst_tys) <- mapAccumLM mk_inst_ty init_subst (con1_tvs `zip` result_inst_tys) ; let rec_res_ty = TcType.substTy result_subst con1_res_ty - scrut_ty = TcType.substTyUnchecked scrut_subst con1_res_ty + scrut_ty = TcType.substTy scrut_subst con1_res_ty con1_arg_tys' = map (TcType.substTy result_subst) con1_arg_tys ; wrap_res <- tcSubTypeHR (exprCtOrigin expr) @@ -1443,20 +1445,14 @@ in the other order, the extra signature in f2 is reqd. ********************************************************************* -} tcExprSig :: LHsExpr Name -> TcIdSigInfo -> TcM (LHsExpr TcId, TcType) -tcExprSig expr sig@(TISI { sig_bndr = s_bndr - , sig_skols = skol_prs - , sig_theta = theta - , sig_tau = tau }) - | null skol_prs -- Fast path when there is no quantification at all - , null theta - , CompleteSig {} <- s_bndr - = do { expr' <- tcPolyExprNC expr tau - ; return (expr', tau) } - - | CompleteSig poly_id <- s_bndr - = do { given <- newEvVars theta +tcExprSig expr (CompleteSig { sig_bndr = poly_id, sig_loc = loc }) + = setSrcSpan loc $ -- Sets the location for the implication constraint + do { (tv_prs, theta, tau) <- tcInstType (tcInstSigTyVars loc) poly_id + ; given <- newEvVars theta + ; let skol_info = SigSkol ExprSigCtxt (mkPhiTy theta tau) + skol_tvs = map snd tv_prs ; (ev_binds, expr') <- checkConstraints skol_info skol_tvs given $ - tcExtendTyVarEnvFromSig sig $ + tcExtendTyVarEnv2 tv_prs $ tcPolyExprNC expr tau ; let poly_wrap = mkWpTyLams skol_tvs @@ -1464,20 +1460,26 @@ tcExprSig expr sig@(TISI { sig_bndr = s_bndr <.> mkWpLet ev_binds ; return (mkLHsWrap poly_wrap expr', idType poly_id) } - | PartialSig { sig_name = name, sig_wcs = wc_prs, sig_hs_ty = hs_ty } <- s_bndr - = do { (tclvl, wanted, expr') +tcExprSig expr sig@(PartialSig { psig_name = name, sig_loc = loc }) + = setSrcSpan loc $ -- Sets the location for the implication constraint + do { (tclvl, wanted, (expr', sig_inst)) <- pushLevelAndCaptureConstraints $ - tcExtendTyVarEnvFromSig sig $ - do { addErrCtxt (pprSigCtxt ExprSigCtxt (ppr hs_ty)) $ - emitWildCardHoleConstraints wc_prs - ; tcPolyExprNC expr tau } + do { sig_inst <- tcInstSig sig + ; expr' <- tcExtendTyVarEnv2 (sig_inst_skols sig_inst) $ + tcExtendTyVarEnv2 (sig_inst_wcs sig_inst) $ + tcPolyExprNC expr (sig_inst_tau sig_inst) + ; return (expr', sig_inst) } + -- See Note [Partial expression signatures] + ; let tau = sig_inst_tau sig_inst + mr = null (sig_inst_theta sig_inst) && + isNothing (sig_inst_wcx sig_inst) ; (qtvs, givens, ev_binds) - <- simplifyInfer tclvl False [sig] [(name, tau)] wanted + <- simplifyInfer tclvl mr [sig_inst] [(name, tau)] wanted ; tau <- zonkTcType tau ; let inferred_theta = map evVarPred givens tau_tvs = tyCoVarsOfType tau ; (binders, my_theta) <- chooseInferredQuantifiers inferred_theta - tau_tvs qtvs (Just sig) + tau_tvs qtvs (Just sig_inst) ; let inferred_sigma = mkInvSigmaTy qtvs inferred_theta tau my_sigma = mkForAllTys binders (mkPhiTy my_theta tau) ; wrap <- if inferred_sigma `eqType` my_sigma -- NB: eqType ignores vis. @@ -1494,10 +1496,34 @@ tcExprSig expr sig@(TISI { sig_bndr = s_bndr <.> mkWpLet ev_binds ; return (mkLHsWrap poly_wrap expr', my_sigma) } - | otherwise = panic "tcExprSig" -- Can't happen - where - skol_info = SigSkol ExprSigCtxt (mkPhiTy theta tau) - skol_tvs = map snd skol_prs + +{- Note [Partial expression signatures] +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +Partial type signatures on expressions are easy to get wrong. But +here is a guiding principile + e :: ty +should behave like + let x :: ty + x = e + in x + +So for partial signatures we apply the MR if no context is given. So + e :: IO _ apply the MR + e :: _ => IO _ do not apply the MR +just like in TcBinds.decideGeneralisationPlan + +This makes a difference (Trac #11670): + peek :: Ptr a -> IO CLong + peek ptr = peekElemOff undefined 0 :: _ +from (peekElemOff undefined 0) we get + type: IO w + constraints: Storable w + +We must NOT try to generalise over 'w' because the signature specifies +no constraints so we'll complain about not being able to solve +Storable w. Instead, don't generalise; then _ gets instantiated to +CLong, as it should. +-} {- ********************************************************************* * * diff --git a/compiler/typecheck/TcHsType.hs b/compiler/typecheck/TcHsType.hs index f09bde5443..5492a8acd5 100644 --- a/compiler/typecheck/TcHsType.hs +++ b/compiler/typecheck/TcHsType.hs @@ -11,7 +11,8 @@ module TcHsType ( -- Type signatures kcHsSigType, tcClassSigType, tcHsSigType, tcHsSigWcType, - funsSigCtxt, addSigCtxt, + tcHsPartialSigType, + funsSigCtxt, addSigCtxt, pprSigCtxt, tcHsClsInstType, tcHsDeriv, tcHsVectInst, @@ -151,11 +152,25 @@ funsSigCtxt (L _ name1 : _) = FunSigCtxt name1 False funsSigCtxt [] = panic "funSigCtxt" addSigCtxt :: UserTypeCtxt -> LHsType Name -> TcM a -> TcM a -addSigCtxt ctxt sig_ty thing_inside - = setSrcSpan (getLoc sig_ty) $ - addErrCtxt (pprSigCtxt ctxt (ppr sig_ty)) $ +addSigCtxt ctxt hs_ty thing_inside + = setSrcSpan (getLoc hs_ty) $ + addErrCtxt (pprSigCtxt ctxt hs_ty) $ thing_inside +pprSigCtxt :: UserTypeCtxt -> LHsType Name -> SDoc +-- (pprSigCtxt ctxt <extra> <type>) +-- prints In the type signature for 'f': +-- f :: <type> +-- The <extra> is either empty or "the ambiguity check for" +pprSigCtxt ctxt hs_ty + | Just n <- isSigMaybe ctxt + = hang (text "In the type signature:") + 2 (pprPrefixOcc n <+> dcolon <+> ppr hs_ty) + + | otherwise + = hang (text "In" <+> pprUserTypeCtxt ctxt <> colon) + 2 (ppr hs_ty) + tcHsSigWcType :: UserTypeCtxt -> LHsSigWcType Name -> TcM Type -- This one is used when we have a LHsSigWcType, but in -- a place where wildards aren't allowed. The renamer has @@ -262,10 +277,10 @@ tcHsVectInst ty -- | Type-check a visible type application tcHsTypeApp :: LHsWcType Name -> Kind -> TcM Type tcHsTypeApp wc_ty kind - | HsWC { hswc_wcs = sig_wcs, hswc_ctx = extra, hswc_body = hs_ty } <- wc_ty - = ASSERT( isNothing extra ) -- handled in RnTypes.rnExtraConstraintWildCard - tcWildCardBinders sig_wcs $ \ _ -> - do { ty <- tcCheckLHsType hs_ty kind + | HsWC { hswc_wcs = sig_wcs, hswc_body = hs_ty } <- wc_ty + = do { ty <- solveEqualities $ + tcWildCardBindersX newWildTyVar sig_wcs $ \ _ -> + tcCheckLHsType hs_ty kind ; ty <- zonkTcType ty ; checkValidType TypeAppCtxt ty ; return ty } @@ -274,11 +289,6 @@ tcHsTypeApp wc_ty kind -- without fuss. No errors, warnings, extensions, etc. {- - These functions are used during knot-tying in - type and class declarations, when we have to - separate kind-checking, desugaring, and validity checking - - ************************************************************************ * * The main kind checker: no validity checks here @@ -419,14 +429,15 @@ we have a bunch of repetitive code just so that we get warnings if we're missing any patterns. -} +------------------------------------------ -- | Check and desugar a type, returning the core type and its -- possibly-polymorphic kind. Much like 'tcInferRho' at the expression -- level. tc_infer_lhs_type :: TcTyMode -> LHsType Name -> TcM (TcType, TcKind) tc_infer_lhs_type mode (L span ty) = setSrcSpan span $ - do { traceTc "tc_infer_lhs_type:" (ppr ty) - ; tc_infer_hs_type mode ty } + do { (ty', kind) <- tc_infer_hs_type mode ty + ; return (ty', kind) } -- | Infer the kind of a type and desugar. This is the "up" type-checker, -- as described in Note [Bidirectional type checking] @@ -454,11 +465,12 @@ tc_infer_hs_type mode other_ty ; ty' <- tc_hs_type mode other_ty kv ; return (ty', kv) } +------------------------------------------ tc_lhs_type :: TcTyMode -> LHsType Name -> TcKind -> TcM TcType tc_lhs_type mode (L span ty) exp_kind = setSrcSpan span $ - do { traceTc "tc_lhs_type:" (ppr ty $$ ppr exp_kind) - ; tc_hs_type mode ty exp_kind } + do { ty' <- tc_hs_type mode ty exp_kind + ; return ty' } ------------------------------------------ tc_fun_type :: TcTyMode -> LHsType Name -> LHsType Name -> TcKind -> TcM TcType @@ -638,14 +650,21 @@ tc_hs_type mode ty@(HsKindSig {}) ek = tc_infer_hs_type_ek mode ty ek tc_hs_type mode ty@(HsCoreTy {}) ek = tc_infer_hs_type_ek mode ty ek tc_hs_type _ (HsWildCardTy wc) exp_kind - = do { let name = wildCardName wc - ; tv <- tcLookupTyVar name - ; checkExpectedKind (mkTyVarTy tv) (tyVarKind tv) exp_kind } + = do { wc_tv <- tcWildCardOcc wc exp_kind + ; return (mkTyVarTy wc_tv) } -- disposed of by renamer tc_hs_type _ ty@(HsAppsTy {}) _ = pprPanic "tc_hs_tyep HsAppsTy" (ppr ty) +tcWildCardOcc :: HsWildCardInfo Name -> Kind -> TcM TcTyVar +tcWildCardOcc wc_info exp_kind + = do { wc_tv <- tcLookupTyVar (wildCardName wc_info) + -- The wildcard's kind should be an un-filled-in meta tyvar + ; let Just wc_kind_var = tcGetTyVar_maybe (tyVarKind wc_tv) + ; writeMetaTyVar wc_kind_var exp_kind + ; return wc_tv } + --------------------------- -- | Call 'tc_infer_hs_type' and check its result against an expected kind. tc_infer_hs_type_ek :: TcTyMode -> HsType Name -> TcKind -> TcM TcType @@ -750,8 +769,10 @@ tc_infer_args :: Outputable fun -> Int -- ^ number to start arg counter at -> TcM (TCvSubst, [TyBinder], [TcType], [LHsType Name], Int) tc_infer_args mode orig_ty binders mb_kind_info orig_args n0 - = do { traceTc "tcInferApps" (ppr binders $$ ppr orig_args) - ; go emptyTCvSubst binders orig_args n0 [] } + = do { traceTc "tc_infer_args {" (ppr binders $$ ppr orig_args) + ; stuff <- go emptyTCvSubst binders orig_args n0 [] + ; traceTc "tc_infer_args }" (ppr stuff) + ; return stuff } where go subst binders [] n acc = return ( subst, binders, reverse acc, [], n ) @@ -762,12 +783,14 @@ tc_infer_args mode orig_ty binders mb_kind_info orig_args n0 go subst binders all_args n acc | (inv_binders, other_binders) <- span isInvisibleBinder binders , not (null inv_binders) - = do { (subst', args') <- tcInstBindersX subst mb_kind_info inv_binders + = do { traceTc "tc_infer_args 1" (ppr inv_binders) + ; (subst', args') <- tcInstBindersX subst mb_kind_info inv_binders ; go subst' other_binders all_args n (reverse args' ++ acc) } go subst (binder:binders) (arg:args) n acc = ASSERT( isVisibleBinder binder ) - do { arg' <- addErrCtxt (funAppCtxt orig_ty arg n) $ + do { traceTc "tc_infer_args 2" (ppr binder $$ ppr arg) + ; arg' <- addErrCtxt (funAppCtxt orig_ty arg n) $ tc_lhs_type mode arg (substTyUnchecked subst $ binderType binder) ; let subst' = case binderVar_maybe binder of Just tv -> extendTvSubst subst tv arg' @@ -777,8 +800,9 @@ tc_infer_args mode orig_ty binders mb_kind_info orig_args n0 go subst [] all_args n acc = return (subst, [], reverse acc, all_args, n) --- | Applies a type to a list of arguments. Always consumes all the --- arguments. +-- | Applies a type to a list of arguments. +-- Always consumes all the arguments. +-- Used for types only tcInferApps :: Outputable fun => TcTyMode -> fun -- ^ Function (for printing only) @@ -1179,18 +1203,20 @@ all get more permissive. tcWildCardBinders :: [Name] -> ([(Name, TcTyVar)] -> TcM a) -> TcM a --- Use the Unique form the specified Name; don't clone it. There is --- no need to clone, and not doing so avoids the need to return a list --- of pairs to bring into scope. -tcWildCardBinders wcs thing_inside - = do { wcs <- mapM new_wildcard wcs - ; tcExtendTyVarEnv2 wcs $ - thing_inside wcs } +tcWildCardBinders = tcWildCardBindersX new_tv where - new_wildcard :: Name -> TcM (Name, TcTyVar) - new_wildcard name = do { kind <- newMetaKindVar - ; tv <- newFlexiTyVar kind - ; return (name, tv) } + new_tv name = do { kind <- newMetaKindVar + ; newSkolemTyVar name kind } + +tcWildCardBindersX :: (Name -> TcM TcTyVar) + -> [Name] + -> ([(Name, TcTyVar)] -> TcM a) + -> TcM a +tcWildCardBindersX new_wc wc_names thing_inside + = do { wcs <- mapM new_wc wc_names + ; let wc_prs = wc_names `zip` wcs + ; tcExtendTyVarEnv2 wc_prs $ + thing_inside wc_prs } -- | Kind-check a 'LHsQTyVars'. If the decl under consideration has a complete, -- user-supplied kind signature (CUSK), generalise the result. @@ -1215,7 +1241,7 @@ kcHsTyVarBndrs name cusk open_fam all_kind_vars , hsq_dependent = dep_names }) thing_inside | cusk = do { kv_kinds <- mk_kv_kinds - ; let scoped_kvs = zipWith new_skolem_tv kv_ns kv_kinds + ; let scoped_kvs = zipWith mk_skolem_tv kv_ns kv_kinds ; tcExtendTyVarEnv2 (kv_ns `zip` scoped_kvs) $ do { (tvs, binders, res_kind, stuff) <- solveEqualities $ bind_telescope hs_tvs thing_inside @@ -1389,6 +1415,15 @@ tcExplicitTKBndrs :: [LHsTyVarBndr Name] -> TcM (a, TyVarSet) -- ^ returns augmented bound vars -- No cloning: returned TyVars have the same Name as the incoming LHsTyVarBndrs tcExplicitTKBndrs orig_hs_tvs thing_inside + = tcExplicitTKBndrsX newSkolemTyVar orig_hs_tvs thing_inside + +tcExplicitTKBndrsX :: (Name -> Kind -> TcM TyVar) + -> [LHsTyVarBndr Name] + -> ([TyVar] -> TcM (a, TyVarSet)) + -- ^ Thing inside returns the set of variables bound + -- in the scope. See Note [Scope-check inferred kinds] + -> TcM (a, TyVarSet) -- ^ returns augmented bound vars +tcExplicitTKBndrsX new_tv orig_hs_tvs thing_inside = go orig_hs_tvs $ \ tvs -> do { (result, bound_tvs) <- thing_inside tvs @@ -1406,12 +1441,13 @@ tcExplicitTKBndrs orig_hs_tvs thing_inside where go [] thing = thing [] go (L _ hs_tv : hs_tvs) thing - = do { tv <- tcHsTyVarBndr hs_tv + = do { tv <- tcHsTyVarBndr new_tv hs_tv ; tcExtendTyVarEnv [tv] $ go hs_tvs $ \ tvs -> thing (tv : tvs) } -tcHsTyVarBndr :: HsTyVarBndr Name -> TcM TcTyVar +tcHsTyVarBndr :: (Name -> Kind -> TcM TyVar) + -> HsTyVarBndr Name -> TcM TcTyVar -- Return a SkolemTv TcTyVar, initialised with a kind variable. -- Typically the Kind inside the HsTyVarBndr will be a tyvar -- with a mutable kind in it. @@ -1421,12 +1457,23 @@ tcHsTyVarBndr :: HsTyVarBndr Name -> TcM TcTyVar -- Returned TcTyVar has the same name; no cloning -- -- See also Note [Associated type tyvar names] in Class -tcHsTyVarBndr (UserTyVar (L _ name)) +-- +tcHsTyVarBndr new_tv (UserTyVar (L _ name)) = do { kind <- newMetaKindVar - ; return (mkTcTyVar name kind (SkolemTv False)) } -tcHsTyVarBndr (KindedTyVar (L _ name) kind) + ; new_tv name kind } + +tcHsTyVarBndr new_tv (KindedTyVar (L _ name) kind) = do { kind <- tcLHsKind kind - ; return (mkTcTyVar name kind (SkolemTv False)) } + ; new_tv name kind } + +newWildTyVar :: Name -> TcM TcTyVar +-- ^ New unification variable for a wildcard +newWildTyVar _name + = do { kind <- newMetaKindVar + ; uniq <- newUnique + ; details <- newMetaDetails TauTv + ; let name = mkSysTvName uniq (fsLit "w") + ; return (mkTcTyVar name kind details) } -- | Produce a tyvar of the given name (with the kind provided, or -- otherwise a meta-var kind). If @@ -1443,12 +1490,17 @@ tcHsTyVarName m_kind name discardResult $ unifyKind (Just (mkTyVarTy tv)) kind (tyVarKind tv) ; return (tv, True) } - _ -> do { kind <- maybe newMetaKindVar return m_kind - ; return (mkTcTyVar name kind vanillaSkolemTv, False) }} + _ -> do { kind <- case m_kind of + Just kind -> return kind + Nothing -> newMetaKindVar + ; return (mk_skolem_tv name kind, False) }} -- makes a new skolem tv -new_skolem_tv :: Name -> Kind -> TcTyVar -new_skolem_tv n k = mkTcTyVar n k vanillaSkolemTv +newSkolemTyVar :: Name -> Kind -> TcM TcTyVar +newSkolemTyVar name kind = return (mk_skolem_tv name kind) + +mk_skolem_tv :: Name -> Kind -> TcTyVar +mk_skolem_tv n k = mkTcTyVar n k vanillaSkolemTv ------------------ kindGeneralizeType :: Type -> TcM Type @@ -1669,50 +1721,93 @@ It isn't essential for correctness. ************************************************************************ * * - Scoped type variables + Partial signatures and pattern signatures * * ************************************************************************ -tcAddScopedTyVars is used for scoped type variables added by pattern -type signatures - e.g. \ ((x::a), (y::a)) -> x+y -They never have explicit kinds (because this is source-code only) -They are mutable (because they can get bound to a more specific type). - -Usually we kind-infer and expand type splices, and then -tupecheck/desugar the type. That doesn't work well for scoped type -variables, because they scope left-right in patterns. (e.g. in the -example above, the 'a' in (y::a) is bound by the 'a' in (x::a). - -The current not-very-good plan is to - * find all the types in the patterns - * find their free tyvars - * do kind inference - * bring the kinded type vars into scope - * BUT throw away the kind-checked type - (we'll kind-check it again when we type-check the pattern) - -This is bad because throwing away the kind checked type throws away -its splices. But too bad for now. [July 03] - -Historical note: - We no longer specify that these type variables must be universally - quantified (lots of email on the subject). If you want to put that - back in, you need to - a) Do a checkSigTyVars after thing_inside - b) More insidiously, don't pass in expected_ty, else - we unify with it too early and checkSigTyVars barfs - Instead you have to pass in a fresh ty var, and unify - it with expected_ty afterwards +Note [Solving equalities in partial type signatures] +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +We treat a partial type signature as a "shape constraint" to impose on +the term: + * We make no attempt to kind-generalise it + * We instantiate the explicit and implicit foralls with SigTvs + * We instantiate the wildcards with meta tyvars + +We /do/ call solveEqualities, and then zonk to propage the result of +solveEqualities, mainly so that functions like matchExpectedFunTys will +be able to decompose the type, and hence higher-rank signatures will +work. Ugh! For example + f :: (forall a. a->a) -> _ + f x = (x True, x 'c') + -} +tcHsPartialSigType + :: UserTypeCtxt + -> LHsSigWcType Name -- The type signature + -> TcM ( [(Name, TcTyVar)] -- Wildcards + , Maybe TcTyVar -- Extra-constraints wildcard + , [TcTyVar] -- Implicitly and explicitly bound type varialbes + , TcThetaType -- Theta part + , TcType ) -- Tau part +tcHsPartialSigType ctxt sig_ty + | HsWC { hswc_wcs = sig_wcs, hswc_body = ib_ty } <- sig_ty + , HsIB { hsib_vars = implicit_hs_tvs, hsib_body = hs_ty } <- ib_ty + , (explicit_hs_tvs, L _ hs_ctxt, hs_tau) <- splitLHsSigmaTy hs_ty + = addSigCtxt ctxt hs_ty $ + do { (implicit_tvs, (wcs, wcx, explicit_tvs, theta, tau)) + <- -- See Note [Solving equalities in partial type signatures] + solveEqualities $ + tcWildCardBindersX newWildTyVar sig_wcs $ \ wcs -> + tcImplicitTKBndrsX new_implicit_tv implicit_hs_tvs $ + tcExplicitTKBndrsX newSigTyVar explicit_hs_tvs $ \ explicit_tvs -> + do { -- Instantiate the type-class context; but if there + -- is an extra-constraints wildcard, just discard it here + (theta, wcx) <- tcPartialContext hs_ctxt + + ; tau <- tcHsOpenType hs_tau + + ; let bound_tvs = unionVarSets [ allBoundVariables tau + , mkVarSet explicit_tvs + , mkVarSet (map snd wcs) ] + + ; return ( (wcs, wcx, explicit_tvs, theta, tau) + , bound_tvs) } + + ; emitWildCardHoleConstraints wcs + + -- See Note [Solving equalities in partial type signatures] + ; all_tvs <- mapM (updateTyVarKindM zonkTcType) + (implicit_tvs ++ explicit_tvs) + ; theta <- mapM zonkTcType theta + ; tau <- zonkTcType tau + ; checkValidType ctxt (mkSpecForAllTys all_tvs $ mkPhiTy theta tau) + + ; traceTc "tcHsPatSigType" (ppr all_tvs) + ; return (wcs, wcx, all_tvs, theta, tau) } + where + new_implicit_tv name = do { kind <- newMetaKindVar + ; tv <- newSigTyVar name kind + ; return (tv, False) } + +tcPartialContext :: HsContext Name -> TcM (TcThetaType, Maybe TcTyVar) +tcPartialContext hs_theta + | Just (hs_theta1, hs_ctxt_last) <- snocView hs_theta + , L _ (HsWildCardTy wc) <- ignoreParens hs_ctxt_last + = do { wc_tv <- tcWildCardOcc wc constraintKind + ; theta <- mapM tcLHsPredType hs_theta1 + ; return (theta, Just wc_tv) } + | otherwise + = do { theta <- mapM tcLHsPredType hs_theta + ; return (theta, Nothing) } + tcHsPatSigType :: UserTypeCtxt -> LHsSigWcType Name -- The type signature - -> TcM ( Type -- The signature + -> TcM ( [(Name, TcTyVar)] -- Wildcards , [TcTyVar] -- The new bit of type environment, binding -- the scoped type variables - , [(Name, TcTyVar)] ) -- The wildcards + , TcType) -- The type -- Used for type-checking type signatures in -- (a) patterns e.g f (x::Int) = e -- (b) RULE forall bndrs e.g. forall (x::Int). f x = x @@ -1720,28 +1815,35 @@ tcHsPatSigType :: UserTypeCtxt -- This may emit constraints tcHsPatSigType ctxt sig_ty - | HsIB { hsib_vars = sig_vars, hsib_body = wc_ty } <- sig_ty - , HsWC { hswc_wcs = sig_wcs, hswc_ctx = extra, hswc_body = hs_ty } <- wc_ty - = ASSERT( isNothing extra ) -- No extra-constraint wildcard in pattern sigs - addSigCtxt ctxt hs_ty $ - tcWildCardBinders sig_wcs $ \ wcs -> - do { emitWildCardHoleConstraints wcs - ; (vars, sig_ty) <- tcImplicitTKBndrsX new_tkv sig_vars $ - do { ty <- tcHsLiftedType hs_ty - ; return (ty, allBoundVariables ty) } + | HsWC { hswc_wcs = sig_wcs, hswc_body = ib_ty } <- sig_ty + , HsIB { hsib_vars = sig_vars, hsib_body = hs_ty } <- ib_ty + = addSigCtxt ctxt hs_ty $ + do { (implicit_tvs, (wcs, sig_ty)) + <- -- See Note [Solving equalities in partial type signatures] + solveEqualities $ + tcWildCardBindersX newWildTyVar sig_wcs $ \ wcs -> + tcImplicitTKBndrsX new_implicit_tv sig_vars $ + do { sig_ty <- tcHsOpenType hs_ty + ; return ((wcs, sig_ty), allBoundVariables sig_ty) } + + ; emitWildCardHoleConstraints wcs + ; sig_ty <- zonkTcType sig_ty - -- don't use zonkTcTypeToType; it mistreats wildcards ; checkValidType ctxt sig_ty + ; traceTc "tcHsPatSigType" (ppr sig_vars) - ; return (sig_ty, vars, wcs) } + ; return (wcs, implicit_tvs, sig_ty) } where - new_tkv name -- See Note [Pattern signature binders] - = (, False) <$> -- "False" means that these tyvars aren't yet in scope - do { kind <- newMetaKindVar - ; case ctxt of - RuleSigCtxt {} -> return $ new_skolem_tv name kind - _ -> newSigTyVar name kind } - -- See Note [Unifying SigTvs] + new_implicit_tv name = do { kind <- newMetaKindVar + ; tv <- new_tv name kind + ; return (tv, False) } + -- "False" means that these tyvars aren't yet in scope + new_tv = case ctxt of + RuleSigCtxt {} -> newSkolemTyVar + _ -> newSigTyVar + -- See Note [Pattern signature binders] + -- See Note [Unifying SigTvs] + tcPatSig :: Bool -- True <=> pattern binding -> LHsSigWcType Name @@ -1749,11 +1851,11 @@ tcPatSig :: Bool -- True <=> pattern binding -> TcM (TcType, -- The type to use for "inside" the signature [TcTyVar], -- The new bit of type environment, binding -- the scoped type variables - [(Name, TcTyVar)], -- The wildcards + [(Name,TcTyVar)], -- The wildcards HsWrapper) -- Coercion due to unification with actual ty -- Of shape: res_ty ~ sig_ty tcPatSig in_pat_bind sig res_ty - = do { (sig_ty, sig_tvs, sig_wcs) <- tcHsPatSigType PatSigCtxt sig + = do { (sig_wcs, sig_tvs, sig_ty) <- tcHsPatSigType PatSigCtxt sig -- sig_tvs are the type variables free in 'sig', -- and not already in scope. These are the ones -- that should be brought into scope diff --git a/compiler/typecheck/TcInstDcls.hs b/compiler/typecheck/TcInstDcls.hs index ffe2d2dd01..d078e2dac5 100644 --- a/compiler/typecheck/TcInstDcls.hs +++ b/compiler/typecheck/TcInstDcls.hs @@ -18,7 +18,7 @@ import TcTyClsDecls import TcClassDcl( tcClassDecl2, tcATDefault, HsSigFun, lookupHsSig, mkHsSigFun, findMethodBind, instantiateMethod ) -import TcPat ( addInlinePrags, lookupPragEnv, emptyPragEnv ) +import TcSigs import TcRnMonad import TcValidity import TcHsSyn ( zonkTcTypeToTypes, emptyZonkEnv ) @@ -761,7 +761,7 @@ tcInstDecl2 (InstInfo { iSpec = ispec, iBinds = ibinds }) setSrcSpan loc $ addErrCtxt (instDeclCtxt2 (idType dfun_id)) $ do { -- Instantiate the instance decl with skolem constants - ; (inst_tyvars, dfun_theta, inst_head) <- tcSkolDFunType (idType dfun_id) + ; (inst_tyvars, dfun_theta, inst_head) <- tcSkolDFunType dfun_id ; dfun_ev_vars <- newEvVars dfun_theta -- We instantiate the dfun_id with superSkolems. -- See Note [Subtle interaction of recursion and overlap] @@ -1349,7 +1349,7 @@ tcMethodBody clas tyvars dfun_ev_vars inst_tys sig_fn (spec_inst_prags, prag_fn) sel_id (L bind_loc meth_bind) bndr_loc = add_meth_ctxt $ - do { traceTc "tcMethodBody" (ppr sel_id <+> ppr (idType sel_id)) + do { traceTc "tcMethodBody" (ppr sel_id <+> ppr (idType sel_id) $$ ppr bndr_loc) ; (global_meth_id, local_meth_id) <- setSrcSpan bndr_loc $ mkMethIds clas tyvars dfun_ev_vars inst_tys sel_id @@ -1396,7 +1396,8 @@ tcMethodBodyHelp sig_fn sel_id local_meth_id meth_bind | Just hs_sig_ty <- lookupHsSig sig_fn sel_name -- There is a signature in the instance -- See Note [Instance method signatures] - = do { (sig_ty, hs_wrap) + = do { let ctxt = FunSigCtxt sel_name True + ; (sig_ty, hs_wrap) <- setSrcSpan (getLoc (hsSigType hs_sig_ty)) $ do { inst_sigs <- xoptM LangExt.InstanceSigs ; checkTc inst_sigs (misplacedInstSig sel_name hs_sig_ty) @@ -1408,8 +1409,13 @@ tcMethodBodyHelp sig_fn sel_id local_meth_id meth_bind ; return (sig_ty, hs_wrap) } ; inner_meth_name <- newName (nameOccName sel_name) - ; tc_sig <- instTcTySig ctxt hs_sig_ty sig_ty inner_meth_name - ; (tc_bind, [inner_id]) <- tcPolyCheck NonRecursive no_prag_fn tc_sig meth_bind + ; let inner_meth_id = mkLocalId inner_meth_name sig_ty + inner_meth_sig = CompleteSig { sig_bndr = inner_meth_id + , sig_ctxt = ctxt + , sig_loc = getLoc (hsSigType hs_sig_ty) } + + + ; (tc_bind, [inner_id]) <- tcPolyCheck no_prag_fn inner_meth_sig meth_bind ; let export = ABE { abe_poly = local_meth_id , abe_mono = inner_id @@ -1422,7 +1428,10 @@ tcMethodBodyHelp sig_fn sel_id local_meth_id meth_bind , abs_binds = tc_bind, abs_ev_binds = [] }) } | otherwise -- No instance signature - = do { tc_sig <- instTcTySigFromId local_meth_id + = do { let ctxt = FunSigCtxt sel_name False + -- False <=> don't report redundant constraints + -- The signature is not under the users control! + tc_sig = completeSigFromId ctxt local_meth_id -- Absent a type sig, there are no new scoped type variables here -- Only the ones from the instance decl itself, which are already -- in scope. Example: @@ -1430,11 +1439,10 @@ tcMethodBodyHelp sig_fn sel_id local_meth_id meth_bind -- instance C [c] where { op = <rhs> } -- In <rhs>, 'c' is scope but 'b' is not! - ; (tc_bind, _) <- tcPolyCheck NonRecursive no_prag_fn tc_sig meth_bind + ; (tc_bind, _) <- tcPolyCheck no_prag_fn tc_sig meth_bind ; return tc_bind } where - ctxt = FunSigCtxt sel_name True sel_name = idName sel_id no_prag_fn = emptyPragEnv -- No pragmas for local_meth_id; -- they are all for meth_id diff --git a/compiler/typecheck/TcMType.hs b/compiler/typecheck/TcMType.hs index ae5e031f31..8f64594401 100644 --- a/compiler/typecheck/TcMType.hs +++ b/compiler/typecheck/TcMType.hs @@ -51,12 +51,12 @@ module TcMType ( -------------------------------- -- Instantiation - newMetaTyVars, newMetaTyVarX, newMetaSigTyVars, - newSigTyVar, + newMetaTyVars, newMetaTyVarX, + newMetaSigTyVars, newMetaSigTyVarX, + newSigTyVar, newWildCardX, tcInstType, - tcInstSkolTyVars, tcInstSkolTyVarsLoc, tcInstSuperSkolTyVarsX, - tcInstSigTyVarsLoc, tcInstSigTyVars, - tcInstSkolType, + tcInstSkolTyVars, tcInstSuperSkolTyVarsX, + tcInstSigTyVars, tcSkolDFunType, tcSuperSkolTyVars, instSkolTyCoVars, freshenTyVarBndrs, freshenCoVarBndrsX, @@ -433,11 +433,11 @@ inferTypeToType u tc_lvl ki ref tcInstType :: ([TyVar] -> TcM (TCvSubst, [TcTyVar])) -- ^ How to instantiate the type variables - -> TcType -- ^ Type to instantiate - -> TcM ([TcTyVar], TcThetaType, TcType) -- ^ Result + -> Id -- ^ Type to instantiate + -> TcM ([(Name, TcTyVar)], TcThetaType, TcType) -- ^ Result -- (type vars, preds (incl equalities), rho) -tcInstType inst_tyvars ty - = case tcSplitForAllTys ty of +tcInstType inst_tyvars id + = case tcSplitForAllTys (idType id) of ([], rho) -> let -- There may be overloading despite no type variables; -- (?x :: Int) => Int -> Int (theta, tau) = tcSplitPhiTy rho @@ -446,12 +446,15 @@ tcInstType inst_tyvars ty (tyvars, rho) -> do { (subst, tyvars') <- inst_tyvars tyvars ; let (theta, tau) = tcSplitPhiTy (substTyAddInScope subst rho) - ; return (tyvars', theta, tau) } + tv_prs = map tyVarName tyvars `zip` tyvars' + ; return (tv_prs, theta, tau) } -tcSkolDFunType :: Type -> TcM ([TcTyVar], TcThetaType, TcType) +tcSkolDFunType :: DFunId -> TcM ([TcTyVar], TcThetaType, TcType) -- Instantiate a type signature with skolem constants. -- We could give them fresh names, but no need to do so -tcSkolDFunType ty = tcInstType tcInstSuperSkolTyVars ty +tcSkolDFunType dfun + = do { (tv_prs, theta, tau) <- tcInstType tcInstSuperSkolTyVars dfun + ; return (map snd tv_prs, theta, tau) } tcSuperSkolTyVars :: [TyVar] -> (TCvSubst, [TcTyVar]) -- Make skolem constants, but do *not* give them new names, as above @@ -467,11 +470,6 @@ tcSuperSkolTyVar subst tv kind = substTyUnchecked subst (tyVarKind tv) new_tv = mkTcTyVar (tyVarName tv) kind superSkolemTv --- Wrappers --- we need to be able to do this from outside the TcM monad: -tcInstSkolTyVarsLoc :: SrcSpan -> [TyVar] -> TcRnIf gbl lcl (TCvSubst, [TcTyVar]) -tcInstSkolTyVarsLoc loc = instSkolTyCoVars (mkTcSkolTyVar loc False) - -- | Given a list of @['TyVar']@, skolemize the type variables, -- returning a substitution mapping the original tyvars to the -- skolems, and the list of newly bound skolems. See also @@ -501,23 +499,9 @@ mkTcSkolTyVar loc overlappable uniq old_name kind kind (SkolemTv overlappable) -tcInstSigTyVarsLoc :: SrcSpan -> [TyVar] - -> TcRnIf gbl lcl (TCvSubst, [TcTyVar]) --- We specify the location -tcInstSigTyVarsLoc loc = instSkolTyCoVars (mkTcSkolTyVar loc False) - -tcInstSigTyVars :: [TyVar] -> TcRnIf gbl lcl (TCvSubst, [TcTyVar]) --- Get the location from the TyVar itself, not the monad -tcInstSigTyVars - = instSkolTyCoVars mk_tv - where - mk_tv uniq old_name kind - = mkTcTyVar (setNameUnique old_name uniq) kind (SkolemTv False) - -tcInstSkolType :: TcType -> TcM ([TcTyVar], TcThetaType, TcType) --- Instantiate a type with fresh skolem constants --- Binding location comes from the monad -tcInstSkolType ty = tcInstType tcInstSkolTyVars ty +tcInstSigTyVars :: SrcSpan -> [TyVar] + -> TcRnIf gbl lcl (TCvSubst, [TcTyVar]) +tcInstSigTyVars loc = instSkolTyCoVars (mkTcSkolTyVar loc False) ------------------ freshenTyVarBndrs :: [TyVar] -> TcRnIf gbl lcl (TCvSubst, [TyVar]) @@ -793,13 +777,18 @@ newMetaSigTyVarX :: TCvSubst -> TyVar -> TcM (TCvSubst, TcTyVar) -- Just like newMetaTyVarX, but make a SigTv newMetaSigTyVarX subst tyvar = new_meta_tv_x SigTv subst tyvar +newWildCardX :: TCvSubst -> TyVar -> TcM (TCvSubst, TcTyVar) +newWildCardX subst tv + = do { new_tv <- newAnonMetaTyVar TauTv (substTy subst (tyVarKind tv)) + ; return (extendTvSubstWithClone subst tv new_tv, new_tv) } + new_meta_tv_x :: MetaInfo -> TCvSubst -> TyVar -> TcM (TCvSubst, TcTyVar) new_meta_tv_x info subst tyvar = do { uniq <- newUnique ; details <- newMetaDetails info ; let name = mkSystemName uniq (getOccName tyvar) -- See Note [Name of an instantiated type variable] - kind = substTyUnchecked subst (tyVarKind tyvar) + kind = substTy subst (tyVarKind tyvar) new_tv = mkTcTyVar name kind details subst1 = extendTvSubstWithClone subst tyvar new_tv ; return (subst1, new_tv) } diff --git a/compiler/typecheck/TcPat.hs b/compiler/typecheck/TcPat.hs index 35624e7d32..7a210f210d 100644 --- a/compiler/typecheck/TcPat.hs +++ b/compiler/typecheck/TcPat.hs @@ -10,9 +10,7 @@ TcPat: Typechecking patterns {-# LANGUAGE FlexibleContexts #-} module TcPat ( tcLetPat - , TcPragEnv, lookupPragEnv, emptyPragEnv - , LetBndrSpec(..), addInlinePrags - , tcPat, tcPat_O, tcPats, newNoSigLetBndr + , tcPat, tcPat_O, tcPats , addDataConStupidTheta, badFieldCon, polyPatSig ) where #include "HsVersions.h" @@ -26,7 +24,6 @@ import Inst import Id import Var import Name -import NameEnv import RdrName import TcEnv import TcMType @@ -47,7 +44,6 @@ import SrcLoc import VarSet import Util import Outputable -import Maybes( orElse ) import qualified GHC.LanguageExtensions as LangExt import Control.Monad import Control.Arrow ( second ) @@ -60,15 +56,15 @@ import Control.Arrow ( second ) ************************************************************************ -} -tcLetPat :: TcSigFun -> LetBndrSpec +tcLetPat :: (Name -> Maybe TcId) -> LPat Name -> ExpSigmaType -> TcM a -> TcM (LPat TcId, a) -tcLetPat sig_fn no_gen pat pat_ty thing_inside +tcLetPat sig_fn pat pat_ty thing_inside = tc_lpat pat pat_ty penv thing_inside where penv = PE { pe_lazy = True - , pe_ctxt = LetPat sig_fn no_gen + , pe_ctxt = LetPat sig_fn , pe_orig = PatOrigin } ----------------- @@ -125,17 +121,7 @@ data PatCtxt | LetPat -- Used only for let(rec) pattern bindings -- See Note [Typing patterns in pattern bindings] - TcSigFun -- Tells type sig if any - LetBndrSpec -- True <=> no generalisation of this let - -data LetBndrSpec - = LetLclBndr -- The binder is just a local one; - -- an AbsBinds will provide the global version - - | LetGblBndr TcPragEnv -- Generalisation plan is NoGen, so there isn't going - -- to be an AbsBinds; So we must bind the global version - -- of the binder right away. - -- Oh, and here is the inline-pragma information + (Name -> Maybe TcId) -- Tells the expected type for this binder makeLazy :: PatEnv -> PatEnv makeLazy penv = penv { pe_lazy = True } @@ -144,15 +130,6 @@ inPatBind :: PatEnv -> Bool inPatBind (PE { pe_ctxt = LetPat {} }) = True inPatBind (PE { pe_ctxt = LamPat {} }) = False ---------------- -type TcPragEnv = NameEnv [LSig Name] - -emptyPragEnv :: TcPragEnv -emptyPragEnv = emptyNameEnv - -lookupPragEnv :: TcPragEnv -> Name -> [LSig Name] -lookupPragEnv prag_fn n = lookupNameEnv prag_fn n `orElse` [] - {- ********************************************************************* * * Binders @@ -163,83 +140,23 @@ tcPatBndr :: PatEnv -> Name -> ExpSigmaType -> TcM (HsWrapper, TcId) -- (coi, xp) = tcPatBndr penv x pat_ty -- Then coi : pat_ty ~ typeof(xp) -- -tcPatBndr (PE { pe_ctxt = LetPat lookup_sig no_gen +tcPatBndr (PE { pe_ctxt = LetPat lookup_sig , pe_orig = orig }) bndr_name pat_ty -- See Note [Typing patterns in pattern bindings] - | LetGblBndr prags <- no_gen - , Just (TcIdSig sig) <- mb_sig - , Just poly_id <- completeIdSigPolyId_maybe sig - = do { bndr_id <- addInlinePrags poly_id (lookupPragEnv prags bndr_name) - ; traceTc "tcPatBndr(gbl,sig)" (ppr bndr_id $$ ppr (idType bndr_id)) - ; co <- unifyPatType bndr_id (idType bndr_id) pat_ty - ; return (mkWpCastN co, bndr_id) } - - -- See Note [Partial signatures for pattern bindings] - | LetLclBndr <- no_gen - , Just (TcIdSig sig) <- mb_sig - = do { mono_name <- newLocalName bndr_name - ; (subst, _) <- newMetaSigTyVars (map snd (sig_skols sig)) - ; let tau = substTy subst (sig_tau sig) - mono_id = mkLocalId mono_name tau - ; wrap <- tcSubTypeET orig pat_ty tau - ; traceTc "tcPatBndr(lsl,sig)" (ppr mono_id $$ ppr tau $$ ppr pat_ty) - ; return (wrap, mono_id) } + | Just bndr_id <- lookup_sig bndr_name + = do { wrap <- tcSubTypeET orig pat_ty (idType bndr_id) + ; traceTc "tcPatBndr(lsl,sig)" (ppr bndr_id $$ ppr (idType bndr_id) $$ ppr pat_ty) + ; return (wrap, bndr_id) } - | otherwise - = do { pat_ty <- expTypeToType pat_ty - ; bndr_id <- newNoSigLetBndr no_gen bndr_name pat_ty - ; traceTc "tcPatBndr(no-sig)" (ppr bndr_id $$ ppr (idType bndr_id)) - ; return (idHsWrapper, bndr_id) } - where - mb_sig = lookup_sig bndr_name + | otherwise -- No signature + = pprPanic "tcPatBndr" (ppr bndr_name) tcPatBndr (PE { pe_ctxt = _lam_or_proc }) bndr_name pat_ty = do { pat_ty <- expTypeToType pat_ty + ; traceTc "tcPatBndr(not let)" (ppr bndr_name $$ ppr pat_ty) ; return (idHsWrapper, mkLocalId bndr_name pat_ty) } - -- whether or not there is a sig is irrelevant, as this - -- is local - ------------- -newNoSigLetBndr :: LetBndrSpec -> Name -> TcType -> TcM TcId --- In the polymorphic case (no_gen = LetLclBndr), generate a "monomorphic version" --- of the Id; the original name will be bound to the polymorphic version --- by the AbsBinds --- In the monomorphic case (no_gen = LetBglBndr) there is no AbsBinds, and we --- use the original name directly -newNoSigLetBndr LetLclBndr name ty - =do { mono_name <- newLocalName name - ; return (mkLocalId mono_name ty) } -newNoSigLetBndr (LetGblBndr prags) name ty - = addInlinePrags (mkLocalId name ty) (lookupPragEnv prags name) - ----------- -addInlinePrags :: TcId -> [LSig Name] -> TcM TcId -addInlinePrags poly_id prags - | inl@(L _ prag) : inls <- inl_prags - = do { traceTc "addInlinePrag" (ppr poly_id $$ ppr prag) - ; unless (null inls) (warn_multiple_inlines inl inls) - ; return (poly_id `setInlinePragma` prag) } - | otherwise - = return poly_id - where - inl_prags = [L loc prag | L loc (InlineSig _ prag) <- prags] - - warn_multiple_inlines _ [] = return () - - warn_multiple_inlines inl1@(L loc prag1) (inl2@(L _ prag2) : inls) - | inlinePragmaActivation prag1 == inlinePragmaActivation prag2 - , isEmptyInlineSpec (inlinePragmaSpec prag1) - = -- Tiresome: inl1 is put there by virtue of being in a hs-boot loop - -- and inl2 is a user NOINLINE pragma; we don't want to complain - warn_multiple_inlines inl2 inls - | otherwise - = setSrcSpan loc $ - addWarnTc NoReason - (hang (text "Multiple INLINE pragmas for" <+> ppr poly_id) - 2 (vcat (text "Ignoring all but the first" - : map pp_inl (inl1:inl2:inls)))) - - pp_inl (L loc prag) = ppr prag <+> parens (ppr loc) + -- Whether or not there is a sig is irrelevant, + -- as this is local {- Note [Partial signatures for pattern bindings] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -276,19 +193,6 @@ Extra notes Moreover, by feeding in the expected type we do less fruitless creation of unification variables, and improve error messages. -* We need to take care with the skolems. Consider - data T a = MkT a a - f :: forall a. a->a - g :: forall b. b->b - MkT f g = MkT (\x->x) (\y->y) - Here we'll infer a type from the pattern of 'T a', but if we feed in - the signature types for f and g, we'll end up unifying 'a' and 'b'. - So we instantiate the skolems with SigTvs; hence newMetaSigTyVars. - - All we are doing here is getting the "shapes" right. In tcExport - we'll check that the Id really does have the claimed type, with - the claimed polymorphism. - * We need to do a subsumption, not equality, check. If data T = MkT (forall a. a->a) f :: forall b. [b]->[b] @@ -302,7 +206,7 @@ Note [Typing patterns in pattern bindings] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Suppose we are typing a pattern binding pat = rhs -Then the PatCtxt will be (LetPat sig_fn let_bndr_spec). +Then the PatCtxt will be (LetPat sig_fn). There can still be signatures for the binders: data T = MkT (forall a. a->a) Int @@ -324,7 +228,7 @@ Two cases, dealt with by the LetPat case of tcPatBndr LetBndrSpec will be LetGblBndr. In that case we must bind the global version of the Id, and do so with precisely the type given in the signature. (Then we unify with the type from the pattern - context type. + context type.) ************************************************************************ @@ -426,8 +330,16 @@ tc_pat penv lpat@(LazyPat pat) pat_ty thing_inside -- see Note [Hopping the LIE in lazy patterns] -- Check there are no unlifted types under the lazy pattern - ; when (any (isUnliftedType . idType) $ collectPatBinders pat') $ - lazyUnliftedPatErr lpat + -- This is a very unsatisfactory test. We have to zonk becuase + -- the binder-tys are typically just a unification variable, + -- which should by now have been unified... but it might be + -- deferred for the constraint solver...Ugh! Also + -- collecting the pattern binders again is not very cool. + -- But it's all very much a corner case: a lazy pattern with + -- unboxed types inside it + ; bndr_tys <- mapM (zonkTcType . idType) (collectPatBinders pat') + ; when (any isUnliftedType bndr_tys) + (lazyUnliftedPatErr lpat) -- Check that the expected pattern type is itself lifted ; pat_ty <- readExpType pat_ty @@ -488,8 +400,8 @@ tc_pat penv (ViewPat expr pat _) overall_pat_ty thing_inside tc_pat penv (SigPatIn pat sig_ty) pat_ty thing_inside = do { (inner_ty, tv_binds, wcs, wrap) <- tcPatSig (inPatBind penv) sig_ty pat_ty - ; (pat', res) <- tcExtendTyVarEnv2 wcs $ - tcExtendTyVarEnv tv_binds $ + ; (pat', res) <- tcExtendTyVarEnv2 wcs $ + tcExtendTyVarEnv tv_binds $ tc_lpat pat (mkCheckExpType inner_ty) penv thing_inside ; pat_ty <- readExpType pat_ty ; return (mkHsWrapPat wrap (SigPatOut pat' inner_ty) pat_ty, res) } @@ -846,9 +758,10 @@ tcDataConPat penv (L con_span con_name) data_con pat_ty arg_pats thing_inside -- order is *important* as we generate the list of -- dictionary binders from theta' no_equalities = not (any isNomEqPred theta') - skol_info = case pe_ctxt penv of - LamPat mc -> PatSkol (RealDataCon data_con) mc - LetPat {} -> UnkSkol -- Doesn't matter + skol_info = PatSkol (RealDataCon data_con) mc + mc = case pe_ctxt penv of + LamPat mc -> mc + LetPat {} -> PatBindRhs ; gadts_on <- xoptM LangExt.GADTs ; families_on <- xoptM LangExt.TypeFamilies @@ -1184,6 +1097,16 @@ Meanwhile, the strategy is: \subsection{Errors and contexts} * * ************************************************************************ + +Note [Existential check] +~~~~~~~~~~~~~~~~~~~~~~~~ +Lazy patterns can't bind existentials. They arise in two ways: + * Let bindings let { C a b = e } in b + * Twiddle patterns f ~(C a b) = e +The pe_lazy field of PatEnv says whether we are inside a lazy +pattern (perhaps deeply) + +See also Note [Existentials in pattern bindings] in TcBinds -} maybeWrapPatCtxt :: Pat Name -> (TcM a -> TcM b) -> TcM a -> TcM b @@ -1203,10 +1126,11 @@ maybeWrapPatCtxt pat tcm thing_inside checkExistentials :: [TyVar] -- existentials -> [Type] -- argument types -> PatEnv -> TcM () - -- See Note [Arrows and patterns] + -- See Note [Existential check]] + -- See Note [Arrows and patterns] checkExistentials ex_tvs tys _ | all (not . (`elemVarSet` tyCoVarsOfTypes tys)) ex_tvs = return () -checkExistentials _ _ (PE { pe_ctxt = LetPat {}}) = failWithTc existentialLetPat +checkExistentials _ _ (PE { pe_ctxt = LetPat {}}) = return () checkExistentials _ _ (PE { pe_ctxt = LamPat ProcExpr }) = failWithTc existentialProcPat checkExistentials _ _ (PE { pe_lazy = True }) = failWithTc existentialLazyPat checkExistentials _ _ _ = return () @@ -1220,12 +1144,6 @@ existentialProcPat :: SDoc existentialProcPat = text "Proc patterns cannot use existential or GADT data constructors" -existentialLetPat :: SDoc -existentialLetPat - = vcat [text "My brain just exploded", - text "I can't handle pattern bindings for existential or GADT data constructors.", - text "Instead, use a case-expression, or do-notation, to unpack the constructor."] - badFieldCon :: ConLike -> FieldLabelString -> SDoc badFieldCon con field = hsep [text "Constructor" <+> quotes (ppr con), diff --git a/compiler/typecheck/TcPatSyn.hs b/compiler/typecheck/TcPatSyn.hs index c73da99dce..c5a0c270b4 100644 --- a/compiler/typecheck/TcPatSyn.hs +++ b/compiler/typecheck/TcPatSyn.hs @@ -8,17 +8,16 @@ {-# LANGUAGE CPP #-} {-# LANGUAGE FlexibleContexts #-} -module TcPatSyn ( tcPatSynSig, tcInferPatSynDecl, tcCheckPatSynDecl +module TcPatSyn ( tcInferPatSynDecl, tcCheckPatSynDecl , tcPatSynBuilderBind, tcPatSynBuilderOcc, nonBidirectionalErr ) where import HsSyn import TcPat -import TcHsType( tcImplicitTKBndrs, tcExplicitTKBndrs - , tcHsContext, tcHsOpenType, kindGeneralize ) -import Type( binderVar, mkNamedBinders, binderVisibility +import Type( binderVar, mkNamedBinders, binderVisibility, mkEmptyTCvSubst , tidyTyCoVarBndrs, tidyTypes, tidyType ) import TcRnMonad +import TcSigs( emptyPragEnv, completeSigFromId ) import TcEnv import TcMType import TysPrim @@ -31,7 +30,7 @@ import Panic import Outputable import FastString import Var -import VarEnv( emptyTidyEnv ) +import VarEnv( emptyTidyEnv, mkInScopeSet ) import Id import IdInfo( RecSelParent(..)) import TcBinds @@ -55,144 +54,6 @@ import Data.List( partition ) #include "HsVersions.h" -{- ********************************************************************* -* * - Type checking a pattern synonym signature -* * -************************************************************************ - -Note [Pattern synonym signatures] -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -Pattern synonym signatures are surprisingly tricky (see Trac #11224 for example). -In general they look like this: - - pattern P :: forall univ_tvs. req_theta - => forall ex_tvs. prov_theta - => arg1 -> .. -> argn -> res_ty - -For parsing and renaming we treat the signature as an ordinary LHsSigType. - -Once we get to type checking, we decompose it into its parts, in tcPatSynSig. - -* Note that 'forall univ_tvs' and 'req_theta =>' - and 'forall ex_tvs' and 'prov_theta =>' - are all optional. We gather the pieces at the the top of tcPatSynSig - -* Initially the implicitly-bound tyvars (added by the renamer) include both - universal and existential vars. - -* After we kind-check the pieces and convert to Types, we do kind generalisation. - -Note [The pattern-synonym signature splitting rule] -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -Given a pattern signature, we must split - the kind-generalised variables, and - the implicitly-bound variables -into universal and existential. The rule is this -(see discussion on Trac #11224): - - The universal tyvars are the ones mentioned in - - univ_tvs: the user-specified (forall'd) universals - - req_theta - - res_ty - The existential tyvars are all the rest - -For example - - pattern P :: () => b -> T a - pattern P x = ... - -Here 'a' is universal, and 'b' is existential. But there is a wrinkle: -how do we split the arg_tys from req_ty? Consider - - pattern Q :: () => b -> S c -> T a - pattern Q x = ... - -This is an odd example because Q has only one syntactic argument, and -so presumably is defined by a view pattern matching a function. But -it can happen (Trac #11977, #12108). - -We don't know Q's arity from the pattern signature, so we have to wait -until we see the pattern declaration itself before deciding res_ty is, -and hence which variables are existential and which are universal. - -And that in turn is why TcPatSynInfo has a separate field, -patsig_implicit_bndrs, to capture the implicitly bound type variables, -because we don't yet know how to split them up. - -It's a slight compromise, because it means we don't really know the -pattern synonym's real signature until we see its declaration. So, -for example, in hs-boot file, we may need to think what to do... -(eg don't have any implicitly-bound variables). --} - -tcPatSynSig :: Name -> LHsSigType Name -> TcM TcPatSynInfo -tcPatSynSig name sig_ty - | HsIB { hsib_vars = implicit_hs_tvs - , hsib_body = hs_ty } <- sig_ty - , (univ_hs_tvs, hs_req, hs_ty1) <- splitLHsSigmaTy hs_ty - , (ex_hs_tvs, hs_prov, hs_body_ty) <- splitLHsSigmaTy hs_ty1 - = do { (implicit_tvs, (univ_tvs, req, ex_tvs, prov, body_ty)) - <- solveEqualities $ - tcImplicitTKBndrs implicit_hs_tvs $ - tcExplicitTKBndrs univ_hs_tvs $ \ univ_tvs -> - tcExplicitTKBndrs ex_hs_tvs $ \ ex_tvs -> - do { req <- tcHsContext hs_req - ; prov <- tcHsContext hs_prov - ; body_ty <- tcHsOpenType hs_body_ty - -- A (literal) pattern can be unlifted; - -- e.g. pattern Zero <- 0# (Trac #12094) - ; let bound_tvs - = unionVarSets [ allBoundVariabless req - , allBoundVariabless prov - , allBoundVariables body_ty - ] - ; return ( (univ_tvs, req, ex_tvs, prov, body_ty) - , bound_tvs) } - - -- Kind generalisation - ; kvs <- kindGeneralize $ - mkSpecForAllTys (implicit_tvs ++ univ_tvs) $ - mkFunTys req $ - mkSpecForAllTys ex_tvs $ - mkFunTys prov $ - body_ty - - -- These are /signatures/ so we zonk to squeeze out any kind - -- unification variables. Do this after quantifyTyVars which may - -- default kind variables to *. - -- ToDo: checkValidType? - ; traceTc "about zonk" empty - ; implicit_tvs <- mapM zonkTcTyCoVarBndr implicit_tvs - ; univ_tvs <- mapM zonkTcTyCoVarBndr univ_tvs - ; ex_tvs <- mapM zonkTcTyCoVarBndr ex_tvs - ; req <- zonkTcTypes req - ; prov <- zonkTcTypes prov - ; body_ty <- zonkTcType body_ty - - ; traceTc "tcTySig }" $ - vcat [ text "implicit_tvs" <+> ppr_tvs implicit_tvs - , text "kvs" <+> ppr_tvs kvs - , text "univ_tvs" <+> ppr_tvs univ_tvs - , text "req" <+> ppr req - , text "ex_tvs" <+> ppr_tvs ex_tvs - , text "prov" <+> ppr prov - , text "body_ty" <+> ppr body_ty ] - ; return (TPSI { patsig_name = name - , patsig_implicit_bndrs = mkNamedBinders Invisible kvs ++ - mkNamedBinders Specified implicit_tvs - , patsig_univ_bndrs = univ_tvs - , patsig_req = req - , patsig_ex_bndrs = ex_tvs - , patsig_prov = prov - , patsig_body_ty = body_ty }) } - where - -ppr_tvs :: [TyVar] -> SDoc -ppr_tvs tvs = braces (vcat [ ppr tv <+> dcolon <+> ppr (tyVarKind tv) - | tv <- tvs]) - - {- ************************************************************************ * * @@ -288,14 +149,16 @@ tcCheckPatSynDecl psb@PSB{ psb_id = lname@(L _ name), psb_args = details pushLevelAndCaptureConstraints $ tcExtendTyVarEnv univ_tvs $ tcPat PatSyn lpat (mkCheckExpType pat_ty) $ - do { (subst, ex_tvs') <- if isUnidirectional dir - then newMetaTyVars ex_tvs - else newMetaSigTyVars ex_tvs + do { let new_tv | isUnidirectional dir = newMetaTyVarX + | otherwise = newMetaSigTyVarX + in_scope = mkInScopeSet (mkVarSet univ_tvs) + empty_subst = mkEmptyTCvSubst in_scope + ; (subst, ex_tvs') <- mapAccumLM new_tv empty_subst ex_tvs -- See the "Existential type variables" part of -- Note [Checking against a pattern signature] ; traceTc "tcpatsyn1" (vcat [ ppr v <+> dcolon <+> ppr (tyVarKind v) | v <- ex_tvs]) ; traceTc "tcpatsyn2" (vcat [ ppr v <+> dcolon <+> ppr (tyVarKind v) | v <- ex_tvs']) - ; let prov_theta' = substTheta (extendTCvInScopeList subst univ_tvs) prov_theta + ; let prov_theta' = substTheta subst prov_theta -- Add univ_tvs to the in_scope set to -- satisfy the substition invariant. There's no need to -- add 'ex_tvs' as they are already in the domain of the @@ -536,11 +399,9 @@ tcPatSynMatcher (L loc name) lpat (univ_tvs, req_theta, req_ev_binds, req_dicts) (ex_tvs, ex_tys, prov_theta, prov_dicts) (args, arg_tys) pat_ty - = do { rr_uniq <- newUnique - ; tv_uniq <- newUnique - ; let rr_name = mkInternalName rr_uniq (mkTyVarOcc "rep") loc - tv_name = mkInternalName tv_uniq (mkTyVarOcc "r") loc - rr_tv = mkTcTyVar rr_name runtimeRepTy (SkolemTv False) + = do { rr_name <- newNameAt (mkTyVarOcc "rep") loc + ; tv_name <- newNameAt (mkTyVarOcc "r") loc + ; let rr_tv = mkTcTyVar rr_name runtimeRepTy (SkolemTv False) rr = mkTyVarTy rr_tv res_tv = mkTcTyVar tv_name (tYPE rr) (SkolemTv False) is_unlifted = null args && null prov_dicts @@ -660,12 +521,11 @@ mkPatSynBuilderId dir (L _ name) ; return (Just (builder_id, need_dummy_arg)) } where -tcPatSynBuilderBind :: TcSigFun - -> PatSynBind Name Name +tcPatSynBuilderBind :: PatSynBind Name Name -> TcM (LHsBinds Id) -- See Note [Matchers and builders for pattern synonyms] in PatSyn -tcPatSynBuilderBind sig_fun PSB{ psb_id = L loc name, psb_def = lpat - , psb_dir = dir, psb_args = details } +tcPatSynBuilderBind (PSB { psb_id = L loc name, psb_def = lpat + , psb_dir = dir, psb_args = details }) | isUnidirectional dir = return emptyBag @@ -691,9 +551,9 @@ tcPatSynBuilderBind sig_fun PSB{ psb_id = L loc name, psb_def = lpat , bind_fvs = placeHolderNamesTc , fun_tick = [] } - ; sig <- get_builder_sig sig_fun name builder_id need_dummy_arg + sig = completeSigFromId (PatSynCtxt name) builder_id - ; (builder_binds, _) <- tcPolyCheck NonRecursive emptyPragEnv sig (noLoc bind) + ; (builder_binds, _) <- tcPolyCheck emptyPragEnv sig (noLoc bind) ; traceTc "tcPatSynBuilderBind }" $ ppr builder_binds ; return builder_binds } @@ -725,34 +585,6 @@ tcPatSynBuilderBind sig_fun PSB{ psb_id = L loc name, psb_def = lpat add_dummy_arg other_mg = pprPanic "add_dummy_arg" $ pprMatches other_mg -get_builder_sig :: TcSigFun -> Name -> Id -> Bool -> TcM TcIdSigInfo -get_builder_sig sig_fun name builder_id need_dummy_arg - | Just (TcPatSynSig sig) <- sig_fun name - , TPSI { patsig_implicit_bndrs = implicit_bndrs - , patsig_univ_bndrs = univ_bndrs - , patsig_req = req - , patsig_ex_bndrs = ex_bndrs - , patsig_prov = prov - , patsig_body_ty = body_ty } <- sig - = -- Constuct a TcIdSigInfo from a TcPatSynInfo - -- This does unfortunately mean that we have to know how to - -- make the builder Id's type from the TcPatSynInfo, which - -- duplicates the construction in mkPatSynBuilderId - -- But we really want to use the scoped type variables from - -- the actual sigature, so this is really the Right Thing - return (TISI { sig_bndr = CompleteSig builder_id - , sig_skols = [ (tyVarName tv, tv) - | tv <- map (binderVar "get_builder_sig") implicit_bndrs - ++ univ_bndrs ++ ex_bndrs ] - , sig_theta = req ++ prov - , sig_tau = add_void need_dummy_arg body_ty - , sig_ctxt = PatSynCtxt name - , sig_loc = getSrcSpan name }) - | otherwise - = -- No signature, so fake up a TcIdSigInfo from the builder Id - instTcTySigFromId builder_id - -- See Note [Redundant constraints for builder] - tcPatSynBuilderOcc :: PatSyn -> TcM (HsExpr TcId, TcSigmaType) -- monadic only for failure tcPatSynBuilderOcc ps diff --git a/compiler/typecheck/TcPatSyn.hs-boot b/compiler/typecheck/TcPatSyn.hs-boot index 583abc11c2..18914bc2ec 100644 --- a/compiler/typecheck/TcPatSyn.hs-boot +++ b/compiler/typecheck/TcPatSyn.hs-boot @@ -2,14 +2,11 @@ module TcPatSyn where import Name ( Name ) import Id ( Id ) -import HsSyn ( PatSynBind, LHsBinds, LHsSigType ) -import TcRnTypes ( TcM, TcSigFun, TcPatSynInfo ) +import HsSyn ( PatSynBind, LHsBinds ) +import TcRnTypes ( TcM, TcPatSynInfo ) import TcRnMonad ( TcGblEnv) import Outputable ( Outputable ) -tcPatSynSig :: Name -> LHsSigType Name - -> TcM TcPatSynInfo - tcInferPatSynDecl :: PatSynBind Name Name -> TcM (LHsBinds Id, TcGblEnv) @@ -17,7 +14,6 @@ tcCheckPatSynDecl :: PatSynBind Name Name -> TcPatSynInfo -> TcM (LHsBinds Id, TcGblEnv) -tcPatSynBuilderBind :: TcSigFun -> PatSynBind Name Name - -> TcM (LHsBinds Id) +tcPatSynBuilderBind :: PatSynBind Name Name -> TcM (LHsBinds Id) nonBidirectionalErr :: Outputable name => name -> TcM a diff --git a/compiler/typecheck/TcRnDriver.hs b/compiler/typecheck/TcRnDriver.hs index 154b127371..378f17a95c 100644 --- a/compiler/typecheck/TcRnDriver.hs +++ b/compiler/typecheck/TcRnDriver.hs @@ -1943,17 +1943,15 @@ tcGhciStmts stmts getGhciStepIO :: TcM (LHsExpr Name) getGhciStepIO = do ghciTy <- getGHCiMonad - fresh_a <- newUnique - loc <- getSrcSpanM - let a_tv = mkInternalName fresh_a (mkTyVarOccFS (fsLit "a")) loc - ghciM = nlHsAppTy (nlHsTyVar ghciTy) (nlHsTyVar a_tv) + a_tv <- newName (mkTyVarOccFS (fsLit "a")) + let ghciM = nlHsAppTy (nlHsTyVar ghciTy) (nlHsTyVar a_tv) ioM = nlHsAppTy (nlHsTyVar ioTyConName) (nlHsTyVar a_tv) step_ty = noLoc $ HsForAllTy { hst_bndrs = [noLoc $ UserTyVar (noLoc a_tv)] , hst_body = nlHsFunTy ghciM ioM } stepTy :: LHsSigWcType Name - stepTy = mkEmptyImplicitBndrs (mkEmptyWildCardBndrs step_ty) + stepTy = mkEmptyWildCardBndrs (mkEmptyImplicitBndrs step_ty) return (noLoc $ ExprWithTySig (nlHsVar ghciStepIoMName) stepTy) diff --git a/compiler/typecheck/TcRnMonad.hs b/compiler/typecheck/TcRnMonad.hs index cd99b7c595..1747ce01a2 100644 --- a/compiler/typecheck/TcRnMonad.hs +++ b/compiler/typecheck/TcRnMonad.hs @@ -453,14 +453,18 @@ newUniqueSupply writeMutVar u_var us1 ; return us2 }}} -newLocalName :: Name -> TcM Name -newLocalName name = newName (nameOccName name) +cloneLocalName :: Name -> TcM Name +-- Make a fresh Internal name with the same OccName and SrcSpan +cloneLocalName name = newNameAt (nameOccName name) (nameSrcSpan name) newName :: OccName -> TcM Name -newName occ +newName occ = do { loc <- getSrcSpanM + ; newNameAt occ loc } + +newNameAt :: OccName -> SrcSpan -> TcM Name +newNameAt occ span = do { uniq <- newUnique - ; loc <- getSrcSpanM - ; return (mkInternalName uniq occ loc) } + ; return (mkInternalName uniq occ span) } newSysName :: OccName -> TcRnIf gbl lcl Name newSysName occ @@ -1274,6 +1278,13 @@ emitInsoluble ct v <- readTcRef lie_var ; traceTc "emitInsoluble" (ppr v) } +emitInsolubles :: [Ct] -> TcM () +emitInsolubles cts + = do { lie_var <- getConstraintVar ; + updTcRef lie_var (`addInsols` listToBag cts) ; + v <- readTcRef lie_var ; + traceTc "emitInsoluble" (ppr v) } + -- | Throw out any constraints emitted by the thing_inside discardConstraints :: TcM a -> TcM a discardConstraints thing_inside = fst <$> captureConstraints thing_inside @@ -1344,19 +1355,21 @@ traceTcConstraints msg emitWildCardHoleConstraints :: [(Name, TcTyVar)] -> TcM () emitWildCardHoleConstraints wcs - = do { ctLoc <- getCtLocM HoleOrigin Nothing - ; forM_ wcs $ \(name, tv) -> do { - ; let real_span = case nameSrcSpan name of + = do { ct_loc <- getCtLocM HoleOrigin Nothing + ; emitInsolubles (map (do_one ct_loc) wcs) } + where + do_one :: CtLoc -> (Name, TcTyVar) -> Ct + do_one ct_loc (name, tv) + = CHoleCan { cc_ev = CtDerived { ctev_pred = mkTyVarTy tv + , ctev_loc = ct_loc' } + , cc_hole = TypeHole (occName name) } + where + real_span = case nameSrcSpan name of RealSrcSpan span -> span UnhelpfulSpan str -> pprPanic "emitWildCardHoleConstraints" (ppr name <+> quotes (ftext str)) -- Wildcards are defined locally, and so have RealSrcSpans - ctLoc' = setCtLocSpan ctLoc real_span - ty = mkTyVarTy tv - can = CHoleCan { cc_ev = CtDerived { ctev_pred = ty - , ctev_loc = ctLoc' } - , cc_hole = TypeHole (occName name) } - ; emitInsoluble can } } + ct_loc' = setCtLocSpan ct_loc real_span {- ************************************************************************ diff --git a/compiler/typecheck/TcRnTypes.hs b/compiler/typecheck/TcRnTypes.hs index 3978302958..a737067678 100644 --- a/compiler/typecheck/TcRnTypes.hs +++ b/compiler/typecheck/TcRnTypes.hs @@ -58,11 +58,9 @@ module TcRnTypes( ArrowCtxt(..), -- TcSigInfo - TcSigFun, TcSigInfo(..), TcIdSigInfo(..), - TcPatSynInfo(..), TcIdSigBndr(..), - findScopedTyVars, isPartialSig, noCompleteSig, tcSigInfoName, - completeIdSigPolyId, completeSigPolyId_maybe, - completeIdSigPolyId_maybe, + TcSigInfo(..), TcIdSigInfo(..), + TcIdSigInst(..), TcPatSynInfo(..), + isPartialSig, -- Canonical constraints Xi, Ct(..), Cts, emptyCts, andCts, andManyCts, pprCts, @@ -144,7 +142,7 @@ import Coercion ( Coercion, mkHoleCo ) import ConLike ( ConLike(..) ) import DataCon ( DataCon, dataConUserType, dataConOrigArgTys ) import PatSyn ( PatSyn, pprPatSynType ) -import Id ( idName ) +import Id ( idType ) import FieldLabel ( FieldLabel ) import TcType import Annotations @@ -1197,62 +1195,111 @@ instance Outputable WhereFrom where * * ********************************************************************* -} -type TcSigFun = Name -> Maybe TcSigInfo +-- These data types need to be here only because +-- TcSimplify uses them, and TcSimplify is fairly +-- low down in the module hierarchy data TcSigInfo = TcIdSig TcIdSigInfo | TcPatSynSig TcPatSynInfo -data TcIdSigInfo - = TISI - { sig_bndr :: TcIdSigBndr - - , sig_skols :: [(Name, TcTyVar)] - -- Instantiated type and kind variables SKOLEMS - -- The Name is the Name that the renamer chose; - -- but the TcTyVar may come from instantiating - -- the type and hence have a different unique. - -- No need to keep track of whether they are truly lexically - -- scoped because the renamer has named them uniquely - -- - -- For Partial signatures, this list /excludes/ any wildcards - -- the named wildcards scope over the binding, and hence - -- their Names may appear in renamed type signatures - -- in the binding; get them from sig_bndr - -- See Note [Binding scoped type variables] - - , sig_theta :: TcThetaType -- Instantiated theta. In the case of a - -- PartialSig, sig_theta does not include - -- the extra-constraints wildcard - - , sig_tau :: TcSigmaType -- Instantiated tau - -- See Note [sig_tau may be polymorphic] - - , sig_ctxt :: UserTypeCtxt -- In the case of type-class default methods, - -- the Name in the FunSigCtxt is not the same - -- as the TcId; the former is 'op', while the - -- latter is '$dmop' or some such - - , sig_loc :: SrcSpan -- Location of the type signature - } - -data TcIdSigBndr -- See Note [Complete and partial type signatures] +data TcIdSigInfo -- See Note [Complete and partial type signatures] = CompleteSig -- A complete signature with no wildcards, -- so the complete polymorphic type is known. - TcId -- The polymorphic Id with that type + { sig_bndr :: TcId -- The polymorphic Id with that type + + , sig_ctxt :: UserTypeCtxt -- In the case of type-class default methods, + -- the Name in the FunSigCtxt is not the same + -- as the TcId; the former is 'op', while the + -- latter is '$dmop' or some such + + , sig_loc :: SrcSpan -- Location of the type signature + } | PartialSig -- A partial type signature (i.e. includes one or more -- wildcards). In this case it doesn't make sense to give -- the polymorphic Id, because we are going to /infer/ its -- type, so we can't make the polymorphic Id ab-initio - { sig_name :: Name -- Name of the function; used when report wildcards - , sig_hs_ty :: LHsType Name -- The original partial signature - , sig_wcs :: [(Name,TcTyVar)] -- Instantiated wildcard variables (named and anonymous) - -- The Name is what the user wrote, such as '_', - -- including SrcSpan for the error message; - -- The TcTyVar is just an ordinary unification variable - , sig_cts :: Maybe SrcSpan -- Just loc <=> An extra-constraints wildcard was present - } -- at location loc - -- e.g. f :: (Eq a, _) => a -> a + { psig_name :: Name -- Name of the function; used when report wildcards + , psig_hs_ty :: LHsSigWcType Name -- The original partial signature in HsSyn form + , sig_ctxt :: UserTypeCtxt + , sig_loc :: SrcSpan -- Location of the type signature + } + + +{- Note [Complete and partial type signatures] +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +A type signature is partial when it contains one or more wildcards +(= type holes). The wildcard can either be: +* A (type) wildcard occurring in sig_theta or sig_tau. These are + stored in sig_wcs. + f :: Bool -> _ + g :: Eq _a => _a -> _a -> Bool +* Or an extra-constraints wildcard, stored in sig_cts: + h :: (Num a, _) => a -> a + +A type signature is a complete type signature when there are no +wildcards in the type signature, i.e. iff sig_wcs is empty and +sig_extra_cts is Nothing. +-} + +data TcIdSigInst + = TISI { sig_inst_sig :: TcIdSigInfo + + , sig_inst_skols :: [(Name, TcTyVar)] + -- Instantiated type and kind variables SKOLEMS + -- The Name is the Name that the renamer chose; + -- but the TcTyVar may come from instantiating + -- the type and hence have a different unique. + -- No need to keep track of whether they are truly lexically + -- scoped because the renamer has named them uniquely + -- See Note [Binding scoped type variables] in TcSigs + + , sig_inst_theta :: TcThetaType + -- Instantiated theta. In the case of a + -- PartialSig, sig_theta does not include + -- the extra-constraints wildcard + + , sig_inst_tau :: TcSigmaType -- Instantiated tau + -- See Note [sig_inst_tau may be polymorphic] + + -- Relevant for partial signature only + , sig_inst_wcs :: [(Name, TcTyVar)] + -- Like sig_inst_skols, but for wildcards. The named + -- wildcards scope over the binding, and hence their + -- Names may appear in type signatures in the binding + + , sig_inst_wcx :: Maybe TcTyVar + -- Extra-constraints wildcard to fill in, if any + } + +{- Note [sig_inst_tau may be polymorphic] +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +Note that "sig_inst_tau" might actually be a polymorphic type, +if the original function had a signature like + forall a. Eq a => forall b. Ord b => .... +But that's ok: tcMatchesFun (called by tcRhs) can deal with that +It happens, too! See Note [Polymorphic methods] in TcClassDcl. + +Note [Wildcards in partial signatures] +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +The wildcards in psig_wcs may stand for a type mentioning +the universally-quantified tyvars of psig_ty + +E.g. f :: forall a. _ -> a + f x = x +We get sig_inst_skols = [a] + sig_inst_tau = _22 -> a + sig_inst_wcs = [_22] +and _22 in the end is unified with the type 'a' + +Moreover the kind of a wildcard in sig_inst_wcs may mention +the universally-quantified tyvars sig_inst_skols +e.g. f :: t a -> t _ +Here we get + sig_inst_skole = [k:*, (t::k ->*), (a::k)] + sig_inst_tau = t a -> t _22 + sig_inst_wcs = [ _22::k ] +-} data TcPatSynInfo = TPSI { @@ -1267,132 +1314,29 @@ data TcPatSynInfo patsig_body_ty :: TcSigmaType } -findScopedTyVars -- See Note [Binding scoped type variables] - :: TcType -- The Type: its forall'd variables are a superset - -- of the lexically scoped variables - -> [TcTyVar] -- The instantiated forall variables of the TcType - -> [(Name, TcTyVar)] -- In 1-1 correspondence with the instantiated vars -findScopedTyVars sig_ty inst_tvs - = zipWith find sig_tvs inst_tvs - where - find sig_tv inst_tv = (tyVarName sig_tv, inst_tv) - (sig_tvs,_) = tcSplitForAllTys sig_ty - instance Outputable TcSigInfo where ppr (TcIdSig idsi) = ppr idsi ppr (TcPatSynSig tpsi) = text "TcPatSynInfo" <+> ppr tpsi instance Outputable TcIdSigInfo where - ppr (TISI { sig_bndr = bndr, sig_skols = tyvars - , sig_theta = theta, sig_tau = tau }) - = ppr (tcIdSigBndrName bndr) <+> dcolon <+> - vcat [ pprSigmaType (mkSpecSigmaTy (map snd tyvars) theta tau) - , ppr (map fst tyvars) ] + ppr (CompleteSig { sig_bndr = bndr }) + = ppr bndr <+> dcolon <+> ppr (idType bndr) + ppr (PartialSig { psig_name = name, psig_hs_ty = hs_ty }) + = text "psig" <+> ppr name <+> dcolon <+> ppr hs_ty -instance Outputable TcIdSigBndr where - ppr (CompleteSig f) = text "CompleteSig" <+> ppr f - ppr (PartialSig { sig_name = n }) = text "PartialSig" <+> ppr n +instance Outputable TcIdSigInst where + ppr (TISI { sig_inst_sig = sig, sig_inst_skols = skols + , sig_inst_theta = theta, sig_inst_tau = tau }) + = hang (ppr sig) 2 (vcat [ ppr skols, ppr theta <+> darrow <+> ppr tau ]) instance Outputable TcPatSynInfo where ppr (TPSI{ patsig_name = name}) = ppr name -isPartialSig :: TcIdSigInfo -> Bool -isPartialSig (TISI { sig_bndr = PartialSig {} }) = True -isPartialSig _ = False - --- | No signature or a partial signature -noCompleteSig :: Maybe TcSigInfo -> Bool -noCompleteSig (Just (TcIdSig sig)) = isPartialSig sig -noCompleteSig _ = True - -tcIdSigBndrName :: TcIdSigBndr -> Name -tcIdSigBndrName (CompleteSig id) = idName id -tcIdSigBndrName (PartialSig { sig_name = n }) = n - -tcSigInfoName :: TcSigInfo -> Name -tcSigInfoName (TcIdSig idsi) = tcIdSigBndrName (sig_bndr idsi) -tcSigInfoName (TcPatSynSig tpsi) = patsig_name tpsi - --- Helper for cases when we know for sure we have a complete type --- signature, e.g. class methods. -completeIdSigPolyId :: TcIdSigInfo -> TcId -completeIdSigPolyId (TISI { sig_bndr = CompleteSig id }) = id -completeIdSigPolyId _ = panic "completeSigPolyId" - -completeIdSigPolyId_maybe :: TcIdSigInfo -> Maybe TcId -completeIdSigPolyId_maybe (TISI { sig_bndr = CompleteSig id }) = Just id -completeIdSigPolyId_maybe _ = Nothing - -completeSigPolyId_maybe :: TcSigInfo -> Maybe TcId -completeSigPolyId_maybe (TcIdSig sig) = completeIdSigPolyId_maybe sig -completeSigPolyId_maybe (TcPatSynSig {}) = Nothing - -{- -Note [Binding scoped type variables] -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -The type variables *brought into lexical scope* by a type signature may -be a subset of the *quantified type variables* of the signatures, for two reasons: - -* With kind polymorphism a signature like - f :: forall f a. f a -> f a - may actually give rise to - f :: forall k. forall (f::k -> *) (a:k). f a -> f a - So the sig_tvs will be [k,f,a], but only f,a are scoped. - NB: the scoped ones are not necessarily the *inital* ones! - -* Even aside from kind polymorphism, there may be more instantiated - type variables than lexically-scoped ones. For example: - type T a = forall b. b -> (a,b) - f :: forall c. T c - Here, the signature for f will have one scoped type variable, c, - but two instantiated type variables, c' and b'. - -The function findScopedTyVars takes - * hs_ty: the original HsForAllTy - * sig_ty: the corresponding Type (which is guaranteed to use the same Names - as the HsForAllTy) - * inst_tvs: the skolems instantiated from the forall's in sig_ty -It returns a [(Maybe Name, TcTyVar)], in 1-1 correspondence with inst_tvs -but with a (Just n) for the lexically scoped name of each in-scope tyvar. - -Note [sig_tau may be polymorphic] -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -Note that "sig_tau" might actually be a polymorphic type, -if the original function had a signature like - forall a. Eq a => forall b. Ord b => .... -But that's ok: tcMatchesFun (called by tcRhs) can deal with that -It happens, too! See Note [Polymorphic methods] in TcClassDcl. +isPartialSig :: TcIdSigInst -> Bool +isPartialSig (TISI { sig_inst_sig = PartialSig {} }) = True +isPartialSig _ = False -Note [Existential check] -~~~~~~~~~~~~~~~~~~~~~~~~ -Lazy patterns can't bind existentials. They arise in two ways: - * Let bindings let { C a b = e } in b - * Twiddle patterns f ~(C a b) = e -The pe_lazy field of PatEnv says whether we are inside a lazy -pattern (perhaps deeply) - -If we aren't inside a lazy pattern then we can bind existentials, -but we need to be careful about "extra" tyvars. Consider - (\C x -> d) : pat_ty -> res_ty -When looking for existential escape we must check that the existential -bound by C don't unify with the free variables of pat_ty, OR res_ty -(or of course the environment). Hence we need to keep track of the -res_ty free vars. - -Note [Complete and partial type signatures] -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -A type signature is partial when it contains one or more wildcards -(= type holes). The wildcard can either be: -* A (type) wildcard occurring in sig_theta or sig_tau. These are - stored in sig_wcs. - f :: Bool -> _ - g :: Eq _a => _a -> _a -> Bool -* Or an extra-constraints wildcard, stored in sig_cts: - h :: (Num a, _) => a -> a -A type signature is a complete type signature when there are no -wildcards in the type signature, i.e. iff sig_wcs is empty and -sig_extra_cts is Nothing. -} {- ************************************************************************ @@ -2751,13 +2695,11 @@ pprSkolInfo UnkSkol = WARN( True, text "pprSkolInfo: UnkSkol" ) text "UnkSkol" pprSigSkolInfo :: UserTypeCtxt -> TcType -> SDoc pprSigSkolInfo ctxt ty = case ctxt of - FunSigCtxt f _ -> pp_sig f + FunSigCtxt f _ -> vcat [ text "the type signature for:" + , nest 2 (pprPrefixOcc f <+> dcolon <+> ppr ty) ] PatSynCtxt {} -> pprUserTypeCtxt ctxt -- See Note [Skolem info for pattern synonyms] _ -> vcat [ pprUserTypeCtxt ctxt <> colon , nest 2 (ppr ty) ] - where - pp_sig f = vcat [ text "the type signature for:" - , nest 2 (pprPrefixOcc f <+> dcolon <+> ppr ty) ] pprPatSkolInfo :: ConLike -> SDoc pprPatSkolInfo (RealDataCon dc) diff --git a/compiler/typecheck/TcRules.hs b/compiler/typecheck/TcRules.hs index 1b4826e1cd..4cfccb6bf0 100644 --- a/compiler/typecheck/TcRules.hs +++ b/compiler/typecheck/TcRules.hs @@ -145,7 +145,7 @@ tcRuleBndrs (L _ (RuleBndrSig (L _ name) rn_ty) : rule_bndrs) -- The tyvar 'a' is brought into scope first, just as if you'd written -- a::*, x :: a->a = do { let ctxt = RuleSigCtxt name - ; (id_ty, tvs, _) <- tcHsPatSigType ctxt rn_ty + ; (_ , tvs, id_ty) <- tcHsPatSigType ctxt rn_ty ; let id = mkLocalIdOrCoVar name id_ty -- See Note [Pattern signature binders] in TcHsType diff --git a/compiler/typecheck/TcSigs.hs b/compiler/typecheck/TcSigs.hs new file mode 100644 index 0000000000..8bccc35577 --- /dev/null +++ b/compiler/typecheck/TcSigs.hs @@ -0,0 +1,763 @@ +{- +(c) The University of Glasgow 2006-2012 +(c) The GRASP Project, Glasgow University, 1992-2002 + +-} + +{-# LANGUAGE CPP #-} + +module TcSigs( + TcSigInfo(..), + TcIdSigInfo(..), TcIdSigInst, + TcPatSynInfo(..), + TcSigFun, + + isPartialSig, noCompleteSig, tcIdSigName, tcSigInfoName, + completeSigPolyId_maybe, + + tcTySigs, tcUserTypeSig, completeSigFromId, + tcInstSig, + + TcPragEnv, emptyPragEnv, lookupPragEnv, extendPragEnv, + mkPragEnv, tcSpecPrags, tcSpecWrapper, tcImpPrags, addInlinePrags + ) where + +#include "HsVersions.h" + +import HsSyn +import TcHsType +import TcRnTypes +import TcRnMonad +import TcType +import TcMType +import TcUnify( tcSkolemise, unifyType, noThing ) +import Inst( topInstantiate ) +import TcEnv( tcLookupId ) +import TcEvidence( HsWrapper, (<.>) ) +import Type( mkNamedBinders ) + +import DynFlags +import Var ( TyVar, tyVarName, tyVarKind ) +import Id ( Id, idName, idType, idInlinePragma, setInlinePragma, mkLocalId ) +import PrelNames( mkUnboundName ) +import BasicTypes +import Bag( foldrBag ) +import Module( getModule ) +import Name +import NameEnv +import VarSet +import Outputable +import SrcLoc +import Util( singleton ) +import Maybes( orElse ) +import Data.Maybe( mapMaybe ) +import Control.Monad( unless ) + + +{- ------------------------------------------------------------- + Note [Overview of type signatures] +---------------------------------------------------------------- +Type signatures, including partial signatures, are jolly tricky, +especially on value bindings. Here's an overview. + + f :: forall a. [a] -> [a] + g :: forall b. _ -> b + + f = ...g... + g = ...f... + +* HsSyn: a signature in a binding starts of as a TypeSig, in + type HsBinds.Sig + +* When starting a mutually recursive group, like f/g above, we + call tcTySig on each signature in the group. + +* tcTySig: Sig -> TcIdSigInfo + - For a /complete/ signature, like 'f' above, tcTySig kind-checks + the HsType, producing a Type, and wraps it in a CompleteSig, and + extend the type environment with this polymorphic 'f'. + + - For a /partial/signauture, like 'g' above, tcTySig does nothing + Instead it just wraps the pieces in a PartialSig, to be handled + later. + +* tcInstSig: TcIdSigInfo -> TcIdSigInst + In tcMonoBinds, when looking at an individual binding, we use + tcInstSig to instantiate the signature forall's in the signature, + and attribute that instantiated (monomorphic) type to the + binder. You can see this in TcBinds.tcLhsId. + + The instantiation does the obvious thing for complete signatures, + but for /partial/ signatures it starts from the HsSyn, so it + has to kind-check it etc: tcHsPartialSigType. It's convenient + to do this at the same time as instantiation, becuase we can + make the wildcards into unification variables right away, raather + than somehow quantifying over them. And the "TcLevel" of those + unification variables is correct because we are in tcMonoBinds. + + +Note [Scoped tyvars] +~~~~~~~~~~~~~~~~~~~~ +The -XScopedTypeVariables flag brings lexically-scoped type variables +into scope for any explicitly forall-quantified type variables: + f :: forall a. a -> a + f x = e +Then 'a' is in scope inside 'e'. + +However, we do *not* support this + - For pattern bindings e.g + f :: forall a. a->a + (f,g) = e + +Note [Binding scoped type variables] +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +The type variables *brought into lexical scope* by a type signature +may be a subset of the *quantified type variables* of the signatures, +for two reasons: + +* With kind polymorphism a signature like + f :: forall f a. f a -> f a + may actually give rise to + f :: forall k. forall (f::k -> *) (a:k). f a -> f a + So the sig_tvs will be [k,f,a], but only f,a are scoped. + NB: the scoped ones are not necessarily the *inital* ones! + +* Even aside from kind polymorphism, there may be more instantiated + type variables than lexically-scoped ones. For example: + type T a = forall b. b -> (a,b) + f :: forall c. T c + Here, the signature for f will have one scoped type variable, c, + but two instantiated type variables, c' and b'. + +However, all of this only applies to the renamer. The typechecker +just puts all of them into the type environment; any lexical-scope +errors were dealt with by the renamer. + +-} + + +{- ********************************************************************* +* * + Utility functions for TcSigInfo +* * +********************************************************************* -} + +type TcSigFun = Name -> Maybe TcSigInfo + +-- | No signature or a partial signature +noCompleteSig :: Maybe TcSigInfo -> Bool +noCompleteSig (Just (TcIdSig (CompleteSig {}))) = False +noCompleteSig _ = True + +tcIdSigName :: TcIdSigInfo -> Name +tcIdSigName (CompleteSig { sig_bndr = id }) = idName id +tcIdSigName (PartialSig { psig_name = n }) = n + +tcSigInfoName :: TcSigInfo -> Name +tcSigInfoName (TcIdSig idsi) = tcIdSigName idsi +tcSigInfoName (TcPatSynSig tpsi) = patsig_name tpsi + +completeSigPolyId_maybe :: TcSigInfo -> Maybe TcId +completeSigPolyId_maybe sig + | TcIdSig sig_info <- sig + , CompleteSig { sig_bndr = id } <- sig_info = Just id + | otherwise = Nothing + + +{- ********************************************************************* +* * + Typechecking user signatures +* * +********************************************************************* -} + +tcTySigs :: [LSig Name] -> TcM ([TcId], TcSigFun) +tcTySigs hs_sigs + = checkNoErrs $ -- See Note [Fail eagerly on bad signatures] + do { ty_sigs_s <- mapAndRecoverM tcTySig hs_sigs + ; let ty_sigs = concat ty_sigs_s + poly_ids = mapMaybe completeSigPolyId_maybe ty_sigs + -- The returned [TcId] are the ones for which we have + -- a complete type signature. + -- See Note [Complete and partial type signatures] + env = mkNameEnv [(tcSigInfoName sig, sig) | sig <- ty_sigs] + ; return (poly_ids, lookupNameEnv env) } + +tcTySig :: LSig Name -> TcM [TcSigInfo] +tcTySig (L _ (IdSig id)) + = do { let ctxt = FunSigCtxt (idName id) False + -- False: do not report redundant constraints + -- The user has no control over the signature! + sig = completeSigFromId ctxt id + ; return [TcIdSig sig] } + +tcTySig (L loc (TypeSig names sig_ty)) + = setSrcSpan loc $ + do { sigs <- sequence [ tcUserTypeSig loc sig_ty (Just name) + | L _ name <- names ] + ; return (map TcIdSig sigs) } + +tcTySig (L loc (PatSynSig (L _ name) sig_ty)) + = setSrcSpan loc $ + do { tpsi <- tcPatSynSig name sig_ty + ; return [TcPatSynSig tpsi] } + +tcTySig _ = return [] + + +tcUserTypeSig :: SrcSpan -> LHsSigWcType Name -> Maybe Name -> TcM TcIdSigInfo +-- A function or expression type signature +-- Returns a fully quantified type signature; even the wildcards +-- are quantified with ordinary skolems that should be instantiated +-- +-- The SrcSpan is what to declare as the binding site of the +-- any skolems in the signature. For function signatures we +-- use the whole `f :: ty' signature; for expression signatures +-- just the type part. +-- +-- Just n => Function type signature name :: type +-- Nothing => Expression type signature <expr> :: type +tcUserTypeSig loc hs_sig_ty mb_name + | isCompleteHsSig hs_sig_ty + = do { sigma_ty <- tcHsSigWcType ctxt_F hs_sig_ty + ; return $ + CompleteSig { sig_bndr = mkLocalId name sigma_ty + , sig_ctxt = ctxt_T + , sig_loc = loc } } + -- Location of the <type> in f :: <type> + + -- Partial sig with wildcards + | otherwise + = return (PartialSig { psig_name = name, psig_hs_ty = hs_sig_ty + , sig_ctxt = ctxt_F, sig_loc = loc }) + where + name = case mb_name of + Just n -> n + Nothing -> mkUnboundName (mkVarOcc "<expression>") + ctxt_F = case mb_name of + Just n -> FunSigCtxt n False + Nothing -> ExprSigCtxt + ctxt_T = case mb_name of + Just n -> FunSigCtxt n True + Nothing -> ExprSigCtxt + + + +completeSigFromId :: UserTypeCtxt -> Id -> TcIdSigInfo +-- Used for instance methods and record selectors +completeSigFromId ctxt id + = CompleteSig { sig_bndr = id + , sig_ctxt = ctxt + , sig_loc = getSrcSpan id } + +isCompleteHsSig :: LHsSigWcType Name -> Bool +-- ^ If there are no wildcards, return a LHsSigType +isCompleteHsSig (HsWC { hswc_wcs = wcs }) = null wcs + +{- Note [Fail eagerly on bad signatures] +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +If a type signaure is wrong, fail immediately: + + * the type sigs may bind type variables, so proceeding without them + can lead to a cascade of errors + + * the type signature might be ambiguous, in which case checking + the code against the signature will give a very similar error + to the ambiguity error. + +ToDo: this means we fall over if any type sig +is wrong (eg at the top level of the module), +which is over-conservative +-} + +{- ********************************************************************* +* * + Type checking a pattern synonym signature +* * +************************************************************************ + +Note [Pattern synonym signatures] +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +Pattern synonym signatures are surprisingly tricky (see Trac #11224 for example). +In general they look like this: + + pattern P :: forall univ_tvs. req_theta + => forall ex_tvs. prov_theta + => arg1 -> .. -> argn -> res_ty + +For parsing and renaming we treat the signature as an ordinary LHsSigType. + +Once we get to type checking, we decompose it into its parts, in tcPatSynSig. + +* Note that 'forall univ_tvs' and 'req_theta =>' + and 'forall ex_tvs' and 'prov_theta =>' + are all optional. We gather the pieces at the the top of tcPatSynSig + +* Initially the implicitly-bound tyvars (added by the renamer) include both + universal and existential vars. + +* After we kind-check the pieces and convert to Types, we do kind generalisation. + +Note [The pattern-synonym signature splitting rule] +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +Given a pattern signature, we must split + the kind-generalised variables, and + the implicitly-bound variables +into universal and existential. The rule is this +(see discussion on Trac #11224): + + The universal tyvars are the ones mentioned in + - univ_tvs: the user-specified (forall'd) universals + - req_theta + - res_ty + The existential tyvars are all the rest + +For example + + pattern P :: () => b -> T a + pattern P x = ... + +Here 'a' is universal, and 'b' is existential. But there is a wrinkle: +how do we split the arg_tys from req_ty? Consider + + pattern Q :: () => b -> S c -> T a + pattern Q x = ... + +This is an odd example because Q has only one syntactic argument, and +so presumably is defined by a view pattern matching a function. But +it can happen (Trac #11977, #12108). + +We don't know Q's arity from the pattern signature, so we have to wait +until we see the pattern declaration itself before deciding res_ty is, +and hence which variables are existential and which are universal. + +And that in turn is why TcPatSynInfo has a separate field, +patsig_implicit_bndrs, to capture the implicitly bound type variables, +because we don't yet know how to split them up. + +It's a slight compromise, because it means we don't really know the +pattern synonym's real signature until we see its declaration. So, +for example, in hs-boot file, we may need to think what to do... +(eg don't have any implicitly-bound variables). +-} + +tcPatSynSig :: Name -> LHsSigType Name -> TcM TcPatSynInfo +tcPatSynSig name sig_ty + | HsIB { hsib_vars = implicit_hs_tvs + , hsib_body = hs_ty } <- sig_ty + , (univ_hs_tvs, hs_req, hs_ty1) <- splitLHsSigmaTy hs_ty + , (ex_hs_tvs, hs_prov, hs_body_ty) <- splitLHsSigmaTy hs_ty1 + = do { (implicit_tvs, (univ_tvs, req, ex_tvs, prov, body_ty)) + <- solveEqualities $ + tcImplicitTKBndrs implicit_hs_tvs $ + tcExplicitTKBndrs univ_hs_tvs $ \ univ_tvs -> + tcExplicitTKBndrs ex_hs_tvs $ \ ex_tvs -> + do { req <- tcHsContext hs_req + ; prov <- tcHsContext hs_prov + ; body_ty <- tcHsOpenType hs_body_ty + -- A (literal) pattern can be unlifted; + -- e.g. pattern Zero <- 0# (Trac #12094) + ; let bound_tvs + = unionVarSets [ allBoundVariabless req + , allBoundVariabless prov + , allBoundVariables body_ty + ] + ; return ( (univ_tvs, req, ex_tvs, prov, body_ty) + , bound_tvs) } + + -- Kind generalisation + ; kvs <- kindGeneralize $ + mkSpecForAllTys (implicit_tvs ++ univ_tvs) $ + mkFunTys req $ + mkSpecForAllTys ex_tvs $ + mkFunTys prov $ + body_ty + + -- These are /signatures/ so we zonk to squeeze out any kind + -- unification variables. Do this after quantifyTyVars which may + -- default kind variables to *. + -- ToDo: checkValidType? + ; traceTc "about zonk" empty + ; implicit_tvs <- mapM zonkTcTyCoVarBndr implicit_tvs + ; univ_tvs <- mapM zonkTcTyCoVarBndr univ_tvs + ; ex_tvs <- mapM zonkTcTyCoVarBndr ex_tvs + ; req <- zonkTcTypes req + ; prov <- zonkTcTypes prov + ; body_ty <- zonkTcType body_ty + + ; traceTc "tcTySig }" $ + vcat [ text "implicit_tvs" <+> ppr_tvs implicit_tvs + , text "kvs" <+> ppr_tvs kvs + , text "univ_tvs" <+> ppr_tvs univ_tvs + , text "req" <+> ppr req + , text "ex_tvs" <+> ppr_tvs ex_tvs + , text "prov" <+> ppr prov + , text "body_ty" <+> ppr body_ty ] + ; return (TPSI { patsig_name = name + , patsig_implicit_bndrs = mkNamedBinders Invisible kvs ++ + mkNamedBinders Specified implicit_tvs + , patsig_univ_bndrs = univ_tvs + , patsig_req = req + , patsig_ex_bndrs = ex_tvs + , patsig_prov = prov + , patsig_body_ty = body_ty }) } + where + +ppr_tvs :: [TyVar] -> SDoc +ppr_tvs tvs = braces (vcat [ ppr tv <+> dcolon <+> ppr (tyVarKind tv) + | tv <- tvs]) + + +{- ********************************************************************* +* * + Instantiating user signatures +* * +********************************************************************* -} + + +tcInstSig :: TcIdSigInfo -> TcM TcIdSigInst +-- Instantiate a type signature; only used with plan InferGen +tcInstSig sig@(CompleteSig { sig_bndr = poly_id, sig_loc = loc }) + = setSrcSpan loc $ -- Set the binding site of the tyvars + do { (tv_prs, theta, tau) <- tcInstType newMetaSigTyVars poly_id + -- See Note [Pattern bindings and complete signatures] + + ; return (TISI { sig_inst_sig = sig + , sig_inst_skols = tv_prs + , sig_inst_wcs = [] + , sig_inst_wcx = Nothing + , sig_inst_theta = theta + , sig_inst_tau = tau }) } + +tcInstSig sig@(PartialSig { psig_hs_ty = hs_ty + , sig_ctxt = ctxt + , sig_loc = loc }) + = setSrcSpan loc $ -- Set the binding site of the tyvars + do { (wcs, wcx, tvs, theta, tau) <- tcHsPartialSigType ctxt hs_ty + ; return (TISI { sig_inst_sig = sig + , sig_inst_skols = map (\tv -> (tyVarName tv, tv)) tvs + , sig_inst_wcs = wcs + , sig_inst_wcx = wcx + , sig_inst_theta = theta + , sig_inst_tau = tau }) } + + +{- Note [Pattern bindings and complete signatures] +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +Consider + data T a = MkT a a + f :: forall a. a->a + g :: forall b. b->b + MkT f g = MkT (\x->x) (\y->y) +Here we'll infer a type from the pattern of 'T a', but if we feed in +the signature types for f and g, we'll end up unifying 'a' and 'b' + +So we instantiate f and g's signature with SigTv skolems +(newMetaSigTyVars) that can unify with each other. If too much +unification takes place, we'll find out when we do the final +impedence-matching check in TcBinds.mkExport + +See Note [Signature skolems] in TcType + +None of this applies to a function binding with a complete +signature, which doesn't use tcInstSig. See TcBinds.tcPolyCheck. +-} + +{- ********************************************************************* +* * + Pragmas and PragEnv +* * +********************************************************************* -} + +type TcPragEnv = NameEnv [LSig Name] + +emptyPragEnv :: TcPragEnv +emptyPragEnv = emptyNameEnv + +lookupPragEnv :: TcPragEnv -> Name -> [LSig Name] +lookupPragEnv prag_fn n = lookupNameEnv prag_fn n `orElse` [] + +extendPragEnv :: TcPragEnv -> (Name, LSig Name) -> TcPragEnv +extendPragEnv prag_fn (n, sig) = extendNameEnv_Acc (:) singleton prag_fn n sig + +--------------- +mkPragEnv :: [LSig Name] -> LHsBinds Name -> TcPragEnv +mkPragEnv sigs binds + = foldl extendPragEnv emptyNameEnv prs + where + prs = mapMaybe get_sig sigs + + get_sig :: LSig Name -> Maybe (Name, LSig Name) + get_sig (L l (SpecSig lnm@(L _ nm) ty inl)) = Just (nm, L l $ SpecSig lnm ty (add_arity nm inl)) + get_sig (L l (InlineSig lnm@(L _ nm) inl)) = Just (nm, L l $ InlineSig lnm (add_arity nm inl)) + get_sig _ = Nothing + + add_arity n inl_prag -- Adjust inl_sat field to match visible arity of function + | Inline <- inl_inline inl_prag + -- add arity only for real INLINE pragmas, not INLINABLE + = case lookupNameEnv ar_env n of + Just ar -> inl_prag { inl_sat = Just ar } + Nothing -> WARN( True, text "mkPragEnv no arity" <+> ppr n ) + -- There really should be a binding for every INLINE pragma + inl_prag + | otherwise + = inl_prag + + -- ar_env maps a local to the arity of its definition + ar_env :: NameEnv Arity + ar_env = foldrBag lhsBindArity emptyNameEnv binds + +lhsBindArity :: LHsBind Name -> NameEnv Arity -> NameEnv Arity +lhsBindArity (L _ (FunBind { fun_id = id, fun_matches = ms })) env + = extendNameEnv env (unLoc id) (matchGroupArity ms) +lhsBindArity _ env = env -- PatBind/VarBind + + +----------------- +addInlinePrags :: TcId -> [LSig Name] -> TcM TcId +addInlinePrags poly_id prags_for_me + | inl@(L _ prag) : inls <- inl_prags + = do { traceTc "addInlinePrag" (ppr poly_id $$ ppr prag) + ; unless (null inls) (warn_multiple_inlines inl inls) + ; return (poly_id `setInlinePragma` prag) } + | otherwise + = return poly_id + where + inl_prags = [L loc prag | L loc (InlineSig _ prag) <- prags_for_me] + + warn_multiple_inlines _ [] = return () + + warn_multiple_inlines inl1@(L loc prag1) (inl2@(L _ prag2) : inls) + | inlinePragmaActivation prag1 == inlinePragmaActivation prag2 + , isEmptyInlineSpec (inlinePragmaSpec prag1) + = -- Tiresome: inl1 is put there by virtue of being in a hs-boot loop + -- and inl2 is a user NOINLINE pragma; we don't want to complain + warn_multiple_inlines inl2 inls + | otherwise + = setSrcSpan loc $ + addWarnTc NoReason + (hang (text "Multiple INLINE pragmas for" <+> ppr poly_id) + 2 (vcat (text "Ignoring all but the first" + : map pp_inl (inl1:inl2:inls)))) + + pp_inl (L loc prag) = ppr prag <+> parens (ppr loc) + + +{- ********************************************************************* +* * + SPECIALISE pragmas +* * +************************************************************************ + +Note [Handling SPECIALISE pragmas] +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +The basic idea is this: + + foo :: Num a => a -> b -> a + {-# SPECIALISE foo :: Int -> b -> Int #-} + +We check that + (forall a b. Num a => a -> b -> a) + is more polymorphic than + forall b. Int -> b -> Int +(for which we could use tcSubType, but see below), generating a HsWrapper +to connect the two, something like + wrap = /\b. <hole> Int b dNumInt +This wrapper is put in the TcSpecPrag, in the ABExport record of +the AbsBinds. + + + f :: (Eq a, Ix b) => a -> b -> Bool + {-# SPECIALISE f :: (Ix p, Ix q) => Int -> (p,q) -> Bool #-} + f = <poly_rhs> + +From this the typechecker generates + + AbsBinds [ab] [d1,d2] [([ab], f, f_mono, prags)] binds + + SpecPrag (wrap_fn :: forall a b. (Eq a, Ix b) => XXX + -> forall p q. (Ix p, Ix q) => XXX[ Int/a, (p,q)/b ]) + +From these we generate: + + Rule: forall p, q, (dp:Ix p), (dq:Ix q). + f Int (p,q) dInt ($dfInPair dp dq) = f_spec p q dp dq + + Spec bind: f_spec = wrap_fn <poly_rhs> + +Note that + + * The LHS of the rule may mention dictionary *expressions* (eg + $dfIxPair dp dq), and that is essential because the dp, dq are + needed on the RHS. + + * The RHS of f_spec, <poly_rhs> has a *copy* of 'binds', so that it + can fully specialise it. + + + +From the TcSpecPrag, in DsBinds we generate a binding for f_spec and a RULE: + + f_spec :: Int -> b -> Int + f_spec = wrap<f rhs> + + RULE: forall b (d:Num b). f b d = f_spec b + +The RULE is generated by taking apart the HsWrapper, which is a little +delicate, but works. + +Some wrinkles + +1. We don't use full-on tcSubType, because that does co and contra + variance and that in turn will generate too complex a LHS for the + RULE. So we use a single invocation of skolemise / + topInstantiate in tcSpecWrapper. (Actually I think that even + the "deeply" stuff may be too much, because it introduces lambdas, + though I think it can be made to work without too much trouble.) + +2. We need to take care with type families (Trac #5821). Consider + type instance F Int = Bool + f :: Num a => a -> F a + {-# SPECIALISE foo :: Int -> Bool #-} + + We *could* try to generate an f_spec with precisely the declared type: + f_spec :: Int -> Bool + f_spec = <f rhs> Int dNumInt |> co + + RULE: forall d. f Int d = f_spec |> sym co + + but the 'co' and 'sym co' are (a) playing no useful role, and (b) are + hard to generate. At all costs we must avoid this: + RULE: forall d. f Int d |> co = f_spec + because the LHS will never match (indeed it's rejected in + decomposeRuleLhs). + + So we simply do this: + - Generate a constraint to check that the specialised type (after + skolemiseation) is equal to the instantiated function type. + - But *discard* the evidence (coercion) for that constraint, + so that we ultimately generate the simpler code + f_spec :: Int -> F Int + f_spec = <f rhs> Int dNumInt + + RULE: forall d. f Int d = f_spec + You can see this discarding happening in + +3. Note that the HsWrapper can transform *any* function with the right + type prefix + forall ab. (Eq a, Ix b) => XXX + regardless of XXX. It's sort of polymorphic in XXX. This is + useful: we use the same wrapper to transform each of the class ops, as + well as the dict. That's what goes on in TcInstDcls.mk_meth_spec_prags +-} + +tcSpecPrags :: Id -> [LSig Name] + -> TcM [LTcSpecPrag] +-- Add INLINE and SPECIALSE pragmas +-- INLINE prags are added to the (polymorphic) Id directly +-- SPECIALISE prags are passed to the desugarer via TcSpecPrags +-- Pre-condition: the poly_id is zonked +-- Reason: required by tcSubExp +tcSpecPrags poly_id prag_sigs + = do { traceTc "tcSpecPrags" (ppr poly_id <+> ppr spec_sigs) + ; unless (null bad_sigs) warn_discarded_sigs + ; pss <- mapAndRecoverM (wrapLocM (tcSpecPrag poly_id)) spec_sigs + ; return $ concatMap (\(L l ps) -> map (L l) ps) pss } + where + spec_sigs = filter isSpecLSig prag_sigs + bad_sigs = filter is_bad_sig prag_sigs + is_bad_sig s = not (isSpecLSig s || isInlineLSig s) + + warn_discarded_sigs + = addWarnTc NoReason + (hang (text "Discarding unexpected pragmas for" <+> ppr poly_id) + 2 (vcat (map (ppr . getLoc) bad_sigs))) + +-------------- +tcSpecPrag :: TcId -> Sig Name -> TcM [TcSpecPrag] +tcSpecPrag poly_id prag@(SpecSig fun_name hs_tys inl) +-- See Note [Handling SPECIALISE pragmas] +-- +-- The Name fun_name in the SpecSig may not be the same as that of the poly_id +-- Example: SPECIALISE for a class method: the Name in the SpecSig is +-- for the selector Id, but the poly_id is something like $cop +-- However we want to use fun_name in the error message, since that is +-- what the user wrote (Trac #8537) + = addErrCtxt (spec_ctxt prag) $ + do { warnIf NoReason (not (isOverloadedTy poly_ty || isInlinePragma inl)) + (text "SPECIALISE pragma for non-overloaded function" + <+> quotes (ppr fun_name)) + -- Note [SPECIALISE pragmas] + ; spec_prags <- mapM tc_one hs_tys + ; traceTc "tcSpecPrag" (ppr poly_id $$ nest 2 (vcat (map ppr spec_prags))) + ; return spec_prags } + where + name = idName poly_id + poly_ty = idType poly_id + spec_ctxt prag = hang (text "In the SPECIALISE pragma") 2 (ppr prag) + + tc_one hs_ty + = do { spec_ty <- tcHsSigType (FunSigCtxt name False) hs_ty + ; wrap <- tcSpecWrapper (FunSigCtxt name True) poly_ty spec_ty + ; return (SpecPrag poly_id wrap inl) } + +tcSpecPrag _ prag = pprPanic "tcSpecPrag" (ppr prag) + +-------------- +tcSpecWrapper :: UserTypeCtxt -> TcType -> TcType -> TcM HsWrapper +-- A simpler variant of tcSubType, used for SPECIALISE pragmas +-- See Note [Handling SPECIALISE pragmas], wrinkle 1 +tcSpecWrapper ctxt poly_ty spec_ty + = do { (sk_wrap, inst_wrap) + <- tcSkolemise ctxt spec_ty $ \ _ spec_tau -> + do { (inst_wrap, tau) <- topInstantiate orig poly_ty + ; _ <- unifyType noThing spec_tau tau + -- Deliberately ignore the evidence + -- See Note [Handling SPECIALISE pragmas], + -- wrinkle (2) + ; return inst_wrap } + ; return (sk_wrap <.> inst_wrap) } + where + orig = SpecPragOrigin ctxt + +-------------- +tcImpPrags :: [LSig Name] -> TcM [LTcSpecPrag] +-- SPECIALISE pragmas for imported things +tcImpPrags prags + = do { this_mod <- getModule + ; dflags <- getDynFlags + ; if (not_specialising dflags) then + return [] + else do + { pss <- mapAndRecoverM (wrapLocM tcImpSpec) + [L loc (name,prag) + | (L loc prag@(SpecSig (L _ name) _ _)) <- prags + , not (nameIsLocalOrFrom this_mod name) ] + ; return $ concatMap (\(L l ps) -> map (L l) ps) pss } } + where + -- Ignore SPECIALISE pragmas for imported things + -- when we aren't specialising, or when we aren't generating + -- code. The latter happens when Haddocking the base library; + -- we don't wnat complaints about lack of INLINABLE pragmas + not_specialising dflags + | not (gopt Opt_Specialise dflags) = True + | otherwise = case hscTarget dflags of + HscNothing -> True + HscInterpreted -> True + _other -> False + +tcImpSpec :: (Name, Sig Name) -> TcM [TcSpecPrag] +tcImpSpec (name, prag) + = do { id <- tcLookupId name + ; unless (isAnyInlinePragma (idInlinePragma id)) + (addWarnTc NoReason (impSpecErr name)) + ; tcSpecPrag id prag } + +impSpecErr :: Name -> SDoc +impSpecErr name + = hang (text "You cannot SPECIALISE" <+> quotes (ppr name)) + 2 (vcat [ text "because its definition has no INLINE/INLINABLE pragma" + , parens $ sep + [ text "or its defining module" <+> quotes (ppr mod) + , text "was compiled without -O"]]) + where + mod = nameModule name diff --git a/compiler/typecheck/TcSimplify.hs b/compiler/typecheck/TcSimplify.hs index c889b4b840..5a727a85ed 100644 --- a/compiler/typecheck/TcSimplify.hs +++ b/compiler/typecheck/TcSimplify.hs @@ -516,7 +516,7 @@ the let binding. simplifyInfer :: TcLevel -- Used when generating the constraints -> Bool -- Apply monomorphism restriction - -> [TcIdSigInfo] -- Any signatures (possibly partial) + -> [TcIdSigInst] -- Any signatures (possibly partial) -> [(Name, TcTauType)] -- Variables to be generalised, -- and their tau-types -> WantedConstraints @@ -540,8 +540,8 @@ simplifyInfer rhs_tclvl apply_mr sigs name_taus wanteds , text "(unzonked) wanted =" <+> ppr wanteds ] - ; let partial_sigs = filter isPartialSig sigs - psig_theta = concatMap sig_theta partial_sigs + ; let partial_sigs = filter isPartialSig sigs + psig_theta = concatMap sig_inst_theta partial_sigs -- First do full-blown solving -- NB: we must gather up all the bindings from doing @@ -654,8 +654,13 @@ simplifyInfer rhs_tclvl apply_mr sigs name_taus wanteds -- Emit an implication constraint for the -- remaining constraints from the RHS + -- extra_qtvs: see Note [Quantification and partial signatures] ; bound_theta_vars <- mapM TcM.newEvVar bound_theta ; psig_theta_vars <- mapM zonkId psig_theta_vars + ; all_qtvs <- add_psig_tvs qtvs + [ tv | sig <- partial_sigs + , (_,tv) <- sig_inst_skols sig ] + ; let full_theta = psig_theta ++ bound_theta full_theta_vars = psig_theta_vars ++ bound_theta_vars skol_info = InferSkol [ (name, mkSigmaTy [] full_theta ty) @@ -664,13 +669,8 @@ simplifyInfer rhs_tclvl apply_mr sigs name_taus wanteds -- they are also bound in ic_skols and we want them -- to be tidied uniformly - -- extra_qtvs: see Note [Quantification and partial signatures] - extra_qtvs = [ tv | sig <- partial_sigs - , (_, tv) <- sig_skols sig - , not (tv `elem` qtvs) ] - implic = Implic { ic_tclvl = rhs_tclvl - , ic_skols = extra_qtvs ++ qtvs + , ic_skols = all_qtvs , ic_no_eqs = False , ic_given = full_theta_vars , ic_wanted = wanted_transformed @@ -691,6 +691,16 @@ simplifyInfer rhs_tclvl apply_mr sigs name_taus wanteds , text "implic =" <+> ppr implic ] ; return ( qtvs, full_theta_vars, TcEvBinds ev_binds_var ) } + where + add_psig_tvs qtvs [] = return qtvs + add_psig_tvs qtvs (tv:tvs) + = do { tv <- zonkTcTyVarToTyVar tv + ; if tv `elem` qtvs + then add_psig_tvs qtvs tvs + else do { mb_tv <- zonkQuantifiedTyVar False tv + ; case mb_tv of + Nothing -> add_psig_tvs qtvs tvs + Just tv -> add_psig_tvs (tv:qtvs) tvs } } {- Note [Add signature contexts as givens] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -727,6 +737,7 @@ type signatures. Note [Deciding quantification] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ If the monomorphism restriction does not apply, then we quantify as follows: + * Take the global tyvars, and "grow" them using the equality constraints E.g. if x:alpha is in the environment, and alpha ~ [beta] (which can happen because alpha is untouchable here) then do not quantify over @@ -759,7 +770,8 @@ decideQuantification -> TcM ( [TcTyVar] -- Quantify over these (skolems) , [PredType] ) -- and this context (fully zonked) -- See Note [Deciding quantification] -decideQuantification apply_mr name_taus psig_theta constraints +decideQuantification apply_mr name_taus psig_theta candidates +{- | apply_mr -- Apply the Monomorphism restriction = do { gbl_tvs <- tcGetGlobalTyCoVars ; zonked_taus <- mapM TcM.zonkTcType (psig_theta ++ taus) @@ -788,30 +800,51 @@ decideQuantification apply_mr name_taus psig_theta constraints ; return (qtvs, []) } | otherwise +-} = do { gbl_tvs <- tcGetGlobalTyCoVars ; zonked_taus <- mapM TcM.zonkTcType (psig_theta ++ taus) -- psig_theta: see Note [Quantification and partial signatures] ; let DV { dv_kvs = zkvs, dv_tvs = ztvs} = splitDepVarsOfTypes zonked_taus - mono_tvs = growThetaTyVars equality_constraints gbl_tvs - tau_tvs_plus = growThetaTyVarsDSet constraints ztvs - dvs_plus = DV { dv_kvs = zkvs, dv_tvs = tau_tvs_plus } + (gbl_cand, quant_cand) -- gbl_cand = do not quantify me + = case apply_mr of -- quant_cand = try to quantify me + True -> (candidates, []) + False -> ([], candidates) + zonked_tkvs = dVarSetToVarSet zkvs `unionVarSet` dVarSetToVarSet ztvs + eq_constraints = filter isEqPred quant_cand + constrained_tvs = tyCoVarsOfTypes gbl_cand + mono_tvs = growThetaTyVars eq_constraints $ + gbl_tvs `unionVarSet` constrained_tvs + tau_tvs_plus = growThetaTyVarsDSet quant_cand ztvs + dvs_plus = DV { dv_kvs = zkvs, dv_tvs = tau_tvs_plus } + ; qtvs <- quantifyZonkedTyVars mono_tvs dvs_plus -- We don't grow the kvs, as there's no real need to. Recall -- that quantifyTyVars uses the separation between kvs and tvs -- only for defaulting, and we don't want (ever) to default a tv -- to *. So, don't grow the kvs. - ; constraints <- TcM.zonkTcTypes constraints + ; quant_cand <- TcM.zonkTcTypes quant_cand -- quantifyTyVars turned some meta tyvars into -- quantified skolems, so we have to zonk again ; let qtv_set = mkVarSet qtvs - theta = pickQuantifiablePreds qtv_set constraints + theta = pickQuantifiablePreds qtv_set quant_cand min_theta = mkMinimalBySCs theta -- See Note [Minimize by Superclasses] + -- Warn about the monomorphism restriction + ; warn_mono <- woptM Opt_WarnMonomorphism + ; let mr_bites = constrained_tvs `intersectsVarSet` zonked_tkvs + ; warnTc (Reason Opt_WarnMonomorphism) (warn_mono && mr_bites) $ + hang (text "The Monomorphism Restriction applies to the binding" + <> plural bndrs <+> text "for" <+> pp_bndrs) + 2 (text "Consider giving a type signature for" + <+> if isSingleton bndrs then pp_bndrs + else text "these binders") + ; traceTc "decideQuantification 2" - (vcat [ text "constraints:" <+> ppr constraints + (vcat [ text "gbl_cand:" <+> ppr gbl_cand + , text "quant_cand:" <+> ppr quant_cand , text "gbl_tvs:" <+> ppr gbl_tvs , text "mono_tvs:" <+> ppr mono_tvs , text "tau_tvs_plus:" <+> ppr tau_tvs_plus @@ -820,7 +853,6 @@ decideQuantification apply_mr name_taus psig_theta constraints ; return (qtvs, min_theta) } where pp_bndrs = pprWithCommas (quotes . ppr) bndrs - equality_constraints = filter isEqPred constraints (bndrs, taus) = unzip name_taus ------------------ diff --git a/compiler/typecheck/TcType.hs b/compiler/typecheck/TcType.hs index 06f6a45a18..b48a0c1e04 100644 --- a/compiler/typecheck/TcType.hs +++ b/compiler/typecheck/TcType.hs @@ -34,7 +34,7 @@ module TcType ( -------------------------------- -- MetaDetails - UserTypeCtxt(..), pprUserTypeCtxt, pprSigCtxt, isSigMaybe, + UserTypeCtxt(..), pprUserTypeCtxt, isSigMaybe, TcTyVarDetails(..), pprTcTyVarDetails, vanillaSkolemTv, superSkolemTv, MetaDetails(Flexi, Indirect), MetaInfo(..), isImmutableTyVar, isSkolemTyVar, isMetaTyVar, isMetaTyVarTy, isTyVarTy, @@ -564,20 +564,6 @@ pprUserTypeCtxt SigmaCtxt = text "the context of a polymorphic type" pprUserTypeCtxt (DataTyCtxt tc) = text "the context of the data type declaration for" <+> quotes (ppr tc) pprUserTypeCtxt (PatSynCtxt n) = text "the signature for pattern synonym" <+> quotes (ppr n) -pprSigCtxt :: UserTypeCtxt -> SDoc -> SDoc --- (pprSigCtxt ctxt <extra> <type>) --- prints In the type signature for 'f': --- f :: <type> --- The <extra> is either empty or "the ambiguity check for" -pprSigCtxt ctxt pp_ty - | Just n <- isSigMaybe ctxt - = hang (text "In the type signature:") - 2 (pprPrefixOcc n <+> dcolon <+> pp_ty) - - | otherwise - = hang (text "In" <+> pprUserTypeCtxt ctxt <> colon) - 2 pp_ty - isSigMaybe :: UserTypeCtxt -> Maybe Name isSigMaybe (FunSigCtxt n _) = Just n isSigMaybe (ConArgCtxt n) = Just n diff --git a/compiler/vectorise/Vectorise/Generic/PData.hs b/compiler/vectorise/Vectorise/Generic/PData.hs index 54f5ace6e6..2c403bf82a 100644 --- a/compiler/vectorise/Vectorise/Generic/PData.hs +++ b/compiler/vectorise/Vectorise/Generic/PData.hs @@ -45,7 +45,7 @@ buildDataFamInst :: Name -> TyCon -> TyCon -> AlgTyConRhs -> VM FamInst buildDataFamInst name' fam_tc vect_tc rhs = do { axiom_name <- mkDerivedName mkInstTyCoOcc name' - ; (_, tyvars') <- liftDs $ tcInstSigTyVarsLoc (getSrcSpan name') tyvars + ; (_, tyvars') <- liftDs $ tcInstSigTyVars (getSrcSpan name') tyvars ; let ax = mkSingleCoAxiom Representational axiom_name tyvars' [] fam_tc pat_tys rep_ty tys' = mkTyVarTys tyvars' rep_ty = mkTyConApp rep_tc tys' |