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
14 rnPat, rnPats, rnBindPat,
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(..),
25 -- Pattern Error messages that are also used elsewhere
26 checkTupSize, patSigErr
29 -- ENH: thin imports to only what is necessary for patterns
31 import {-# SOURCE #-} RnExpr ( rnLExpr )
33 import {-# SOURCE #-} TcSplice ( runQuasiQuotePat )
36 #include "HsVersions.h"
40 import TcHsSyn ( hsOverLitName )
43 import DynFlags ( DynFlag(..) )
45 import Constants ( mAX_TUPLE_SIZE )
50 import ListSetOps ( removeDups, minusList )
54 import Literal ( inCharRange )
55 import Control.Monad ( when )
59 %*********************************************************
63 %*********************************************************
67 The CpsRn monad uses continuation-passing style to support this
74 where rs::[RdrName], ns::[Name]
76 The idea is that '...blah...'
77 a) sees the bindings of ns
78 b) returns the free variables it mentions
79 so that bindNames can report unused ones
82 mapM rnPatAndThen [p1, p2, p3]
83 has a *left-to-right* scoping: it makes the binders in
87 newtype CpsRn b = CpsRn { unCpsRn :: forall r. (b -> RnM (r, FreeVars))
88 -> RnM (r, FreeVars) }
89 -- See Note [CpsRn monad]
91 instance Monad CpsRn where
92 return x = CpsRn (\k -> k x)
93 (CpsRn m) >>= mk = CpsRn (\k -> m (\v -> unCpsRn (mk v) k))
95 runCps :: CpsRn a -> RnM (a, FreeVars)
96 runCps (CpsRn m) = m (\r -> return (r, emptyFVs))
98 liftCps :: RnM a -> CpsRn a
99 liftCps rn_thing = CpsRn (\k -> rn_thing >>= k)
101 liftCpsFV :: RnM (a, FreeVars) -> CpsRn a
102 liftCpsFV rn_thing = CpsRn (\k -> do { (v,fvs1) <- rn_thing
104 ; return (r, fvs1 `plusFV` fvs2) })
106 wrapSrcSpanCps :: (a -> CpsRn b) -> Located a -> CpsRn (Located b)
107 -- Set the location, and also wrap it around the value returned
108 wrapSrcSpanCps fn (L loc a)
109 = CpsRn (\k -> setSrcSpan loc $
110 unCpsRn (fn a) $ \v ->
113 lookupConCps :: Located RdrName -> CpsRn (Located Name)
115 = CpsRn (\k -> do { con_name <- lookupLocatedOccRn con_rdr
116 ; (r, fvs) <- k con_name
117 ; return (r, fvs `plusFV` unitFV (unLoc con_name)) })
120 %*********************************************************
124 %*********************************************************
126 Externally abstract type of name makers,
127 which is how you go from a RdrName to a Name
132 Bool -- True <=> report unused bindings
133 -- (even if True, the warning only comes out
134 -- if -fwarn-unused-matches is on)
136 | LetMk -- Let bindings, incl top level
137 -- Do *not* check for unused bindings
138 (Maybe Module) -- Just m => top level of module m
139 -- Nothing => not top level
142 topRecNameMaker :: Module -> MiniFixityEnv -> NameMaker
143 topRecNameMaker mod fix_env = LetMk (Just mod) fix_env
145 localRecNameMaker :: MiniFixityEnv -> NameMaker
146 localRecNameMaker fix_env = LetMk Nothing fix_env
148 matchNameMaker :: HsMatchContext a -> NameMaker
149 matchNameMaker ctxt = LamMk report_unused
151 -- Do not report unused names in interactive contexts
152 -- i.e. when you type 'x <- e' at the GHCi prompt
153 report_unused = case ctxt of
154 StmtCtxt GhciStmt -> False
157 newName :: NameMaker -> Located RdrName -> CpsRn Name
158 newName (LamMk report_unused) rdr_name
159 = CpsRn (\ thing_inside ->
160 do { name <- newLocalBndrRn rdr_name
161 ; (res, fvs) <- bindLocalName name (thing_inside name)
162 ; when report_unused $ warnUnusedMatches [name] fvs
163 ; return (res, name `delFV` fvs) })
165 newName (LetMk mb_top fix_env) rdr_name
166 = CpsRn (\ thing_inside ->
167 do { name <- case mb_top of
168 Nothing -> newLocalBndrRn rdr_name
169 Just mod -> newTopSrcBinder mod rdr_name
170 ; bindLocalName name $ -- Do *not* use bindLocalNameFV here
171 -- See Note [View pattern usage]
172 addLocalFixities fix_env [name] $
175 -- Note: the bindLocalName is somewhat suspicious
176 -- because it binds a top-level name as a local name.
177 -- however, this binding seems to work, and it only exists for
178 -- the duration of the patterns and the continuation;
179 -- then the top-level name is added to the global env
180 -- before going on to the RHSes (see RnSource.lhs).
183 Note [View pattern usage]
184 ~~~~~~~~~~~~~~~~~~~~~~~~~
186 let (r, (r -> x)) = x in ...
187 Here the pattern binds 'r', and then uses it *only* in the view pattern.
188 We want to "see" this use, and in let-bindings we collect all uses and
189 report unused variables at the binding level. So we must use bindLocalName
190 here, *not* bindLocalNameFV. Trac #3943.
192 %*********************************************************
194 External entry points
196 %*********************************************************
198 There are various entry points to renaming patterns, depending on
199 (1) whether the names created should be top-level names or local names
200 (2) whether the scope of the names is entirely given in a continuation
201 (e.g., in a case or lambda, but not in a let or at the top-level,
202 because of the way mutually recursive bindings are handled)
203 (3) whether the a type signature in the pattern can bind
204 lexically-scoped type variables (for unpacking existential
205 type vars in data constructors)
206 (4) whether we do duplicate and unused variable checking
207 (5) whether there are fixity declarations associated with the names
208 bound by the patterns that need to be brought into scope with them.
210 Rather than burdening the clients of this module with all of these choices,
211 we export the three points in this design space that we actually need:
214 -- ----------- Entry point 1: rnPats -------------------
215 -- Binds local names; the scope of the bindings is entirely in the thing_inside
216 -- * allows type sigs to bind type vars
218 -- * unused and duplicate checking
220 rnPats :: HsMatchContext Name -- for error messages
222 -> ([LPat Name] -> RnM (a, FreeVars))
224 rnPats ctxt pats thing_inside
225 = do { envs_before <- getRdrEnvs
227 -- (0) bring into scope all of the type variables bound by the patterns
228 -- (1) rename the patterns, bringing into scope all of the term variables
229 -- (2) then do the thing inside.
230 ; bindPatSigTyVarsFV (collectSigTysFromPats pats) $
231 unCpsRn (rnLPatsAndThen (matchNameMaker ctxt) pats) $ \ pats' -> do
232 { -- Check for duplicated and shadowed names
233 -- Because we don't bind the vars all at once, we can't
234 -- check incrementally for duplicates;
235 -- Nor can we check incrementally for shadowing, else we'll
236 -- complain *twice* about duplicates e.g. f (x,x) = ...
237 ; let names = collectPatsBinders pats'
238 ; addErrCtxt doc_pat $ checkDupAndShadowedNames envs_before names
239 ; thing_inside pats' } }
241 doc_pat = ptext (sLit "In") <+> pprMatchContext ctxt
243 rnPat :: HsMatchContext Name -- for error messages
245 -> (LPat Name -> RnM (a, FreeVars))
246 -> RnM (a, FreeVars) -- Variables bound by pattern do not
247 -- appear in the result FreeVars
248 rnPat ctxt pat thing_inside
249 = rnPats ctxt [pat] (\[pat'] -> thing_inside pat')
251 applyNameMaker :: NameMaker -> Located RdrName -> RnM Name
252 applyNameMaker mk rdr = do { (n, _fvs) <- runCps (newName mk rdr); return n }
254 -- ----------- Entry point 2: rnBindPat -------------------
255 -- Binds local names; in a recursive scope that involves other bound vars
256 -- e.g let { (x, Just y) = e1; ... } in ...
257 -- * does NOT allows type sig to bind type vars
259 -- * no unused and duplicate checking
260 -- * fixities might be coming in
261 rnBindPat :: NameMaker
263 -> RnM (LPat Name, FreeVars)
264 -- Returned FreeVars are the free variables of the pattern,
265 -- of course excluding variables bound by this pattern
267 rnBindPat name_maker pat = runCps (rnLPatAndThen name_maker pat)
271 %*********************************************************
275 %*********************************************************
278 -- ----------- Entry point 3: rnLPatAndThen -------------------
279 -- General version: parametrized by how you make new names
281 rnLPatsAndThen :: NameMaker -> [LPat RdrName] -> CpsRn [LPat Name]
282 rnLPatsAndThen mk = mapM (rnLPatAndThen mk)
283 -- Despite the map, the monad ensures that each pattern binds
284 -- variables that may be mentioned in subsequent patterns in the list
288 rnLPatAndThen :: NameMaker -> LPat RdrName -> CpsRn (LPat Name)
289 rnLPatAndThen nm lpat = wrapSrcSpanCps (rnPatAndThen nm) lpat
291 rnPatAndThen :: NameMaker -> Pat RdrName -> CpsRn (Pat Name)
292 rnPatAndThen _ (WildPat _) = return (WildPat placeHolderType)
293 rnPatAndThen mk (ParPat pat) = do { pat' <- rnLPatAndThen mk pat; return (ParPat pat') }
294 rnPatAndThen mk (LazyPat pat) = do { pat' <- rnLPatAndThen mk pat; return (LazyPat pat') }
295 rnPatAndThen mk (BangPat pat) = do { pat' <- rnLPatAndThen mk pat; return (BangPat pat') }
296 rnPatAndThen mk (VarPat rdr) = do { loc <- liftCps getSrcSpanM
297 ; name <- newName mk (L loc rdr)
298 ; return (VarPat name) }
299 -- we need to bind pattern variables for view pattern expressions
300 -- (e.g. in the pattern (x, x -> y) x needs to be bound in the rhs of the tuple)
302 rnPatAndThen mk (SigPatIn pat ty)
303 = do { patsigs <- liftCps (doptM Opt_ScopedTypeVariables)
305 then do { pat' <- rnLPatAndThen mk pat
306 ; ty' <- liftCpsFV (rnHsTypeFVs tvdoc ty)
307 ; return (SigPatIn pat' ty') }
308 else do { liftCps (addErr (patSigErr ty))
309 ; rnPatAndThen mk (unLoc pat) } }
311 tvdoc = text "In a pattern type-signature"
313 rnPatAndThen mk (LitPat lit)
315 = do { ovlStr <- liftCps (doptM Opt_OverloadedStrings)
317 then rnPatAndThen mk (mkNPat (mkHsIsString s placeHolderType) Nothing)
319 | otherwise = normal_lit
321 normal_lit = do { liftCps (rnLit lit); return (LitPat lit) }
323 rnPatAndThen _ (NPat lit mb_neg _eq)
324 = do { lit' <- liftCpsFV $ rnOverLit lit
325 ; mb_neg' <- liftCpsFV $ case mb_neg of
326 Nothing -> return (Nothing, emptyFVs)
327 Just _ -> do { (neg, fvs) <- lookupSyntaxName negateName
328 ; return (Just neg, fvs) }
329 ; eq' <- liftCpsFV $ lookupSyntaxName eqName
330 ; return (NPat lit' mb_neg' eq') }
332 rnPatAndThen mk (NPlusKPat rdr lit _ _)
333 = do { new_name <- newName mk rdr
334 ; lit' <- liftCpsFV $ rnOverLit lit
335 ; minus <- liftCpsFV $ lookupSyntaxName minusName
336 ; ge <- liftCpsFV $ lookupSyntaxName geName
337 ; return (NPlusKPat (L (nameSrcSpan new_name) new_name) lit' ge minus) }
338 -- The Report says that n+k patterns must be in Integral
340 rnPatAndThen mk (AsPat rdr pat)
341 = do { new_name <- newName mk rdr
342 ; pat' <- rnLPatAndThen mk pat
343 ; return (AsPat (L (nameSrcSpan new_name) new_name) pat') }
345 rnPatAndThen mk p@(ViewPat expr pat ty)
346 = do { liftCps $ do { vp_flag <- doptM Opt_ViewPatterns
347 ; checkErr vp_flag (badViewPat p) }
348 -- Because of the way we're arranging the recursive calls,
349 -- this will be in the right context
350 ; expr' <- liftCpsFV $ rnLExpr expr
351 ; pat' <- rnLPatAndThen mk pat
352 ; return (ViewPat expr' pat' ty) }
354 rnPatAndThen mk (ConPatIn con stuff)
355 -- rnConPatAndThen takes care of reconstructing the pattern
356 = rnConPatAndThen mk con stuff
358 rnPatAndThen mk (ListPat pats _)
359 = do { pats' <- rnLPatsAndThen mk pats
360 ; return (ListPat pats' placeHolderType) }
362 rnPatAndThen mk (PArrPat pats _)
363 = do { pats' <- rnLPatsAndThen mk pats
364 ; return (PArrPat pats' placeHolderType) }
366 rnPatAndThen mk (TuplePat pats boxed _)
367 = do { liftCps $ checkTupSize (length pats)
368 ; pats' <- rnLPatsAndThen mk pats
369 ; return (TuplePat pats' boxed placeHolderType) }
371 rnPatAndThen _ (TypePat ty)
372 = do { ty' <- liftCpsFV $ rnHsTypeFVs (text "In a type pattern") ty
373 ; return (TypePat ty') }
376 rnPatAndThen _ p@(QuasiQuotePat {})
377 = pprPanic "Can't do QuasiQuotePat without GHCi" (ppr p)
379 rnPatAndThen mk (QuasiQuotePat qq)
380 = do { pat <- liftCps $ runQuasiQuotePat qq
381 ; L _ pat' <- rnLPatAndThen mk pat
385 rnPatAndThen _ pat = pprPanic "rnLPatAndThen" (ppr pat)
389 rnConPatAndThen :: NameMaker
390 -> Located RdrName -- the constructor
391 -> HsConPatDetails RdrName
394 rnConPatAndThen mk con (PrefixCon pats)
395 = do { con' <- lookupConCps con
396 ; pats' <- rnLPatsAndThen mk pats
397 ; return (ConPatIn con' (PrefixCon pats')) }
399 rnConPatAndThen mk con (InfixCon pat1 pat2)
400 = do { con' <- lookupConCps con
401 ; pat1' <- rnLPatAndThen mk pat1
402 ; pat2' <- rnLPatAndThen mk pat2
403 ; fixity <- liftCps $ lookupFixityRn (unLoc con')
404 ; liftCps $ mkConOpPatRn con' fixity pat1' pat2' }
406 rnConPatAndThen mk con (RecCon rpats)
407 = do { con' <- lookupConCps con
408 ; rpats' <- rnHsRecPatsAndThen mk con' rpats
409 ; return (ConPatIn con' (RecCon rpats')) }
412 rnHsRecPatsAndThen :: NameMaker
413 -> Located Name -- Constructor
414 -> HsRecFields RdrName (LPat RdrName)
415 -> CpsRn (HsRecFields Name (LPat Name))
416 rnHsRecPatsAndThen mk (L _ con) hs_rec_fields@(HsRecFields { rec_dotdot = dd })
417 = do { flds <- liftCpsFV $ rnHsRecFields1 (HsRecFieldPat con) VarPat hs_rec_fields
418 ; flds' <- mapM rn_field (flds `zip` [1..])
419 ; return (HsRecFields { rec_flds = flds', rec_dotdot = dd }) }
421 rn_field (fld, n') = do { arg' <- rnLPatAndThen (nested_mk dd mk n')
423 ; return (fld { hsRecFieldArg = arg' }) }
425 -- Suppress unused-match reporting for fields introduced by ".."
426 nested_mk Nothing mk _ = mk
427 nested_mk (Just _) mk@(LetMk {}) _ = mk
428 nested_mk (Just n) (LamMk report_unused) n' = LamMk (report_unused && (n' <= n))
432 %************************************************************************
436 %************************************************************************
439 data HsRecFieldContext
446 -> (RdrName -> arg) -- When punning, use this to build a new field
447 -> HsRecFields RdrName (Located arg)
448 -> RnM ([HsRecField Name (Located arg)], FreeVars)
450 -- This supprisingly complicated pass
451 -- a) looks up the field name (possibly using disambiguation)
452 -- b) fills in puns and dot-dot stuff
453 -- When we we've finished, we've renamed the LHS, but not the RHS,
454 -- of each x=e binding
456 rnHsRecFields1 ctxt mk_arg (HsRecFields { rec_flds = flds, rec_dotdot = dotdot })
457 = do { pun_ok <- doptM Opt_RecordPuns
458 ; disambig_ok <- doptM Opt_DisambiguateRecordFields
459 ; parent <- check_disambiguation disambig_ok mb_con
460 ; flds1 <- mapM (rn_fld pun_ok parent) flds
461 ; mapM_ (addErr . dupFieldErr ctxt) dup_flds
462 ; flds2 <- rn_dotdot dotdot mb_con flds1
463 ; return (flds2, mkFVs (getFieldIds flds2)) }
465 mb_con = case ctxt of
466 HsRecFieldUpd -> Nothing
467 HsRecFieldCon con -> Just con
468 HsRecFieldPat con -> Just con
470 Nothing -> ptext (sLit "constructor field name")
471 Just con -> ptext (sLit "field of constructor") <+> quotes (ppr con)
473 name_to_arg (L loc n) = L loc (mk_arg (mkRdrUnqual (nameOccName n)))
475 rn_fld pun_ok parent (HsRecField { hsRecFieldId = fld
476 , hsRecFieldArg = arg
478 = do { fld' <- wrapLocM (lookupSubBndr parent doc) fld
480 then do { checkErr pun_ok (badPun fld)
481 ; return (name_to_arg fld') }
483 ; return (HsRecField { hsRecFieldId = fld'
484 , hsRecFieldArg = arg'
485 , hsRecPun = pun }) }
487 rn_dotdot Nothing _mb_con flds -- No ".." at all
489 rn_dotdot (Just {}) Nothing flds -- ".." on record update
490 = do { addErr (badDotDot ctxt); return flds }
491 rn_dotdot (Just n) (Just con) flds -- ".." on record con/pat
492 = ASSERT( n == length flds )
493 do { loc <- getSrcSpanM -- Rather approximate
494 ; dd_flag <- doptM Opt_RecordWildCards
495 ; checkErr dd_flag (needFlagDotDot ctxt)
497 ; con_fields <- lookupConstructorFields con
498 ; let present_flds = getFieldIds flds
499 absent_flds = con_fields `minusList` present_flds
500 extras = [ HsRecField
501 { hsRecFieldId = L loc f
502 , hsRecFieldArg = name_to_arg (L loc f)
506 ; return (flds ++ extras) }
508 check_disambiguation :: Bool -> Maybe Name -> RnM Parent
509 -- When disambiguation is on, return the parent *type constructor*
510 -- That is, the parent of the data constructor. That's the parent
511 -- to use for looking up record fields.
512 check_disambiguation disambig_ok mb_con
513 | disambig_ok, Just con <- mb_con
514 = do { env <- getGlobalRdrEnv
515 ; return (case lookupGRE_Name env con of
517 gres -> WARN( True, ppr con <+> ppr gres ) NoParent) }
518 | otherwise = return NoParent
520 dup_flds :: [[RdrName]]
521 -- Each list represents a RdrName that occurred more than once
522 -- (the list contains all occurrences)
523 -- Each list in dup_fields is non-empty
524 (_, dup_flds) = removeDups compare (getFieldIds flds)
526 getFieldIds :: [HsRecField id arg] -> [id]
527 getFieldIds flds = map (unLoc . hsRecFieldId) flds
529 needFlagDotDot :: HsRecFieldContext -> SDoc
530 needFlagDotDot ctxt = vcat [ptext (sLit "Illegal `..' in record") <+> pprRFC ctxt,
531 ptext (sLit "Use -XRecordWildCards to permit this")]
533 badDotDot :: HsRecFieldContext -> SDoc
534 badDotDot ctxt = ptext (sLit "You cannot use `..' in a record") <+> pprRFC ctxt
536 badPun :: Located RdrName -> SDoc
537 badPun fld = vcat [ptext (sLit "Illegal use of punning for field") <+> quotes (ppr fld),
538 ptext (sLit "Use -XNamedFieldPuns to permit this")]
540 dupFieldErr :: HsRecFieldContext -> [RdrName] -> SDoc
541 dupFieldErr ctxt dups
542 = hsep [ptext (sLit "duplicate field name"),
543 quotes (ppr (head dups)),
544 ptext (sLit "in record"), pprRFC ctxt]
546 pprRFC :: HsRecFieldContext -> SDoc
547 pprRFC (HsRecFieldCon {}) = ptext (sLit "construction")
548 pprRFC (HsRecFieldPat {}) = ptext (sLit "pattern")
549 pprRFC (HsRecFieldUpd {}) = ptext (sLit "update")
553 %************************************************************************
555 \subsubsection{Literals}
557 %************************************************************************
559 When literals occur we have to make sure
560 that the types and classes they involve
564 rnLit :: HsLit -> RnM ()
565 rnLit (HsChar c) = checkErr (inCharRange c) (bogusCharError c)
568 rnOverLit :: HsOverLit t -> RnM (HsOverLit Name, FreeVars)
569 rnOverLit lit@(OverLit {ol_val=val})
570 = do { let std_name = hsOverLitName val
571 ; (from_thing_name, fvs) <- lookupSyntaxName std_name
572 ; let rebindable = case from_thing_name of
573 HsVar v -> v /= std_name
574 _ -> panic "rnOverLit"
575 ; return (lit { ol_witness = from_thing_name
576 , ol_rebindable = rebindable }, fvs) }
579 %************************************************************************
581 \subsubsection{Errors}
583 %************************************************************************
586 checkTupSize :: Int -> RnM ()
587 checkTupSize tup_size
588 | tup_size <= mAX_TUPLE_SIZE
591 = addErr (sep [ptext (sLit "A") <+> int tup_size <> ptext (sLit "-tuple is too large for GHC"),
592 nest 2 (parens (ptext (sLit "max size is") <+> int mAX_TUPLE_SIZE)),
593 nest 2 (ptext (sLit "Workaround: use nested tuples or define a data type"))])
595 patSigErr :: Outputable a => a -> SDoc
597 = (ptext (sLit "Illegal signature in pattern:") <+> ppr ty)
598 $$ nest 4 (ptext (sLit "Use -XScopedTypeVariables to permit it"))
600 bogusCharError :: Char -> SDoc
602 = ptext (sLit "character literal out of range: '\\") <> char c <> char '\''
604 badViewPat :: Pat RdrName -> SDoc
605 badViewPat pat = vcat [ptext (sLit "Illegal view pattern: ") <+> ppr pat,
606 ptext (sLit "Use -XViewPatterns to enable view patterns")]