2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section[RnPat]{Renaming of patterns}
6 Basically dependency analysis.
8 Handles @Match@, @GRHSs@, @HsExpr@, and @Qualifier@ datatypes. In
9 general, all of these functions return a renamed thing, and a set of
14 -- The above warning supression flag is a temporary kludge.
15 -- While working on this module you are encouraged to remove it and fix
16 -- any warnings in the module. See
17 -- http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#Warnings
20 module RnPat (-- main entry points
21 rnPatsAndThen_LocalRightwards, rnBindPat,
23 NameMaker, applyNameMaker, -- a utility for making names:
24 localRecNameMaker, topRecNameMaker, -- sometimes we want to make local names,
25 -- sometimes we want to make top (qualified) names.
27 rnHsRecFields_Con, rnHsRecFields_Update, --rename record fields in a constructor
33 -- Pattern Error messages that are also used elsewhere
34 checkTupSize, patSigErr
37 -- ENH: thin imports to only what is necessary for patterns
39 import {-# SOURCE #-} RnExpr( rnLExpr, rnStmts)
41 #include "HsVersions.h"
46 import HscTypes ( availNames )
47 import RnNames ( getLocalDeclBinders, extendRdrEnvRn )
48 import RnTypes ( rnHsTypeFVs,
49 mkOpFormRn, mkOpAppRn, mkNegAppRn, checkSectionPrec, mkConOpPatRn
51 import DynFlags ( DynFlag(..) )
52 import BasicTypes ( FixityDirection(..) )
53 import SrcLoc ( SrcSpan )
54 import PrelNames ( thFAKE, hasKey, assertIdKey, assertErrorName,
55 loopAName, choiceAName, appAName, arrAName, composeAName, firstAName,
56 negateName, thenMName, bindMName, failMName,
57 eqClassName, integralClassName, geName, eqName,
58 negateName, minusName, lengthPName, indexPName,
59 plusIntegerName, fromIntegerName, timesIntegerName,
60 ratioDataConName, fromRationalName, fromStringName )
61 import Constants ( mAX_TUPLE_SIZE )
62 import Name ( Name, nameOccName, nameIsLocalOrFrom, getOccName, nameSrcSpan )
65 import RdrName ( RdrName, extendLocalRdrEnv, lookupLocalRdrEnv, hideSomeUnquals, mkRdrUnqual, nameRdrName )
66 import LoadIface ( loadInterfaceForName )
67 import UniqFM ( isNullUFM )
68 import UniqSet ( emptyUniqSet )
70 import Util ( isSingleton )
71 import ListSetOps ( removeDups, minusList )
72 import Maybes ( expectJust )
74 import SrcLoc ( Located(..), unLoc, getLoc, cmpLocated, noLoc )
76 import Literal ( inIntRange, inCharRange )
77 import List ( unzip4 )
80 import ErrUtils (Message)
84 *********************************************************
88 *********************************************************
91 -- externally abstract type of name makers,
92 -- which is how you go from a RdrName to a Name
93 data NameMaker = NM (forall a. Located RdrName -> (Name -> RnM (a, FreeVars))
96 matchNameMaker :: NameMaker
98 = NM (\ rdr_name thing_inside ->
99 do { names@[name] <- newLocalsRn [rdr_name]
100 ; bindLocalNamesFV names $
101 warnUnusedMatches names $
104 topRecNameMaker, localRecNameMaker
105 :: UniqFM (Located Fixity) -- mini fixity env for the names we're about to bind
106 -- these fixities need to be brought into scope with the names
109 -- topNameMaker and localBindMaker do not check for unused binding
110 localRecNameMaker fix_env
111 = NM (\ rdr_name thing_inside ->
112 do { [name] <- newLocalsRn [rdr_name]
113 ; bindLocalNamesFV_WithFixities [name] fix_env $
116 topRecNameMaker fix_env
117 = NM (\rdr_name thing_inside ->
118 do { mod <- getModule
119 ; name <- newTopSrcBinder mod rdr_name
120 ; bindLocalNamesFV_WithFixities [name] fix_env $
122 -- Note: the bindLocalNamesFV_WithFixities is somewhat suspicious
123 -- because it binds a top-level name as a local name.
124 -- however, this binding seems to work, and it only exists for
125 -- the duration of the patterns and the continuation;
126 -- then the top-level name is added to the global env
127 -- before going on to the RHSes (see RnSource.lhs).
129 applyNameMaker :: NameMaker -> Located RdrName
130 -> (Name -> RnM (a,FreeVars)) -> RnM (a, FreeVars)
131 applyNameMaker (NM f) = f
134 -- There are various entry points to renaming patterns, depending on
135 -- (1) whether the names created should be top-level names or local names
136 -- (2) whether the scope of the names is entirely given in a continuation
137 -- (e.g., in a case or lambda, but not in a let or at the top-level,
138 -- because of the way mutually recursive bindings are handled)
139 -- (3) whether the a type signature in the pattern can bind
140 -- lexically-scoped type variables (for unpacking existential
141 -- type vars in data constructors)
142 -- (4) whether we do duplicate and unused variable checking
143 -- (5) whether there are fixity declarations associated with the names
144 -- bound by the patterns that need to be brought into scope with them.
146 -- Rather than burdening the clients of this module with all of these choices,
147 -- we export the three points in this design space that we actually need:
150 -- binds local names; the scope of the bindings is entirely in the thing_inside
151 -- allows type sigs to bind type vars
153 -- unused and duplicate checking
155 rnPatsAndThen_LocalRightwards :: HsMatchContext Name -- for error messages
157 -- the continuation gets:
158 -- the list of renamed patterns
159 -- the (overall) free vars of all of them
160 -> ([LPat Name] -> RnM (a, FreeVars))
163 rnPatsAndThen_LocalRightwards ctxt pats thing_inside
164 = do { -- Check for duplicated and shadowed names
165 -- Because we don't bind the vars all at once, we can't
166 -- check incrementally for duplicates;
167 -- Nor can we check incrementally for shadowing, else we'll
168 -- complain *twice* about duplicates e.g. f (x,x) = ...
169 let rdr_names_w_loc = collectLocatedPatsBinders pats
170 ; checkDupNames doc_pat rdr_names_w_loc
171 ; checkShadowing doc_pat rdr_names_w_loc
173 -- (0) bring into scope all of the type variables bound by the patterns
174 -- (1) rename the patterns, bringing into scope all of the term variables
175 -- (2) then do the thing inside.
176 ; bindPatSigTyVarsFV (collectSigTysFromPats pats) $
177 rnLPatsAndThen matchNameMaker pats $
180 doc_pat = ptext SLIT("In") <+> pprMatchContext ctxt
184 -- binds local names; in a recursive scope that involves other bound vars
185 -- e.g let { (x, Just y) = e1; ... } in ...
186 -- does NOT allows type sig to bind type vars
188 -- no unused and duplicate checking
189 -- fixities might be coming in
190 rnBindPat :: NameMaker
193 -- free variables of the pattern,
194 -- but not including variables bound by this pattern
197 rnBindPat name_maker pat
198 = rnLPatsAndThen name_maker [pat] $ \ [pat'] ->
199 return (pat', emptyFVs)
202 -- general version: parametrized by how you make new names
203 -- invariant: what-to-do continuation only gets called with a list whose length is the same as
204 -- the part of the pattern we're currently renaming
205 rnLPatsAndThen :: NameMaker -- how to make a new variable
206 -> [LPat RdrName] -- part of pattern we're currently renaming
207 -> ([LPat Name] -> RnM (a, FreeVars)) -- what to do afterwards
208 -> RnM (a, FreeVars) -- renaming of the whole thing
210 rnLPatsAndThen var = mapFvRnCPS (rnLPatAndThen var)
214 rnLPatAndThen :: NameMaker
215 -> LPat RdrName -- part of pattern we're currently renaming
216 -> (LPat Name -> RnM (a, FreeVars)) -- what to do afterwards
217 -> RnM (a, FreeVars) -- renaming of the whole thing
218 rnLPatAndThen var@(NM varf) (L loc p) cont =
221 lcont = \ unlocated -> cont (reloc unlocated)
224 WildPat _ -> lcont (WildPat placeHolderType)
226 ParPat pat -> rnLPatAndThen var pat $ \ pat' -> lcont (ParPat pat')
227 LazyPat pat -> rnLPatAndThen var pat $ \ pat' -> lcont (LazyPat pat')
228 BangPat pat -> rnLPatAndThen var pat $ \ pat' -> lcont (BangPat pat')
231 varf (reloc name) $ \ newBoundName ->
232 lcont (VarPat newBoundName)
233 -- we need to bind pattern variables for view pattern expressions
234 -- (e.g. in the pattern (x, x -> y) x needs to be bound in the rhs of the tuple)
237 doptM Opt_PatternSignatures `thenM` \ patsigs ->
239 then rnLPatAndThen var pat
240 (\ pat' -> do { (ty', fvs1) <- rnHsTypeFVs tvdoc ty
241 ; (res, fvs2) <- lcont (SigPatIn pat' ty')
242 ; return (res, fvs1 `plusFV` fvs2) })
243 else addErr (patSigErr ty) `thenM_`
244 rnLPatAndThen var pat cont
246 tvdoc = text "In a pattern type-signature"
248 LitPat lit@(HsString s) ->
249 do ovlStr <- doptM Opt_OverloadedStrings
251 then rnLPatAndThen var (reloc $ mkNPat (mkHsIsString s placeHolderType) Nothing) cont
252 else do { rnLit lit; lcont (LitPat lit) } -- Same as below
254 LitPat lit -> do { rnLit lit; lcont (LitPat lit) }
256 NPat lit mb_neg eq ->
257 do { (lit', fvs1) <- rnOverLit lit
258 ; (mb_neg', fvs2) <- case mb_neg of
259 Nothing -> return (Nothing, emptyFVs)
260 Just _ -> do { (neg, fvs) <- lookupSyntaxName negateName
261 ; return (Just neg, fvs) }
262 ; (eq', fvs3) <- lookupSyntaxName eqName
263 ; (res, fvs4) <- lcont (NPat lit' mb_neg' eq')
264 ; return (res, fvs1 `plusFV` fvs2 `plusFV` fvs3 `plusFV` fvs4) }
265 -- Needed to find equality on pattern
267 NPlusKPat name lit _ _ ->
268 varf name $ \ new_name ->
269 do { (lit', fvs1) <- rnOverLit lit
270 ; (minus, fvs2) <- lookupSyntaxName minusName
271 ; (ge, fvs3) <- lookupSyntaxName geName
272 ; (res, fvs4) <- lcont (NPlusKPat (L (nameSrcSpan new_name) new_name) lit' ge minus)
273 ; return (res, fvs1 `plusFV` fvs2 `plusFV` fvs3 `plusFV` fvs4) }
274 -- The Report says that n+k patterns must be in Integral
277 varf name $ \ new_name ->
278 rnLPatAndThen var pat $ \ pat' ->
279 lcont (AsPat (L (nameSrcSpan new_name) new_name) pat')
281 ViewPat expr pat ty ->
282 do { vp_flag <- doptM Opt_ViewPatterns
283 ; checkErr vp_flag (badViewPat p)
284 -- because of the way we're arranging the recursive calls,
285 -- this will be in the right context
286 ; (expr', fv_expr) <- rnLExpr expr
287 ; (res, fvs_res) <- rnLPatAndThen var pat $ \ pat' ->
288 lcont (ViewPat expr' pat' ty)
289 ; return (res, fvs_res `plusFV` fv_expr) }
291 ConPatIn con stuff ->
292 -- rnConPatAndThen takes care of reconstructing the pattern
293 rnConPatAndThen var con stuff cont
296 rnLPatsAndThen var pats $ \ patslist ->
297 lcont (ListPat patslist placeHolderType)
300 do { (res, res_fvs) <- rnLPatsAndThen var pats $ \ patslist ->
301 lcont (PArrPat patslist placeHolderType)
302 ; return (res, res_fvs `plusFV` implicit_fvs) }
304 implicit_fvs = mkFVs [lengthPName, indexPName]
306 TuplePat pats boxed _ ->
307 do { checkTupSize (length pats)
308 ; rnLPatsAndThen var pats $ \ patslist ->
309 lcont (TuplePat patslist boxed placeHolderType) }
312 do { (name', fvs1) <- rnHsTypeFVs (text "In a type pattern") name
313 ; (res, fvs2) <- lcont (TypePat name')
314 ; return (res, fvs1 `plusFV` fvs2) }
317 -- helper for renaming constructor patterns
318 rnConPatAndThen :: NameMaker
319 -> Located RdrName -- the constructor
320 -> HsConPatDetails RdrName
321 -> (LPat Name -> RnM (a, FreeVars)) -- what to do afterwards
324 rnConPatAndThen var (con@(L loc _)) (PrefixCon pats) cont
325 = do { con' <- lookupLocatedOccRn con
326 ; (res, res_fvs) <- rnLPatsAndThen var pats $ \ pats' ->
327 cont (L loc $ ConPatIn con' (PrefixCon pats'))
328 ; return (res, res_fvs `addOneFV` unLoc con') }
330 rnConPatAndThen var (con@(L loc _)) (InfixCon pat1 pat2) cont
331 = do { con' <- lookupLocatedOccRn con
332 ; (res, res_fvs) <- rnLPatAndThen var pat1 $ \ pat1' ->
333 rnLPatAndThen var pat2 $ \ pat2' ->
334 do { fixity <- lookupFixityRn (unLoc con')
335 ; pat' <- mkConOpPatRn con' fixity pat1' pat2'
336 ; cont (L loc pat') }
337 ; return (res, res_fvs `addOneFV` unLoc con') }
339 rnConPatAndThen var (con@(L loc _)) (RecCon rpats) cont
340 = do { con' <- lookupLocatedOccRn con
341 ; (res, res_fvs) <- rnHsRecFieldsAndThen_Pattern con' var rpats $ \ rpats' ->
342 cont (L loc $ ConPatIn con' (RecCon rpats'))
343 ; return (res, res_fvs `addOneFV` unLoc con') }
345 -- what kind of record expression we're doing
346 -- the first two tell the name of the datatype constructor in question
347 -- and give a way of creating a variable to fill in a ..
348 data RnHsRecFieldsChoice a = Constructor (Located Name) (RdrName -> a)
349 | Pattern (Located Name) (RdrName -> a)
352 choiceToMessage (Constructor _ _) = "construction"
353 choiceToMessage (Pattern _ _) = "pattern"
354 choiceToMessage Update = "update"
356 doDotDot (Constructor a b) = Just (a,b)
357 doDotDot (Pattern a b) = Just (a,b)
358 doDotDot Update = Nothing
360 getChoiceName (Constructor n _) = Just n
361 getChoiceName (Pattern n _) = Just n
362 getChoiceName (Update) = Nothing
366 -- helper for renaming record patterns;
367 -- parameterized so that it can also be used for expressions
368 rnHsRecFieldsAndThen :: RnHsRecFieldsChoice field
369 -- how to rename the fields (CPSed)
370 -> (Located field -> (Located field' -> RnM (c, FreeVars))
371 -> RnM (c, FreeVars))
373 -> HsRecFields RdrName (Located field)
374 -- what to do in the scope of the field vars
375 -> (HsRecFields Name (Located field') -> RnM (c, FreeVars))
377 -- Haddock comments for record fields are renamed to Nothing here
378 rnHsRecFieldsAndThen choice rn_thing (HsRecFields fields dd) cont =
381 -- helper to collect and report duplicate record fields
382 reportDuplicateFields doingstr fields =
384 -- each list represents a RdrName that occurred more than once
385 -- (the list contains all occurrences)
386 -- invariant: each list in dup_fields is non-empty
387 (_, dup_fields :: [[RdrName]]) = removeDups compare
388 (map (unLoc . hsRecFieldId) fields)
390 -- duplicate field reporting function
391 field_dup_err dup_group = addErr (dupFieldErr doingstr (head dup_group))
393 mappM_ field_dup_err dup_fields
395 -- helper to rename each field
396 rn_field pun_ok (HsRecField field inside pun) cont = do
397 fieldname <- lookupRecordBndr (getChoiceName choice) field
398 checkErr (not pun || pun_ok) (badPun field)
399 (res, res_fvs) <- rn_thing inside $ \ inside' ->
400 cont (HsRecField fieldname inside' pun)
401 return (res, res_fvs `addOneFV` unLoc fieldname)
403 -- Compute the extra fields to be filled in by the dot-dot notation
404 dot_dot_fields fs con mk_field cont = do
405 con_fields <- lookupConstructorFields (unLoc con)
406 let missing_fields = con_fields `minusList` fs
407 loc <- getSrcSpanM -- Rather approximate
408 -- it's important that we make the RdrName fields that we morally wrote
409 -- and then rename them in the usual manner
410 -- (rather than trying to make the result of renaming directly)
411 -- because, for patterns, renaming can bind vars in the continuation
413 (map (L loc . mk_field . mkRdrUnqual . getOccName) missing_fields) $
415 let new_fs = [ HsRecField (L loc f) r False
416 | (f, r) <- missing_fields `zip` rhss ]
421 -- report duplicate fields
422 let doingstr = choiceToMessage choice
423 reportDuplicateFields doingstr fields
425 -- rename the records as written
426 -- check whether punning (implicit x=x) is allowed
427 pun_flag <- doptM Opt_RecordPuns
429 mapFvRnCPS (rn_field pun_flag) fields $ \ fields1 ->
433 Nothing -> cont (HsRecFields fields1 dd)
434 Just n -> ASSERT( n == length fields ) do
435 dd_flag <- doptM Opt_RecordWildCards
436 checkErr dd_flag (needFlagDotDot doingstr)
437 let fld_names1 = map (unLoc . hsRecFieldId) fields1
438 case doDotDot choice of
439 Nothing -> addErr (badDotDot doingstr) `thenM_`
440 -- we return a junk value here so that error reporting goes on
441 cont (HsRecFields fields1 dd)
442 Just (con, mk_field) ->
443 dot_dot_fields fld_names1 con mk_field $
445 cont (HsRecFields (fields1 ++ fields2) dd)
447 needFlagDotDot str = vcat [ptext SLIT("Illegal `..' in record") <+> text str,
448 ptext SLIT("Use -XRecordWildCards to permit this")]
450 badDotDot str = ptext SLIT("You cannot use `..' in record") <+> text str
452 badPun fld = vcat [ptext SLIT("Illegal use of punning for field") <+> quotes (ppr fld),
453 ptext SLIT("Use -XRecordPuns to permit this")]
457 rnHsRecFieldsAndThen_Pattern :: Located Name
458 -> NameMaker -- new name maker
459 -> HsRecFields RdrName (LPat RdrName)
460 -> (HsRecFields Name (LPat Name) -> RnM (c, FreeVars))
462 rnHsRecFieldsAndThen_Pattern n var
463 = rnHsRecFieldsAndThen (Pattern n VarPat) (rnLPatAndThen var)
466 -- wrapper to use rnLExpr in CPS style;
467 -- because it does not bind any vars going forward, it does not need
468 -- to be written that way
469 rnLExprAndThen :: (LHsExpr RdrName -> RnM (LHsExpr Name, FreeVars))
471 -> (LHsExpr Name -> RnM (c, FreeVars))
473 rnLExprAndThen f e cont = do { (x, fvs1) <- f e
474 ; (res, fvs2) <- cont x
475 ; return (res, fvs1 `plusFV` fvs2) }
478 -- non-CPSed because exprs don't leave anything bound
479 rnHsRecFields_Con :: Located Name
480 -> (LHsExpr RdrName -> RnM (LHsExpr Name, FreeVars))
481 -> HsRecFields RdrName (LHsExpr RdrName)
482 -> RnM (HsRecFields Name (LHsExpr Name), FreeVars)
483 rnHsRecFields_Con n rnLExpr fields = rnHsRecFieldsAndThen (Constructor n HsVar)
484 (rnLExprAndThen rnLExpr) fields $ \ res ->
485 return (res, emptyFVs)
487 rnHsRecFields_Update :: (LHsExpr RdrName -> RnM (LHsExpr Name, FreeVars))
488 -> HsRecFields RdrName (LHsExpr RdrName)
489 -> RnM (HsRecFields Name (LHsExpr Name), FreeVars)
490 rnHsRecFields_Update rnLExpr fields = rnHsRecFieldsAndThen Update
491 (rnLExprAndThen rnLExpr) fields $ \ res ->
492 return (res, emptyFVs)
497 %************************************************************************
499 \subsubsection{Literals}
501 %************************************************************************
503 When literals occur we have to make sure
504 that the types and classes they involve
508 rnLit :: HsLit -> RnM ()
509 rnLit (HsChar c) = checkErr (inCharRange c) (bogusCharError c)
510 rnLit other = returnM ()
512 rnOverLit (HsIntegral i _ _)
513 = lookupSyntaxName fromIntegerName `thenM` \ (from_integer_name, fvs) ->
515 returnM (HsIntegral i from_integer_name placeHolderType, fvs)
517 extra_fvs = mkFVs [plusIntegerName, timesIntegerName]
518 -- Big integer literals are built, using + and *,
519 -- out of small integers (DsUtils.mkIntegerLit)
520 -- [NB: plusInteger, timesInteger aren't rebindable...
521 -- they are used to construct the argument to fromInteger,
522 -- which is the rebindable one.]
524 returnM (HsIntegral i from_integer_name placeHolderType, fvs `plusFV` extra_fvs)
526 rnOverLit (HsFractional i _ _)
527 = lookupSyntaxName fromRationalName `thenM` \ (from_rat_name, fvs) ->
529 extra_fvs = mkFVs [ratioDataConName, plusIntegerName, timesIntegerName]
530 -- We have to make sure that the Ratio type is imported with
531 -- its constructor, because literals of type Ratio t are
532 -- built with that constructor.
533 -- The Rational type is needed too, but that will come in
534 -- as part of the type for fromRational.
535 -- The plus/times integer operations may be needed to construct the numerator
536 -- and denominator (see DsUtils.mkIntegerLit)
538 returnM (HsFractional i from_rat_name placeHolderType, fvs `plusFV` extra_fvs)
540 rnOverLit (HsIsString s _ _)
541 = lookupSyntaxName fromStringName `thenM` \ (from_string_name, fvs) ->
542 returnM (HsIsString s from_string_name placeHolderType, fvs)
546 %************************************************************************
548 \subsubsection{Errors}
550 %************************************************************************
553 checkTupSize :: Int -> RnM ()
554 checkTupSize tup_size
555 | tup_size <= mAX_TUPLE_SIZE
558 = addErr (sep [ptext SLIT("A") <+> int tup_size <> ptext SLIT("-tuple is too large for GHC"),
559 nest 2 (parens (ptext SLIT("max size is") <+> int mAX_TUPLE_SIZE)),
560 nest 2 (ptext SLIT("Workaround: use nested tuples or define a data type"))])
563 = (ptext SLIT("Illegal signature in pattern:") <+> ppr ty)
564 $$ nest 4 (ptext SLIT("Use -XPatternSignatures to permit it"))
567 = hsep [ptext SLIT("duplicate field name"),
569 ptext SLIT("in record"), text str]
572 = ptext SLIT("character literal out of range: '\\") <> char c <> char '\''
574 badViewPat pat = vcat [ptext SLIT("Illegal view pattern: ") <+> ppr pat,
575 ptext SLIT("Use -XViewPatterns to enalbe view patterns")]