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