56a03314eecbf4e22f89adeb83bf5031c6936e05
[ghc.git] / compiler / rename / RnTypes.hs
1 {-
2 (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3
4 \section[RnSource]{Main pass of renamer}
5 -}
6
7 {-# LANGUAGE ScopedTypeVariables #-}
8 {-# LANGUAGE CPP #-}
9
10 module RnTypes (
11 -- Type related stuff
12 rnHsType, rnLHsType, rnLHsTypes, rnContext,
13 rnHsKind, rnLHsKind,
14 rnHsSigType, rnHsWcType,
15 rnHsSigWcType, rnHsSigWcTypeScoped,
16 rnLHsInstType,
17 newTyVarNameRn, collectAnonWildCards,
18 rnConDeclFields,
19 rnLTyVar,
20
21 -- Precence related stuff
22 mkOpAppRn, mkNegAppRn, mkOpFormRn, mkConOpPatRn,
23 checkPrecMatch, checkSectionPrec,
24
25 -- Binding related stuff
26 bindLHsTyVarBndr,
27 bindSigTyVarsFV, bindHsQTyVars, bindLRdrNames,
28 extractFilteredRdrTyVars,
29 extractHsTyRdrTyVars, extractHsTysRdrTyVars,
30 extractHsTysRdrTyVarsDups, rmDupsInRdrTyVars,
31 extractRdrKindSigVars, extractDataDefnKindVars,
32 freeKiTyVarsAllVars, freeKiTyVarsKindVars, freeKiTyVarsTypeVars
33 ) where
34
35 import {-# SOURCE #-} RnSplice( rnSpliceType )
36
37 import DynFlags
38 import HsSyn
39 import RnHsDoc ( rnLHsDoc, rnMbLHsDoc )
40 import RnEnv
41 import TcRnMonad
42 import RdrName
43 import PrelNames
44 import TysPrim ( funTyConName )
45 import TysWiredIn ( starKindTyConName, unicodeStarKindTyConName )
46 import Name
47 import SrcLoc
48 import NameSet
49 import FieldLabel
50
51 import Util
52 import BasicTypes ( compareFixity, funTyFixity, negateFixity,
53 Fixity(..), FixityDirection(..) )
54 import Outputable
55 import FastString
56 import Maybes
57 import qualified GHC.LanguageExtensions as LangExt
58
59 import Data.List ( (\\), nubBy, partition )
60 import Control.Monad ( unless, when )
61
62 #include "HsVersions.h"
63
64 {-
65 These type renamers are in a separate module, rather than in (say) RnSource,
66 to break several loop.
67
68 *********************************************************
69 * *
70 HsSigWcType (i.e with wildcards)
71 * *
72 *********************************************************
73 -}
74
75 rnHsSigWcType :: HsDocContext -> LHsSigWcType RdrName
76 -> RnM (LHsSigWcType Name, FreeVars)
77 rnHsSigWcType doc sig_ty
78 = rn_hs_sig_wc_type True doc sig_ty $ \sig_ty' ->
79 return (sig_ty', emptyFVs)
80
81 rnHsSigWcTypeScoped :: HsDocContext -> LHsSigWcType RdrName
82 -> (LHsSigWcType Name -> RnM (a, FreeVars))
83 -> RnM (a, FreeVars)
84 -- Used for
85 -- - Signatures on binders in a RULE
86 -- - Pattern type signatures
87 -- Wildcards are allowed
88 -- type signatures on binders only allowed with ScopedTypeVariables
89 rnHsSigWcTypeScoped ctx sig_ty thing_inside
90 = do { ty_sig_okay <- xoptM LangExt.ScopedTypeVariables
91 ; checkErr ty_sig_okay (unexpectedTypeSigErr sig_ty)
92 ; rn_hs_sig_wc_type False ctx sig_ty thing_inside
93 }
94 -- False: for pattern type sigs and rules we /do/ want
95 -- to bring those type variables into scope
96 -- e.g \ (x :: forall a. a-> b) -> e
97 -- Here we do bring 'b' into scope
98
99 rn_hs_sig_wc_type :: Bool -- see rnImplicitBndrs
100 -> HsDocContext
101 -> LHsSigWcType RdrName
102 -> (LHsSigWcType Name -> RnM (a, FreeVars))
103 -> RnM (a, FreeVars)
104 -- rn_hs_sig_wc_type is used for source-language type signatures
105 rn_hs_sig_wc_type no_implicit_if_forall ctxt
106 (HsWC { hswc_body = HsIB { hsib_body = hs_ty }})
107 thing_inside
108 = do { free_vars <- extractFilteredRdrTyVars hs_ty
109 ; (tv_rdrs, nwc_rdrs) <- partition_nwcs free_vars
110 ; rnImplicitBndrs no_implicit_if_forall tv_rdrs hs_ty $ \ vars ->
111 do { (wcs, hs_ty', fvs1) <- rnWcBody ctxt nwc_rdrs hs_ty
112 ; let sig_ty' = HsWC { hswc_wcs = wcs, hswc_body = ib_ty' }
113 ib_ty' = HsIB { hsib_vars = vars, hsib_body = hs_ty' }
114 ; (res, fvs2) <- thing_inside sig_ty'
115 ; return (res, fvs1 `plusFV` fvs2) } }
116
117 rnHsWcType :: HsDocContext -> LHsWcType RdrName -> RnM (LHsWcType Name, FreeVars)
118 rnHsWcType ctxt (HsWC { hswc_body = hs_ty })
119 = do { free_vars <- extractFilteredRdrTyVars hs_ty
120 ; (_, nwc_rdrs) <- partition_nwcs free_vars
121 ; (wcs, hs_ty', fvs) <- rnWcBody ctxt nwc_rdrs hs_ty
122 ; let sig_ty' = HsWC { hswc_wcs = wcs, hswc_body = hs_ty' }
123 ; return (sig_ty', fvs) }
124
125 rnWcBody :: HsDocContext -> [Located RdrName] -> LHsType RdrName
126 -> RnM ([Name], LHsType Name, FreeVars)
127 rnWcBody ctxt nwc_rdrs hs_ty
128 = do { nwcs <- mapM newLocalBndrRn nwc_rdrs
129 ; let env = RTKE { rtke_level = TypeLevel
130 , rtke_what = RnTypeBody
131 , rtke_nwcs = mkNameSet nwcs
132 , rtke_ctxt = ctxt }
133 ; (hs_ty', fvs) <- bindLocalNamesFV nwcs $
134 rn_lty env hs_ty
135 ; let awcs = collectAnonWildCards hs_ty'
136 ; return (nwcs ++ awcs, hs_ty', fvs) }
137 where
138 rn_lty env (L loc hs_ty)
139 = setSrcSpan loc $
140 do { (hs_ty', fvs) <- rn_ty env hs_ty
141 ; return (L loc hs_ty', fvs) }
142
143 rn_ty :: RnTyKiEnv -> HsType RdrName -> RnM (HsType Name, FreeVars)
144 -- A lot of faff just to allow the extra-constraints wildcard to appear
145 rn_ty env hs_ty@(HsForAllTy { hst_bndrs = tvs, hst_body = hs_body })
146 = bindLHsTyVarBndrs (rtke_ctxt env) (Just $ inTypeDoc hs_ty)
147 Nothing [] tvs $ \ _ tvs' _ _ ->
148 do { (hs_body', fvs) <- rn_lty env hs_body
149 ; return (HsForAllTy { hst_bndrs = tvs', hst_body = hs_body' }, fvs) }
150
151 rn_ty env (HsQualTy { hst_ctxt = L cx hs_ctxt, hst_body = hs_ty })
152 | Just (hs_ctxt1, hs_ctxt_last) <- snocView hs_ctxt
153 , L lx (HsWildCardTy wc) <- ignoreParens hs_ctxt_last
154 = do { (hs_ctxt1', fvs1) <- mapFvRn (rn_top_constraint env) hs_ctxt1
155 ; wc' <- setSrcSpan lx $
156 do { checkExtraConstraintWildCard env wc
157 ; rnAnonWildCard wc }
158 ; let hs_ctxt' = hs_ctxt1' ++ [L lx (HsWildCardTy wc')]
159 ; (hs_ty', fvs2) <- rnLHsTyKi env hs_ty
160 ; return (HsQualTy { hst_ctxt = L cx hs_ctxt', hst_body = hs_ty' }
161 , fvs1 `plusFV` fvs2) }
162
163 | otherwise
164 = do { (hs_ctxt', fvs1) <- mapFvRn (rn_top_constraint env) hs_ctxt
165 ; (hs_ty', fvs2) <- rnLHsTyKi env hs_ty
166 ; return (HsQualTy { hst_ctxt = L cx hs_ctxt', hst_body = hs_ty' }
167 , fvs1 `plusFV` fvs2) }
168
169 rn_ty env hs_ty = rnHsTyKi env hs_ty
170
171 rn_top_constraint env = rnLHsTyKi (env { rtke_what = RnTopConstraint })
172
173
174 checkExtraConstraintWildCard :: RnTyKiEnv -> HsWildCardInfo RdrName
175 -> RnM ()
176 -- Rename the extra-constraint spot in a type signature
177 -- (blah, _) => type
178 -- Check that extra-constraints are allowed at all, and
179 -- if so that it's an anonymous wildcard
180 checkExtraConstraintWildCard env wc
181 = checkWildCard env mb_bad
182 where
183 mb_bad | not (extraConstraintWildCardsAllowed env)
184 = Just (text "Extra-constraint wildcard" <+> quotes (ppr wc)
185 <+> text "not allowed")
186 | otherwise
187 = Nothing
188
189 extraConstraintWildCardsAllowed :: RnTyKiEnv -> Bool
190 extraConstraintWildCardsAllowed env
191 = case rtke_ctxt env of
192 TypeSigCtx {} -> True
193 ExprWithTySigCtx {} -> True
194 _ -> False
195
196 -- | Finds free type and kind variables in a type,
197 -- without duplicates, and
198 -- without variables that are already in scope in LocalRdrEnv
199 -- NB: this includes named wildcards, which look like perfectly
200 -- ordinary type variables at this point
201 extractFilteredRdrTyVars :: LHsType RdrName -> RnM FreeKiTyVars
202 extractFilteredRdrTyVars hs_ty
203 = do { rdr_env <- getLocalRdrEnv
204 ; filterInScope rdr_env <$> extractHsTyRdrTyVars hs_ty }
205
206 -- | When the NamedWildCards extension is enabled, partition_nwcs
207 -- removes type variables that start with an underscore from the
208 -- FreeKiTyVars in the argument and returns them in a separate list.
209 -- When the extension is disabled, the function returns the argument
210 -- and empty list. See Note [Renaming named wild cards]
211 partition_nwcs :: FreeKiTyVars -> RnM (FreeKiTyVars, [Located RdrName])
212 partition_nwcs free_vars@(FKTV { fktv_tys = tys, fktv_all = all })
213 = do { wildcards_enabled <- fmap (xopt LangExt.NamedWildCards) getDynFlags
214 ; let (nwcs, no_nwcs) | wildcards_enabled = partition is_wildcard tys
215 | otherwise = ([], tys)
216 free_vars' = free_vars { fktv_tys = no_nwcs
217 , fktv_all = all \\ nwcs }
218 ; return (free_vars', nwcs) }
219 where
220 is_wildcard :: Located RdrName -> Bool
221 is_wildcard rdr = startsWithUnderscore (rdrNameOcc (unLoc rdr))
222
223 {- Note [Renaming named wild cards]
224 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
225 Identifiers starting with an underscore are always parsed as type variables.
226 It is only here in the renamer that we give the special treatment.
227 See Note [The wildcard story for types] in HsTypes.
228
229 It's easy! When we collect the implicitly bound type variables, ready
230 to bring them into scope, and NamedWildCards is on, we partition the
231 variables into the ones that start with an underscore (the named
232 wildcards) and the rest. Then we just add them to the hswc_wcs field
233 of the HsWildCardBndrs structure, and we are done.
234
235
236 *********************************************************
237 * *
238 HsSigtype (i.e. no wildcards)
239 * *
240 ****************************************************** -}
241
242 rnHsSigType :: HsDocContext -> LHsSigType RdrName
243 -> RnM (LHsSigType Name, FreeVars)
244 -- Used for source-language type signatures
245 -- that cannot have wildcards
246 rnHsSigType ctx (HsIB { hsib_body = hs_ty })
247 = do { vars <- extractFilteredRdrTyVars hs_ty
248 ; rnImplicitBndrs True vars hs_ty $ \ vars ->
249 do { (body', fvs) <- rnLHsType ctx hs_ty
250 ; return (HsIB { hsib_vars = vars
251 , hsib_body = body' }, fvs) } }
252
253 rnImplicitBndrs :: Bool -- True <=> no implicit quantification
254 -- if type is headed by a forall
255 -- E.g. f :: forall a. a->b
256 -- Do not quantify over 'b' too.
257 -> FreeKiTyVars
258 -> LHsType RdrName
259 -> ([Name] -> RnM (a, FreeVars))
260 -> RnM (a, FreeVars)
261 rnImplicitBndrs no_implicit_if_forall free_vars hs_ty@(L loc _) thing_inside
262 = do { let real_tv_rdrs -- Implicit quantification only if
263 -- there is no explicit forall
264 | no_implicit_if_forall
265 , L _ (HsForAllTy {}) <- hs_ty = []
266 | otherwise = freeKiTyVarsTypeVars free_vars
267 real_rdrs = freeKiTyVarsKindVars free_vars ++ real_tv_rdrs
268 ; traceRn "rnSigType" (ppr hs_ty $$ ppr free_vars $$
269 ppr real_rdrs)
270
271 ; traceRn "" (text "rnSigType2" <+> ppr hs_ty $$ ppr free_vars $$
272 ppr real_rdrs)
273 ; vars <- mapM (newLocalBndrRn . L loc . unLoc) real_rdrs
274 ; bindLocalNamesFV vars $
275 thing_inside vars }
276
277 rnLHsInstType :: SDoc -> LHsSigType RdrName -> RnM (LHsSigType Name, FreeVars)
278 -- Rename the type in an instance or standalone deriving decl
279 -- The 'doc_str' is "an instance declaration" or "a VECTORISE pragma"
280 rnLHsInstType doc_str inst_ty
281 | Just cls <- getLHsInstDeclClass_maybe inst_ty
282 , isTcOcc (rdrNameOcc (unLoc cls))
283 -- The guards check that the instance type looks like
284 -- blah => C ty1 .. tyn
285 = do { let full_doc = doc_str <+> text "for" <+> quotes (ppr cls)
286 ; rnHsSigType (GenericCtx full_doc) inst_ty }
287
288 | otherwise -- The instance is malformed, but we'd still like
289 -- to make progress rather than failing outright, so
290 -- we report more errors. So we rename it anyway.
291 = do { addErrAt (getLoc (hsSigType inst_ty)) $
292 text "Malformed instance:" <+> ppr inst_ty
293 ; rnHsSigType (GenericCtx doc_str) inst_ty }
294
295
296 {- ******************************************************
297 * *
298 LHsType and HsType
299 * *
300 ****************************************************** -}
301
302 {-
303 rnHsType is here because we call it from loadInstDecl, and I didn't
304 want a gratuitous knot.
305
306 Note [Context quantification]
307 -----------------------------
308 Variables in type signatures are implicitly quantified
309 when (1) they are in a type signature not beginning
310 with "forall" or (2) in any qualified type T => R.
311 We are phasing out (2) since it leads to inconsistencies
312 (Trac #4426):
313
314 data A = A (a -> a) is an error
315 data A = A (Eq a => a -> a) binds "a"
316 data A = A (Eq a => a -> b) binds "a" and "b"
317 data A = A (() => a -> b) binds "a" and "b"
318 f :: forall a. a -> b is an error
319 f :: forall a. () => a -> b is an error
320 f :: forall a. a -> (() => b) binds "a" and "b"
321
322 This situation is now considered to be an error. See rnHsTyKi for case
323 HsForAllTy Qualified.
324
325 Note [Dealing with *]
326 ~~~~~~~~~~~~~~~~~~~~~
327 As a legacy from the days when types and kinds were different, we use
328 the type * to mean what we now call GHC.Types.Type. The problem is that
329 * should associate just like an identifier, *not* a symbol.
330 Running example: the user has written
331
332 T (Int, Bool) b + c * d
333
334 At this point, we have a bunch of stretches of types
335
336 [[T, (Int, Bool), b], [c], [d]]
337
338 these are the [[LHsType Name]] and a bunch of operators
339
340 [GHC.TypeLits.+, GHC.Types.*]
341
342 Note that the * is GHC.Types.*. So, we want to rearrange to have
343
344 [[T, (Int, Bool), b], [c, *, d]]
345
346 and
347
348 [GHC.TypeLits.+]
349
350 as our lists. We can then do normal fixity resolution on these. The fixities
351 must come along for the ride just so that the list stays in sync with the
352 operators.
353
354 Note [QualTy in kinds]
355 ~~~~~~~~~~~~~~~~~~~~~~
356 I was wondering whether QualTy could occur only at TypeLevel. But no,
357 we can have a qualified type in a kind too. Here is an example:
358
359 type family F a where
360 F Bool = Nat
361 F Nat = Type
362
363 type family G a where
364 G Type = Type -> Type
365 G () = Nat
366
367 data X :: forall k1 k2. (F k1 ~ G k2) => k1 -> k2 -> Type where
368 MkX :: X 'True '()
369
370 See that k1 becomes Bool and k2 becomes (), so the equality is
371 satisfied. If I write MkX :: X 'True 'False, compilation fails with a
372 suitable message:
373
374 MkX :: X 'True '()
375 • Couldn't match kind ‘G Bool’ with ‘Nat’
376 Expected kind: G Bool
377 Actual kind: F Bool
378
379 However: in a kind, the constraints in the QualTy must all be
380 equalities; or at least, any kinds with a class constraint are
381 uninhabited.
382 -}
383
384 data RnTyKiEnv
385 = RTKE { rtke_ctxt :: HsDocContext
386 , rtke_level :: TypeOrKind -- Am I renaming a type or a kind?
387 , rtke_what :: RnTyKiWhat -- And within that what am I renaming?
388 , rtke_nwcs :: NameSet -- These are the in-scope named wildcards
389 }
390
391 data RnTyKiWhat = RnTypeBody
392 | RnTopConstraint -- Top-level context of HsSigWcTypes
393 | RnConstraint -- All other constraints
394
395 instance Outputable RnTyKiEnv where
396 ppr (RTKE { rtke_level = lev, rtke_what = what
397 , rtke_nwcs = wcs, rtke_ctxt = ctxt })
398 = text "RTKE"
399 <+> braces (sep [ ppr lev, ppr what, ppr wcs
400 , pprHsDocContext ctxt ])
401
402 instance Outputable RnTyKiWhat where
403 ppr RnTypeBody = text "RnTypeBody"
404 ppr RnTopConstraint = text "RnTopConstraint"
405 ppr RnConstraint = text "RnConstraint"
406
407 mkTyKiEnv :: HsDocContext -> TypeOrKind -> RnTyKiWhat -> RnTyKiEnv
408 mkTyKiEnv cxt level what
409 = RTKE { rtke_level = level, rtke_nwcs = emptyNameSet
410 , rtke_what = what, rtke_ctxt = cxt }
411
412 isRnKindLevel :: RnTyKiEnv -> Bool
413 isRnKindLevel (RTKE { rtke_level = KindLevel }) = True
414 isRnKindLevel _ = False
415
416 --------------
417 rnLHsType :: HsDocContext -> LHsType RdrName -> RnM (LHsType Name, FreeVars)
418 rnLHsType ctxt ty = rnLHsTyKi (mkTyKiEnv ctxt TypeLevel RnTypeBody) ty
419
420 rnLHsTypes :: HsDocContext -> [LHsType RdrName] -> RnM ([LHsType Name], FreeVars)
421 rnLHsTypes doc tys = mapFvRn (rnLHsType doc) tys
422
423 rnHsType :: HsDocContext -> HsType RdrName -> RnM (HsType Name, FreeVars)
424 rnHsType ctxt ty = rnHsTyKi (mkTyKiEnv ctxt TypeLevel RnTypeBody) ty
425
426 rnLHsKind :: HsDocContext -> LHsKind RdrName -> RnM (LHsKind Name, FreeVars)
427 rnLHsKind ctxt kind = rnLHsTyKi (mkTyKiEnv ctxt KindLevel RnTypeBody) kind
428
429 rnHsKind :: HsDocContext -> HsKind RdrName -> RnM (HsKind Name, FreeVars)
430 rnHsKind ctxt kind = rnHsTyKi (mkTyKiEnv ctxt KindLevel RnTypeBody) kind
431
432 --------------
433 rnTyKiContext :: RnTyKiEnv -> LHsContext RdrName -> RnM (LHsContext Name, FreeVars)
434 rnTyKiContext env (L loc cxt)
435 = do { traceRn "rncontext" (ppr cxt)
436 ; let env' = env { rtke_what = RnConstraint }
437 ; (cxt', fvs) <- mapFvRn (rnLHsTyKi env') cxt
438 ; return (L loc cxt', fvs) }
439
440 rnContext :: HsDocContext -> LHsContext RdrName -> RnM (LHsContext Name, FreeVars)
441 rnContext doc theta = rnTyKiContext (mkTyKiEnv doc TypeLevel RnConstraint) theta
442
443 --------------
444 rnLHsTyKi :: RnTyKiEnv -> LHsType RdrName -> RnM (LHsType Name, FreeVars)
445 rnLHsTyKi env (L loc ty)
446 = setSrcSpan loc $
447 do { (ty', fvs) <- rnHsTyKi env ty
448 ; return (L loc ty', fvs) }
449
450 rnHsTyKi :: RnTyKiEnv -> HsType RdrName -> RnM (HsType Name, FreeVars)
451
452 rnHsTyKi env ty@(HsForAllTy { hst_bndrs = tyvars, hst_body = tau })
453 = do { checkTypeInType env ty
454 ; bindLHsTyVarBndrs (rtke_ctxt env) (Just $ inTypeDoc ty)
455 Nothing [] tyvars $ \ _ tyvars' _ _ ->
456 do { (tau', fvs) <- rnLHsTyKi env tau
457 ; return ( HsForAllTy { hst_bndrs = tyvars', hst_body = tau' }
458 , fvs) } }
459
460 rnHsTyKi env ty@(HsQualTy { hst_ctxt = lctxt, hst_body = tau })
461 = do { checkTypeInType env ty -- See Note [QualTy in kinds]
462 ; (ctxt', fvs1) <- rnTyKiContext env lctxt
463 ; (tau', fvs2) <- rnLHsTyKi env tau
464 ; return (HsQualTy { hst_ctxt = ctxt', hst_body = tau' }
465 , fvs1 `plusFV` fvs2) }
466
467 rnHsTyKi env (HsTyVar (L loc rdr_name))
468 = do { name <- rnTyVar env rdr_name
469 ; return (HsTyVar (L loc name), unitFV name) }
470
471 rnHsTyKi env ty@(HsOpTy ty1 l_op ty2)
472 = setSrcSpan (getLoc l_op) $
473 do { (l_op', fvs1) <- rnHsTyOp env ty l_op
474 ; fix <- lookupTyFixityRn l_op'
475 ; (ty1', fvs2) <- rnLHsTyKi env ty1
476 ; (ty2', fvs3) <- rnLHsTyKi env ty2
477 ; res_ty <- mkHsOpTyRn (\t1 t2 -> HsOpTy t1 l_op' t2)
478 (unLoc l_op') fix ty1' ty2'
479 ; return (res_ty, plusFVs [fvs1, fvs2, fvs3]) }
480
481 rnHsTyKi env (HsParTy ty)
482 = do { (ty', fvs) <- rnLHsTyKi env ty
483 ; return (HsParTy ty', fvs) }
484
485 rnHsTyKi env (HsBangTy b ty)
486 = do { (ty', fvs) <- rnLHsTyKi env ty
487 ; return (HsBangTy b ty', fvs) }
488
489 rnHsTyKi env ty@(HsRecTy flds)
490 = do { let ctxt = rtke_ctxt env
491 ; fls <- get_fields ctxt
492 ; (flds', fvs) <- rnConDeclFields ctxt fls flds
493 ; return (HsRecTy flds', fvs) }
494 where
495 get_fields (ConDeclCtx names)
496 = concatMapM (lookupConstructorFields . unLoc) names
497 get_fields _
498 = do { addErr (hang (text "Record syntax is illegal here:")
499 2 (ppr ty))
500 ; return [] }
501
502 rnHsTyKi env (HsFunTy ty1 ty2)
503 = do { (ty1', fvs1) <- rnLHsTyKi env ty1
504 -- Might find a for-all as the arg of a function type
505 ; (ty2', fvs2) <- rnLHsTyKi env ty2
506 -- Or as the result. This happens when reading Prelude.hi
507 -- when we find return :: forall m. Monad m -> forall a. a -> m a
508
509 -- Check for fixity rearrangements
510 ; res_ty <- mkHsOpTyRn HsFunTy funTyConName funTyFixity ty1' ty2'
511 ; return (res_ty, fvs1 `plusFV` fvs2) }
512
513 rnHsTyKi env listTy@(HsListTy ty)
514 = do { data_kinds <- xoptM LangExt.DataKinds
515 ; when (not data_kinds && isRnKindLevel env)
516 (addErr (dataKindsErr env listTy))
517 ; (ty', fvs) <- rnLHsTyKi env ty
518 ; return (HsListTy ty', fvs) }
519
520 rnHsTyKi env t@(HsKindSig ty k)
521 = do { checkTypeInType env t
522 ; kind_sigs_ok <- xoptM LangExt.KindSignatures
523 ; unless kind_sigs_ok (badKindSigErr (rtke_ctxt env) ty)
524 ; (ty', fvs1) <- rnLHsTyKi env ty
525 ; (k', fvs2) <- rnLHsTyKi (env { rtke_level = KindLevel }) k
526 ; return (HsKindSig ty' k', fvs1 `plusFV` fvs2) }
527
528 rnHsTyKi env t@(HsPArrTy ty)
529 = do { notInKinds env t
530 ; (ty', fvs) <- rnLHsTyKi env ty
531 ; return (HsPArrTy ty', fvs) }
532
533 -- Unboxed tuples are allowed to have poly-typed arguments. These
534 -- sometimes crop up as a result of CPR worker-wrappering dictionaries.
535 rnHsTyKi env tupleTy@(HsTupleTy tup_con tys)
536 = do { data_kinds <- xoptM LangExt.DataKinds
537 ; when (not data_kinds && isRnKindLevel env)
538 (addErr (dataKindsErr env tupleTy))
539 ; (tys', fvs) <- mapFvRn (rnLHsTyKi env) tys
540 ; return (HsTupleTy tup_con tys', fvs) }
541
542 rnHsTyKi env sumTy@(HsSumTy tys)
543 = do { data_kinds <- xoptM LangExt.DataKinds
544 ; when (not data_kinds && isRnKindLevel env)
545 (addErr (dataKindsErr env sumTy))
546 ; (tys', fvs) <- mapFvRn (rnLHsTyKi env) tys
547 ; return (HsSumTy tys', fvs) }
548
549 -- Ensure that a type-level integer is nonnegative (#8306, #8412)
550 rnHsTyKi env tyLit@(HsTyLit t)
551 = do { data_kinds <- xoptM LangExt.DataKinds
552 ; unless data_kinds (addErr (dataKindsErr env tyLit))
553 ; when (negLit t) (addErr negLitErr)
554 ; checkTypeInType env tyLit
555 ; return (HsTyLit t, emptyFVs) }
556 where
557 negLit (HsStrTy _ _) = False
558 negLit (HsNumTy _ i) = i < 0
559 negLitErr = text "Illegal literal in type (type literals must not be negative):" <+> ppr tyLit
560
561 rnHsTyKi env overall_ty@(HsAppsTy tys)
562 = do { -- Step 1: Break up the HsAppsTy into symbols and non-symbol regions
563 let (non_syms, syms) = splitHsAppsTy tys
564
565 -- Step 2: rename the pieces
566 ; (syms1, fvs1) <- mapFvRn (rnHsTyOp env overall_ty) syms
567 ; (non_syms1, fvs2) <- (mapFvRn . mapFvRn) (rnLHsTyKi env) non_syms
568
569 -- Step 3: deal with *. See Note [Dealing with *]
570 ; let (non_syms2, syms2) = deal_with_star [] [] non_syms1 syms1
571
572 -- Step 4: collapse the non-symbol regions with HsAppTy
573 ; non_syms3 <- mapM deal_with_non_syms non_syms2
574
575 -- Step 5: assemble the pieces, using mkHsOpTyRn
576 ; L _ res_ty <- build_res_ty non_syms3 syms2
577
578 -- all done. Phew.
579 ; return (res_ty, fvs1 `plusFV` fvs2) }
580 where
581 -- See Note [Dealing with *]
582 deal_with_star :: [[LHsType Name]] -> [Located Name]
583 -> [[LHsType Name]] -> [Located Name]
584 -> ([[LHsType Name]], [Located Name])
585 deal_with_star acc1 acc2
586 (non_syms1 : non_syms2 : non_syms) (L loc star : ops)
587 | star `hasKey` starKindTyConKey || star `hasKey` unicodeStarKindTyConKey
588 = deal_with_star acc1 acc2
589 ((non_syms1 ++ L loc (HsTyVar (L loc star)) : non_syms2) : non_syms)
590 ops
591 deal_with_star acc1 acc2 (non_syms1 : non_syms) (op1 : ops)
592 = deal_with_star (non_syms1 : acc1) (op1 : acc2) non_syms ops
593 deal_with_star acc1 acc2 [non_syms] []
594 = (reverse (non_syms : acc1), reverse acc2)
595 deal_with_star _ _ _ _
596 = pprPanic "deal_with_star" (ppr overall_ty)
597
598 -- collapse [LHsType Name] to LHsType Name by making applications
599 -- monadic only for failure
600 deal_with_non_syms :: [LHsType Name] -> RnM (LHsType Name)
601 deal_with_non_syms (non_sym : non_syms) = return $ mkHsAppTys non_sym non_syms
602 deal_with_non_syms [] = failWith (emptyNonSymsErr overall_ty)
603
604 -- assemble a right-biased OpTy for use in mkHsOpTyRn
605 build_res_ty :: [LHsType Name] -> [Located Name] -> RnM (LHsType Name)
606 build_res_ty (arg1 : args) (op1 : ops)
607 = do { rhs <- build_res_ty args ops
608 ; fix <- lookupTyFixityRn op1
609 ; res <-
610 mkHsOpTyRn (\t1 t2 -> HsOpTy t1 op1 t2) (unLoc op1) fix arg1 rhs
611 ; let loc = combineSrcSpans (getLoc arg1) (getLoc rhs)
612 ; return (L loc res)
613 }
614 build_res_ty [arg] [] = return arg
615 build_res_ty _ _ = pprPanic "build_op_ty" (ppr overall_ty)
616
617 rnHsTyKi env (HsAppTy ty1 ty2)
618 = do { (ty1', fvs1) <- rnLHsTyKi env ty1
619 ; (ty2', fvs2) <- rnLHsTyKi env ty2
620 ; return (HsAppTy ty1' ty2', fvs1 `plusFV` fvs2) }
621
622 rnHsTyKi env t@(HsIParamTy n ty)
623 = do { notInKinds env t
624 ; (ty', fvs) <- rnLHsTyKi env ty
625 ; return (HsIParamTy n ty', fvs) }
626
627 rnHsTyKi env t@(HsEqTy ty1 ty2)
628 = do { checkTypeInType env t
629 ; (ty1', fvs1) <- rnLHsTyKi env ty1
630 ; (ty2', fvs2) <- rnLHsTyKi env ty2
631 ; return (HsEqTy ty1' ty2', fvs1 `plusFV` fvs2) }
632
633 rnHsTyKi _ (HsSpliceTy sp k)
634 = rnSpliceType sp k
635
636 rnHsTyKi env (HsDocTy ty haddock_doc)
637 = do { (ty', fvs) <- rnLHsTyKi env ty
638 ; haddock_doc' <- rnLHsDoc haddock_doc
639 ; return (HsDocTy ty' haddock_doc', fvs) }
640
641 rnHsTyKi _ (HsCoreTy ty)
642 = return (HsCoreTy ty, emptyFVs)
643 -- The emptyFVs probably isn't quite right
644 -- but I don't think it matters
645
646 rnHsTyKi env ty@(HsExplicitListTy k tys)
647 = do { checkTypeInType env ty
648 ; data_kinds <- xoptM LangExt.DataKinds
649 ; unless data_kinds (addErr (dataKindsErr env ty))
650 ; (tys', fvs) <- mapFvRn (rnLHsTyKi env) tys
651 ; return (HsExplicitListTy k tys', fvs) }
652
653 rnHsTyKi env ty@(HsExplicitTupleTy kis tys)
654 = do { checkTypeInType env ty
655 ; data_kinds <- xoptM LangExt.DataKinds
656 ; unless data_kinds (addErr (dataKindsErr env ty))
657 ; (tys', fvs) <- mapFvRn (rnLHsTyKi env) tys
658 ; return (HsExplicitTupleTy kis tys', fvs) }
659
660 rnHsTyKi env (HsWildCardTy wc)
661 = do { checkAnonWildCard env wc
662 ; wc' <- rnAnonWildCard wc
663 ; return (HsWildCardTy wc', emptyFVs) }
664 -- emptyFVs: this occurrence does not refer to a
665 -- user-written binding site, so don't treat
666 -- it as a free variable
667
668 --------------
669 rnTyVar :: RnTyKiEnv -> RdrName -> RnM Name
670 rnTyVar env rdr_name
671 = do { name <- if isRnKindLevel env
672 then lookupKindOccRn rdr_name
673 else lookupTypeOccRn rdr_name
674 ; checkNamedWildCard env name
675 ; return name }
676
677 rnLTyVar :: Located RdrName -> RnM (Located Name)
678 -- Called externally; does not deal with wildards
679 rnLTyVar (L loc rdr_name)
680 = do { tyvar <- lookupTypeOccRn rdr_name
681 ; return (L loc tyvar) }
682
683 --------------
684 rnHsTyOp :: Outputable a
685 => RnTyKiEnv -> a -> Located RdrName -> RnM (Located Name, FreeVars)
686 rnHsTyOp env overall_ty (L loc op)
687 = do { ops_ok <- xoptM LangExt.TypeOperators
688 ; op' <- rnTyVar env op
689 ; unless (ops_ok
690 || op' == starKindTyConName
691 || op' == unicodeStarKindTyConName
692 || op' `hasKey` eqTyConKey) $
693 addErr (opTyErr op overall_ty)
694 ; let l_op' = L loc op'
695 ; return (l_op', unitFV op') }
696
697 --------------
698 notAllowed :: SDoc -> SDoc
699 notAllowed doc
700 = text "Wildcard" <+> quotes doc <+> ptext (sLit "not allowed")
701
702 checkWildCard :: RnTyKiEnv -> Maybe SDoc -> RnM ()
703 checkWildCard env (Just doc)
704 = addErr $ vcat [doc, nest 2 (text "in" <+> pprHsDocContext (rtke_ctxt env))]
705 checkWildCard _ Nothing
706 = return ()
707
708 checkAnonWildCard :: RnTyKiEnv -> HsWildCardInfo RdrName -> RnM ()
709 -- Report an error if an anonymoous wildcard is illegal here
710 checkAnonWildCard env wc
711 = checkWildCard env mb_bad
712 where
713 mb_bad :: Maybe SDoc
714 mb_bad | not (wildCardsAllowed env)
715 = Just (notAllowed (ppr wc))
716 | otherwise
717 = case rtke_what env of
718 RnTypeBody -> Nothing
719 RnConstraint -> Just constraint_msg
720 RnTopConstraint -> Just constraint_msg
721
722 constraint_msg = hang (notAllowed (ppr wc) <+> text "in a constraint")
723 2 hint_msg
724 hint_msg = vcat [ text "except as the last top-level constraint of a type signature"
725 , nest 2 (text "e.g f :: (Eq a, _) => blah") ]
726
727 checkNamedWildCard :: RnTyKiEnv -> Name -> RnM ()
728 -- Report an error if a named wildcard is illegal here
729 checkNamedWildCard env name
730 = checkWildCard env mb_bad
731 where
732 mb_bad | not (name `elemNameSet` rtke_nwcs env)
733 = Nothing -- Not a wildcard
734 | not (wildCardsAllowed env)
735 = Just (notAllowed (ppr name))
736 | otherwise
737 = case rtke_what env of
738 RnTypeBody -> Nothing -- Allowed
739 RnTopConstraint -> Nothing -- Allowed
740 RnConstraint -> Just constraint_msg
741 constraint_msg = notAllowed (ppr name) <+> text "in a constraint"
742
743 wildCardsAllowed :: RnTyKiEnv -> Bool
744 -- ^ In what contexts are wildcards permitted
745 wildCardsAllowed env
746 = case rtke_ctxt env of
747 TypeSigCtx {} -> True
748 TypBrCtx {} -> True -- Template Haskell quoted type
749 SpliceTypeCtx {} -> True -- Result of a Template Haskell splice
750 ExprWithTySigCtx {} -> True
751 PatCtx {} -> True
752 RuleCtx {} -> True
753 FamPatCtx {} -> True -- Not named wildcards though
754 GHCiCtx {} -> True
755 HsTypeCtx {} -> True
756 _ -> False
757
758 rnAnonWildCard :: HsWildCardInfo RdrName -> RnM (HsWildCardInfo Name)
759 rnAnonWildCard (AnonWildCard _)
760 = do { loc <- getSrcSpanM
761 ; uniq <- newUnique
762 ; let name = mkInternalName uniq (mkTyVarOcc "_") loc
763 ; return (AnonWildCard (L loc name)) }
764
765 ---------------
766 -- | Ensures either that we're in a type or that -XTypeInType is set
767 checkTypeInType :: Outputable ty
768 => RnTyKiEnv
769 -> ty -- ^ type
770 -> RnM ()
771 checkTypeInType env ty
772 | isRnKindLevel env
773 = do { type_in_type <- xoptM LangExt.TypeInType
774 ; unless type_in_type $
775 addErr (text "Illegal kind:" <+> ppr ty $$
776 text "Did you mean to enable TypeInType?") }
777 checkTypeInType _ _ = return ()
778
779 notInKinds :: Outputable ty
780 => RnTyKiEnv
781 -> ty
782 -> RnM ()
783 notInKinds env ty
784 | isRnKindLevel env
785 = addErr (text "Illegal kind (even with TypeInType enabled):" <+> ppr ty)
786 notInKinds _ _ = return ()
787
788 {- *****************************************************
789 * *
790 Binding type variables
791 * *
792 ***************************************************** -}
793
794 bindSigTyVarsFV :: [Name]
795 -> RnM (a, FreeVars)
796 -> RnM (a, FreeVars)
797 -- Used just before renaming the defn of a function
798 -- with a separate type signature, to bring its tyvars into scope
799 -- With no -XScopedTypeVariables, this is a no-op
800 bindSigTyVarsFV tvs thing_inside
801 = do { scoped_tyvars <- xoptM LangExt.ScopedTypeVariables
802 ; if not scoped_tyvars then
803 thing_inside
804 else
805 bindLocalNamesFV tvs thing_inside }
806
807 -- | Simply bring a bunch of RdrNames into scope. No checking for
808 -- validity, at all. The binding location is taken from the location
809 -- on each name.
810 bindLRdrNames :: [Located RdrName]
811 -> ([Name] -> RnM (a, FreeVars))
812 -> RnM (a, FreeVars)
813 bindLRdrNames rdrs thing_inside
814 = do { var_names <- mapM (newTyVarNameRn Nothing) rdrs
815 ; bindLocalNamesFV var_names $
816 thing_inside var_names }
817
818 ---------------
819 bindHsQTyVars :: forall a b.
820 HsDocContext
821 -> Maybe SDoc -- if we are to check for unused tvs,
822 -- a phrase like "in the type ..."
823 -> Maybe a -- Just _ => an associated type decl
824 -> [Located RdrName] -- Kind variables from scope, in l-to-r
825 -- order, but not from ...
826 -> (LHsQTyVars RdrName) -- ... these user-written tyvars
827 -> (LHsQTyVars Name -> NameSet -> RnM (b, FreeVars))
828 -- also returns all names used in kind signatures, for the
829 -- TypeInType clause of Note [Complete user-supplied kind
830 -- signatures] in HsDecls
831 -> RnM (b, FreeVars)
832 -- (a) Bring kind variables into scope
833 -- both (i) passed in (kv_bndrs)
834 -- and (ii) mentioned in the kinds of tv_bndrs
835 -- (b) Bring type variables into scope
836 bindHsQTyVars doc mb_in_doc mb_assoc kv_bndrs tv_bndrs thing_inside
837 = do { bindLHsTyVarBndrs doc mb_in_doc
838 mb_assoc kv_bndrs (hsQTvExplicit tv_bndrs) $
839 \ rn_kvs rn_bndrs dep_var_set all_dep_vars ->
840 thing_inside (HsQTvs { hsq_implicit = rn_kvs
841 , hsq_explicit = rn_bndrs
842 , hsq_dependent = dep_var_set }) all_dep_vars }
843
844 bindLHsTyVarBndrs :: forall a b.
845 HsDocContext
846 -> Maybe SDoc -- if we are to check for unused tvs,
847 -- a phrase like "in the type ..."
848 -> Maybe a -- Just _ => an associated type decl
849 -> [Located RdrName] -- Unbound kind variables from scope,
850 -- in l-to-r order, but not from ...
851 -> [LHsTyVarBndr RdrName] -- ... these user-written tyvars
852 -> ( [Name] -- all kv names
853 -> [LHsTyVarBndr Name]
854 -> NameSet -- which names, from the preceding list,
855 -- are used dependently within that list
856 -- See Note [Dependent LHsQTyVars] in TcHsType
857 -> NameSet -- all names used in kind signatures
858 -> RnM (b, FreeVars))
859 -> RnM (b, FreeVars)
860 bindLHsTyVarBndrs doc mb_in_doc mb_assoc kv_bndrs tv_bndrs thing_inside
861 = do { when (isNothing mb_assoc) (checkShadowedRdrNames tv_names_w_loc)
862 ; go [] [] emptyNameSet emptyNameSet emptyNameSet tv_bndrs }
863 where
864 tv_names_w_loc = map hsLTyVarLocName tv_bndrs
865
866 go :: [Name] -- kind-vars found (in reverse order)
867 -> [LHsTyVarBndr Name] -- already renamed (in reverse order)
868 -> NameSet -- kind vars already in scope (for dup checking)
869 -> NameSet -- type vars already in scope (for dup checking)
870 -> NameSet -- (all) variables used dependently
871 -> [LHsTyVarBndr RdrName] -- still to be renamed, scoped
872 -> RnM (b, FreeVars)
873 go rn_kvs rn_tvs kv_names tv_names dep_vars (tv_bndr : tv_bndrs)
874 = bindLHsTyVarBndr doc mb_assoc kv_names tv_names tv_bndr $
875 \ kv_nms used_dependently tv_bndr' ->
876 do { (b, fvs) <- go (reverse kv_nms ++ rn_kvs)
877 (tv_bndr' : rn_tvs)
878 (kv_names `extendNameSetList` kv_nms)
879 (tv_names `extendNameSet` hsLTyVarName tv_bndr')
880 (dep_vars `unionNameSet` used_dependently)
881 tv_bndrs
882 ; warn_unused tv_bndr' fvs
883 ; return (b, fvs) }
884
885 go rn_kvs rn_tvs _kv_names tv_names dep_vars []
886 = -- still need to deal with the kv_bndrs passed in originally
887 bindImplicitKvs doc mb_assoc kv_bndrs tv_names $ \ kv_nms others ->
888 do { let all_rn_kvs = reverse (reverse kv_nms ++ rn_kvs)
889 all_rn_tvs = reverse rn_tvs
890 ; env <- getLocalRdrEnv
891 ; let all_dep_vars = dep_vars `unionNameSet` others
892 exp_dep_vars -- variables in all_rn_tvs that are in dep_vars
893 = mkNameSet [ name
894 | v <- all_rn_tvs
895 , let name = hsLTyVarName v
896 , name `elemNameSet` all_dep_vars ]
897 ; traceRn "bindHsTyVars" (ppr env $$
898 ppr all_rn_kvs $$
899 ppr all_rn_tvs $$
900 ppr exp_dep_vars)
901 ; thing_inside all_rn_kvs all_rn_tvs exp_dep_vars all_dep_vars }
902
903 warn_unused tv_bndr fvs = case mb_in_doc of
904 Just in_doc -> warnUnusedForAll in_doc tv_bndr fvs
905 Nothing -> return ()
906
907 bindLHsTyVarBndr :: HsDocContext
908 -> Maybe a -- associated class
909 -> NameSet -- kind vars already in scope
910 -> NameSet -- type vars already in scope
911 -> LHsTyVarBndr RdrName
912 -> ([Name] -> NameSet -> LHsTyVarBndr Name -> RnM (b, FreeVars))
913 -- passed the newly-bound implicitly-declared kind vars,
914 -- any other names used in a kind
915 -- and the renamed LHsTyVarBndr
916 -> RnM (b, FreeVars)
917 bindLHsTyVarBndr doc mb_assoc kv_names tv_names hs_tv_bndr thing_inside
918 = case hs_tv_bndr of
919 L loc (UserTyVar lrdr@(L lv rdr)) ->
920 do { check_dup loc rdr
921 ; nm <- newTyVarNameRn mb_assoc lrdr
922 ; bindLocalNamesFV [nm] $
923 thing_inside [] emptyNameSet (L loc (UserTyVar (L lv nm))) }
924 L loc (KindedTyVar lrdr@(L lv rdr) kind) ->
925 do { check_dup lv rdr
926
927 -- check for -XKindSignatures
928 ; sig_ok <- xoptM LangExt.KindSignatures
929 ; unless sig_ok (badKindSigErr doc kind)
930
931 -- deal with kind vars in the user-written kind
932 ; free_kvs <- freeKiTyVarsAllVars <$> extractHsTyRdrTyVars kind
933 ; bindImplicitKvs doc mb_assoc free_kvs tv_names $
934 \ new_kv_nms other_kv_nms ->
935 do { (kind', fvs1) <- rnLHsKind doc kind
936 ; tv_nm <- newTyVarNameRn mb_assoc lrdr
937 ; (b, fvs2) <- bindLocalNamesFV [tv_nm] $
938 thing_inside new_kv_nms other_kv_nms
939 (L loc (KindedTyVar (L lv tv_nm) kind'))
940 ; return (b, fvs1 `plusFV` fvs2) }}
941 where
942 -- make sure that the RdrName isn't in the sets of
943 -- names. We can't just check that it's not in scope at all
944 -- because we might be inside an associated class.
945 check_dup :: SrcSpan -> RdrName -> RnM ()
946 check_dup loc rdr
947 = do { m_name <- lookupLocalOccRn_maybe rdr
948 ; whenIsJust m_name $ \name ->
949 do { when (name `elemNameSet` kv_names) $
950 addErrAt loc (vcat [ ki_ty_err_msg name
951 , pprHsDocContext doc ])
952 ; when (name `elemNameSet` tv_names) $
953 dupNamesErr getLoc [L loc name, L (nameSrcSpan name) name] }}
954
955 ki_ty_err_msg n = text "Variable" <+> quotes (ppr n) <+>
956 text "used as a kind variable before being bound" $$
957 text "as a type variable. Perhaps reorder your variables?"
958
959
960 bindImplicitKvs :: HsDocContext
961 -> Maybe a
962 -> [Located RdrName] -- ^ kind var *occurrences*, from which
963 -- intent to bind is inferred
964 -> NameSet -- ^ *type* variables, for type/kind
965 -- misuse check for -XNoTypeInType
966 -> ([Name] -> NameSet -> RnM (b, FreeVars))
967 -- ^ passed new kv_names, and any other names used in a kind
968 -> RnM (b, FreeVars)
969 bindImplicitKvs _ _ [] _ thing_inside
970 = thing_inside [] emptyNameSet
971 bindImplicitKvs doc mb_assoc free_kvs tv_names thing_inside
972 = do { rdr_env <- getLocalRdrEnv
973 ; let part_kvs lrdr@(L loc kv_rdr)
974 = case lookupLocalRdrEnv rdr_env kv_rdr of
975 Just kv_name -> Left (L loc kv_name)
976 _ -> Right lrdr
977 (bound_kvs, new_kvs) = partitionWith part_kvs free_kvs
978
979 -- check whether we're mixing types & kinds illegally
980 ; type_in_type <- xoptM LangExt.TypeInType
981 ; unless type_in_type $
982 mapM_ (check_tv_used_in_kind tv_names) bound_kvs
983
984 ; poly_kinds <- xoptM LangExt.PolyKinds
985 ; unless poly_kinds $
986 addErr (badKindBndrs doc new_kvs)
987
988 -- bind the vars and move on
989 ; kv_nms <- mapM (newTyVarNameRn mb_assoc) new_kvs
990 ; bindLocalNamesFV kv_nms $
991 thing_inside kv_nms (mkNameSet (map unLoc bound_kvs)) }
992 where
993 -- check to see if the variables free in a kind are bound as type
994 -- variables. Assume -XNoTypeInType.
995 check_tv_used_in_kind :: NameSet -- ^ *type* variables
996 -> Located Name -- ^ renamed var used in kind
997 -> RnM ()
998 check_tv_used_in_kind tv_names (L loc kv_name)
999 = when (kv_name `elemNameSet` tv_names) $
1000 addErrAt loc (vcat [ text "Type variable" <+> quotes (ppr kv_name) <+>
1001 text "used in a kind." $$
1002 text "Did you mean to use TypeInType?"
1003 , pprHsDocContext doc ])
1004
1005
1006 newTyVarNameRn :: Maybe a -> Located RdrName -> RnM Name
1007 newTyVarNameRn mb_assoc (L loc rdr)
1008 = do { rdr_env <- getLocalRdrEnv
1009 ; case (mb_assoc, lookupLocalRdrEnv rdr_env rdr) of
1010 (Just _, Just n) -> return n
1011 -- Use the same Name as the parent class decl
1012
1013 _ -> newLocalBndrRn (L loc rdr) }
1014
1015 ---------------------
1016 collectAnonWildCards :: LHsType Name -> [Name]
1017 -- | Extract all wild cards from a type.
1018 collectAnonWildCards lty = go lty
1019 where
1020 go (L _ ty) = case ty of
1021 HsWildCardTy (AnonWildCard (L _ wc)) -> [wc]
1022 HsAppsTy tys -> gos (mapMaybe (prefix_types_only . unLoc) tys)
1023 HsAppTy ty1 ty2 -> go ty1 `mappend` go ty2
1024 HsFunTy ty1 ty2 -> go ty1 `mappend` go ty2
1025 HsListTy ty -> go ty
1026 HsPArrTy ty -> go ty
1027 HsTupleTy _ tys -> gos tys
1028 HsOpTy ty1 _ ty2 -> go ty1 `mappend` go ty2
1029 HsParTy ty -> go ty
1030 HsIParamTy _ ty -> go ty
1031 HsEqTy ty1 ty2 -> go ty1 `mappend` go ty2
1032 HsKindSig ty kind -> go ty `mappend` go kind
1033 HsDocTy ty _ -> go ty
1034 HsBangTy _ ty -> go ty
1035 HsRecTy flds -> gos $ map (cd_fld_type . unLoc) flds
1036 HsExplicitListTy _ tys -> gos tys
1037 HsExplicitTupleTy _ tys -> gos tys
1038 HsForAllTy { hst_bndrs = bndrs
1039 , hst_body = ty } -> collectAnonWildCardsBndrs bndrs
1040 `mappend` go ty
1041 HsQualTy { hst_ctxt = L _ ctxt
1042 , hst_body = ty } -> gos ctxt `mappend` go ty
1043 HsSpliceTy (HsSpliced _ (HsSplicedTy ty)) _ -> go $ L noSrcSpan ty
1044 -- HsQuasiQuoteTy, HsSpliceTy, HsCoreTy, HsTyLit
1045 _ -> mempty
1046
1047 gos = mconcat . map go
1048
1049 prefix_types_only (HsAppPrefix ty) = Just ty
1050 prefix_types_only (HsAppInfix _) = Nothing
1051
1052 collectAnonWildCardsBndrs :: [LHsTyVarBndr Name] -> [Name]
1053 collectAnonWildCardsBndrs ltvs = concatMap (go . unLoc) ltvs
1054 where
1055 go (UserTyVar _) = []
1056 go (KindedTyVar _ ki) = collectAnonWildCards ki
1057
1058 {-
1059 *********************************************************
1060 * *
1061 ConDeclField
1062 * *
1063 *********************************************************
1064
1065 When renaming a ConDeclField, we have to find the FieldLabel
1066 associated with each field. But we already have all the FieldLabels
1067 available (since they were brought into scope by
1068 RnNames.getLocalNonValBinders), so we just take the list as an
1069 argument, build a map and look them up.
1070 -}
1071
1072 rnConDeclFields :: HsDocContext -> [FieldLabel] -> [LConDeclField RdrName]
1073 -> RnM ([LConDeclField Name], FreeVars)
1074 -- Also called from RnSource
1075 -- No wildcards can appear in record fields
1076 rnConDeclFields ctxt fls fields
1077 = mapFvRn (rnField fl_env env) fields
1078 where
1079 env = mkTyKiEnv ctxt TypeLevel RnTypeBody
1080 fl_env = mkFsEnv [ (flLabel fl, fl) | fl <- fls ]
1081
1082 rnField :: FastStringEnv FieldLabel -> RnTyKiEnv -> LConDeclField RdrName
1083 -> RnM (LConDeclField Name, FreeVars)
1084 rnField fl_env env (L l (ConDeclField names ty haddock_doc))
1085 = do { let new_names = map (fmap lookupField) names
1086 ; (new_ty, fvs) <- rnLHsTyKi env ty
1087 ; new_haddock_doc <- rnMbLHsDoc haddock_doc
1088 ; return (L l (ConDeclField new_names new_ty new_haddock_doc), fvs) }
1089 where
1090 lookupField :: FieldOcc RdrName -> FieldOcc Name
1091 lookupField (FieldOcc (L lr rdr) _) = FieldOcc (L lr rdr) (flSelector fl)
1092 where
1093 lbl = occNameFS $ rdrNameOcc rdr
1094 fl = expectJust "rnField" $ lookupFsEnv fl_env lbl
1095
1096 {-
1097 ************************************************************************
1098 * *
1099 Fixities and precedence parsing
1100 * *
1101 ************************************************************************
1102
1103 @mkOpAppRn@ deals with operator fixities. The argument expressions
1104 are assumed to be already correctly arranged. It needs the fixities
1105 recorded in the OpApp nodes, because fixity info applies to the things
1106 the programmer actually wrote, so you can't find it out from the Name.
1107
1108 Furthermore, the second argument is guaranteed not to be another
1109 operator application. Why? Because the parser parses all
1110 operator appications left-associatively, EXCEPT negation, which
1111 we need to handle specially.
1112 Infix types are read in a *right-associative* way, so that
1113 a `op` b `op` c
1114 is always read in as
1115 a `op` (b `op` c)
1116
1117 mkHsOpTyRn rearranges where necessary. The two arguments
1118 have already been renamed and rearranged. It's made rather tiresome
1119 by the presence of ->, which is a separate syntactic construct.
1120 -}
1121
1122 ---------------
1123 -- Building (ty1 `op1` (ty21 `op2` ty22))
1124 mkHsOpTyRn :: (LHsType Name -> LHsType Name -> HsType Name)
1125 -> Name -> Fixity -> LHsType Name -> LHsType Name
1126 -> RnM (HsType Name)
1127
1128 mkHsOpTyRn mk1 pp_op1 fix1 ty1 (L loc2 (HsOpTy ty21 op2 ty22))
1129 = do { fix2 <- lookupTyFixityRn op2
1130 ; mk_hs_op_ty mk1 pp_op1 fix1 ty1
1131 (\t1 t2 -> HsOpTy t1 op2 t2)
1132 (unLoc op2) fix2 ty21 ty22 loc2 }
1133
1134 mkHsOpTyRn mk1 pp_op1 fix1 ty1 (L loc2 (HsFunTy ty21 ty22))
1135 = mk_hs_op_ty mk1 pp_op1 fix1 ty1
1136 HsFunTy funTyConName funTyFixity ty21 ty22 loc2
1137
1138 mkHsOpTyRn mk1 _ _ ty1 ty2 -- Default case, no rearrangment
1139 = return (mk1 ty1 ty2)
1140
1141 ---------------
1142 mk_hs_op_ty :: (LHsType Name -> LHsType Name -> HsType Name)
1143 -> Name -> Fixity -> LHsType Name
1144 -> (LHsType Name -> LHsType Name -> HsType Name)
1145 -> Name -> Fixity -> LHsType Name -> LHsType Name -> SrcSpan
1146 -> RnM (HsType Name)
1147 mk_hs_op_ty mk1 op1 fix1 ty1
1148 mk2 op2 fix2 ty21 ty22 loc2
1149 | nofix_error = do { precParseErr (op1,fix1) (op2,fix2)
1150 ; return (mk1 ty1 (L loc2 (mk2 ty21 ty22))) }
1151 | associate_right = return (mk1 ty1 (L loc2 (mk2 ty21 ty22)))
1152 | otherwise = do { -- Rearrange to ((ty1 `op1` ty21) `op2` ty22)
1153 new_ty <- mkHsOpTyRn mk1 op1 fix1 ty1 ty21
1154 ; return (mk2 (noLoc new_ty) ty22) }
1155 where
1156 (nofix_error, associate_right) = compareFixity fix1 fix2
1157
1158
1159 ---------------------------
1160 mkOpAppRn :: LHsExpr Name -- Left operand; already rearranged
1161 -> LHsExpr Name -> Fixity -- Operator and fixity
1162 -> LHsExpr Name -- Right operand (not an OpApp, but might
1163 -- be a NegApp)
1164 -> RnM (HsExpr Name)
1165
1166 -- (e11 `op1` e12) `op2` e2
1167 mkOpAppRn e1@(L _ (OpApp e11 op1 fix1 e12)) op2 fix2 e2
1168 | nofix_error
1169 = do precParseErr (get_op op1,fix1) (get_op op2,fix2)
1170 return (OpApp e1 op2 fix2 e2)
1171
1172 | associate_right = do
1173 new_e <- mkOpAppRn e12 op2 fix2 e2
1174 return (OpApp e11 op1 fix1 (L loc' new_e))
1175 where
1176 loc'= combineLocs e12 e2
1177 (nofix_error, associate_right) = compareFixity fix1 fix2
1178
1179 ---------------------------
1180 -- (- neg_arg) `op` e2
1181 mkOpAppRn e1@(L _ (NegApp neg_arg neg_name)) op2 fix2 e2
1182 | nofix_error
1183 = do precParseErr (negateName,negateFixity) (get_op op2,fix2)
1184 return (OpApp e1 op2 fix2 e2)
1185
1186 | associate_right
1187 = do new_e <- mkOpAppRn neg_arg op2 fix2 e2
1188 return (NegApp (L loc' new_e) neg_name)
1189 where
1190 loc' = combineLocs neg_arg e2
1191 (nofix_error, associate_right) = compareFixity negateFixity fix2
1192
1193 ---------------------------
1194 -- e1 `op` - neg_arg
1195 mkOpAppRn e1 op1 fix1 e2@(L _ (NegApp _ _)) -- NegApp can occur on the right
1196 | not associate_right -- We *want* right association
1197 = do precParseErr (get_op op1, fix1) (negateName, negateFixity)
1198 return (OpApp e1 op1 fix1 e2)
1199 where
1200 (_, associate_right) = compareFixity fix1 negateFixity
1201
1202 ---------------------------
1203 -- Default case
1204 mkOpAppRn e1 op fix e2 -- Default case, no rearrangment
1205 = ASSERT2( right_op_ok fix (unLoc e2),
1206 ppr e1 $$ text "---" $$ ppr op $$ text "---" $$ ppr fix $$ text "---" $$ ppr e2
1207 )
1208 return (OpApp e1 op fix e2)
1209
1210 ----------------------------
1211 get_op :: LHsExpr Name -> Name
1212 -- An unbound name could be either HsVar or HsUnboundVar
1213 -- See RnExpr.rnUnboundVar
1214 get_op (L _ (HsVar (L _ n))) = n
1215 get_op (L _ (HsUnboundVar uv)) = mkUnboundName (unboundVarOcc uv)
1216 get_op other = pprPanic "get_op" (ppr other)
1217
1218 -- Parser left-associates everything, but
1219 -- derived instances may have correctly-associated things to
1220 -- in the right operarand. So we just check that the right operand is OK
1221 right_op_ok :: Fixity -> HsExpr Name -> Bool
1222 right_op_ok fix1 (OpApp _ _ fix2 _)
1223 = not error_please && associate_right
1224 where
1225 (error_please, associate_right) = compareFixity fix1 fix2
1226 right_op_ok _ _
1227 = True
1228
1229 -- Parser initially makes negation bind more tightly than any other operator
1230 -- And "deriving" code should respect this (use HsPar if not)
1231 mkNegAppRn :: LHsExpr id -> SyntaxExpr id -> RnM (HsExpr id)
1232 mkNegAppRn neg_arg neg_name
1233 = ASSERT( not_op_app (unLoc neg_arg) )
1234 return (NegApp neg_arg neg_name)
1235
1236 not_op_app :: HsExpr id -> Bool
1237 not_op_app (OpApp _ _ _ _) = False
1238 not_op_app _ = True
1239
1240 ---------------------------
1241 mkOpFormRn :: LHsCmdTop Name -- Left operand; already rearranged
1242 -> LHsExpr Name -> Fixity -- Operator and fixity
1243 -> LHsCmdTop Name -- Right operand (not an infix)
1244 -> RnM (HsCmd Name)
1245
1246 -- (e11 `op1` e12) `op2` e2
1247 mkOpFormRn a1@(L loc (HsCmdTop (L _ (HsCmdArrForm op1 (Just fix1) [a11,a12])) _ _ _))
1248 op2 fix2 a2
1249 | nofix_error
1250 = do precParseErr (get_op op1,fix1) (get_op op2,fix2)
1251 return (HsCmdArrForm op2 (Just fix2) [a1, a2])
1252
1253 | associate_right
1254 = do new_c <- mkOpFormRn a12 op2 fix2 a2
1255 return (HsCmdArrForm op1 (Just fix1)
1256 [a11, L loc (HsCmdTop (L loc new_c)
1257 placeHolderType placeHolderType [])])
1258 -- TODO: locs are wrong
1259 where
1260 (nofix_error, associate_right) = compareFixity fix1 fix2
1261
1262 -- Default case
1263 mkOpFormRn arg1 op fix arg2 -- Default case, no rearrangment
1264 = return (HsCmdArrForm op (Just fix) [arg1, arg2])
1265
1266
1267 --------------------------------------
1268 mkConOpPatRn :: Located Name -> Fixity -> LPat Name -> LPat Name
1269 -> RnM (Pat Name)
1270
1271 mkConOpPatRn op2 fix2 p1@(L loc (ConPatIn op1 (InfixCon p11 p12))) p2
1272 = do { fix1 <- lookupFixityRn (unLoc op1)
1273 ; let (nofix_error, associate_right) = compareFixity fix1 fix2
1274
1275 ; if nofix_error then do
1276 { precParseErr (unLoc op1,fix1) (unLoc op2,fix2)
1277 ; return (ConPatIn op2 (InfixCon p1 p2)) }
1278
1279 else if associate_right then do
1280 { new_p <- mkConOpPatRn op2 fix2 p12 p2
1281 ; return (ConPatIn op1 (InfixCon p11 (L loc new_p))) } -- XXX loc right?
1282 else return (ConPatIn op2 (InfixCon p1 p2)) }
1283
1284 mkConOpPatRn op _ p1 p2 -- Default case, no rearrangment
1285 = ASSERT( not_op_pat (unLoc p2) )
1286 return (ConPatIn op (InfixCon p1 p2))
1287
1288 not_op_pat :: Pat Name -> Bool
1289 not_op_pat (ConPatIn _ (InfixCon _ _)) = False
1290 not_op_pat _ = True
1291
1292 --------------------------------------
1293 checkPrecMatch :: Name -> MatchGroup Name body -> RnM ()
1294 -- Check precedence of a function binding written infix
1295 -- eg a `op` b `C` c = ...
1296 -- See comments with rnExpr (OpApp ...) about "deriving"
1297
1298 checkPrecMatch op (MG { mg_alts = L _ ms })
1299 = mapM_ check ms
1300 where
1301 check (L _ (Match _ (L l1 p1 : L l2 p2 :_) _ _))
1302 = setSrcSpan (combineSrcSpans l1 l2) $
1303 do checkPrec op p1 False
1304 checkPrec op p2 True
1305
1306 check _ = return ()
1307 -- This can happen. Consider
1308 -- a `op` True = ...
1309 -- op = ...
1310 -- The infix flag comes from the first binding of the group
1311 -- but the second eqn has no args (an error, but not discovered
1312 -- until the type checker). So we don't want to crash on the
1313 -- second eqn.
1314
1315 checkPrec :: Name -> Pat Name -> Bool -> IOEnv (Env TcGblEnv TcLclEnv) ()
1316 checkPrec op (ConPatIn op1 (InfixCon _ _)) right = do
1317 op_fix@(Fixity _ op_prec op_dir) <- lookupFixityRn op
1318 op1_fix@(Fixity _ op1_prec op1_dir) <- lookupFixityRn (unLoc op1)
1319 let
1320 inf_ok = op1_prec > op_prec ||
1321 (op1_prec == op_prec &&
1322 (op1_dir == InfixR && op_dir == InfixR && right ||
1323 op1_dir == InfixL && op_dir == InfixL && not right))
1324
1325 info = (op, op_fix)
1326 info1 = (unLoc op1, op1_fix)
1327 (infol, infor) = if right then (info, info1) else (info1, info)
1328 unless inf_ok (precParseErr infol infor)
1329
1330 checkPrec _ _ _
1331 = return ()
1332
1333 -- Check precedence of (arg op) or (op arg) respectively
1334 -- If arg is itself an operator application, then either
1335 -- (a) its precedence must be higher than that of op
1336 -- (b) its precedency & associativity must be the same as that of op
1337 checkSectionPrec :: FixityDirection -> HsExpr RdrName
1338 -> LHsExpr Name -> LHsExpr Name -> RnM ()
1339 checkSectionPrec direction section op arg
1340 = case unLoc arg of
1341 OpApp _ op fix _ -> go_for_it (get_op op) fix
1342 NegApp _ _ -> go_for_it negateName negateFixity
1343 _ -> return ()
1344 where
1345 op_name = get_op op
1346 go_for_it arg_op arg_fix@(Fixity _ arg_prec assoc) = do
1347 op_fix@(Fixity _ op_prec _) <- lookupFixityRn op_name
1348 unless (op_prec < arg_prec
1349 || (op_prec == arg_prec && direction == assoc))
1350 (sectionPrecErr (op_name, op_fix)
1351 (arg_op, arg_fix) section)
1352
1353 -- Precedence-related error messages
1354
1355 precParseErr :: (Name, Fixity) -> (Name, Fixity) -> RnM ()
1356 precParseErr op1@(n1,_) op2@(n2,_)
1357 | isUnboundName n1 || isUnboundName n2
1358 = return () -- Avoid error cascade
1359 | otherwise
1360 = addErr $ hang (text "Precedence parsing error")
1361 4 (hsep [text "cannot mix", ppr_opfix op1, ptext (sLit "and"),
1362 ppr_opfix op2,
1363 text "in the same infix expression"])
1364
1365 sectionPrecErr :: (Name, Fixity) -> (Name, Fixity) -> HsExpr RdrName -> RnM ()
1366 sectionPrecErr op@(n1,_) arg_op@(n2,_) section
1367 | isUnboundName n1 || isUnboundName n2
1368 = return () -- Avoid error cascade
1369 | otherwise
1370 = addErr $ vcat [text "The operator" <+> ppr_opfix op <+> ptext (sLit "of a section"),
1371 nest 4 (sep [text "must have lower precedence than that of the operand,",
1372 nest 2 (text "namely" <+> ppr_opfix arg_op)]),
1373 nest 4 (text "in the section:" <+> quotes (ppr section))]
1374
1375 ppr_opfix :: (Name, Fixity) -> SDoc
1376 ppr_opfix (op, fixity) = pp_op <+> brackets (ppr fixity)
1377 where
1378 pp_op | op == negateName = text "prefix `-'"
1379 | otherwise = quotes (ppr op)
1380
1381 {- *****************************************************
1382 * *
1383 Errors
1384 * *
1385 ***************************************************** -}
1386
1387 unexpectedTypeSigErr :: LHsSigWcType RdrName -> SDoc
1388 unexpectedTypeSigErr ty
1389 = hang (text "Illegal type signature:" <+> quotes (ppr ty))
1390 2 (text "Type signatures are only allowed in patterns with ScopedTypeVariables")
1391
1392 badKindBndrs :: HsDocContext -> [Located RdrName] -> SDoc
1393 badKindBndrs doc kvs
1394 = withHsDocContext doc $
1395 hang (text "Unexpected kind variable" <> plural kvs
1396 <+> pprQuotedList kvs)
1397 2 (text "Perhaps you intended to use PolyKinds")
1398
1399 badKindSigErr :: HsDocContext -> LHsType RdrName -> TcM ()
1400 badKindSigErr doc (L loc ty)
1401 = setSrcSpan loc $ addErr $
1402 withHsDocContext doc $
1403 hang (text "Illegal kind signature:" <+> quotes (ppr ty))
1404 2 (text "Perhaps you intended to use KindSignatures")
1405
1406 dataKindsErr :: RnTyKiEnv -> HsType RdrName -> SDoc
1407 dataKindsErr env thing
1408 = hang (text "Illegal" <+> pp_what <> colon <+> quotes (ppr thing))
1409 2 (text "Perhaps you intended to use DataKinds")
1410 where
1411 pp_what | isRnKindLevel env = text "kind"
1412 | otherwise = text "type"
1413
1414 inTypeDoc :: HsType RdrName -> SDoc
1415 inTypeDoc ty = text "In the type" <+> quotes (ppr ty)
1416
1417 warnUnusedForAll :: SDoc -> LHsTyVarBndr Name -> FreeVars -> TcM ()
1418 warnUnusedForAll in_doc (L loc tv) used_names
1419 = whenWOptM Opt_WarnUnusedForalls $
1420 unless (hsTyVarName tv `elemNameSet` used_names) $
1421 addWarnAt (Reason Opt_WarnUnusedForalls) loc $
1422 vcat [ text "Unused quantified type variable" <+> quotes (ppr tv)
1423 , in_doc ]
1424
1425 opTyErr :: Outputable a => RdrName -> a -> SDoc
1426 opTyErr op overall_ty
1427 = hang (text "Illegal operator" <+> quotes (ppr op) <+> ptext (sLit "in type") <+> quotes (ppr overall_ty))
1428 2 extra
1429 where
1430 extra | op == dot_tv_RDR
1431 = perhapsForallMsg
1432 | otherwise
1433 = text "Use TypeOperators to allow operators in types"
1434
1435 emptyNonSymsErr :: HsType RdrName -> SDoc
1436 emptyNonSymsErr overall_ty
1437 = text "Operator applied to too few arguments:" <+> ppr overall_ty
1438
1439 {-
1440 ************************************************************************
1441 * *
1442 Finding the free type variables of a (HsType RdrName)
1443 * *
1444 ************************************************************************
1445
1446
1447 Note [Kind and type-variable binders]
1448 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1449 In a type signature we may implicitly bind type variable and, more
1450 recently, kind variables. For example:
1451 * f :: a -> a
1452 f = ...
1453 Here we need to find the free type variables of (a -> a),
1454 so that we know what to quantify
1455
1456 * class C (a :: k) where ...
1457 This binds 'k' in ..., as well as 'a'
1458
1459 * f (x :: a -> [a]) = ....
1460 Here we bind 'a' in ....
1461
1462 * f (x :: T a -> T (b :: k)) = ...
1463 Here we bind both 'a' and the kind variable 'k'
1464
1465 * type instance F (T (a :: Maybe k)) = ...a...k...
1466 Here we want to constrain the kind of 'a', and bind 'k'.
1467
1468 In general we want to walk over a type, and find
1469 * Its free type variables
1470 * The free kind variables of any kind signatures in the type
1471
1472 Hence we returns a pair (kind-vars, type vars)
1473 See also Note [HsBSig binder lists] in HsTypes
1474 -}
1475
1476 data FreeKiTyVars = FKTV { fktv_kis :: [Located RdrName]
1477 , _fktv_k_set :: OccSet -- for efficiency,
1478 -- only used internally
1479 , fktv_tys :: [Located RdrName]
1480 , _fktv_t_set :: OccSet
1481 , fktv_all :: [Located RdrName] }
1482
1483 instance Outputable FreeKiTyVars where
1484 ppr (FKTV kis _ tys _ _) = ppr (kis, tys)
1485
1486 emptyFKTV :: FreeKiTyVars
1487 emptyFKTV = FKTV [] emptyOccSet [] emptyOccSet []
1488
1489 freeKiTyVarsAllVars :: FreeKiTyVars -> [Located RdrName]
1490 freeKiTyVarsAllVars = fktv_all
1491
1492 freeKiTyVarsKindVars :: FreeKiTyVars -> [Located RdrName]
1493 freeKiTyVarsKindVars = fktv_kis
1494
1495 freeKiTyVarsTypeVars :: FreeKiTyVars -> [Located RdrName]
1496 freeKiTyVarsTypeVars = fktv_tys
1497
1498 filterInScope :: LocalRdrEnv -> FreeKiTyVars -> FreeKiTyVars
1499 filterInScope rdr_env (FKTV kis k_set tys t_set all)
1500 = FKTV (filterOut in_scope kis)
1501 (filterOccSet (not . in_scope_occ) k_set)
1502 (filterOut in_scope tys)
1503 (filterOccSet (not . in_scope_occ) t_set)
1504 (filterOut in_scope all)
1505 where
1506 in_scope = inScope rdr_env . unLoc
1507 in_scope_occ occ = isJust $ lookupLocalRdrOcc rdr_env occ
1508
1509 inScope :: LocalRdrEnv -> RdrName -> Bool
1510 inScope rdr_env rdr = rdr `elemLocalRdrEnv` rdr_env
1511
1512 extractHsTyRdrTyVars :: LHsType RdrName -> RnM FreeKiTyVars
1513 -- extractHsTyRdrNames finds the free (kind, type) variables of a HsType
1514 -- or the free (sort, kind) variables of a HsKind
1515 -- It's used when making the for-alls explicit.
1516 -- Does not return any wildcards
1517 -- When the same name occurs multiple times in the types, only the first
1518 -- occurence is returned.
1519 -- See Note [Kind and type-variable binders]
1520 extractHsTyRdrTyVars ty
1521 = do { FKTV kis k_set tys t_set all <- extract_lty TypeLevel ty emptyFKTV
1522 ; return (FKTV (nubL kis) k_set
1523 (nubL tys) t_set
1524 (nubL all)) }
1525
1526 -- | Extracts free type and kind variables from types in a list.
1527 -- When the same name occurs multiple times in the types, only the first
1528 -- occurence is returned and the rest is filtered out.
1529 -- See Note [Kind and type-variable binders]
1530 extractHsTysRdrTyVars :: [LHsType RdrName] -> RnM FreeKiTyVars
1531 extractHsTysRdrTyVars tys
1532 = rmDupsInRdrTyVars <$> extractHsTysRdrTyVarsDups tys
1533
1534 -- | Extracts free type and kind variables from types in a list.
1535 -- When the same name occurs multiple times in the types, all occurences
1536 -- are returned.
1537 extractHsTysRdrTyVarsDups :: [LHsType RdrName] -> RnM FreeKiTyVars
1538 extractHsTysRdrTyVarsDups tys
1539 = extract_ltys TypeLevel tys emptyFKTV
1540
1541 -- | Removes multiple occurences of the same name from FreeKiTyVars.
1542 rmDupsInRdrTyVars :: FreeKiTyVars -> FreeKiTyVars
1543 rmDupsInRdrTyVars (FKTV kis k_set tys t_set all)
1544 = FKTV (nubL kis) k_set (nubL tys) t_set (nubL all)
1545
1546 extractRdrKindSigVars :: LFamilyResultSig RdrName -> RnM [Located RdrName]
1547 extractRdrKindSigVars (L _ resultSig)
1548 | KindSig k <- resultSig = kindRdrNameFromSig k
1549 | TyVarSig (L _ (KindedTyVar _ k)) <- resultSig = kindRdrNameFromSig k
1550 | otherwise = return []
1551 where kindRdrNameFromSig k = freeKiTyVarsAllVars <$> extractHsTyRdrTyVars k
1552
1553 extractDataDefnKindVars :: HsDataDefn RdrName -> RnM [Located RdrName]
1554 -- Get the scoped kind variables mentioned free in the constructor decls
1555 -- Eg data T a = T1 (S (a :: k) | forall (b::k). T2 (S b)
1556 -- Here k should scope over the whole definition
1557 extractDataDefnKindVars (HsDataDefn { dd_ctxt = ctxt, dd_kindSig = ksig
1558 , dd_cons = cons, dd_derivs = L _ derivs })
1559 = (nubL . freeKiTyVarsKindVars) <$>
1560 (extract_lctxt TypeLevel ctxt =<<
1561 extract_mb extract_lkind ksig =<<
1562 extract_sig_tys (concatMap (unLoc . deriv_clause_tys . unLoc) derivs) =<<
1563 foldrM (extract_con . unLoc) emptyFKTV cons)
1564 where
1565 extract_con (ConDeclGADT { }) acc = return acc
1566 extract_con (ConDeclH98 { con_qvars = qvs
1567 , con_cxt = ctxt, con_details = details }) acc
1568 = extract_hs_tv_bndrs (maybe [] hsQTvExplicit qvs) acc =<<
1569 extract_mlctxt ctxt =<<
1570 extract_ltys TypeLevel (hsConDeclArgTys details) emptyFKTV
1571
1572 extract_mlctxt :: Maybe (LHsContext RdrName) -> FreeKiTyVars -> RnM FreeKiTyVars
1573 extract_mlctxt Nothing acc = return acc
1574 extract_mlctxt (Just ctxt) acc = extract_lctxt TypeLevel ctxt acc
1575
1576 extract_lctxt :: TypeOrKind
1577 -> LHsContext RdrName -> FreeKiTyVars -> RnM FreeKiTyVars
1578 extract_lctxt t_or_k ctxt = extract_ltys t_or_k (unLoc ctxt)
1579
1580 extract_sig_tys :: [LHsSigType RdrName] -> FreeKiTyVars -> RnM FreeKiTyVars
1581 extract_sig_tys sig_tys acc
1582 = foldrM (\sig_ty acc -> extract_lty TypeLevel (hsSigType sig_ty) acc)
1583 acc sig_tys
1584
1585 extract_ltys :: TypeOrKind
1586 -> [LHsType RdrName] -> FreeKiTyVars -> RnM FreeKiTyVars
1587 extract_ltys t_or_k tys acc = foldrM (extract_lty t_or_k) acc tys
1588
1589 extract_mb :: (a -> FreeKiTyVars -> RnM FreeKiTyVars)
1590 -> Maybe a -> FreeKiTyVars -> RnM FreeKiTyVars
1591 extract_mb _ Nothing acc = return acc
1592 extract_mb f (Just x) acc = f x acc
1593
1594 extract_lkind :: LHsType RdrName -> FreeKiTyVars -> RnM FreeKiTyVars
1595 extract_lkind = extract_lty KindLevel
1596
1597 extract_lty :: TypeOrKind -> LHsType RdrName -> FreeKiTyVars -> RnM FreeKiTyVars
1598 extract_lty t_or_k (L _ ty) acc
1599 = case ty of
1600 HsTyVar ltv -> extract_tv t_or_k ltv acc
1601 HsBangTy _ ty -> extract_lty t_or_k ty acc
1602 HsRecTy flds -> foldrM (extract_lty t_or_k
1603 . cd_fld_type . unLoc) acc
1604 flds
1605 HsAppsTy tys -> extract_apps t_or_k tys acc
1606 HsAppTy ty1 ty2 -> extract_lty t_or_k ty1 =<<
1607 extract_lty t_or_k ty2 acc
1608 HsListTy ty -> extract_lty t_or_k ty acc
1609 HsPArrTy ty -> extract_lty t_or_k ty acc
1610 HsTupleTy _ tys -> extract_ltys t_or_k tys acc
1611 HsSumTy tys -> extract_ltys t_or_k tys acc
1612 HsFunTy ty1 ty2 -> extract_lty t_or_k ty1 =<<
1613 extract_lty t_or_k ty2 acc
1614 HsIParamTy _ ty -> extract_lty t_or_k ty acc
1615 HsEqTy ty1 ty2 -> extract_lty t_or_k ty1 =<<
1616 extract_lty t_or_k ty2 acc
1617 HsOpTy ty1 tv ty2 -> extract_tv t_or_k tv =<<
1618 extract_lty t_or_k ty1 =<<
1619 extract_lty t_or_k ty2 acc
1620 HsParTy ty -> extract_lty t_or_k ty acc
1621 HsCoreTy {} -> return acc -- The type is closed
1622 HsSpliceTy {} -> return acc -- Type splices mention no tvs
1623 HsDocTy ty _ -> extract_lty t_or_k ty acc
1624 HsExplicitListTy _ tys -> extract_ltys t_or_k tys acc
1625 HsExplicitTupleTy _ tys -> extract_ltys t_or_k tys acc
1626 HsTyLit _ -> return acc
1627 HsKindSig ty ki -> extract_lty t_or_k ty =<<
1628 extract_lkind ki acc
1629 HsForAllTy { hst_bndrs = tvs, hst_body = ty }
1630 -> extract_hs_tv_bndrs tvs acc =<<
1631 extract_lty t_or_k ty emptyFKTV
1632 HsQualTy { hst_ctxt = ctxt, hst_body = ty }
1633 -> extract_lctxt t_or_k ctxt =<<
1634 extract_lty t_or_k ty acc
1635 -- We deal with these separately in rnLHsTypeWithWildCards
1636 HsWildCardTy {} -> return acc
1637
1638 extract_apps :: TypeOrKind
1639 -> [LHsAppType RdrName] -> FreeKiTyVars -> RnM FreeKiTyVars
1640 extract_apps t_or_k tys acc = foldrM (extract_app t_or_k) acc tys
1641
1642 extract_app :: TypeOrKind -> LHsAppType RdrName -> FreeKiTyVars
1643 -> RnM FreeKiTyVars
1644 extract_app t_or_k (L _ (HsAppInfix tv)) acc = extract_tv t_or_k tv acc
1645 extract_app t_or_k (L _ (HsAppPrefix ty)) acc = extract_lty t_or_k ty acc
1646
1647 extract_hs_tv_bndrs :: [LHsTyVarBndr RdrName] -> FreeKiTyVars
1648 -> FreeKiTyVars -> RnM FreeKiTyVars
1649 -- In (forall (a :: Maybe e). a -> b) we have
1650 -- 'a' is bound by the forall
1651 -- 'b' is a free type variable
1652 -- 'e' is a free kind variable
1653 extract_hs_tv_bndrs tvs
1654 (FKTV acc_kvs acc_k_set acc_tvs acc_t_set acc_all)
1655 -- Note accumulator comes first
1656 (FKTV body_kvs body_k_set body_tvs body_t_set body_all)
1657 | null tvs
1658 = return $
1659 FKTV (body_kvs ++ acc_kvs) (body_k_set `unionOccSets` acc_k_set)
1660 (body_tvs ++ acc_tvs) (body_t_set `unionOccSets` acc_t_set)
1661 (body_all ++ acc_all)
1662 | otherwise
1663 = do { FKTV bndr_kvs bndr_k_set _ _ _
1664 <- foldrM extract_lkind emptyFKTV [k | L _ (KindedTyVar _ k) <- tvs]
1665
1666 ; let locals = mkOccSet $ map (rdrNameOcc . hsLTyVarName) tvs
1667 ; return $
1668 FKTV (filterOut ((`elemOccSet` locals) . rdrNameOcc . unLoc) (bndr_kvs ++ body_kvs) ++ acc_kvs)
1669 ((body_k_set `minusOccSet` locals) `unionOccSets` acc_k_set `unionOccSets` bndr_k_set)
1670 (filterOut ((`elemOccSet` locals) . rdrNameOcc . unLoc) body_tvs ++ acc_tvs)
1671 ((body_t_set `minusOccSet` locals) `unionOccSets` acc_t_set)
1672 (filterOut ((`elemOccSet` locals) . rdrNameOcc . unLoc) (bndr_kvs ++ body_all) ++ acc_all) }
1673
1674 extract_tv :: TypeOrKind -> Located RdrName -> FreeKiTyVars -> RnM FreeKiTyVars
1675 extract_tv t_or_k ltv@(L _ tv) acc
1676 | isRdrTyVar tv = case acc of
1677 FKTV kvs k_set tvs t_set all
1678 | isTypeLevel t_or_k
1679 -> do { when (occ `elemOccSet` k_set) $
1680 mixedVarsErr ltv
1681 ; return (FKTV kvs k_set (ltv : tvs) (t_set `extendOccSet` occ)
1682 (ltv : all)) }
1683 | otherwise
1684 -> do { when (occ `elemOccSet` t_set) $
1685 mixedVarsErr ltv
1686 ; return (FKTV (ltv : kvs) (k_set `extendOccSet` occ) tvs t_set
1687 (ltv : all)) }
1688 | otherwise = return acc
1689 where
1690 occ = rdrNameOcc tv
1691
1692 mixedVarsErr :: Located RdrName -> RnM ()
1693 mixedVarsErr (L loc tv)
1694 = do { typeintype <- xoptM LangExt.TypeInType
1695 ; unless typeintype $
1696 addErrAt loc $ text "Variable" <+> quotes (ppr tv) <+>
1697 text "used as both a kind and a type" $$
1698 text "Did you intend to use TypeInType?" }
1699
1700 -- just used in this module; seemed convenient here
1701 nubL :: Eq a => [Located a] -> [Located a]
1702 nubL = nubBy eqLocated