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