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 ; addErrCtxt doc_pat $ checkDupAndShadowedNames envs_before names
224 ; thing_inside pats' } }
226 doc_pat = ptext (sLit "In") <+> pprMatchContext ctxt
229 applyNameMaker :: NameMaker -> Located RdrName -> RnM Name
230 applyNameMaker mk rdr = do { (n, _fvs) <- runCps (newName mk rdr); return n }
232 -- ----------- Entry point 2: rnBindPat -------------------
233 -- Binds local names; in a recursive scope that involves other bound vars
234 -- e.g let { (x, Just y) = e1; ... } in ...
235 -- * does NOT allows type sig to bind type vars
237 -- * no unused and duplicate checking
238 -- * fixities might be coming in
239 rnBindPat :: NameMaker
241 -> RnM (LPat Name, FreeVars)
242 -- Returned FreeVars are the free variables of the pattern,
243 -- of course excluding variables bound by this pattern
245 rnBindPat name_maker pat = runCps (rnLPatAndThen name_maker pat)
249 %*********************************************************
253 %*********************************************************
256 -- ----------- Entry point 3: rnLPatAndThen -------------------
257 -- General version: parametrized by how you make new names
259 rnLPatsAndThen :: NameMaker -> [LPat RdrName] -> CpsRn [LPat Name]
260 rnLPatsAndThen mk = mapM (rnLPatAndThen mk)
261 -- Despite the map, the monad ensures that each pattern binds
262 -- variables that may be mentioned in subsequent patterns in the list
266 rnLPatAndThen :: NameMaker -> LPat RdrName -> CpsRn (LPat Name)
267 rnLPatAndThen nm lpat = wrapSrcSpanCps (rnPatAndThen nm) lpat
269 rnPatAndThen :: NameMaker -> Pat RdrName -> CpsRn (Pat Name)
270 rnPatAndThen _ (WildPat _) = return (WildPat placeHolderType)
271 rnPatAndThen mk (ParPat pat) = do { pat' <- rnLPatAndThen mk pat; return (ParPat pat') }
272 rnPatAndThen mk (LazyPat pat) = do { pat' <- rnLPatAndThen mk pat; return (LazyPat pat') }
273 rnPatAndThen mk (BangPat pat) = do { pat' <- rnLPatAndThen mk pat; return (BangPat pat') }
274 rnPatAndThen mk (VarPat rdr) = do { loc <- liftCps getSrcSpanM
275 ; name <- newName mk (L loc rdr)
276 ; return (VarPat name) }
277 -- we need to bind pattern variables for view pattern expressions
278 -- (e.g. in the pattern (x, x -> y) x needs to be bound in the rhs of the tuple)
280 rnPatAndThen mk (SigPatIn pat ty)
281 = do { patsigs <- liftCps (doptM Opt_ScopedTypeVariables)
283 then do { pat' <- rnLPatAndThen mk pat
284 ; ty' <- liftCpsFV (rnHsTypeFVs tvdoc ty)
285 ; return (SigPatIn pat' ty') }
286 else do { liftCps (addErr (patSigErr ty))
287 ; rnPatAndThen mk (unLoc pat) } }
289 tvdoc = text "In a pattern type-signature"
291 rnPatAndThen mk (LitPat lit)
293 = do { ovlStr <- liftCps (doptM Opt_OverloadedStrings)
295 then rnPatAndThen mk (mkNPat (mkHsIsString s placeHolderType) Nothing)
297 | otherwise = normal_lit
299 normal_lit = do { liftCps (rnLit lit); return (LitPat lit) }
301 rnPatAndThen _ (NPat lit mb_neg _eq)
302 = do { lit' <- liftCpsFV $ rnOverLit lit
303 ; mb_neg' <- liftCpsFV $ case mb_neg of
304 Nothing -> return (Nothing, emptyFVs)
305 Just _ -> do { (neg, fvs) <- lookupSyntaxName negateName
306 ; return (Just neg, fvs) }
307 ; eq' <- liftCpsFV $ lookupSyntaxName eqName
308 ; return (NPat lit' mb_neg' eq') }
310 rnPatAndThen mk (NPlusKPat rdr lit _ _)
311 = do { new_name <- newName mk rdr
312 ; lit' <- liftCpsFV $ rnOverLit lit
313 ; minus <- liftCpsFV $ lookupSyntaxName minusName
314 ; ge <- liftCpsFV $ lookupSyntaxName geName
315 ; return (NPlusKPat (L (nameSrcSpan new_name) new_name) lit' ge minus) }
316 -- The Report says that n+k patterns must be in Integral
318 rnPatAndThen mk (AsPat rdr pat)
319 = do { new_name <- newName mk rdr
320 ; pat' <- rnLPatAndThen mk pat
321 ; return (AsPat (L (nameSrcSpan new_name) new_name) pat') }
323 rnPatAndThen mk p@(ViewPat expr pat ty)
324 = do { liftCps $ do { vp_flag <- doptM Opt_ViewPatterns
325 ; checkErr vp_flag (badViewPat p) }
326 -- Because of the way we're arranging the recursive calls,
327 -- this will be in the right context
328 ; expr' <- liftCpsFV $ rnLExpr expr
329 ; pat' <- rnLPatAndThen mk pat
330 ; return (ViewPat expr' pat' ty) }
332 rnPatAndThen mk (ConPatIn con stuff)
333 -- rnConPatAndThen takes care of reconstructing the pattern
334 = rnConPatAndThen mk con stuff
336 rnPatAndThen mk (ListPat pats _)
337 = do { pats' <- rnLPatsAndThen mk pats
338 ; return (ListPat pats' placeHolderType) }
340 rnPatAndThen mk (PArrPat pats _)
341 = do { pats' <- rnLPatsAndThen mk pats
342 ; return (PArrPat pats' placeHolderType) }
344 rnPatAndThen mk (TuplePat pats boxed _)
345 = do { liftCps $ checkTupSize (length pats)
346 ; pats' <- rnLPatsAndThen mk pats
347 ; return (TuplePat pats' boxed placeHolderType) }
349 rnPatAndThen _ (TypePat ty)
350 = do { ty' <- liftCpsFV $ rnHsTypeFVs (text "In a type pattern") ty
351 ; return (TypePat ty') }
354 rnPatAndThen _ p@(QuasiQuotePat {})
355 = pprPanic "Can't do QuasiQuotePat without GHCi" (ppr p)
357 rnPatAndThen mk (QuasiQuotePat qq)
358 = do { qq' <- liftCpsFV $ rnQuasiQuote qq
359 ; pat <- liftCps $ runQuasiQuotePat qq'
360 ; L _ pat' <- rnLPatAndThen mk pat
364 rnPatAndThen _ pat = pprPanic "rnLPatAndThen" (ppr pat)
368 rnConPatAndThen :: NameMaker
369 -> Located RdrName -- the constructor
370 -> HsConPatDetails RdrName
373 rnConPatAndThen mk con (PrefixCon pats)
374 = do { con' <- lookupConCps con
375 ; pats' <- rnLPatsAndThen mk pats
376 ; return (ConPatIn con' (PrefixCon pats')) }
378 rnConPatAndThen mk con (InfixCon pat1 pat2)
379 = do { con' <- lookupConCps con
380 ; pat1' <- rnLPatAndThen mk pat1
381 ; pat2' <- rnLPatAndThen mk pat2
382 ; fixity <- liftCps $ lookupFixityRn (unLoc con')
383 ; liftCps $ mkConOpPatRn con' fixity pat1' pat2' }
385 rnConPatAndThen mk con (RecCon rpats)
386 = do { con' <- lookupConCps con
387 ; rpats' <- rnHsRecPatsAndThen mk con' rpats
388 ; return (ConPatIn con' (RecCon rpats')) }
391 rnHsRecPatsAndThen :: NameMaker
392 -> Located Name -- Constructor
393 -> HsRecFields RdrName (LPat RdrName)
394 -> CpsRn (HsRecFields Name (LPat Name))
395 rnHsRecPatsAndThen mk (L _ con) hs_rec_fields@(HsRecFields { rec_dotdot = dd })
396 = do { flds <- liftCpsFV $ rnHsRecFields1 (HsRecFieldPat con) VarPat hs_rec_fields
397 ; flds' <- mapM rn_field (flds `zip` [1..])
398 ; return (HsRecFields { rec_flds = flds', rec_dotdot = dd }) }
400 rn_field (fld, n') = do { arg' <- rnLPatAndThen (nested_mk dd mk n')
402 ; return (fld { hsRecFieldArg = arg' }) }
404 -- Suppress unused-match reporting for fields introduced by ".."
405 nested_mk Nothing mk _ = mk
406 nested_mk (Just _) mk@(LetMk {}) _ = mk
407 nested_mk (Just n) (LamMk report_unused) n' = LamMk (report_unused && (n' <= n))
411 %************************************************************************
415 %************************************************************************
418 data HsRecFieldContext
425 -> (RdrName -> arg) -- When punning, use this to build a new field
426 -> HsRecFields RdrName (Located arg)
427 -> RnM ([HsRecField Name (Located arg)], FreeVars)
429 -- This supprisingly complicated pass
430 -- a) looks up the field name (possibly using disambiguation)
431 -- b) fills in puns and dot-dot stuff
432 -- When we we've finished, we've renamed the LHS, but not the RHS,
433 -- of each x=e binding
435 rnHsRecFields1 ctxt mk_arg (HsRecFields { rec_flds = flds, rec_dotdot = dotdot })
436 = do { pun_ok <- doptM Opt_RecordPuns
437 ; disambig_ok <- doptM Opt_DisambiguateRecordFields
438 ; parent <- check_disambiguation disambig_ok mb_con
439 ; flds1 <- mapM (rn_fld pun_ok parent) flds
440 ; mapM_ (addErr . dupFieldErr ctxt) dup_flds
441 ; flds2 <- rn_dotdot dotdot mb_con flds1
442 ; return (flds2, mkFVs (getFieldIds flds2)) }
444 mb_con = case ctxt of
445 HsRecFieldUpd -> Nothing
446 HsRecFieldCon con -> Just con
447 HsRecFieldPat con -> Just con
449 Nothing -> ptext (sLit "constructor field name")
450 Just con -> ptext (sLit "field of constructor") <+> quotes (ppr con)
452 name_to_arg (L loc n) = L loc (mk_arg (mkRdrUnqual (nameOccName n)))
454 rn_fld pun_ok parent (HsRecField { hsRecFieldId = fld
455 , hsRecFieldArg = arg
457 = do { fld' <- wrapLocM (lookupSubBndr parent doc) fld
459 then do { checkErr pun_ok (badPun fld)
460 ; return (name_to_arg fld') }
462 ; return (HsRecField { hsRecFieldId = fld'
463 , hsRecFieldArg = arg'
464 , hsRecPun = pun }) }
466 rn_dotdot Nothing _mb_con flds -- No ".." at all
468 rn_dotdot (Just {}) Nothing flds -- ".." on record update
469 = do { addErr (badDotDot ctxt); return flds }
470 rn_dotdot (Just n) (Just con) flds -- ".." on record con/pat
471 = ASSERT( n == length flds )
472 do { loc <- getSrcSpanM -- Rather approximate
473 ; dd_flag <- doptM Opt_RecordWildCards
474 ; checkErr dd_flag (needFlagDotDot ctxt)
476 ; con_fields <- lookupConstructorFields con
477 ; let present_flds = getFieldIds flds
478 absent_flds = con_fields `minusList` present_flds
479 extras = [ HsRecField
480 { hsRecFieldId = L loc f
481 , hsRecFieldArg = name_to_arg (L loc f)
485 ; return (flds ++ extras) }
487 check_disambiguation :: Bool -> Maybe Name -> RnM Parent
488 -- When disambiguation is on, return the parent *type constructor*
489 -- That is, the parent of the data constructor. That's the parent
490 -- to use for looking up record fields.
491 check_disambiguation disambig_ok mb_con
492 | disambig_ok, Just con <- mb_con
493 = do { env <- getGlobalRdrEnv
494 ; return (case lookupGRE_Name env con of
496 gres -> WARN( True, ppr con <+> ppr gres ) NoParent) }
497 | otherwise = return NoParent
499 dup_flds :: [[RdrName]]
500 -- Each list represents a RdrName that occurred more than once
501 -- (the list contains all occurrences)
502 -- Each list in dup_fields is non-empty
503 (_, dup_flds) = removeDups compare (getFieldIds flds)
505 getFieldIds :: [HsRecField id arg] -> [id]
506 getFieldIds flds = map (unLoc . hsRecFieldId) flds
508 needFlagDotDot :: HsRecFieldContext -> SDoc
509 needFlagDotDot ctxt = vcat [ptext (sLit "Illegal `..' in record") <+> pprRFC ctxt,
510 ptext (sLit "Use -XRecordWildCards to permit this")]
512 badDotDot :: HsRecFieldContext -> SDoc
513 badDotDot ctxt = ptext (sLit "You cannot use `..' in a record") <+> pprRFC ctxt
515 badPun :: Located RdrName -> SDoc
516 badPun fld = vcat [ptext (sLit "Illegal use of punning for field") <+> quotes (ppr fld),
517 ptext (sLit "Use -XNamedFieldPuns to permit this")]
519 dupFieldErr :: HsRecFieldContext -> [RdrName] -> SDoc
520 dupFieldErr ctxt dups
521 = hsep [ptext (sLit "duplicate field name"),
522 quotes (ppr (head dups)),
523 ptext (sLit "in record"), pprRFC ctxt]
525 pprRFC :: HsRecFieldContext -> SDoc
526 pprRFC (HsRecFieldCon {}) = ptext (sLit "construction")
527 pprRFC (HsRecFieldPat {}) = ptext (sLit "pattern")
528 pprRFC (HsRecFieldUpd {}) = ptext (sLit "update")
532 %************************************************************************
534 \subsubsection{Literals}
536 %************************************************************************
538 When literals occur we have to make sure
539 that the types and classes they involve
543 rnLit :: HsLit -> RnM ()
544 rnLit (HsChar c) = checkErr (inCharRange c) (bogusCharError c)
547 rnOverLit :: HsOverLit t -> RnM (HsOverLit Name, FreeVars)
548 rnOverLit lit@(OverLit {ol_val=val})
549 = do { let std_name = hsOverLitName val
550 ; (from_thing_name, fvs) <- lookupSyntaxName std_name
551 ; let rebindable = case from_thing_name of
552 HsVar v -> v /= std_name
553 _ -> panic "rnOverLit"
554 ; return (lit { ol_witness = from_thing_name
555 , ol_rebindable = rebindable }, fvs) }
558 %************************************************************************
560 \subsubsection{Quasiquotation}
562 %************************************************************************
564 See Note [Quasi-quote overview] in TcSplice.
567 rnQuasiQuote :: HsQuasiQuote RdrName -> RnM (HsQuasiQuote Name, FreeVars)
568 rnQuasiQuote (HsQuasiQuote n quoter quoteSpan quote)
569 = do { loc <- getSrcSpanM
570 ; n' <- newLocalBndrRn (L loc n)
571 ; quoter' <- lookupOccRn quoter
572 -- If 'quoter' is not in scope, proceed no further
573 -- Otherwise lookupOcc adds an error messsage and returns
574 -- an "unubound name", which makes the subsequent attempt to
575 -- run the quote fail
576 ; return (HsQuasiQuote n' quoter' quoteSpan quote, unitFV quoter') }
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")]