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
13 module RnPat (-- main entry points
16 NameMaker, applyNameMaker, -- a utility for making names:
17 localRecNameMaker, topRecNameMaker, -- sometimes we want to make local names,
18 -- sometimes we want to make top (qualified) names.
20 rnHsRecFields1, HsRecFieldContext(..),
28 -- Pattern Error messages that are also used elsewhere
29 checkTupSize, patSigErr
32 -- ENH: thin imports to only what is necessary for patterns
34 import {-# SOURCE #-} RnExpr ( rnLExpr )
36 import {-# SOURCE #-} TcSplice ( runQuasiQuotePat )
39 #include "HsVersions.h"
43 import TcHsSyn ( hsOverLitName )
46 import DynFlags ( DynFlag(..) )
48 import Constants ( mAX_TUPLE_SIZE )
53 import ListSetOps ( removeDups, minusList )
57 import Literal ( inCharRange )
58 import Control.Monad ( when )
62 %*********************************************************
66 %*********************************************************
70 The CpsRn monad uses continuation-passing style to support this
77 where rs::[RdrName], ns::[Name]
79 The idea is that '...blah...'
80 a) sees the bindings of ns
81 b) returns the free variables it mentions
82 so that bindNames can report unused ones
85 mapM rnPatAndThen [p1, p2, p3]
86 has a *left-to-right* scoping: it makes the binders in
90 newtype CpsRn b = CpsRn { unCpsRn :: forall r. (b -> RnM (r, FreeVars))
91 -> RnM (r, FreeVars) }
92 -- See Note [CpsRn monad]
94 instance Monad CpsRn where
95 return x = CpsRn (\k -> k x)
96 (CpsRn m) >>= mk = CpsRn (\k -> m (\v -> unCpsRn (mk v) k))
98 runCps :: CpsRn a -> RnM (a, FreeVars)
99 runCps (CpsRn m) = m (\r -> return (r, emptyFVs))
101 liftCps :: RnM a -> CpsRn a
102 liftCps rn_thing = CpsRn (\k -> rn_thing >>= k)
104 liftCpsFV :: RnM (a, FreeVars) -> CpsRn a
105 liftCpsFV rn_thing = CpsRn (\k -> do { (v,fvs1) <- rn_thing
107 ; return (r, fvs1 `plusFV` fvs2) })
109 wrapSrcSpanCps :: (a -> CpsRn b) -> Located a -> CpsRn (Located b)
110 -- Set the location, and also wrap it around the value returned
111 wrapSrcSpanCps fn (L loc a)
112 = CpsRn (\k -> setSrcSpan loc $
113 unCpsRn (fn a) $ \v ->
116 lookupConCps :: Located RdrName -> CpsRn (Located Name)
118 = CpsRn (\k -> do { con_name <- lookupLocatedOccRn con_rdr
119 ; (r, fvs) <- k con_name
120 ; return (r, fvs `plusFV` unitFV (unLoc con_name)) })
123 %*********************************************************
127 %*********************************************************
129 Externally abstract type of name makers,
130 which is how you go from a RdrName to a Name
135 Bool -- True <=> report unused bindings
137 | LetMk -- Let bindings, incl top level
138 -- Do not check for unused bindings
139 (Maybe Module) -- Just m => top level of module m
140 -- Nothing => not top level
143 topRecNameMaker :: Module -> MiniFixityEnv -> NameMaker
144 topRecNameMaker mod fix_env = LetMk (Just mod) fix_env
146 localRecNameMaker :: MiniFixityEnv -> NameMaker
147 localRecNameMaker fix_env = LetMk Nothing fix_env
149 matchNameMaker :: NameMaker
150 matchNameMaker = LamMk True
152 newName :: NameMaker -> Located RdrName -> CpsRn Name
153 newName (LamMk report_unused) rdr_name
154 = CpsRn (\ thing_inside ->
155 do { name <- newLocalBndrRn rdr_name
156 ; (res, fvs) <- bindLocalName name (thing_inside name)
157 ; when report_unused $ warnUnusedMatches [name] fvs
158 ; return (res, name `delFV` fvs) })
160 newName (LetMk mb_top fix_env) rdr_name
161 = CpsRn (\ thing_inside ->
162 do { name <- case mb_top of
163 Nothing -> newLocalBndrRn rdr_name
164 Just mod -> newTopSrcBinder mod rdr_name
165 ; bindLocalNamesFV_WithFixities [name] fix_env $
168 -- Note: the bindLocalNamesFV_WithFixities is somewhat suspicious
169 -- because it binds a top-level name as a local name.
170 -- however, this binding seems to work, and it only exists for
171 -- the duration of the patterns and the continuation;
172 -- then the top-level name is added to the global env
173 -- before going on to the RHSes (see RnSource.lhs).
177 %*********************************************************
179 External entry points
181 %*********************************************************
183 There are various entry points to renaming patterns, depending on
184 (1) whether the names created should be top-level names or local names
185 (2) whether the scope of the names is entirely given in a continuation
186 (e.g., in a case or lambda, but not in a let or at the top-level,
187 because of the way mutually recursive bindings are handled)
188 (3) whether the a type signature in the pattern can bind
189 lexically-scoped type variables (for unpacking existential
190 type vars in data constructors)
191 (4) whether we do duplicate and unused variable checking
192 (5) whether there are fixity declarations associated with the names
193 bound by the patterns that need to be brought into scope with them.
195 Rather than burdening the clients of this module with all of these choices,
196 we export the three points in this design space that we actually need:
199 -- ----------- Entry point 1: rnPats -------------------
200 -- Binds local names; the scope of the bindings is entirely in the thing_inside
201 -- * allows type sigs to bind type vars
203 -- * unused and duplicate checking
205 rnPats :: HsMatchContext Name -- for error messages
207 -> ([LPat Name] -> RnM (a, FreeVars))
209 rnPats ctxt pats thing_inside
210 = do { envs_before <- getRdrEnvs
212 -- (0) bring into scope all of the type variables bound by the patterns
213 -- (1) rename the patterns, bringing into scope all of the term variables
214 -- (2) then do the thing inside.
215 ; bindPatSigTyVarsFV (collectSigTysFromPats pats) $
216 unCpsRn (rnLPatsAndThen matchNameMaker pats) $ \ pats' -> do
217 { -- Check for duplicated and shadowed names
218 -- Because we don't bind the vars all at once, we can't
219 -- check incrementally for duplicates;
220 -- Nor can we check incrementally for shadowing, else we'll
221 -- complain *twice* about duplicates e.g. f (x,x) = ...
222 ; let names = collectPatsBinders pats'
223 ; checkDupNames doc_pat names
224 ; checkShadowedNames doc_pat envs_before
225 [(nameSrcSpan name, nameOccName name) | name <- names]
226 ; thing_inside pats' } }
228 doc_pat = ptext (sLit "In") <+> pprMatchContext ctxt
231 applyNameMaker :: NameMaker -> Located RdrName -> RnM Name
232 applyNameMaker mk rdr = do { (n, _fvs) <- runCps (newName mk rdr); return n }
234 -- ----------- Entry point 2: rnBindPat -------------------
235 -- Binds local names; in a recursive scope that involves other bound vars
236 -- e.g let { (x, Just y) = e1; ... } in ...
237 -- * does NOT allows type sig to bind type vars
239 -- * no unused and duplicate checking
240 -- * fixities might be coming in
241 rnBindPat :: NameMaker
243 -> RnM (LPat Name, FreeVars)
244 -- Returned FreeVars are the free variables of the pattern,
245 -- of course excluding variables bound by this pattern
247 rnBindPat name_maker pat = runCps (rnLPatAndThen name_maker pat)
251 %*********************************************************
255 %*********************************************************
258 -- ----------- Entry point 3: rnLPatAndThen -------------------
259 -- General version: parametrized by how you make new names
261 rnLPatsAndThen :: NameMaker -> [LPat RdrName] -> CpsRn [LPat Name]
262 rnLPatsAndThen mk = mapM (rnLPatAndThen mk)
263 -- Despite the map, the monad ensures that each pattern binds
264 -- variables that may be mentioned in subsequent patterns in the list
268 rnLPatAndThen :: NameMaker -> LPat RdrName -> CpsRn (LPat Name)
269 rnLPatAndThen nm lpat = wrapSrcSpanCps (rnPatAndThen nm) lpat
271 rnPatAndThen :: NameMaker -> Pat RdrName -> CpsRn (Pat Name)
272 rnPatAndThen _ (WildPat _) = return (WildPat placeHolderType)
273 rnPatAndThen mk (ParPat pat) = do { pat' <- rnLPatAndThen mk pat; return (ParPat pat') }
274 rnPatAndThen mk (LazyPat pat) = do { pat' <- rnLPatAndThen mk pat; return (LazyPat pat') }
275 rnPatAndThen mk (BangPat pat) = do { pat' <- rnLPatAndThen mk pat; return (BangPat pat') }
276 rnPatAndThen mk (VarPat rdr) = do { loc <- liftCps getSrcSpanM
277 ; name <- newName mk (L loc rdr)
278 ; return (VarPat name) }
279 -- we need to bind pattern variables for view pattern expressions
280 -- (e.g. in the pattern (x, x -> y) x needs to be bound in the rhs of the tuple)
282 rnPatAndThen mk (SigPatIn pat ty)
283 = do { patsigs <- liftCps (doptM Opt_ScopedTypeVariables)
285 then do { pat' <- rnLPatAndThen mk pat
286 ; ty' <- liftCpsFV (rnHsTypeFVs tvdoc ty)
287 ; return (SigPatIn pat' ty') }
288 else do { liftCps (addErr (patSigErr ty))
289 ; rnPatAndThen mk (unLoc pat) } }
291 tvdoc = text "In a pattern type-signature"
293 rnPatAndThen mk (LitPat lit)
295 = do { ovlStr <- liftCps (doptM Opt_OverloadedStrings)
297 then rnPatAndThen mk (mkNPat (mkHsIsString s placeHolderType) Nothing)
299 | otherwise = normal_lit
301 normal_lit = do { liftCps (rnLit lit); return (LitPat lit) }
303 rnPatAndThen _ (NPat lit mb_neg _eq)
304 = do { lit' <- liftCpsFV $ rnOverLit lit
305 ; mb_neg' <- liftCpsFV $ case mb_neg of
306 Nothing -> return (Nothing, emptyFVs)
307 Just _ -> do { (neg, fvs) <- lookupSyntaxName negateName
308 ; return (Just neg, fvs) }
309 ; eq' <- liftCpsFV $ lookupSyntaxName eqName
310 ; return (NPat lit' mb_neg' eq') }
312 rnPatAndThen mk (NPlusKPat rdr lit _ _)
313 = do { new_name <- newName mk rdr
314 ; lit' <- liftCpsFV $ rnOverLit lit
315 ; minus <- liftCpsFV $ lookupSyntaxName minusName
316 ; ge <- liftCpsFV $ lookupSyntaxName geName
317 ; return (NPlusKPat (L (nameSrcSpan new_name) new_name) lit' ge minus) }
318 -- The Report says that n+k patterns must be in Integral
320 rnPatAndThen mk (AsPat rdr pat)
321 = do { new_name <- newName mk rdr
322 ; pat' <- rnLPatAndThen mk pat
323 ; return (AsPat (L (nameSrcSpan new_name) new_name) pat') }
325 rnPatAndThen mk p@(ViewPat expr pat ty)
326 = do { liftCps $ do { vp_flag <- doptM Opt_ViewPatterns
327 ; checkErr vp_flag (badViewPat p) }
328 -- Because of the way we're arranging the recursive calls,
329 -- this will be in the right context
330 ; expr' <- liftCpsFV $ rnLExpr expr
331 ; pat' <- rnLPatAndThen mk pat
332 ; return (ViewPat expr' pat' ty) }
334 rnPatAndThen mk (ConPatIn con stuff)
335 -- rnConPatAndThen takes care of reconstructing the pattern
336 = rnConPatAndThen mk con stuff
338 rnPatAndThen mk (ListPat pats _)
339 = do { pats' <- rnLPatsAndThen mk pats
340 ; return (ListPat pats' placeHolderType) }
342 rnPatAndThen mk (PArrPat pats _)
343 = do { pats' <- rnLPatsAndThen mk pats
344 ; return (PArrPat pats' placeHolderType) }
346 rnPatAndThen mk (TuplePat pats boxed _)
347 = do { liftCps $ checkTupSize (length pats)
348 ; pats' <- rnLPatsAndThen mk pats
349 ; return (TuplePat pats' boxed placeHolderType) }
351 rnPatAndThen _ (TypePat ty)
352 = do { ty' <- liftCpsFV $ rnHsTypeFVs (text "In a type pattern") ty
353 ; return (TypePat ty') }
356 rnPatAndThen _ p@(QuasiQuotePat {})
357 = pprPanic "Can't do QuasiQuotePat without GHCi" (ppr p)
359 rnPatAndThen mk (QuasiQuotePat qq)
360 = do { qq' <- liftCpsFV $ rnQuasiQuote qq
361 ; pat <- liftCps $ runQuasiQuotePat qq'
362 ; L _ pat' <- rnLPatAndThen mk pat
366 rnPatAndThen _ pat = pprPanic "rnLPatAndThen" (ppr pat)
370 rnConPatAndThen :: NameMaker
371 -> Located RdrName -- the constructor
372 -> HsConPatDetails RdrName
375 rnConPatAndThen mk con (PrefixCon pats)
376 = do { con' <- lookupConCps con
377 ; pats' <- rnLPatsAndThen mk pats
378 ; return (ConPatIn con' (PrefixCon pats')) }
380 rnConPatAndThen mk con (InfixCon pat1 pat2)
381 = do { con' <- lookupConCps con
382 ; pat1' <- rnLPatAndThen mk pat1
383 ; pat2' <- rnLPatAndThen mk pat2
384 ; fixity <- liftCps $ lookupFixityRn (unLoc con')
385 ; liftCps $ mkConOpPatRn con' fixity pat1' pat2' }
387 rnConPatAndThen mk con (RecCon rpats)
388 = do { con' <- lookupConCps con
389 ; rpats' <- rnHsRecPatsAndThen mk con' rpats
390 ; return (ConPatIn con' (RecCon rpats')) }
393 rnHsRecPatsAndThen :: NameMaker
394 -> Located Name -- Constructor
395 -> HsRecFields RdrName (LPat RdrName)
396 -> CpsRn (HsRecFields Name (LPat Name))
397 rnHsRecPatsAndThen mk (L _ con) hs_rec_fields@(HsRecFields { rec_dotdot = dd })
398 = do { flds <- liftCpsFV $ rnHsRecFields1 (HsRecFieldPat con) VarPat hs_rec_fields
399 ; flds' <- mapM rn_field (flds `zip` [1..])
400 ; return (HsRecFields { rec_flds = flds', rec_dotdot = dd }) }
402 rn_field (fld, n') = do { arg' <- rnLPatAndThen (nested_mk dd mk n')
404 ; return (fld { hsRecFieldArg = arg' }) }
406 -- Suppress unused-match reporting for fields introduced by ".."
407 nested_mk Nothing mk _ = mk
408 nested_mk (Just _) mk@(LetMk {}) _ = mk
409 nested_mk (Just n) (LamMk report_unused) n' = LamMk (report_unused && (n' <= n))
413 %************************************************************************
417 %************************************************************************
420 data HsRecFieldContext
427 -> (RdrName -> arg) -- When punning, use this to build a new field
428 -> HsRecFields RdrName (Located arg)
429 -> RnM ([HsRecField Name (Located arg)], FreeVars)
431 -- This supprisingly complicated pass
432 -- a) looks up the field name (possibly using disambiguation)
433 -- b) fills in puns and dot-dot stuff
434 -- When we we've finished, we've renamed the LHS, but not the RHS,
435 -- of each x=e binding
437 rnHsRecFields1 ctxt mk_arg (HsRecFields { rec_flds = flds, rec_dotdot = dotdot })
438 = do { pun_ok <- doptM Opt_RecordPuns
439 ; disambig_ok <- doptM Opt_DisambiguateRecordFields
440 ; parent <- check_disambiguation disambig_ok mb_con
441 ; flds1 <- mapM (rn_fld pun_ok parent) flds
442 ; mapM_ (addErr . dupFieldErr ctxt) dup_flds
443 ; flds2 <- rn_dotdot dotdot mb_con flds1
444 ; return (flds2, mkFVs (getFieldIds flds2)) }
446 mb_con = case ctxt of
447 HsRecFieldUpd -> Nothing
448 HsRecFieldCon con -> Just con
449 HsRecFieldPat con -> Just con
451 Nothing -> ptext (sLit "constructor field name")
452 Just con -> ptext (sLit "field of constructor") <+> quotes (ppr con)
454 name_to_arg (L loc n) = L loc (mk_arg (mkRdrUnqual (nameOccName n)))
456 rn_fld pun_ok parent (HsRecField { hsRecFieldId = fld
457 , hsRecFieldArg = arg
459 = do { fld' <- wrapLocM (lookupSubBndr parent doc) fld
461 then do { checkErr pun_ok (badPun fld)
462 ; return (name_to_arg fld') }
464 ; return (HsRecField { hsRecFieldId = fld'
465 , hsRecFieldArg = arg'
466 , hsRecPun = pun }) }
468 rn_dotdot Nothing _mb_con flds -- No ".." at all
470 rn_dotdot (Just {}) Nothing flds -- ".." on record update
471 = do { addErr (badDotDot ctxt); return flds }
472 rn_dotdot (Just n) (Just con) flds -- ".." on record con/pat
473 = ASSERT( n == length flds )
474 do { loc <- getSrcSpanM -- Rather approximate
475 ; dd_flag <- doptM Opt_RecordWildCards
476 ; checkErr dd_flag (needFlagDotDot ctxt)
478 ; con_fields <- lookupConstructorFields con
479 ; let present_flds = getFieldIds flds
480 absent_flds = con_fields `minusList` present_flds
481 extras = [ HsRecField
482 { hsRecFieldId = L loc f
483 , hsRecFieldArg = name_to_arg (L loc f)
487 ; return (flds ++ extras) }
489 check_disambiguation :: Bool -> Maybe Name -> RnM Parent
490 -- When disambiguation is on, return the parent *type constructor*
491 -- That is, the parent of the data constructor. That's the parent
492 -- to use for looking up record fields.
493 check_disambiguation disambig_ok mb_con
494 | disambig_ok, Just con <- mb_con
495 = do { env <- getGlobalRdrEnv
496 ; return (case lookupGRE_Name env con of
498 gres -> WARN( True, ppr con <+> ppr gres ) NoParent) }
499 | otherwise = return NoParent
501 dup_flds :: [[RdrName]]
502 -- Each list represents a RdrName that occurred more than once
503 -- (the list contains all occurrences)
504 -- Each list in dup_fields is non-empty
505 (_, dup_flds) = removeDups compare (getFieldIds flds)
507 getFieldIds :: [HsRecField id arg] -> [id]
508 getFieldIds flds = map (unLoc . hsRecFieldId) flds
510 needFlagDotDot :: HsRecFieldContext -> SDoc
511 needFlagDotDot ctxt = vcat [ptext (sLit "Illegal `..' in record") <+> pprRFC ctxt,
512 ptext (sLit "Use -XRecordWildCards to permit this")]
514 badDotDot :: HsRecFieldContext -> SDoc
515 badDotDot ctxt = ptext (sLit "You cannot use `..' in a record") <+> pprRFC ctxt
517 badPun :: Located RdrName -> SDoc
518 badPun fld = vcat [ptext (sLit "Illegal use of punning for field") <+> quotes (ppr fld),
519 ptext (sLit "Use -XNamedFieldPuns to permit this")]
521 dupFieldErr :: HsRecFieldContext -> [RdrName] -> SDoc
522 dupFieldErr ctxt dups
523 = hsep [ptext (sLit "duplicate field name"),
524 quotes (ppr (head dups)),
525 ptext (sLit "in record"), pprRFC ctxt]
527 pprRFC :: HsRecFieldContext -> SDoc
528 pprRFC (HsRecFieldCon {}) = ptext (sLit "construction")
529 pprRFC (HsRecFieldPat {}) = ptext (sLit "pattern")
530 pprRFC (HsRecFieldUpd {}) = ptext (sLit "update")
534 %************************************************************************
536 \subsubsection{Literals}
538 %************************************************************************
540 When literals occur we have to make sure
541 that the types and classes they involve
545 rnLit :: HsLit -> RnM ()
546 rnLit (HsChar c) = checkErr (inCharRange c) (bogusCharError c)
549 rnOverLit :: HsOverLit t -> RnM (HsOverLit Name, FreeVars)
550 rnOverLit lit@(OverLit {ol_val=val})
551 = do { let std_name = hsOverLitName val
552 ; (from_thing_name, fvs) <- lookupSyntaxName std_name
553 ; let rebindable = case from_thing_name of
554 HsVar v -> v /= std_name
555 _ -> panic "rnOverLit"
556 ; return (lit { ol_witness = from_thing_name
557 , ol_rebindable = rebindable }, fvs) }
560 %************************************************************************
562 \subsubsection{Quasiquotation}
564 %************************************************************************
566 See Note [Quasi-quote overview] in TcSplice.
569 rnQuasiQuote :: HsQuasiQuote RdrName -> RnM (HsQuasiQuote Name, FreeVars)
570 rnQuasiQuote (HsQuasiQuote n quoter quoteSpan quote)
571 = do { loc <- getSrcSpanM
572 ; n' <- newLocalBndrRn (L loc n)
573 ; quoter' <- lookupOccRn quoter
574 -- If 'quoter' is not in scope, proceed no further
575 -- Otherwise lookupOcc adds an error messsage and returns
576 -- an "unubound name", which makes the subsequent attempt to
577 -- run the quote fail
578 ; return (HsQuasiQuote n' quoter' quoteSpan quote, unitFV quoter') }
581 %************************************************************************
583 \subsubsection{Errors}
585 %************************************************************************
588 checkTupSize :: Int -> RnM ()
589 checkTupSize tup_size
590 | tup_size <= mAX_TUPLE_SIZE
593 = addErr (sep [ptext (sLit "A") <+> int tup_size <> ptext (sLit "-tuple is too large for GHC"),
594 nest 2 (parens (ptext (sLit "max size is") <+> int mAX_TUPLE_SIZE)),
595 nest 2 (ptext (sLit "Workaround: use nested tuples or define a data type"))])
597 patSigErr :: Outputable a => a -> SDoc
599 = (ptext (sLit "Illegal signature in pattern:") <+> ppr ty)
600 $$ nest 4 (ptext (sLit "Use -XScopedTypeVariables to permit it"))
602 bogusCharError :: Char -> SDoc
604 = ptext (sLit "character literal out of range: '\\") <> char c <> char '\''
606 badViewPat :: Pat RdrName -> SDoc
607 badViewPat pat = vcat [ptext (sLit "Illegal view pattern: ") <+> ppr pat,
608 ptext (sLit "Use -XViewPatterns to enable view patterns")]