Collect wildcards in sum types during renaming (#12711)
[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 HsSumTy tys -> gos tys
1029 HsOpTy ty1 _ ty2 -> go ty1 `mappend` go ty2
1030 HsParTy ty -> go ty
1031 HsIParamTy _ ty -> go ty
1032 HsEqTy ty1 ty2 -> go ty1 `mappend` go ty2
1033 HsKindSig ty kind -> go ty `mappend` go kind
1034 HsDocTy ty _ -> go ty
1035 HsBangTy _ ty -> go ty
1036 HsRecTy flds -> gos $ map (cd_fld_type . unLoc) flds
1037 HsExplicitListTy _ tys -> gos tys
1038 HsExplicitTupleTy _ tys -> gos tys
1039 HsForAllTy { hst_bndrs = bndrs
1040 , hst_body = ty } -> collectAnonWildCardsBndrs bndrs
1041 `mappend` go ty
1042 HsQualTy { hst_ctxt = L _ ctxt
1043 , hst_body = ty } -> gos ctxt `mappend` go ty
1044 HsSpliceTy (HsSpliced _ (HsSplicedTy ty)) _ -> go $ L noSrcSpan ty
1045 HsSpliceTy{} -> mempty
1046 HsCoreTy{} -> mempty
1047 HsTyLit{} -> mempty
1048 HsTyVar{} -> mempty
1049
1050 gos = mconcat . map go
1051
1052 prefix_types_only (HsAppPrefix ty) = Just ty
1053 prefix_types_only (HsAppInfix _) = Nothing
1054
1055 collectAnonWildCardsBndrs :: [LHsTyVarBndr Name] -> [Name]
1056 collectAnonWildCardsBndrs ltvs = concatMap (go . unLoc) ltvs
1057 where
1058 go (UserTyVar _) = []
1059 go (KindedTyVar _ ki) = collectAnonWildCards ki
1060
1061 {-
1062 *********************************************************
1063 * *
1064 ConDeclField
1065 * *
1066 *********************************************************
1067
1068 When renaming a ConDeclField, we have to find the FieldLabel
1069 associated with each field. But we already have all the FieldLabels
1070 available (since they were brought into scope by
1071 RnNames.getLocalNonValBinders), so we just take the list as an
1072 argument, build a map and look them up.
1073 -}
1074
1075 rnConDeclFields :: HsDocContext -> [FieldLabel] -> [LConDeclField RdrName]
1076 -> RnM ([LConDeclField Name], FreeVars)
1077 -- Also called from RnSource
1078 -- No wildcards can appear in record fields
1079 rnConDeclFields ctxt fls fields
1080 = mapFvRn (rnField fl_env env) fields
1081 where
1082 env = mkTyKiEnv ctxt TypeLevel RnTypeBody
1083 fl_env = mkFsEnv [ (flLabel fl, fl) | fl <- fls ]
1084
1085 rnField :: FastStringEnv FieldLabel -> RnTyKiEnv -> LConDeclField RdrName
1086 -> RnM (LConDeclField Name, FreeVars)
1087 rnField fl_env env (L l (ConDeclField names ty haddock_doc))
1088 = do { let new_names = map (fmap lookupField) names
1089 ; (new_ty, fvs) <- rnLHsTyKi env ty
1090 ; new_haddock_doc <- rnMbLHsDoc haddock_doc
1091 ; return (L l (ConDeclField new_names new_ty new_haddock_doc), fvs) }
1092 where
1093 lookupField :: FieldOcc RdrName -> FieldOcc Name
1094 lookupField (FieldOcc (L lr rdr) _) = FieldOcc (L lr rdr) (flSelector fl)
1095 where
1096 lbl = occNameFS $ rdrNameOcc rdr
1097 fl = expectJust "rnField" $ lookupFsEnv fl_env lbl
1098
1099 {-
1100 ************************************************************************
1101 * *
1102 Fixities and precedence parsing
1103 * *
1104 ************************************************************************
1105
1106 @mkOpAppRn@ deals with operator fixities. The argument expressions
1107 are assumed to be already correctly arranged. It needs the fixities
1108 recorded in the OpApp nodes, because fixity info applies to the things
1109 the programmer actually wrote, so you can't find it out from the Name.
1110
1111 Furthermore, the second argument is guaranteed not to be another
1112 operator application. Why? Because the parser parses all
1113 operator appications left-associatively, EXCEPT negation, which
1114 we need to handle specially.
1115 Infix types are read in a *right-associative* way, so that
1116 a `op` b `op` c
1117 is always read in as
1118 a `op` (b `op` c)
1119
1120 mkHsOpTyRn rearranges where necessary. The two arguments
1121 have already been renamed and rearranged. It's made rather tiresome
1122 by the presence of ->, which is a separate syntactic construct.
1123 -}
1124
1125 ---------------
1126 -- Building (ty1 `op1` (ty21 `op2` ty22))
1127 mkHsOpTyRn :: (LHsType Name -> LHsType Name -> HsType Name)
1128 -> Name -> Fixity -> LHsType Name -> LHsType Name
1129 -> RnM (HsType Name)
1130
1131 mkHsOpTyRn mk1 pp_op1 fix1 ty1 (L loc2 (HsOpTy ty21 op2 ty22))
1132 = do { fix2 <- lookupTyFixityRn op2
1133 ; mk_hs_op_ty mk1 pp_op1 fix1 ty1
1134 (\t1 t2 -> HsOpTy t1 op2 t2)
1135 (unLoc op2) fix2 ty21 ty22 loc2 }
1136
1137 mkHsOpTyRn mk1 pp_op1 fix1 ty1 (L loc2 (HsFunTy ty21 ty22))
1138 = mk_hs_op_ty mk1 pp_op1 fix1 ty1
1139 HsFunTy funTyConName funTyFixity ty21 ty22 loc2
1140
1141 mkHsOpTyRn mk1 _ _ ty1 ty2 -- Default case, no rearrangment
1142 = return (mk1 ty1 ty2)
1143
1144 ---------------
1145 mk_hs_op_ty :: (LHsType Name -> LHsType Name -> HsType Name)
1146 -> Name -> Fixity -> LHsType Name
1147 -> (LHsType Name -> LHsType Name -> HsType Name)
1148 -> Name -> Fixity -> LHsType Name -> LHsType Name -> SrcSpan
1149 -> RnM (HsType Name)
1150 mk_hs_op_ty mk1 op1 fix1 ty1
1151 mk2 op2 fix2 ty21 ty22 loc2
1152 | nofix_error = do { precParseErr (op1,fix1) (op2,fix2)
1153 ; return (mk1 ty1 (L loc2 (mk2 ty21 ty22))) }
1154 | associate_right = return (mk1 ty1 (L loc2 (mk2 ty21 ty22)))
1155 | otherwise = do { -- Rearrange to ((ty1 `op1` ty21) `op2` ty22)
1156 new_ty <- mkHsOpTyRn mk1 op1 fix1 ty1 ty21
1157 ; return (mk2 (noLoc new_ty) ty22) }
1158 where
1159 (nofix_error, associate_right) = compareFixity fix1 fix2
1160
1161
1162 ---------------------------
1163 mkOpAppRn :: LHsExpr Name -- Left operand; already rearranged
1164 -> LHsExpr Name -> Fixity -- Operator and fixity
1165 -> LHsExpr Name -- Right operand (not an OpApp, but might
1166 -- be a NegApp)
1167 -> RnM (HsExpr Name)
1168
1169 -- (e11 `op1` e12) `op2` e2
1170 mkOpAppRn e1@(L _ (OpApp e11 op1 fix1 e12)) op2 fix2 e2
1171 | nofix_error
1172 = do precParseErr (get_op op1,fix1) (get_op op2,fix2)
1173 return (OpApp e1 op2 fix2 e2)
1174
1175 | associate_right = do
1176 new_e <- mkOpAppRn e12 op2 fix2 e2
1177 return (OpApp e11 op1 fix1 (L loc' new_e))
1178 where
1179 loc'= combineLocs e12 e2
1180 (nofix_error, associate_right) = compareFixity fix1 fix2
1181
1182 ---------------------------
1183 -- (- neg_arg) `op` e2
1184 mkOpAppRn e1@(L _ (NegApp neg_arg neg_name)) op2 fix2 e2
1185 | nofix_error
1186 = do precParseErr (negateName,negateFixity) (get_op op2,fix2)
1187 return (OpApp e1 op2 fix2 e2)
1188
1189 | associate_right
1190 = do new_e <- mkOpAppRn neg_arg op2 fix2 e2
1191 return (NegApp (L loc' new_e) neg_name)
1192 where
1193 loc' = combineLocs neg_arg e2
1194 (nofix_error, associate_right) = compareFixity negateFixity fix2
1195
1196 ---------------------------
1197 -- e1 `op` - neg_arg
1198 mkOpAppRn e1 op1 fix1 e2@(L _ (NegApp _ _)) -- NegApp can occur on the right
1199 | not associate_right -- We *want* right association
1200 = do precParseErr (get_op op1, fix1) (negateName, negateFixity)
1201 return (OpApp e1 op1 fix1 e2)
1202 where
1203 (_, associate_right) = compareFixity fix1 negateFixity
1204
1205 ---------------------------
1206 -- Default case
1207 mkOpAppRn e1 op fix e2 -- Default case, no rearrangment
1208 = ASSERT2( right_op_ok fix (unLoc e2),
1209 ppr e1 $$ text "---" $$ ppr op $$ text "---" $$ ppr fix $$ text "---" $$ ppr e2
1210 )
1211 return (OpApp e1 op fix e2)
1212
1213 ----------------------------
1214 get_op :: LHsExpr Name -> Name
1215 -- An unbound name could be either HsVar or HsUnboundVar
1216 -- See RnExpr.rnUnboundVar
1217 get_op (L _ (HsVar (L _ n))) = n
1218 get_op (L _ (HsUnboundVar uv)) = mkUnboundName (unboundVarOcc uv)
1219 get_op other = pprPanic "get_op" (ppr other)
1220
1221 -- Parser left-associates everything, but
1222 -- derived instances may have correctly-associated things to
1223 -- in the right operarand. So we just check that the right operand is OK
1224 right_op_ok :: Fixity -> HsExpr Name -> Bool
1225 right_op_ok fix1 (OpApp _ _ fix2 _)
1226 = not error_please && associate_right
1227 where
1228 (error_please, associate_right) = compareFixity fix1 fix2
1229 right_op_ok _ _
1230 = True
1231
1232 -- Parser initially makes negation bind more tightly than any other operator
1233 -- And "deriving" code should respect this (use HsPar if not)
1234 mkNegAppRn :: LHsExpr id -> SyntaxExpr id -> RnM (HsExpr id)
1235 mkNegAppRn neg_arg neg_name
1236 = ASSERT( not_op_app (unLoc neg_arg) )
1237 return (NegApp neg_arg neg_name)
1238
1239 not_op_app :: HsExpr id -> Bool
1240 not_op_app (OpApp _ _ _ _) = False
1241 not_op_app _ = True
1242
1243 ---------------------------
1244 mkOpFormRn :: LHsCmdTop Name -- Left operand; already rearranged
1245 -> LHsExpr Name -> Fixity -- Operator and fixity
1246 -> LHsCmdTop Name -- Right operand (not an infix)
1247 -> RnM (HsCmd Name)
1248
1249 -- (e11 `op1` e12) `op2` e2
1250 mkOpFormRn a1@(L loc (HsCmdTop (L _ (HsCmdArrForm op1 (Just fix1) [a11,a12])) _ _ _))
1251 op2 fix2 a2
1252 | nofix_error
1253 = do precParseErr (get_op op1,fix1) (get_op op2,fix2)
1254 return (HsCmdArrForm op2 (Just fix2) [a1, a2])
1255
1256 | associate_right
1257 = do new_c <- mkOpFormRn a12 op2 fix2 a2
1258 return (HsCmdArrForm op1 (Just fix1)
1259 [a11, L loc (HsCmdTop (L loc new_c)
1260 placeHolderType placeHolderType [])])
1261 -- TODO: locs are wrong
1262 where
1263 (nofix_error, associate_right) = compareFixity fix1 fix2
1264
1265 -- Default case
1266 mkOpFormRn arg1 op fix arg2 -- Default case, no rearrangment
1267 = return (HsCmdArrForm op (Just fix) [arg1, arg2])
1268
1269
1270 --------------------------------------
1271 mkConOpPatRn :: Located Name -> Fixity -> LPat Name -> LPat Name
1272 -> RnM (Pat Name)
1273
1274 mkConOpPatRn op2 fix2 p1@(L loc (ConPatIn op1 (InfixCon p11 p12))) p2
1275 = do { fix1 <- lookupFixityRn (unLoc op1)
1276 ; let (nofix_error, associate_right) = compareFixity fix1 fix2
1277
1278 ; if nofix_error then do
1279 { precParseErr (unLoc op1,fix1) (unLoc op2,fix2)
1280 ; return (ConPatIn op2 (InfixCon p1 p2)) }
1281
1282 else if associate_right then do
1283 { new_p <- mkConOpPatRn op2 fix2 p12 p2
1284 ; return (ConPatIn op1 (InfixCon p11 (L loc new_p))) } -- XXX loc right?
1285 else return (ConPatIn op2 (InfixCon p1 p2)) }
1286
1287 mkConOpPatRn op _ p1 p2 -- Default case, no rearrangment
1288 = ASSERT( not_op_pat (unLoc p2) )
1289 return (ConPatIn op (InfixCon p1 p2))
1290
1291 not_op_pat :: Pat Name -> Bool
1292 not_op_pat (ConPatIn _ (InfixCon _ _)) = False
1293 not_op_pat _ = True
1294
1295 --------------------------------------
1296 checkPrecMatch :: Name -> MatchGroup Name body -> RnM ()
1297 -- Check precedence of a function binding written infix
1298 -- eg a `op` b `C` c = ...
1299 -- See comments with rnExpr (OpApp ...) about "deriving"
1300
1301 checkPrecMatch op (MG { mg_alts = L _ ms })
1302 = mapM_ check ms
1303 where
1304 check (L _ (Match _ (L l1 p1 : L l2 p2 :_) _ _))
1305 = setSrcSpan (combineSrcSpans l1 l2) $
1306 do checkPrec op p1 False
1307 checkPrec op p2 True
1308
1309 check _ = return ()
1310 -- This can happen. Consider
1311 -- a `op` True = ...
1312 -- op = ...
1313 -- The infix flag comes from the first binding of the group
1314 -- but the second eqn has no args (an error, but not discovered
1315 -- until the type checker). So we don't want to crash on the
1316 -- second eqn.
1317
1318 checkPrec :: Name -> Pat Name -> Bool -> IOEnv (Env TcGblEnv TcLclEnv) ()
1319 checkPrec op (ConPatIn op1 (InfixCon _ _)) right = do
1320 op_fix@(Fixity _ op_prec op_dir) <- lookupFixityRn op
1321 op1_fix@(Fixity _ op1_prec op1_dir) <- lookupFixityRn (unLoc op1)
1322 let
1323 inf_ok = op1_prec > op_prec ||
1324 (op1_prec == op_prec &&
1325 (op1_dir == InfixR && op_dir == InfixR && right ||
1326 op1_dir == InfixL && op_dir == InfixL && not right))
1327
1328 info = (op, op_fix)
1329 info1 = (unLoc op1, op1_fix)
1330 (infol, infor) = if right then (info, info1) else (info1, info)
1331 unless inf_ok (precParseErr infol infor)
1332
1333 checkPrec _ _ _
1334 = return ()
1335
1336 -- Check precedence of (arg op) or (op arg) respectively
1337 -- If arg is itself an operator application, then either
1338 -- (a) its precedence must be higher than that of op
1339 -- (b) its precedency & associativity must be the same as that of op
1340 checkSectionPrec :: FixityDirection -> HsExpr RdrName
1341 -> LHsExpr Name -> LHsExpr Name -> RnM ()
1342 checkSectionPrec direction section op arg
1343 = case unLoc arg of
1344 OpApp _ op fix _ -> go_for_it (get_op op) fix
1345 NegApp _ _ -> go_for_it negateName negateFixity
1346 _ -> return ()
1347 where
1348 op_name = get_op op
1349 go_for_it arg_op arg_fix@(Fixity _ arg_prec assoc) = do
1350 op_fix@(Fixity _ op_prec _) <- lookupFixityRn op_name
1351 unless (op_prec < arg_prec
1352 || (op_prec == arg_prec && direction == assoc))
1353 (sectionPrecErr (op_name, op_fix)
1354 (arg_op, arg_fix) section)
1355
1356 -- Precedence-related error messages
1357
1358 precParseErr :: (Name, Fixity) -> (Name, Fixity) -> RnM ()
1359 precParseErr op1@(n1,_) op2@(n2,_)
1360 | isUnboundName n1 || isUnboundName n2
1361 = return () -- Avoid error cascade
1362 | otherwise
1363 = addErr $ hang (text "Precedence parsing error")
1364 4 (hsep [text "cannot mix", ppr_opfix op1, ptext (sLit "and"),
1365 ppr_opfix op2,
1366 text "in the same infix expression"])
1367
1368 sectionPrecErr :: (Name, Fixity) -> (Name, Fixity) -> HsExpr RdrName -> RnM ()
1369 sectionPrecErr op@(n1,_) arg_op@(n2,_) section
1370 | isUnboundName n1 || isUnboundName n2
1371 = return () -- Avoid error cascade
1372 | otherwise
1373 = addErr $ vcat [text "The operator" <+> ppr_opfix op <+> ptext (sLit "of a section"),
1374 nest 4 (sep [text "must have lower precedence than that of the operand,",
1375 nest 2 (text "namely" <+> ppr_opfix arg_op)]),
1376 nest 4 (text "in the section:" <+> quotes (ppr section))]
1377
1378 ppr_opfix :: (Name, Fixity) -> SDoc
1379 ppr_opfix (op, fixity) = pp_op <+> brackets (ppr fixity)
1380 where
1381 pp_op | op == negateName = text "prefix `-'"
1382 | otherwise = quotes (ppr op)
1383
1384 {- *****************************************************
1385 * *
1386 Errors
1387 * *
1388 ***************************************************** -}
1389
1390 unexpectedTypeSigErr :: LHsSigWcType RdrName -> SDoc
1391 unexpectedTypeSigErr ty
1392 = hang (text "Illegal type signature:" <+> quotes (ppr ty))
1393 2 (text "Type signatures are only allowed in patterns with ScopedTypeVariables")
1394
1395 badKindBndrs :: HsDocContext -> [Located RdrName] -> SDoc
1396 badKindBndrs doc kvs
1397 = withHsDocContext doc $
1398 hang (text "Unexpected kind variable" <> plural kvs
1399 <+> pprQuotedList kvs)
1400 2 (text "Perhaps you intended to use PolyKinds")
1401
1402 badKindSigErr :: HsDocContext -> LHsType RdrName -> TcM ()
1403 badKindSigErr doc (L loc ty)
1404 = setSrcSpan loc $ addErr $
1405 withHsDocContext doc $
1406 hang (text "Illegal kind signature:" <+> quotes (ppr ty))
1407 2 (text "Perhaps you intended to use KindSignatures")
1408
1409 dataKindsErr :: RnTyKiEnv -> HsType RdrName -> SDoc
1410 dataKindsErr env thing
1411 = hang (text "Illegal" <+> pp_what <> colon <+> quotes (ppr thing))
1412 2 (text "Perhaps you intended to use DataKinds")
1413 where
1414 pp_what | isRnKindLevel env = text "kind"
1415 | otherwise = text "type"
1416
1417 inTypeDoc :: HsType RdrName -> SDoc
1418 inTypeDoc ty = text "In the type" <+> quotes (ppr ty)
1419
1420 warnUnusedForAll :: SDoc -> LHsTyVarBndr Name -> FreeVars -> TcM ()
1421 warnUnusedForAll in_doc (L loc tv) used_names
1422 = whenWOptM Opt_WarnUnusedForalls $
1423 unless (hsTyVarName tv `elemNameSet` used_names) $
1424 addWarnAt (Reason Opt_WarnUnusedForalls) loc $
1425 vcat [ text "Unused quantified type variable" <+> quotes (ppr tv)
1426 , in_doc ]
1427
1428 opTyErr :: Outputable a => RdrName -> a -> SDoc
1429 opTyErr op overall_ty
1430 = hang (text "Illegal operator" <+> quotes (ppr op) <+> ptext (sLit "in type") <+> quotes (ppr overall_ty))
1431 2 extra
1432 where
1433 extra | op == dot_tv_RDR
1434 = perhapsForallMsg
1435 | otherwise
1436 = text "Use TypeOperators to allow operators in types"
1437
1438 emptyNonSymsErr :: HsType RdrName -> SDoc
1439 emptyNonSymsErr overall_ty
1440 = text "Operator applied to too few arguments:" <+> ppr overall_ty
1441
1442 {-
1443 ************************************************************************
1444 * *
1445 Finding the free type variables of a (HsType RdrName)
1446 * *
1447 ************************************************************************
1448
1449
1450 Note [Kind and type-variable binders]
1451 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1452 In a type signature we may implicitly bind type variable and, more
1453 recently, kind variables. For example:
1454 * f :: a -> a
1455 f = ...
1456 Here we need to find the free type variables of (a -> a),
1457 so that we know what to quantify
1458
1459 * class C (a :: k) where ...
1460 This binds 'k' in ..., as well as 'a'
1461
1462 * f (x :: a -> [a]) = ....
1463 Here we bind 'a' in ....
1464
1465 * f (x :: T a -> T (b :: k)) = ...
1466 Here we bind both 'a' and the kind variable 'k'
1467
1468 * type instance F (T (a :: Maybe k)) = ...a...k...
1469 Here we want to constrain the kind of 'a', and bind 'k'.
1470
1471 In general we want to walk over a type, and find
1472 * Its free type variables
1473 * The free kind variables of any kind signatures in the type
1474
1475 Hence we returns a pair (kind-vars, type vars)
1476 See also Note [HsBSig binder lists] in HsTypes
1477 -}
1478
1479 data FreeKiTyVars = FKTV { fktv_kis :: [Located RdrName]
1480 , _fktv_k_set :: OccSet -- for efficiency,
1481 -- only used internally
1482 , fktv_tys :: [Located RdrName]
1483 , _fktv_t_set :: OccSet
1484 , fktv_all :: [Located RdrName] }
1485
1486 instance Outputable FreeKiTyVars where
1487 ppr (FKTV kis _ tys _ _) = ppr (kis, tys)
1488
1489 emptyFKTV :: FreeKiTyVars
1490 emptyFKTV = FKTV [] emptyOccSet [] emptyOccSet []
1491
1492 freeKiTyVarsAllVars :: FreeKiTyVars -> [Located RdrName]
1493 freeKiTyVarsAllVars = fktv_all
1494
1495 freeKiTyVarsKindVars :: FreeKiTyVars -> [Located RdrName]
1496 freeKiTyVarsKindVars = fktv_kis
1497
1498 freeKiTyVarsTypeVars :: FreeKiTyVars -> [Located RdrName]
1499 freeKiTyVarsTypeVars = fktv_tys
1500
1501 filterInScope :: LocalRdrEnv -> FreeKiTyVars -> FreeKiTyVars
1502 filterInScope rdr_env (FKTV kis k_set tys t_set all)
1503 = FKTV (filterOut in_scope kis)
1504 (filterOccSet (not . in_scope_occ) k_set)
1505 (filterOut in_scope tys)
1506 (filterOccSet (not . in_scope_occ) t_set)
1507 (filterOut in_scope all)
1508 where
1509 in_scope = inScope rdr_env . unLoc
1510 in_scope_occ occ = isJust $ lookupLocalRdrOcc rdr_env occ
1511
1512 inScope :: LocalRdrEnv -> RdrName -> Bool
1513 inScope rdr_env rdr = rdr `elemLocalRdrEnv` rdr_env
1514
1515 extractHsTyRdrTyVars :: LHsType RdrName -> RnM FreeKiTyVars
1516 -- extractHsTyRdrNames finds the free (kind, type) variables of a HsType
1517 -- or the free (sort, kind) variables of a HsKind
1518 -- It's used when making the for-alls explicit.
1519 -- Does not return any wildcards
1520 -- When the same name occurs multiple times in the types, only the first
1521 -- occurence is returned.
1522 -- See Note [Kind and type-variable binders]
1523 extractHsTyRdrTyVars ty
1524 = do { FKTV kis k_set tys t_set all <- extract_lty TypeLevel ty emptyFKTV
1525 ; return (FKTV (nubL kis) k_set
1526 (nubL tys) t_set
1527 (nubL all)) }
1528
1529 -- | Extracts free type and kind variables from types in a list.
1530 -- When the same name occurs multiple times in the types, only the first
1531 -- occurence is returned and the rest is filtered out.
1532 -- See Note [Kind and type-variable binders]
1533 extractHsTysRdrTyVars :: [LHsType RdrName] -> RnM FreeKiTyVars
1534 extractHsTysRdrTyVars tys
1535 = rmDupsInRdrTyVars <$> extractHsTysRdrTyVarsDups tys
1536
1537 -- | Extracts free type and kind variables from types in a list.
1538 -- When the same name occurs multiple times in the types, all occurences
1539 -- are returned.
1540 extractHsTysRdrTyVarsDups :: [LHsType RdrName] -> RnM FreeKiTyVars
1541 extractHsTysRdrTyVarsDups tys
1542 = extract_ltys TypeLevel tys emptyFKTV
1543
1544 -- | Removes multiple occurences of the same name from FreeKiTyVars.
1545 rmDupsInRdrTyVars :: FreeKiTyVars -> FreeKiTyVars
1546 rmDupsInRdrTyVars (FKTV kis k_set tys t_set all)
1547 = FKTV (nubL kis) k_set (nubL tys) t_set (nubL all)
1548
1549 extractRdrKindSigVars :: LFamilyResultSig RdrName -> RnM [Located RdrName]
1550 extractRdrKindSigVars (L _ resultSig)
1551 | KindSig k <- resultSig = kindRdrNameFromSig k
1552 | TyVarSig (L _ (KindedTyVar _ k)) <- resultSig = kindRdrNameFromSig k
1553 | otherwise = return []
1554 where kindRdrNameFromSig k = freeKiTyVarsAllVars <$> extractHsTyRdrTyVars k
1555
1556 extractDataDefnKindVars :: HsDataDefn RdrName -> RnM [Located RdrName]
1557 -- Get the scoped kind variables mentioned free in the constructor decls
1558 -- Eg data T a = T1 (S (a :: k) | forall (b::k). T2 (S b)
1559 -- Here k should scope over the whole definition
1560 extractDataDefnKindVars (HsDataDefn { dd_ctxt = ctxt, dd_kindSig = ksig
1561 , dd_cons = cons, dd_derivs = L _ derivs })
1562 = (nubL . freeKiTyVarsKindVars) <$>
1563 (extract_lctxt TypeLevel ctxt =<<
1564 extract_mb extract_lkind ksig =<<
1565 extract_sig_tys (concatMap (unLoc . deriv_clause_tys . unLoc) derivs) =<<
1566 foldrM (extract_con . unLoc) emptyFKTV cons)
1567 where
1568 extract_con (ConDeclGADT { }) acc = return acc
1569 extract_con (ConDeclH98 { con_qvars = qvs
1570 , con_cxt = ctxt, con_details = details }) acc
1571 = extract_hs_tv_bndrs (maybe [] hsQTvExplicit qvs) acc =<<
1572 extract_mlctxt ctxt =<<
1573 extract_ltys TypeLevel (hsConDeclArgTys details) emptyFKTV
1574
1575 extract_mlctxt :: Maybe (LHsContext RdrName) -> FreeKiTyVars -> RnM FreeKiTyVars
1576 extract_mlctxt Nothing acc = return acc
1577 extract_mlctxt (Just ctxt) acc = extract_lctxt TypeLevel ctxt acc
1578
1579 extract_lctxt :: TypeOrKind
1580 -> LHsContext RdrName -> FreeKiTyVars -> RnM FreeKiTyVars
1581 extract_lctxt t_or_k ctxt = extract_ltys t_or_k (unLoc ctxt)
1582
1583 extract_sig_tys :: [LHsSigType RdrName] -> FreeKiTyVars -> RnM FreeKiTyVars
1584 extract_sig_tys sig_tys acc
1585 = foldrM (\sig_ty acc -> extract_lty TypeLevel (hsSigType sig_ty) acc)
1586 acc sig_tys
1587
1588 extract_ltys :: TypeOrKind
1589 -> [LHsType RdrName] -> FreeKiTyVars -> RnM FreeKiTyVars
1590 extract_ltys t_or_k tys acc = foldrM (extract_lty t_or_k) acc tys
1591
1592 extract_mb :: (a -> FreeKiTyVars -> RnM FreeKiTyVars)
1593 -> Maybe a -> FreeKiTyVars -> RnM FreeKiTyVars
1594 extract_mb _ Nothing acc = return acc
1595 extract_mb f (Just x) acc = f x acc
1596
1597 extract_lkind :: LHsType RdrName -> FreeKiTyVars -> RnM FreeKiTyVars
1598 extract_lkind = extract_lty KindLevel
1599
1600 extract_lty :: TypeOrKind -> LHsType RdrName -> FreeKiTyVars -> RnM FreeKiTyVars
1601 extract_lty t_or_k (L _ ty) acc
1602 = case ty of
1603 HsTyVar ltv -> extract_tv t_or_k ltv acc
1604 HsBangTy _ ty -> extract_lty t_or_k ty acc
1605 HsRecTy flds -> foldrM (extract_lty t_or_k
1606 . cd_fld_type . unLoc) acc
1607 flds
1608 HsAppsTy tys -> extract_apps t_or_k tys acc
1609 HsAppTy ty1 ty2 -> extract_lty t_or_k ty1 =<<
1610 extract_lty t_or_k ty2 acc
1611 HsListTy ty -> extract_lty t_or_k ty acc
1612 HsPArrTy ty -> extract_lty t_or_k ty acc
1613 HsTupleTy _ tys -> extract_ltys t_or_k tys acc
1614 HsSumTy tys -> extract_ltys t_or_k tys acc
1615 HsFunTy ty1 ty2 -> extract_lty t_or_k ty1 =<<
1616 extract_lty t_or_k ty2 acc
1617 HsIParamTy _ ty -> extract_lty t_or_k ty acc
1618 HsEqTy ty1 ty2 -> extract_lty t_or_k ty1 =<<
1619 extract_lty t_or_k ty2 acc
1620 HsOpTy ty1 tv ty2 -> extract_tv t_or_k tv =<<
1621 extract_lty t_or_k ty1 =<<
1622 extract_lty t_or_k ty2 acc
1623 HsParTy ty -> extract_lty t_or_k ty acc
1624 HsCoreTy {} -> return acc -- The type is closed
1625 HsSpliceTy {} -> return acc -- Type splices mention no tvs
1626 HsDocTy ty _ -> extract_lty t_or_k ty acc
1627 HsExplicitListTy _ tys -> extract_ltys t_or_k tys acc
1628 HsExplicitTupleTy _ tys -> extract_ltys t_or_k tys acc
1629 HsTyLit _ -> return acc
1630 HsKindSig ty ki -> extract_lty t_or_k ty =<<
1631 extract_lkind ki acc
1632 HsForAllTy { hst_bndrs = tvs, hst_body = ty }
1633 -> extract_hs_tv_bndrs tvs acc =<<
1634 extract_lty t_or_k ty emptyFKTV
1635 HsQualTy { hst_ctxt = ctxt, hst_body = ty }
1636 -> extract_lctxt t_or_k ctxt =<<
1637 extract_lty t_or_k ty acc
1638 -- We deal with these separately in rnLHsTypeWithWildCards
1639 HsWildCardTy {} -> return acc
1640
1641 extract_apps :: TypeOrKind
1642 -> [LHsAppType RdrName] -> FreeKiTyVars -> RnM FreeKiTyVars
1643 extract_apps t_or_k tys acc = foldrM (extract_app t_or_k) acc tys
1644
1645 extract_app :: TypeOrKind -> LHsAppType RdrName -> FreeKiTyVars
1646 -> RnM FreeKiTyVars
1647 extract_app t_or_k (L _ (HsAppInfix tv)) acc = extract_tv t_or_k tv acc
1648 extract_app t_or_k (L _ (HsAppPrefix ty)) acc = extract_lty t_or_k ty acc
1649
1650 extract_hs_tv_bndrs :: [LHsTyVarBndr RdrName] -> FreeKiTyVars
1651 -> FreeKiTyVars -> RnM FreeKiTyVars
1652 -- In (forall (a :: Maybe e). a -> b) we have
1653 -- 'a' is bound by the forall
1654 -- 'b' is a free type variable
1655 -- 'e' is a free kind variable
1656 extract_hs_tv_bndrs tvs
1657 (FKTV acc_kvs acc_k_set acc_tvs acc_t_set acc_all)
1658 -- Note accumulator comes first
1659 (FKTV body_kvs body_k_set body_tvs body_t_set body_all)
1660 | null tvs
1661 = return $
1662 FKTV (body_kvs ++ acc_kvs) (body_k_set `unionOccSets` acc_k_set)
1663 (body_tvs ++ acc_tvs) (body_t_set `unionOccSets` acc_t_set)
1664 (body_all ++ acc_all)
1665 | otherwise
1666 = do { FKTV bndr_kvs bndr_k_set _ _ _
1667 <- foldrM extract_lkind emptyFKTV [k | L _ (KindedTyVar _ k) <- tvs]
1668
1669 ; let locals = mkOccSet $ map (rdrNameOcc . hsLTyVarName) tvs
1670 ; return $
1671 FKTV (filterOut ((`elemOccSet` locals) . rdrNameOcc . unLoc) (bndr_kvs ++ body_kvs) ++ acc_kvs)
1672 ((body_k_set `minusOccSet` locals) `unionOccSets` acc_k_set `unionOccSets` bndr_k_set)
1673 (filterOut ((`elemOccSet` locals) . rdrNameOcc . unLoc) body_tvs ++ acc_tvs)
1674 ((body_t_set `minusOccSet` locals) `unionOccSets` acc_t_set)
1675 (filterOut ((`elemOccSet` locals) . rdrNameOcc . unLoc) (bndr_kvs ++ body_all) ++ acc_all) }
1676
1677 extract_tv :: TypeOrKind -> Located RdrName -> FreeKiTyVars -> RnM FreeKiTyVars
1678 extract_tv t_or_k ltv@(L _ tv) acc
1679 | isRdrTyVar tv = case acc of
1680 FKTV kvs k_set tvs t_set all
1681 | isTypeLevel t_or_k
1682 -> do { when (occ `elemOccSet` k_set) $
1683 mixedVarsErr ltv
1684 ; return (FKTV kvs k_set (ltv : tvs) (t_set `extendOccSet` occ)
1685 (ltv : all)) }
1686 | otherwise
1687 -> do { when (occ `elemOccSet` t_set) $
1688 mixedVarsErr ltv
1689 ; return (FKTV (ltv : kvs) (k_set `extendOccSet` occ) tvs t_set
1690 (ltv : all)) }
1691 | otherwise = return acc
1692 where
1693 occ = rdrNameOcc tv
1694
1695 mixedVarsErr :: Located RdrName -> RnM ()
1696 mixedVarsErr (L loc tv)
1697 = do { typeintype <- xoptM LangExt.TypeInType
1698 ; unless typeintype $
1699 addErrAt loc $ text "Variable" <+> quotes (ppr tv) <+>
1700 text "used as both a kind and a type" $$
1701 text "Did you intend to use TypeInType?" }
1702
1703 -- just used in this module; seemed convenient here
1704 nubL :: Eq a => [Located a] -> [Located a]
1705 nubL = nubBy eqLocated