88496d496b441f378e8d831cb3a9935824a43bfe
[ghc.git] / compiler / rename / RnPat.hs
1 {-
2 (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3
4 \section[RnPat]{Renaming of patterns}
5
6 Basically dependency analysis.
7
8 Handles @Match@, @GRHSs@, @HsExpr@, and @Qualifier@ datatypes. In
9 general, all of these functions return a renamed thing, and a set of
10 free variables.
11 -}
12
13 {-# LANGUAGE CPP, RankNTypes, ScopedTypeVariables #-}
14
15 module RnPat (-- main entry points
16 rnPat, rnPats, rnBindPat, rnPatAndThen,
17
18 NameMaker, applyNameMaker, -- a utility for making names:
19 localRecNameMaker, topRecNameMaker, -- sometimes we want to make local names,
20 -- sometimes we want to make top (qualified) names.
21 isTopRecNameMaker,
22
23 rnHsRecFields, HsRecFieldContext(..),
24 rnHsRecUpdFields,
25
26 -- CpsRn monad
27 CpsRn, liftCps,
28
29 -- Literals
30 rnLit, rnOverLit,
31
32 -- Pattern Error messages that are also used elsewhere
33 checkTupSize, patSigErr
34 ) where
35
36 -- ENH: thin imports to only what is necessary for patterns
37
38 import {-# SOURCE #-} RnExpr ( rnLExpr )
39 import {-# SOURCE #-} RnSplice ( rnSplicePat )
40
41 #include "HsVersions.h"
42
43 import HsSyn
44 import TcRnMonad
45 import TcHsSyn ( hsOverLitName )
46 import RnEnv
47 import RnTypes
48 import DynFlags
49 import PrelNames
50 import TyCon ( tyConName )
51 import ConLike
52 import Type ( TyThing(..) )
53 import Name
54 import NameSet
55 import RdrName
56 import BasicTypes
57 import Util
58 import ListSetOps ( removeDups )
59 import Outputable
60 import SrcLoc
61 import FastString
62 import Literal ( inCharRange )
63 import TysWiredIn ( nilDataCon )
64 import DataCon
65 import Control.Monad ( when, liftM, ap )
66 import Data.Ratio
67
68 {-
69 *********************************************************
70 * *
71 The CpsRn Monad
72 * *
73 *********************************************************
74
75 Note [CpsRn monad]
76 ~~~~~~~~~~~~~~~~~~
77 The CpsRn monad uses continuation-passing style to support this
78 style of programming:
79
80 do { ...
81 ; ns <- bindNames rs
82 ; ...blah... }
83
84 where rs::[RdrName], ns::[Name]
85
86 The idea is that '...blah...'
87 a) sees the bindings of ns
88 b) returns the free variables it mentions
89 so that bindNames can report unused ones
90
91 In particular,
92 mapM rnPatAndThen [p1, p2, p3]
93 has a *left-to-right* scoping: it makes the binders in
94 p1 scope over p2,p3.
95 -}
96
97 newtype CpsRn b = CpsRn { unCpsRn :: forall r. (b -> RnM (r, FreeVars))
98 -> RnM (r, FreeVars) }
99 -- See Note [CpsRn monad]
100
101 instance Functor CpsRn where
102 fmap = liftM
103
104 instance Applicative CpsRn where
105 pure x = CpsRn (\k -> k x)
106 (<*>) = ap
107
108 instance Monad CpsRn where
109 return = pure
110 (CpsRn m) >>= mk = CpsRn (\k -> m (\v -> unCpsRn (mk v) k))
111
112 runCps :: CpsRn a -> RnM (a, FreeVars)
113 runCps (CpsRn m) = m (\r -> return (r, emptyFVs))
114
115 liftCps :: RnM a -> CpsRn a
116 liftCps rn_thing = CpsRn (\k -> rn_thing >>= k)
117
118 liftCpsFV :: RnM (a, FreeVars) -> CpsRn a
119 liftCpsFV rn_thing = CpsRn (\k -> do { (v,fvs1) <- rn_thing
120 ; (r,fvs2) <- k v
121 ; return (r, fvs1 `plusFV` fvs2) })
122
123 wrapSrcSpanCps :: (a -> CpsRn b) -> Located a -> CpsRn (Located b)
124 -- Set the location, and also wrap it around the value returned
125 wrapSrcSpanCps fn (L loc a)
126 = CpsRn (\k -> setSrcSpan loc $
127 unCpsRn (fn a) $ \v ->
128 k (L loc v))
129
130 lookupConCps :: Located RdrName -> CpsRn (Located Name)
131 lookupConCps con_rdr
132 = CpsRn (\k -> do { con_name <- lookupLocatedOccRn con_rdr
133 ; (r, fvs) <- k con_name
134 ; return (r, addOneFV fvs (unLoc con_name)) })
135 -- We add the constructor name to the free vars
136 -- See Note [Patterns are uses]
137
138 {-
139 Note [Patterns are uses]
140 ~~~~~~~~~~~~~~~~~~~~~~~~
141 Consider
142 module Foo( f, g ) where
143 data T = T1 | T2
144
145 f T1 = True
146 f T2 = False
147
148 g _ = T1
149
150 Arguably we should report T2 as unused, even though it appears in a
151 pattern, because it never occurs in a constructed position. See
152 Trac #7336.
153 However, implementing this in the face of pattern synonyms would be
154 less straightforward, since given two pattern synonyms
155
156 pattern P1 <- P2
157 pattern P2 <- ()
158
159 we need to observe the dependency between P1 and P2 so that type
160 checking can be done in the correct order (just like for value
161 bindings). Dependencies between bindings is analyzed in the renamer,
162 where we don't know yet whether P2 is a constructor or a pattern
163 synonym. So for now, we do report conid occurrences in patterns as
164 uses.
165
166 *********************************************************
167 * *
168 Name makers
169 * *
170 *********************************************************
171
172 Externally abstract type of name makers,
173 which is how you go from a RdrName to a Name
174 -}
175
176 data NameMaker
177 = LamMk -- Lambdas
178 Bool -- True <=> report unused bindings
179 -- (even if True, the warning only comes out
180 -- if -fwarn-unused-matches is on)
181
182 | LetMk -- Let bindings, incl top level
183 -- Do *not* check for unused bindings
184 TopLevelFlag
185 MiniFixityEnv
186
187 topRecNameMaker :: MiniFixityEnv -> NameMaker
188 topRecNameMaker fix_env = LetMk TopLevel fix_env
189
190 isTopRecNameMaker :: NameMaker -> Bool
191 isTopRecNameMaker (LetMk TopLevel _) = True
192 isTopRecNameMaker _ = False
193
194 localRecNameMaker :: MiniFixityEnv -> NameMaker
195 localRecNameMaker fix_env = LetMk NotTopLevel fix_env
196
197 matchNameMaker :: HsMatchContext a -> NameMaker
198 matchNameMaker ctxt = LamMk report_unused
199 where
200 -- Do not report unused names in interactive contexts
201 -- i.e. when you type 'x <- e' at the GHCi prompt
202 report_unused = case ctxt of
203 StmtCtxt GhciStmtCtxt -> False
204 -- also, don't warn in pattern quotes, as there
205 -- is no RHS where the variables can be used!
206 ThPatQuote -> False
207 _ -> True
208
209 rnHsSigCps :: LHsSigWcType RdrName -> CpsRn (LHsSigWcType Name)
210 rnHsSigCps sig = CpsRn (rnHsSigWcTypeScoped PatCtx sig)
211
212 newPatLName :: NameMaker -> Located RdrName -> CpsRn (Located Name)
213 newPatLName name_maker rdr_name@(L loc _)
214 = do { name <- newPatName name_maker rdr_name
215 ; return (L loc name) }
216
217 newPatName :: NameMaker -> Located RdrName -> CpsRn Name
218 newPatName (LamMk report_unused) rdr_name
219 = CpsRn (\ thing_inside ->
220 do { name <- newLocalBndrRn rdr_name
221 ; (res, fvs) <- bindLocalNames [name] (thing_inside name)
222 ; when report_unused $ warnUnusedMatches [name] fvs
223 ; return (res, name `delFV` fvs) })
224
225 newPatName (LetMk is_top fix_env) rdr_name
226 = CpsRn (\ thing_inside ->
227 do { name <- case is_top of
228 NotTopLevel -> newLocalBndrRn rdr_name
229 TopLevel -> newTopSrcBinder rdr_name
230 ; bindLocalNames [name] $ -- Do *not* use bindLocalNameFV here
231 -- See Note [View pattern usage]
232 addLocalFixities fix_env [name] $
233 thing_inside name })
234
235 -- Note: the bindLocalNames is somewhat suspicious
236 -- because it binds a top-level name as a local name.
237 -- however, this binding seems to work, and it only exists for
238 -- the duration of the patterns and the continuation;
239 -- then the top-level name is added to the global env
240 -- before going on to the RHSes (see RnSource.hs).
241
242 {-
243 Note [View pattern usage]
244 ~~~~~~~~~~~~~~~~~~~~~~~~~
245 Consider
246 let (r, (r -> x)) = x in ...
247 Here the pattern binds 'r', and then uses it *only* in the view pattern.
248 We want to "see" this use, and in let-bindings we collect all uses and
249 report unused variables at the binding level. So we must use bindLocalNames
250 here, *not* bindLocalNameFV. Trac #3943.
251
252 *********************************************************
253 * *
254 External entry points
255 * *
256 *********************************************************
257
258 There are various entry points to renaming patterns, depending on
259 (1) whether the names created should be top-level names or local names
260 (2) whether the scope of the names is entirely given in a continuation
261 (e.g., in a case or lambda, but not in a let or at the top-level,
262 because of the way mutually recursive bindings are handled)
263 (3) whether the a type signature in the pattern can bind
264 lexically-scoped type variables (for unpacking existential
265 type vars in data constructors)
266 (4) whether we do duplicate and unused variable checking
267 (5) whether there are fixity declarations associated with the names
268 bound by the patterns that need to be brought into scope with them.
269
270 Rather than burdening the clients of this module with all of these choices,
271 we export the three points in this design space that we actually need:
272 -}
273
274 -- ----------- Entry point 1: rnPats -------------------
275 -- Binds local names; the scope of the bindings is entirely in the thing_inside
276 -- * allows type sigs to bind type vars
277 -- * local namemaker
278 -- * unused and duplicate checking
279 -- * no fixities
280 rnPats :: HsMatchContext Name -- for error messages
281 -> [LPat RdrName]
282 -> ([LPat Name] -> RnM (a, FreeVars))
283 -> RnM (a, FreeVars)
284 rnPats ctxt pats thing_inside
285 = do { envs_before <- getRdrEnvs
286
287 -- (1) rename the patterns, bringing into scope all of the term variables
288 -- (2) then do the thing inside.
289 ; unCpsRn (rnLPatsAndThen (matchNameMaker ctxt) pats) $ \ pats' -> do
290 { -- Check for duplicated and shadowed names
291 -- Must do this *after* renaming the patterns
292 -- See Note [Collect binders only after renaming] in HsUtils
293 -- Because we don't bind the vars all at once, we can't
294 -- check incrementally for duplicates;
295 -- Nor can we check incrementally for shadowing, else we'll
296 -- complain *twice* about duplicates e.g. f (x,x) = ...
297 ; addErrCtxt doc_pat $
298 checkDupAndShadowedNames envs_before $
299 collectPatsBinders pats'
300 ; thing_inside pats' } }
301 where
302 doc_pat = ptext (sLit "In") <+> pprMatchContext ctxt
303
304 rnPat :: HsMatchContext Name -- for error messages
305 -> LPat RdrName
306 -> (LPat Name -> RnM (a, FreeVars))
307 -> RnM (a, FreeVars) -- Variables bound by pattern do not
308 -- appear in the result FreeVars
309 rnPat ctxt pat thing_inside
310 = rnPats ctxt [pat] (\pats' -> let [pat'] = pats' in thing_inside pat')
311
312 applyNameMaker :: NameMaker -> Located RdrName -> RnM (Located Name)
313 applyNameMaker mk rdr = do { (n, _fvs) <- runCps (newPatLName mk rdr)
314 ; return n }
315
316 -- ----------- Entry point 2: rnBindPat -------------------
317 -- Binds local names; in a recursive scope that involves other bound vars
318 -- e.g let { (x, Just y) = e1; ... } in ...
319 -- * does NOT allows type sig to bind type vars
320 -- * local namemaker
321 -- * no unused and duplicate checking
322 -- * fixities might be coming in
323 rnBindPat :: NameMaker
324 -> LPat RdrName
325 -> RnM (LPat Name, FreeVars)
326 -- Returned FreeVars are the free variables of the pattern,
327 -- of course excluding variables bound by this pattern
328
329 rnBindPat name_maker pat = runCps (rnLPatAndThen name_maker pat)
330
331 {-
332 *********************************************************
333 * *
334 The main event
335 * *
336 *********************************************************
337 -}
338
339 -- ----------- Entry point 3: rnLPatAndThen -------------------
340 -- General version: parametrized by how you make new names
341
342 rnLPatsAndThen :: NameMaker -> [LPat RdrName] -> CpsRn [LPat Name]
343 rnLPatsAndThen mk = mapM (rnLPatAndThen mk)
344 -- Despite the map, the monad ensures that each pattern binds
345 -- variables that may be mentioned in subsequent patterns in the list
346
347 --------------------
348 -- The workhorse
349 rnLPatAndThen :: NameMaker -> LPat RdrName -> CpsRn (LPat Name)
350 rnLPatAndThen nm lpat = wrapSrcSpanCps (rnPatAndThen nm) lpat
351
352 rnPatAndThen :: NameMaker -> Pat RdrName -> CpsRn (Pat Name)
353 rnPatAndThen _ (WildPat _) = return (WildPat placeHolderType)
354 rnPatAndThen mk (ParPat pat) = do { pat' <- rnLPatAndThen mk pat; return (ParPat pat') }
355 rnPatAndThen mk (LazyPat pat) = do { pat' <- rnLPatAndThen mk pat; return (LazyPat pat') }
356 rnPatAndThen mk (BangPat pat) = do { pat' <- rnLPatAndThen mk pat; return (BangPat pat') }
357 rnPatAndThen mk (VarPat (L l rdr)) = do { loc <- liftCps getSrcSpanM
358 ; name <- newPatName mk (L loc rdr)
359 ; return (VarPat (L l name)) }
360 -- we need to bind pattern variables for view pattern expressions
361 -- (e.g. in the pattern (x, x -> y) x needs to be bound in the rhs of the tuple)
362
363 rnPatAndThen mk (SigPatIn pat sig)
364 -- When renaming a pattern type signature (e.g. f (a :: T) = ...), it is
365 -- important to rename its type signature _before_ renaming the rest of the
366 -- pattern, so that type variables are first bound by the _outermost_ pattern
367 -- type signature they occur in. This keeps the type checker happy when
368 -- pattern type signatures happen to be nested (#7827)
369 --
370 -- f ((Just (x :: a) :: Maybe a)
371 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~^ `a' is first bound here
372 -- ~~~~~~~~~~~~~~~^ the same `a' then used here
373 = do { sig' <- rnHsSigCps sig
374 ; pat' <- rnLPatAndThen mk pat
375 ; return (SigPatIn pat' sig') }
376
377 rnPatAndThen mk (LitPat lit)
378 | HsString src s <- lit
379 = do { ovlStr <- liftCps (xoptM Opt_OverloadedStrings)
380 ; if ovlStr
381 then rnPatAndThen mk
382 (mkNPat (noLoc (mkHsIsString src s placeHolderType))
383 Nothing)
384 else normal_lit }
385 | otherwise = normal_lit
386 where
387 normal_lit = do { liftCps (rnLit lit); return (LitPat lit) }
388
389 rnPatAndThen _ (NPat (L l lit) mb_neg _eq)
390 = do { lit' <- liftCpsFV $ rnOverLit lit
391 ; mb_neg' <- liftCpsFV $ case mb_neg of
392 Nothing -> return (Nothing, emptyFVs)
393 Just _ -> do { (neg, fvs) <- lookupSyntaxName negateName
394 ; return (Just neg, fvs) }
395 ; eq' <- liftCpsFV $ lookupSyntaxName eqName
396 ; return (NPat (L l lit') mb_neg' eq') }
397
398 rnPatAndThen mk (NPlusKPat rdr (L l lit) _ _)
399 = do { new_name <- newPatName mk rdr
400 ; lit' <- liftCpsFV $ rnOverLit lit
401 ; minus <- liftCpsFV $ lookupSyntaxName minusName
402 ; ge <- liftCpsFV $ lookupSyntaxName geName
403 ; return (NPlusKPat (L (nameSrcSpan new_name) new_name)
404 (L l lit') ge minus) }
405 -- The Report says that n+k patterns must be in Integral
406
407 rnPatAndThen mk (AsPat rdr pat)
408 = do { new_name <- newPatLName mk rdr
409 ; pat' <- rnLPatAndThen mk pat
410 ; return (AsPat new_name pat') }
411
412 rnPatAndThen mk p@(ViewPat expr pat _ty)
413 = do { liftCps $ do { vp_flag <- xoptM Opt_ViewPatterns
414 ; checkErr vp_flag (badViewPat p) }
415 -- Because of the way we're arranging the recursive calls,
416 -- this will be in the right context
417 ; expr' <- liftCpsFV $ rnLExpr expr
418 ; pat' <- rnLPatAndThen mk pat
419 -- Note: at this point the PreTcType in ty can only be a placeHolder
420 -- ; return (ViewPat expr' pat' ty) }
421 ; return (ViewPat expr' pat' placeHolderType) }
422
423 rnPatAndThen mk (ConPatIn con stuff)
424 -- rnConPatAndThen takes care of reconstructing the pattern
425 -- The pattern for the empty list needs to be replaced by an empty explicit list pattern when overloaded lists is turned on.
426 = case unLoc con == nameRdrName (dataConName nilDataCon) of
427 True -> do { ol_flag <- liftCps $ xoptM Opt_OverloadedLists
428 ; if ol_flag then rnPatAndThen mk (ListPat [] placeHolderType Nothing)
429 else rnConPatAndThen mk con stuff}
430 False -> rnConPatAndThen mk con stuff
431
432 rnPatAndThen mk (ListPat pats _ _)
433 = do { opt_OverloadedLists <- liftCps $ xoptM Opt_OverloadedLists
434 ; pats' <- rnLPatsAndThen mk pats
435 ; case opt_OverloadedLists of
436 True -> do { (to_list_name,_) <- liftCps $ lookupSyntaxName toListName
437 ; return (ListPat pats' placeHolderType
438 (Just (placeHolderType, to_list_name)))}
439 False -> return (ListPat pats' placeHolderType Nothing) }
440
441 rnPatAndThen mk (PArrPat pats _)
442 = do { pats' <- rnLPatsAndThen mk pats
443 ; return (PArrPat pats' placeHolderType) }
444
445 rnPatAndThen mk (TuplePat pats boxed _)
446 = do { liftCps $ checkTupSize (length pats)
447 ; pats' <- rnLPatsAndThen mk pats
448 ; return (TuplePat pats' boxed []) }
449
450 rnPatAndThen mk (SplicePat splice)
451 = do { eith <- liftCpsFV $ rnSplicePat splice
452 ; case eith of -- See Note [rnSplicePat] in RnSplice
453 Left not_yet_renamed -> rnPatAndThen mk not_yet_renamed
454 Right already_renamed -> return already_renamed }
455
456 rnPatAndThen _ pat = pprPanic "rnLPatAndThen" (ppr pat)
457
458
459 --------------------
460 rnConPatAndThen :: NameMaker
461 -> Located RdrName -- the constructor
462 -> HsConPatDetails RdrName
463 -> CpsRn (Pat Name)
464
465 rnConPatAndThen mk con (PrefixCon pats)
466 = do { con' <- lookupConCps con
467 ; pats' <- rnLPatsAndThen mk pats
468 ; return (ConPatIn con' (PrefixCon pats')) }
469
470 rnConPatAndThen mk con (InfixCon pat1 pat2)
471 = do { con' <- lookupConCps con
472 ; pat1' <- rnLPatAndThen mk pat1
473 ; pat2' <- rnLPatAndThen mk pat2
474 ; fixity <- liftCps $ lookupFixityRn (unLoc con')
475 ; liftCps $ mkConOpPatRn con' fixity pat1' pat2' }
476
477 rnConPatAndThen mk con (RecCon rpats)
478 = do { con' <- lookupConCps con
479 ; rpats' <- rnHsRecPatsAndThen mk con' rpats
480 ; return (ConPatIn con' (RecCon rpats')) }
481
482 --------------------
483 rnHsRecPatsAndThen :: NameMaker
484 -> Located Name -- Constructor
485 -> HsRecFields RdrName (LPat RdrName)
486 -> CpsRn (HsRecFields Name (LPat Name))
487 rnHsRecPatsAndThen mk (L _ con) hs_rec_fields@(HsRecFields { rec_dotdot = dd })
488 = do { flds <- liftCpsFV $ rnHsRecFields (HsRecFieldPat con) mkVarPat
489 hs_rec_fields
490 ; flds' <- mapM rn_field (flds `zip` [1..])
491 ; return (HsRecFields { rec_flds = flds', rec_dotdot = dd }) }
492 where
493 mkVarPat l n = VarPat (L l n)
494 rn_field (L l fld, n') = do { arg' <- rnLPatAndThen (nested_mk dd mk n')
495 (hsRecFieldArg fld)
496 ; return (L l (fld { hsRecFieldArg = arg' })) }
497
498 -- Suppress unused-match reporting for fields introduced by ".."
499 nested_mk Nothing mk _ = mk
500 nested_mk (Just _) mk@(LetMk {}) _ = mk
501 nested_mk (Just n) (LamMk report_unused) n' = LamMk (report_unused && (n' <= n))
502
503 {-
504 ************************************************************************
505 * *
506 Record fields
507 * *
508 ************************************************************************
509 -}
510
511 data HsRecFieldContext
512 = HsRecFieldCon Name
513 | HsRecFieldPat Name
514 | HsRecFieldUpd
515
516 rnHsRecFields
517 :: forall arg.
518 HsRecFieldContext
519 -> (SrcSpan -> RdrName -> arg)
520 -- When punning, use this to build a new field
521 -> HsRecFields RdrName (Located arg)
522 -> RnM ([LHsRecField Name (Located arg)], FreeVars)
523
524 -- This surprisingly complicated pass
525 -- a) looks up the field name (possibly using disambiguation)
526 -- b) fills in puns and dot-dot stuff
527 -- When we we've finished, we've renamed the LHS, but not the RHS,
528 -- of each x=e binding
529 --
530 -- This is used for record construction and pattern-matching, but not updates.
531
532 rnHsRecFields ctxt mk_arg (HsRecFields { rec_flds = flds, rec_dotdot = dotdot })
533 = do { pun_ok <- xoptM Opt_RecordPuns
534 ; disambig_ok <- xoptM Opt_DisambiguateRecordFields
535 ; parent <- check_disambiguation disambig_ok mb_con
536 ; flds1 <- mapM (rn_fld pun_ok parent) flds
537 ; mapM_ (addErr . dupFieldErr ctxt) dup_flds
538 ; dotdot_flds <- rn_dotdot dotdot mb_con flds1
539 ; let all_flds | null dotdot_flds = flds1
540 | otherwise = flds1 ++ dotdot_flds
541 ; return (all_flds, mkFVs (getFieldIds all_flds)) }
542 where
543 mb_con = case ctxt of
544 HsRecFieldCon con | not (isUnboundName con) -> Just con
545 HsRecFieldPat con | not (isUnboundName con) -> Just con
546 _ {- update or isUnboundName con -} -> Nothing
547 -- The unbound name test is because if the constructor
548 -- isn't in scope the constructor lookup will add an error
549 -- add an error, but still return an unbound name.
550 -- We don't want that to screw up the dot-dot fill-in stuff.
551
552 doc = case mb_con of
553 Nothing -> ptext (sLit "constructor field name")
554 Just con -> ptext (sLit "field of constructor") <+> quotes (ppr con)
555
556 rn_fld :: Bool -> Maybe Name -> LHsRecField RdrName (Located arg)
557 -> RnM (LHsRecField Name (Located arg))
558 rn_fld pun_ok parent (L l (HsRecField { hsRecFieldLbl = L loc (FieldOcc lbl _)
559 , hsRecFieldArg = arg
560 , hsRecPun = pun }))
561 = do { sel <- setSrcSpan loc $ lookupRecFieldOcc parent doc lbl
562 ; arg' <- if pun
563 then do { checkErr pun_ok (badPun (L loc lbl))
564 ; return (L loc (mk_arg loc lbl)) }
565 else return arg
566 ; return (L l (HsRecField { hsRecFieldLbl = L loc (FieldOcc lbl sel)
567 , hsRecFieldArg = arg'
568 , hsRecPun = pun })) }
569
570 rn_dotdot :: Maybe Int -- See Note [DotDot fields] in HsPat
571 -> Maybe Name -- The constructor (Nothing for an
572 -- out of scope constructor)
573 -> [LHsRecField Name (Located arg)] -- Explicit fields
574 -> RnM [LHsRecField Name (Located arg)] -- Filled in .. fields
575 rn_dotdot Nothing _mb_con _flds -- No ".." at all
576 = return []
577 rn_dotdot (Just {}) Nothing _flds -- Constructor out of scope
578 = return []
579 rn_dotdot (Just n) (Just con) flds -- ".." on record construction / pat match
580 = ASSERT( n == length flds )
581 do { loc <- getSrcSpanM -- Rather approximate
582 ; dd_flag <- xoptM Opt_RecordWildCards
583 ; checkErr dd_flag (needFlagDotDot ctxt)
584 ; (rdr_env, lcl_env) <- getRdrEnvs
585 ; con_fields <- lookupConstructorFields con
586 ; when (null con_fields) (addErr (badDotDotCon con))
587 ; let present_flds = map (occNameFS . rdrNameOcc) $ getFieldLbls flds
588 parent_tc = find_tycon rdr_env con
589
590 -- For constructor uses (but not patterns)
591 -- the arg should be in scope (unqualified)
592 -- ignoring the record field itself
593 -- Eg. data R = R { x,y :: Int }
594 -- f x = R { .. } -- Should expand to R {x=x}, not R{x=x,y=y}
595 arg_in_scope lbl
596 = rdr `elemLocalRdrEnv` lcl_env
597 || notNull [ gre | gre <- lookupGRE_RdrName rdr rdr_env
598 , case gre_par gre of
599 ParentIs p -> p /= parent_tc
600 FldParent { par_is = p } -> p /= parent_tc
601 PatternSynonym -> True
602 NoParent -> True ]
603 where
604 rdr = mkVarUnqual lbl
605
606 dot_dot_gres = [ (lbl, sel, head gres)
607 | fl <- con_fields
608 , let lbl = flLabel fl
609 , let sel = flSelector fl
610 , not (lbl `elem` present_flds)
611 , let gres = lookupGRE_Field_Name rdr_env sel lbl
612 , not (null gres) -- Check selector is in scope
613 , case ctxt of
614 HsRecFieldCon {} -> arg_in_scope lbl
615 _other -> True ]
616
617 ; addUsedGREs (map thdOf3 dot_dot_gres)
618 ; return [ L loc (HsRecField
619 { hsRecFieldLbl = L loc (FieldOcc arg_rdr sel)
620 , hsRecFieldArg = L loc (mk_arg loc arg_rdr)
621 , hsRecPun = False })
622 | (lbl, sel, _) <- dot_dot_gres
623 , let arg_rdr = mkVarUnqual lbl ] }
624
625 check_disambiguation :: Bool -> Maybe Name -> RnM (Maybe Name)
626 -- When disambiguation is on, return name of parent tycon.
627 check_disambiguation disambig_ok mb_con
628 | disambig_ok, Just con <- mb_con
629 = do { env <- getGlobalRdrEnv; return (Just (find_tycon env con)) }
630 | otherwise = return Nothing
631
632 find_tycon :: GlobalRdrEnv -> Name {- DataCon -} -> Name {- TyCon -}
633 -- Return the parent *type constructor* of the data constructor
634 -- That is, the parent of the data constructor.
635 -- That's the parent to use for looking up record fields.
636 find_tycon env con
637 | Just (AConLike (RealDataCon dc)) <- wiredInNameTyThing_maybe con
638 = tyConName (dataConTyCon dc) -- Special case for [], which is built-in syntax
639 -- and not in the GlobalRdrEnv (Trac #8448)
640 | [GRE { gre_par = ParentIs p }] <- lookupGRE_Name env con
641 = p
642
643 | otherwise
644 = pprPanic "find_tycon" (ppr con $$ ppr (lookupGRE_Name env con))
645
646 dup_flds :: [[RdrName]]
647 -- Each list represents a RdrName that occurred more than once
648 -- (the list contains all occurrences)
649 -- Each list in dup_fields is non-empty
650 (_, dup_flds) = removeDups compare (getFieldLbls flds)
651
652
653 rnHsRecUpdFields
654 :: [LHsRecUpdField RdrName]
655 -> RnM ([LHsRecUpdField Name], FreeVars)
656 rnHsRecUpdFields flds
657 = do { pun_ok <- xoptM Opt_RecordPuns
658 ; overload_ok <- xoptM Opt_DuplicateRecordFields
659 ; (flds1, fvss) <- mapAndUnzipM (rn_fld pun_ok overload_ok) flds
660 ; mapM_ (addErr . dupFieldErr HsRecFieldUpd) dup_flds
661
662 -- Check for an empty record update e {}
663 -- NB: don't complain about e { .. }, because rn_dotdot has done that already
664 ; when (null flds) $ addErr emptyUpdateErr
665
666 ; return (flds1, plusFVs fvss) }
667 where
668 doc = ptext (sLit "constructor field name")
669
670 rn_fld :: Bool -> Bool -> LHsRecUpdField RdrName -> RnM (LHsRecUpdField Name, FreeVars)
671 rn_fld pun_ok overload_ok (L l (HsRecField { hsRecFieldLbl = L loc f
672 , hsRecFieldArg = arg
673 , hsRecPun = pun }))
674 = do { let lbl = rdrNameAmbiguousFieldOcc f
675 ; sel <- setSrcSpan loc $
676 -- Defer renaming of overloaded fields to the typechecker
677 -- See Note [Disambiguating record fields] in TcExpr
678 if overload_ok
679 then do { mb <- lookupGlobalOccRn_overloaded overload_ok lbl
680 ; case mb of
681 Nothing -> do { addErr (unknownSubordinateErr doc lbl)
682 ; return (Right []) }
683 Just r -> return r }
684 else fmap Left $ lookupGlobalOccRn lbl
685 ; arg' <- if pun
686 then do { checkErr pun_ok (badPun (L loc lbl))
687 ; return (L loc (HsVar (L loc lbl))) }
688 else return arg
689 ; (arg'', fvs) <- rnLExpr arg'
690
691 ; let fvs' = case sel of
692 Left sel_name -> fvs `addOneFV` sel_name
693 Right [FieldOcc _ sel_name] -> fvs `addOneFV` sel_name
694 Right _ -> fvs
695 lbl' = case sel of
696 Left sel_name -> L loc (Unambiguous lbl sel_name)
697 Right [FieldOcc lbl sel_name] -> L loc (Unambiguous lbl sel_name)
698 Right _ -> L loc (Ambiguous lbl PlaceHolder)
699
700 ; return (L l (HsRecField { hsRecFieldLbl = lbl'
701 , hsRecFieldArg = arg''
702 , hsRecPun = pun }), fvs') }
703
704 dup_flds :: [[RdrName]]
705 -- Each list represents a RdrName that occurred more than once
706 -- (the list contains all occurrences)
707 -- Each list in dup_fields is non-empty
708 (_, dup_flds) = removeDups compare (getFieldUpdLbls flds)
709
710
711
712 getFieldIds :: [LHsRecField Name arg] -> [Name]
713 getFieldIds flds = map (unLoc . hsRecFieldSel . unLoc) flds
714
715 getFieldLbls :: [LHsRecField id arg] -> [RdrName]
716 getFieldLbls flds = map (rdrNameFieldOcc . unLoc . hsRecFieldLbl . unLoc) flds
717
718 getFieldUpdLbls :: [LHsRecUpdField id] -> [RdrName]
719 getFieldUpdLbls flds = map (rdrNameAmbiguousFieldOcc . unLoc . hsRecFieldLbl . unLoc) flds
720
721 needFlagDotDot :: HsRecFieldContext -> SDoc
722 needFlagDotDot ctxt = vcat [ptext (sLit "Illegal `..' in record") <+> pprRFC ctxt,
723 ptext (sLit "Use RecordWildCards to permit this")]
724
725 badDotDotCon :: Name -> SDoc
726 badDotDotCon con
727 = vcat [ ptext (sLit "Illegal `..' notation for constructor") <+> quotes (ppr con)
728 , nest 2 (ptext (sLit "The constructor has no labelled fields")) ]
729
730 emptyUpdateErr :: SDoc
731 emptyUpdateErr = ptext (sLit "Empty record update")
732
733 badPun :: Located RdrName -> SDoc
734 badPun fld = vcat [ptext (sLit "Illegal use of punning for field") <+> quotes (ppr fld),
735 ptext (sLit "Use NamedFieldPuns to permit this")]
736
737 dupFieldErr :: HsRecFieldContext -> [RdrName] -> SDoc
738 dupFieldErr ctxt dups
739 = hsep [ptext (sLit "duplicate field name"),
740 quotes (ppr (head dups)),
741 ptext (sLit "in record"), pprRFC ctxt]
742
743 pprRFC :: HsRecFieldContext -> SDoc
744 pprRFC (HsRecFieldCon {}) = ptext (sLit "construction")
745 pprRFC (HsRecFieldPat {}) = ptext (sLit "pattern")
746 pprRFC (HsRecFieldUpd {}) = ptext (sLit "update")
747
748 {-
749 ************************************************************************
750 * *
751 \subsubsection{Literals}
752 * *
753 ************************************************************************
754
755 When literals occur we have to make sure
756 that the types and classes they involve
757 are made available.
758 -}
759
760 rnLit :: HsLit -> RnM ()
761 rnLit (HsChar _ c) = checkErr (inCharRange c) (bogusCharError c)
762 rnLit _ = return ()
763
764 -- Turn a Fractional-looking literal which happens to be an integer into an
765 -- Integer-looking literal.
766 generalizeOverLitVal :: OverLitVal -> OverLitVal
767 generalizeOverLitVal (HsFractional (FL {fl_text=src,fl_value=val}))
768 | denominator val == 1 = HsIntegral src (numerator val)
769 generalizeOverLitVal lit = lit
770
771 rnOverLit :: HsOverLit t -> RnM (HsOverLit Name, FreeVars)
772 rnOverLit origLit
773 = do { opt_NumDecimals <- xoptM Opt_NumDecimals
774 ; let { lit@(OverLit {ol_val=val})
775 | opt_NumDecimals = origLit {ol_val = generalizeOverLitVal (ol_val origLit)}
776 | otherwise = origLit
777 }
778 ; let std_name = hsOverLitName val
779 ; (from_thing_name, fvs) <- lookupSyntaxName std_name
780 ; let rebindable = case from_thing_name of
781 HsVar (L _ v) -> v /= std_name
782 _ -> panic "rnOverLit"
783 ; return (lit { ol_witness = from_thing_name
784 , ol_rebindable = rebindable
785 , ol_type = placeHolderType }, fvs) }
786
787 {-
788 ************************************************************************
789 * *
790 \subsubsection{Errors}
791 * *
792 ************************************************************************
793 -}
794
795 patSigErr :: Outputable a => a -> SDoc
796 patSigErr ty
797 = (ptext (sLit "Illegal signature in pattern:") <+> ppr ty)
798 $$ nest 4 (ptext (sLit "Use ScopedTypeVariables to permit it"))
799
800 bogusCharError :: Char -> SDoc
801 bogusCharError c
802 = ptext (sLit "character literal out of range: '\\") <> char c <> char '\''
803
804 badViewPat :: Pat RdrName -> SDoc
805 badViewPat pat = vcat [ptext (sLit "Illegal view pattern: ") <+> ppr pat,
806 ptext (sLit "Use ViewPatterns to enable view patterns")]