2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section[RnSource]{Main pass of renamer}
7 module RnTypes ( rnHsType, rnContext,
8 rnHsSigType, rnHsTypeFVs, rnHsSigTypeFVs,
9 rnPat, rnPats, rnPatsAndThen, -- Here because it's not part
10 rnOverLit, litFVs, -- of any mutual recursion
11 precParseErr, sectionPrecErr, dupFieldErr, patSigErr, checkTupSize
14 import CmdLineOpts ( DynFlag(Opt_WarnMisc, Opt_WarnUnusedMatches, Opt_GlasgowExts) )
17 import RdrHsSyn ( RdrNameContext, RdrNameHsType, RdrNamePat,
18 extractHsTyRdrTyVars, extractHsCtxtRdrTyVars )
19 import RnHsSyn ( RenamedContext, RenamedHsType, RenamedPat,
21 parrTyCon_name, tupleTyCon_name, listTyCon_name, charTyCon_name )
22 import RnEnv ( lookupOccRn, lookupBndrRn, lookupSyntaxName, lookupGlobalOccRn,
23 newIPName, bindTyVarsRn, lookupFixityRn, mapFvRn,
24 bindPatSigTyVarsFV, bindLocalsFV, warnUnusedMatches )
27 import PrelNames( eqStringName, eqClassName, integralClassName,
28 negateName, minusName, lengthPName, indexPName, plusIntegerName, fromIntegerName,
29 timesIntegerName, ratioDataConName, fromRationalName )
30 import Constants ( mAX_TUPLE_SIZE )
31 import TysWiredIn ( intTyCon )
32 import TysPrim ( charPrimTyCon, addrPrimTyCon, intPrimTyCon,
33 floatPrimTyCon, doublePrimTyCon )
34 import RdrName ( elemRdrEnv )
35 import Name ( Name, NamedThing(..) )
37 import Unique ( Uniquable(..) )
39 import Literal ( inIntRange, inCharRange )
40 import BasicTypes ( compareFixity, arrowFixity )
42 import ListSetOps ( removeDupsEq, removeDups )
45 #include "HsVersions.h"
48 These type renamers are in a separate module, rather than in (say) RnSource,
49 to break several loop.
51 %*********************************************************
53 \subsection{Renaming types}
55 %*********************************************************
58 rnHsTypeFVs :: SDoc -> RdrNameHsType -> RnM (RenamedHsType, FreeVars)
59 rnHsTypeFVs doc_str ty
60 = rnHsType doc_str ty `thenM` \ ty' ->
61 returnM (ty', extractHsTyNames ty')
63 rnHsSigTypeFVs :: SDoc -> RdrNameHsType -> RnM (RenamedHsType, FreeVars)
64 rnHsSigTypeFVs doc_str ty
65 = rnHsSigType doc_str ty `thenM` \ ty' ->
66 returnM (ty', extractHsTyNames ty')
68 rnHsSigType :: SDoc -> RdrNameHsType -> RnM RenamedHsType
69 -- rnHsSigType is used for source-language type signatures,
70 -- which use *implicit* universal quantification.
71 rnHsSigType doc_str ty
72 = rnHsType (text "In the type signature for" <+> doc_str) ty
75 rnHsType is here because we call it from loadInstDecl, and I didn't
76 want a gratuitous knot.
79 rnHsType :: SDoc -> RdrNameHsType -> RnM RenamedHsType
81 rnHsType doc (HsForAllTy Nothing ctxt ty)
82 -- Implicit quantifiction in source code (no kinds on tyvars)
83 -- Given the signature C => T we universally quantify
84 -- over FV(T) \ {in-scope-tyvars}
85 = getLocalRdrEnv `thenM` \ name_env ->
87 mentioned_in_tau = extractHsTyRdrTyVars ty
88 mentioned_in_ctxt = extractHsCtxtRdrTyVars ctxt
89 mentioned = nub (mentioned_in_tau ++ mentioned_in_ctxt)
91 -- Don't quantify over type variables that are in scope;
92 -- when GlasgowExts is off, there usually won't be any, except for
94 -- class C a where { op :: a -> a }
95 forall_tyvars = filter (not . (`elemRdrEnv` name_env)) mentioned
97 rnForAll doc (map UserTyVar forall_tyvars) ctxt ty
99 rnHsType doc (HsForAllTy (Just forall_tyvars) ctxt tau)
100 -- Explicit quantification.
101 -- Check that the forall'd tyvars are actually
102 -- mentioned in the type, and produce a warning if not
104 mentioned_in_tau = extractHsTyRdrTyVars tau
105 mentioned_in_ctxt = extractHsCtxtRdrTyVars ctxt
106 mentioned = nub (mentioned_in_tau ++ mentioned_in_ctxt)
107 forall_tyvar_names = hsTyVarNames forall_tyvars
109 -- Explicitly quantified but not mentioned in ctxt or tau
110 warn_guys = filter (`notElem` mentioned) forall_tyvar_names
112 mappM_ (forAllWarn doc tau) warn_guys `thenM_`
113 rnForAll doc forall_tyvars ctxt tau
115 rnHsType doc (HsTyVar tyvar)
116 = lookupOccRn tyvar `thenM` \ tyvar' ->
117 returnM (HsTyVar tyvar')
119 rnHsType doc (HsOpTy ty1 op ty2)
121 HsArrow -> returnM HsArrow
122 HsTyOp n -> lookupOccRn n `thenM` \ n' ->
125 rnHsType doc ty1 `thenM` \ ty1' ->
126 rnHsType doc ty2 `thenM` \ ty2' ->
127 lookupTyFixityRn op' `thenM` \ fix ->
128 mkHsOpTyRn op' fix ty1' ty2'
130 rnHsType doc (HsParTy ty)
131 = rnHsType doc ty `thenM` \ ty' ->
132 returnM (HsParTy ty')
134 rnHsType doc (HsNumTy i)
135 | i == 1 = returnM (HsNumTy i)
136 | otherwise = addErr err_msg `thenM_` returnM (HsNumTy i)
138 err_msg = ptext SLIT("Only unit numeric type pattern is valid")
141 rnHsType doc (HsFunTy ty1 ty2)
142 = rnHsType doc ty1 `thenM` \ ty1' ->
143 -- Might find a for-all as the arg of a function type
144 rnHsType doc ty2 `thenM` \ ty2' ->
145 -- Or as the result. This happens when reading Prelude.hi
146 -- when we find return :: forall m. Monad m -> forall a. a -> m a
147 returnM (HsFunTy ty1' ty2')
149 rnHsType doc (HsListTy ty)
150 = rnHsType doc ty `thenM` \ ty' ->
151 returnM (HsListTy ty')
153 rnHsType doc (HsKindSig ty k)
154 = rnHsType doc ty `thenM` \ ty' ->
155 returnM (HsKindSig ty' k)
157 rnHsType doc (HsPArrTy ty)
158 = rnHsType doc ty `thenM` \ ty' ->
159 returnM (HsPArrTy ty')
161 -- Unboxed tuples are allowed to have poly-typed arguments. These
162 -- sometimes crop up as a result of CPR worker-wrappering dictionaries.
163 rnHsType doc (HsTupleTy tup_con tys)
164 = mappM (rnHsType doc) tys `thenM` \ tys' ->
165 returnM (HsTupleTy tup_con tys')
167 rnHsType doc (HsAppTy ty1 ty2)
168 = rnHsType doc ty1 `thenM` \ ty1' ->
169 rnHsType doc ty2 `thenM` \ ty2' ->
170 returnM (HsAppTy ty1' ty2')
172 rnHsType doc (HsPredTy pred)
173 = rnPred doc pred `thenM` \ pred' ->
174 returnM (HsPredTy pred')
176 rnHsTypes doc tys = mappM (rnHsType doc) tys
181 rnForAll doc forall_tyvars ctxt ty
182 = bindTyVarsRn doc forall_tyvars $ \ new_tyvars ->
183 rnContext doc ctxt `thenM` \ new_ctxt ->
184 rnHsType doc ty `thenM` \ new_ty ->
185 returnM (mkHsForAllTy (Just new_tyvars) new_ctxt new_ty)
189 %*********************************************************
191 \subsection{Fixities}
193 %*********************************************************
195 Infix types are read in a *right-associative* way, so that
200 mkHsOpTyRn rearranges where necessary. The two arguments
201 have already been renamed and rearranged. It's made rather tiresome
202 by the presence of ->
205 lookupTyFixityRn HsArrow = returnM arrowFixity
206 lookupTyFixityRn (HsTyOp n)
207 = doptM Opt_GlasgowExts `thenM` \ glaExts ->
208 warnIf (not glaExts) (infixTyConWarn n) `thenM_`
211 -- Building (ty1 `op1` (ty21 `op2` ty22))
212 mkHsOpTyRn :: HsTyOp Name -> Fixity
213 -> RenamedHsType -> RenamedHsType
216 mkHsOpTyRn op1 fix1 ty1 ty2@(HsOpTy ty21 op2 ty22)
217 = lookupTyFixityRn op2 `thenM` \ fix2 ->
219 (nofix_error, associate_right) = compareFixity fix1 fix2
222 addErr (precParseErr (quotes (ppr op1),fix1)
223 (quotes (ppr op2),fix2)) `thenM_`
224 returnM (HsOpTy ty1 op1 ty2)
226 if not associate_right then
227 -- Rearrange to ((ty1 `op1` ty21) `op2` ty22)
228 mkHsOpTyRn op1 fix1 ty1 ty21 `thenM` \ new_ty ->
229 returnM (HsOpTy new_ty op2 ty22)
231 returnM (HsOpTy ty1 op1 ty2)
233 mkHsOpTyRn op fix ty1 ty2 -- Default case, no rearrangment
234 = returnM (HsOpTy ty1 op ty2)
236 mkHsFunTyRn ty1 ty2 -- Precedence of function arrow is 0
237 = returnM (HsFunTy ty1 ty2) -- so no rearrangement reqd. Change
238 -- this if fixity of -> increases.
240 not_op_ty (HsOpTy _ _ _) = False
241 not_op_ty other = True
244 %*********************************************************
246 \subsection{Contexts and predicates}
248 %*********************************************************
251 rnContext :: SDoc -> RdrNameContext -> RnM RenamedContext
253 = mappM rn_pred ctxt `thenM` \ theta ->
255 -- Check for duplicate assertions
256 -- If this isn't an error, then it ought to be:
257 ifOptM Opt_WarnMisc (
259 (_, dups) = removeDupsEq theta
260 -- We only have equality, not ordering
262 mappM_ (addWarn . dupClassAssertWarn theta) dups
267 rn_pred pred = rnPred doc pred `thenM` \ pred'->
271 rnPred doc (HsClassP clas tys)
272 = lookupOccRn clas `thenM` \ clas_name ->
273 rnHsTypes doc tys `thenM` \ tys' ->
274 returnM (HsClassP clas_name tys')
276 rnPred doc (HsIParam n ty)
277 = newIPName n `thenM` \ name ->
278 rnHsType doc ty `thenM` \ ty' ->
279 returnM (HsIParam name ty')
283 *********************************************************
285 \subsection{Patterns}
287 *********************************************************
290 rnPatsAndThen :: HsMatchContext Name
292 -> ([RenamedPat] -> RnM (a, FreeVars))
294 -- Bring into scope all the binders and type variables
295 -- bound by the patterns; then rename the patterns; then
296 -- do the thing inside.
298 -- Note that we do a single bindLocalsRn for all the
299 -- matches together, so that we spot the repeated variable in
302 rnPatsAndThen ctxt pats thing_inside
303 = bindPatSigTyVarsFV pat_sig_tys $
304 bindLocalsFV doc_pat bndrs $ \ new_bndrs ->
305 rnPats pats `thenM` \ (pats', pat_fvs) ->
306 thing_inside pats' `thenM` \ (res, res_fvs) ->
309 unused_binders = filter (not . (`elemNameSet` res_fvs)) new_bndrs
311 warnUnusedMatches unused_binders `thenM_`
313 returnM (res, res_fvs `plusFV` pat_fvs)
315 pat_sig_tys = collectSigTysFromPats pats
316 bndrs = collectPatsBinders pats
317 doc_pat = ptext SLIT("In") <+> pprMatchContext ctxt
319 rnPats :: [RdrNamePat] -> RnM ([RenamedPat], FreeVars)
320 rnPats ps = mapFvRn rnPat ps
322 rnPat :: RdrNamePat -> RnM (RenamedPat, FreeVars)
324 rnPat (WildPat _) = returnM (WildPat placeHolderType, emptyFVs)
327 = lookupBndrRn name `thenM` \ vname ->
328 returnM (VarPat vname, emptyFVs)
330 rnPat (SigPatIn pat ty)
331 = doptM Opt_GlasgowExts `thenM` \ glaExts ->
334 then rnPat pat `thenM` \ (pat', fvs1) ->
335 rnHsTypeFVs doc ty `thenM` \ (ty', fvs2) ->
336 returnM (SigPatIn pat' ty', fvs1 `plusFV` fvs2)
338 else addErr (patSigErr ty) `thenM_`
341 doc = text "In a pattern type-signature"
343 rnPat (LitPat s@(HsString _))
344 = returnM (LitPat s, unitFV eqStringName)
347 = litFVs lit `thenM` \ fvs ->
348 returnM (LitPat lit, fvs)
350 rnPat (NPatIn lit mb_neg)
351 = rnOverLit lit `thenM` \ (lit', fvs1) ->
353 Nothing -> returnM (Nothing, emptyFVs)
354 Just _ -> lookupSyntaxName negateName `thenM` \ (neg, fvs) ->
355 returnM (Just neg, fvs)
356 ) `thenM` \ (mb_neg', fvs2) ->
357 returnM (NPatIn lit' mb_neg',
358 fvs1 `plusFV` fvs2 `addOneFV` eqClassName)
359 -- Needed to find equality on pattern
361 rnPat (NPlusKPatIn name lit _)
362 = rnOverLit lit `thenM` \ (lit', fvs1) ->
363 lookupBndrRn name `thenM` \ name' ->
364 lookupSyntaxName minusName `thenM` \ (minus, fvs2) ->
365 returnM (NPlusKPatIn name' lit' minus,
366 fvs1 `plusFV` fvs2 `addOneFV` integralClassName)
367 -- The Report says that n+k patterns must be in Integral
370 = rnPat pat `thenM` \ (pat', fvs) ->
371 returnM (LazyPat pat', fvs)
373 rnPat (AsPat name pat)
374 = rnPat pat `thenM` \ (pat', fvs) ->
375 lookupBndrRn name `thenM` \ vname ->
376 returnM (AsPat vname pat', fvs)
378 rnPat (ConPatIn con stuff) = rnConPat con stuff
382 = rnPat pat `thenM` \ (pat', fvs) ->
383 returnM (ParPat pat', fvs)
385 rnPat (ListPat pats _)
386 = rnPats pats `thenM` \ (patslist, fvs) ->
387 returnM (ListPat patslist placeHolderType, fvs `addOneFV` listTyCon_name)
389 rnPat (PArrPat pats _)
390 = rnPats pats `thenM` \ (patslist, fvs) ->
391 returnM (PArrPat patslist placeHolderType,
392 fvs `plusFV` implicit_fvs `addOneFV` parrTyCon_name)
394 implicit_fvs = mkFVs [lengthPName, indexPName]
396 rnPat (TuplePat pats boxed)
397 = checkTupSize tup_size `thenM_`
398 rnPats pats `thenM` \ (patslist, fvs) ->
399 returnM (TuplePat patslist boxed, fvs `addOneFV` tycon_name)
401 tup_size = length pats
402 tycon_name = tupleTyCon_name boxed tup_size
404 rnPat (TypePat name) =
405 rnHsTypeFVs (text "In a type pattern") name `thenM` \ (name', fvs) ->
406 returnM (TypePat name', fvs)
408 ------------------------------
409 rnConPat con (PrefixCon pats)
410 = lookupOccRn con `thenM` \ con' ->
411 rnPats pats `thenM` \ (pats', fvs) ->
412 returnM (ConPatIn con' (PrefixCon pats'), fvs `addOneFV` con')
414 rnConPat con (RecCon rpats)
415 = lookupOccRn con `thenM` \ con' ->
416 rnRpats rpats `thenM` \ (rpats', fvs) ->
417 returnM (ConPatIn con' (RecCon rpats'), fvs `addOneFV` con')
419 rnConPat con (InfixCon pat1 pat2)
420 = lookupOccRn con `thenM` \ con' ->
421 rnPat pat1 `thenM` \ (pat1', fvs1) ->
422 rnPat pat2 `thenM` \ (pat2', fvs2) ->
424 getModeRn `thenM` \ mode ->
425 -- See comments with rnExpr (OpApp ...)
426 (if isInterfaceMode mode
427 then returnM (ConPatIn con' (InfixCon pat1' pat2'))
428 else lookupFixityRn con' `thenM` \ fixity ->
429 mkConOpPatRn con' fixity pat1' pat2'
431 returnM (pat', fvs1 `plusFV` fvs2 `addOneFV` con')
433 ------------------------
435 = mappM_ field_dup_err dup_fields `thenM_`
436 mapFvRn rn_rpat rpats `thenM` \ (rpats', fvs) ->
437 returnM (rpats', fvs)
439 (_, dup_fields) = removeDups compare [ f | (f,_) <- rpats ]
441 field_dup_err dups = addErr (dupFieldErr "pattern" dups)
444 = lookupGlobalOccRn field `thenM` \ fieldname ->
445 rnPat pat `thenM` \ (pat', fvs) ->
446 returnM ((fieldname, pat'), fvs `addOneFV` fieldname)
450 mkConOpPatRn :: Name -> Fixity -> RenamedPat -> RenamedPat
453 mkConOpPatRn op2 fix2 p1@(ConPatIn op1 (InfixCon p11 p12)) p2
454 = lookupFixityRn op1 `thenM` \ fix1 ->
456 (nofix_error, associate_right) = compareFixity fix1 fix2
459 addErr (precParseErr (ppr_op op1,fix1) (ppr_op op2,fix2)) `thenM_`
460 returnM (ConPatIn op2 (InfixCon p1 p2))
462 if associate_right then
463 mkConOpPatRn op2 fix2 p12 p2 `thenM` \ new_p ->
464 returnM (ConPatIn op1 (InfixCon p11 new_p))
466 returnM (ConPatIn op2 (InfixCon p1 p2))
468 mkConOpPatRn op fix p1 p2 -- Default case, no rearrangment
469 = ASSERT( not_op_pat p2 )
470 returnM (ConPatIn op (InfixCon p1 p2))
472 not_op_pat (ConPatIn _ (InfixCon _ _)) = False
473 not_op_pat other = True
477 %************************************************************************
479 \subsubsection{Literals}
481 %************************************************************************
483 When literals occur we have to make sure
484 that the types and classes they involve
489 = checkErr (inCharRange c) (bogusCharError c) `thenM_`
490 returnM (unitFV charTyCon_name)
492 litFVs (HsCharPrim c) = returnM (unitFV (getName charPrimTyCon))
493 litFVs (HsString s) = returnM (mkFVs [listTyCon_name, charTyCon_name])
494 litFVs (HsStringPrim s) = returnM (unitFV (getName addrPrimTyCon))
495 litFVs (HsInt i) = returnM (unitFV (getName intTyCon))
496 litFVs (HsIntPrim i) = returnM (unitFV (getName intPrimTyCon))
497 litFVs (HsFloatPrim f) = returnM (unitFV (getName floatPrimTyCon))
498 litFVs (HsDoublePrim d) = returnM (unitFV (getName doublePrimTyCon))
499 litFVs lit = pprPanic "RnExpr.litFVs" (ppr lit) -- HsInteger and HsRat only appear
500 -- in post-typechecker translations
502 = ptext SLIT("character literal out of range: '\\") <> int c <> char '\''
504 rnOverLit (HsIntegral i _)
505 = lookupSyntaxName fromIntegerName `thenM` \ (from_integer_name, fvs) ->
507 returnM (HsIntegral i from_integer_name, fvs)
509 extra_fvs = mkFVs [plusIntegerName, timesIntegerName]
510 -- Big integer literals are built, using + and *,
511 -- out of small integers (DsUtils.mkIntegerLit)
512 -- [NB: plusInteger, timesInteger aren't rebindable...
513 -- they are used to construct the argument to fromInteger,
514 -- which is the rebindable one.]
516 returnM (HsIntegral i from_integer_name, fvs `plusFV` extra_fvs)
518 rnOverLit (HsFractional i _)
519 = lookupSyntaxName fromRationalName `thenM` \ (from_rat_name, fvs) ->
521 extra_fvs = mkFVs [ratioDataConName, plusIntegerName, timesIntegerName]
522 -- We have to make sure that the Ratio type is imported with
523 -- its constructor, because literals of type Ratio t are
524 -- built with that constructor.
525 -- The Rational type is needed too, but that will come in
526 -- as part of the type for fromRational.
527 -- The plus/times integer operations may be needed to construct the numerator
528 -- and denominator (see DsUtils.mkIntegerLit)
530 returnM (HsFractional i from_rat_name, fvs `plusFV` extra_fvs)
535 %*********************************************************
539 %*********************************************************
542 checkTupSize :: Int -> RnM ()
543 checkTupSize tup_size
544 | tup_size <= mAX_TUPLE_SIZE
547 = addErr (sep [ptext SLIT("A") <+> int tup_size <> ptext SLIT("-tuple is too large for GHC"),
548 nest 2 (parens (ptext SLIT("max size is") <+> int mAX_TUPLE_SIZE)),
549 nest 2 (ptext SLIT("Workaround: use nested tuples or define a data type"))])
551 forAllWarn doc ty tyvar
552 = ifOptM Opt_WarnUnusedMatches $
553 getModeRn `thenM` \ mode ->
556 InterfaceMode _ -> returnM () ; -- Don't warn of unused tyvars in interface files
557 -- unless DEBUG is on, in which case it is slightly
558 -- informative. They can arise from mkRhsTyLam,
559 -- leading to (say) f :: forall a b. [b] -> [b]
563 sep [ptext SLIT("The universally quantified type variable") <+> quotes (ppr tyvar),
564 nest 4 (ptext SLIT("does not appear in the type") <+> quotes (ppr ty))]
570 dupClassAssertWarn ctxt (assertion : dups)
571 = sep [hsep [ptext SLIT("Duplicate class assertion"),
572 quotes (ppr assertion),
573 ptext SLIT("in the context:")],
574 nest 4 (pprHsContext ctxt <+> ptext SLIT("..."))]
576 naughtyCCallContextErr (HsClassP clas _)
577 = sep [ptext SLIT("Can't use class") <+> quotes (ppr clas),
578 ptext SLIT("in a context")]
581 = hang (ptext SLIT("precedence parsing error"))
582 4 (hsep [ptext SLIT("cannot mix"), ppr_opfix op1, ptext SLIT("and"),
584 ptext SLIT("in the same infix expression")])
586 sectionPrecErr op arg_op section
587 = vcat [ptext SLIT("The operator") <+> ppr_opfix op <+> ptext SLIT("of a section"),
588 nest 4 (ptext SLIT("must have lower precedence than the operand") <+> ppr_opfix arg_op),
589 nest 4 (ptext SLIT("in the section:") <+> quotes (ppr section))]
592 = ftext FSLIT("Accepting non-standard infix type constructor") <+> quotes (ppr op)
595 = (ptext SLIT("Illegal signature in pattern:") <+> ppr ty)
596 $$ nest 4 (ptext SLIT("Use -fglasgow-exts to permit it"))
598 dupFieldErr str (dup:rest)
599 = hsep [ptext SLIT("duplicate field name"),
601 ptext SLIT("in record"), text str]
603 ppr_op op = quotes (ppr op) -- Here, op can be a Name or a (Var n), where n is a Name
604 ppr_opfix (pp_op, fixity) = pp_op <+> brackets (ppr fixity)