RnPat.lhs 29 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12
%
% (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
%
\section[RnPat]{Renaming of patterns}

Basically dependency analysis.

Handles @Match@, @GRHSs@, @HsExpr@, and @Qualifier@ datatypes.  In
general, all of these functions return a renamed thing, and a set of
free variables.

\begin{code}
Ian Lynagh's avatar
Ian Lynagh committed
13 14 15
-- The above warning supression flag is a temporary kludge.
-- While working on this module you are encouraged to remove it and
-- detab the module (please do the detabbing in a separate patch). See
16
--     http://ghc.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#TabsvsSpaces
Ian Lynagh's avatar
Ian Lynagh committed
17 18
-- for details

19
{-# LANGUAGE ScopedTypeVariables #-}
20
module RnPat (-- main entry points
gmainland's avatar
gmainland committed
21
              rnPat, rnPats, rnBindPat, rnPatAndThen,
22 23 24 25

              NameMaker, applyNameMaker,     -- a utility for making names:
              localRecNameMaker, topRecNameMaker,  --   sometimes we want to make local names,
                                             --   sometimes we want to make top (qualified) names.
26
              isTopRecNameMaker,
27

28
              rnHsRecFields1, HsRecFieldContext(..),
29

gmainland's avatar
gmainland committed
30 31 32
              -- CpsRn monad
              CpsRn, liftCps,

thoughtpolice's avatar
thoughtpolice committed
33
              -- Literals
gmainland's avatar
gmainland committed
34
              rnLit, rnOverLit,
35 36 37 38 39 40 41

             -- Pattern Error messages that are also used elsewhere
             checkTupSize, patSigErr
             ) where

-- ENH: thin imports to only what is necessary for patterns

Ian Lynagh's avatar
Ian Lynagh committed
42
import {-# SOURCE #-} RnExpr ( rnLExpr )
gmainland's avatar
gmainland committed
43
import {-# SOURCE #-} RnSplice ( rnSplicePat )
Ian Lynagh's avatar
Ian Lynagh committed
44
import {-# SOURCE #-} TcSplice ( runQuasiQuotePat )
45 46 47 48 49

#include "HsVersions.h"

import HsSyn            
import TcRnMonad
Austin Seipp's avatar
Austin Seipp committed
50
import TcHsSyn             ( hsOverLitName )
51
import RnEnv
Ian Lynagh's avatar
Ian Lynagh committed
52
import RnTypes
53
import DynFlags
Ian Lynagh's avatar
Ian Lynagh committed
54
import PrelNames
Simon Peyton Jones's avatar
Simon Peyton Jones committed
55
import TyCon               ( tyConName )
cactus's avatar
cactus committed
56
import ConLike
Simon Peyton Jones's avatar
Simon Peyton Jones committed
57 58
import DataCon             ( dataConTyCon )
import TypeRep             ( TyThing(..) )
Ian Lynagh's avatar
Ian Lynagh committed
59
import Name
60
import NameSet
Ian Lynagh's avatar
Ian Lynagh committed
61
import RdrName
62
import BasicTypes
63
import Util
Austin Seipp's avatar
Austin Seipp committed
64
import ListSetOps          ( removeDups )
65
import Outputable
Ian Lynagh's avatar
Ian Lynagh committed
66
import SrcLoc
67
import FastString
Austin Seipp's avatar
Austin Seipp committed
68 69 70 71
import Literal             ( inCharRange )
import TysWiredIn          ( nilDataCon )
import DataCon             ( dataConName )
import Control.Monad       ( when, liftM, ap )
72
import Data.Ratio
73 74 75
\end{code}


Thomas Schilling's avatar
Thomas Schilling committed
76
%*********************************************************
thoughtpolice's avatar
thoughtpolice committed
77 78 79
%*                                                      *
        The CpsRn Monad
%*                                                      *
Thomas Schilling's avatar
Thomas Schilling committed
80
%*********************************************************
81

82 83 84 85 86
Note [CpsRn monad]
~~~~~~~~~~~~~~~~~~
The CpsRn monad uses continuation-passing style to support this
style of programming:

thoughtpolice's avatar
thoughtpolice committed
87
        do { ...
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
           ; ns <- bindNames rs
           ; ...blah... }

   where rs::[RdrName], ns::[Name]

The idea is that '...blah...' 
  a) sees the bindings of ns
  b) returns the free variables it mentions
     so that bindNames can report unused ones

In particular, 
    mapM rnPatAndThen [p1, p2, p3]
has a *left-to-right* scoping: it makes the binders in 
p1 scope over p2,p3.

103
\begin{code}
104 105
newtype CpsRn b = CpsRn { unCpsRn :: forall r. (b -> RnM (r, FreeVars))
                                            -> RnM (r, FreeVars) }
thoughtpolice's avatar
thoughtpolice committed
106
        -- See Note [CpsRn monad]
107

Austin Seipp's avatar
Austin Seipp committed
108 109 110 111 112 113 114
instance Functor CpsRn where
    fmap = liftM

instance Applicative CpsRn where
    pure = return
    (<*>) = ap

115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
instance Monad CpsRn where
  return x = CpsRn (\k -> k x)
  (CpsRn m) >>= mk = CpsRn (\k -> m (\v -> unCpsRn (mk v) k))

runCps :: CpsRn a -> RnM (a, FreeVars)
runCps (CpsRn m) = m (\r -> return (r, emptyFVs))

liftCps :: RnM a -> CpsRn a
liftCps rn_thing = CpsRn (\k -> rn_thing >>= k)

liftCpsFV :: RnM (a, FreeVars) -> CpsRn a
liftCpsFV rn_thing = CpsRn (\k -> do { (v,fvs1) <- rn_thing
                                     ; (r,fvs2) <- k v
                                     ; return (r, fvs1 `plusFV` fvs2) })

wrapSrcSpanCps :: (a -> CpsRn b) -> Located a -> CpsRn (Located b)
-- Set the location, and also wrap it around the value returned
wrapSrcSpanCps fn (L loc a)
  = CpsRn (\k -> setSrcSpan loc $ 
                 unCpsRn (fn a) $ \v -> 
                 k (L loc v))

lookupConCps :: Located RdrName -> CpsRn (Located Name)
lookupConCps con_rdr 
  = CpsRn (\k -> do { con_name <- lookupLocatedOccRn con_rdr
cactus's avatar
cactus committed
140 141 142 143
                    ; (r, fvs) <- k con_name
                    ; return (r, addOneFV fvs (unLoc con_name)) })
    -- We add the constructor name to the free vars
    -- See Note [Patterns are uses]
144
\end{code}
145

cactus's avatar
cactus committed
146 147
Note [Patterns are uses]
~~~~~~~~~~~~~~~~~~~~~~~~
148 149 150 151 152 153 154 155 156
Consider
  module Foo( f, g ) where
  data T = T1 | T2

  f T1 = True
  f T2 = False

  g _ = T1

Gabor Greif's avatar
Gabor Greif committed
157
Arguably we should report T2 as unused, even though it appears in a
158 159
pattern, because it never occurs in a constructed position.  See
Trac #7336.
cactus's avatar
cactus committed
160 161 162 163 164 165 166 167 168 169
However, implementing this in the face of pattern synonyms would be
less straightforward, since given two pattern synonyms

  pattern P1 <- P2
  pattern P2 <- ()

we need to observe the dependency between P1 and P2 so that type
checking can be done in the correct order (just like for value
bindings). Dependencies between bindings is analyzed in the renamer,
where we don't know yet whether P2 is a constructor or a pattern
Gabor Greif's avatar
Gabor Greif committed
170
synonym. So for now, we do report conid occurrences in patterns as
cactus's avatar
cactus committed
171
uses.
172

173
%*********************************************************
thoughtpolice's avatar
thoughtpolice committed
174 175 176
%*                                                      *
        Name makers
%*                                                      *
177
%*********************************************************
178

179 180 181 182 183
Externally abstract type of name makers,
which is how you go from a RdrName to a Name

\begin{code}
data NameMaker 
thoughtpolice's avatar
thoughtpolice committed
184 185 186 187
  = LamMk       -- Lambdas 
      Bool      -- True <=> report unused bindings
                --   (even if True, the warning only comes out 
                --    if -fwarn-unused-matches is on)
188 189

  | LetMk       -- Let bindings, incl top level
thoughtpolice's avatar
thoughtpolice committed
190
                -- Do *not* check for unused bindings
191
      TopLevelFlag
192 193
      MiniFixityEnv

194 195
topRecNameMaker :: MiniFixityEnv -> NameMaker
topRecNameMaker fix_env = LetMk TopLevel fix_env
196

197 198 199 200
isTopRecNameMaker :: NameMaker -> Bool
isTopRecNameMaker (LetMk TopLevel _) = True
isTopRecNameMaker _ = False

201
localRecNameMaker :: MiniFixityEnv -> NameMaker
202
localRecNameMaker fix_env = LetMk NotTopLevel fix_env 
203

204 205 206 207 208 209
matchNameMaker :: HsMatchContext a -> NameMaker
matchNameMaker ctxt = LamMk report_unused
  where
    -- Do not report unused names in interactive contexts
    -- i.e. when you type 'x <- e' at the GHCi prompt
    report_unused = case ctxt of
210 211
                      StmtCtxt GhciStmtCtxt -> False
                      _                     -> True
212

213
rnHsSigCps :: HsWithBndrs (LHsType RdrName) -> CpsRn (HsWithBndrs (LHsType Name))
214
rnHsSigCps sig 
215
  = CpsRn (rnHsBndrSig PatCtx sig)
216

batterseapower's avatar
batterseapower committed
217 218
newPatName :: NameMaker -> Located RdrName -> CpsRn Name
newPatName (LamMk report_unused) rdr_name
219
  = CpsRn (\ thing_inside -> 
thoughtpolice's avatar
thoughtpolice committed
220
        do { name <- newLocalBndrRn rdr_name
221
           ; (res, fvs) <- bindLocalNames [name] (thing_inside name)
thoughtpolice's avatar
thoughtpolice committed
222 223
           ; when report_unused $ warnUnusedMatches [name] fvs
           ; return (res, name `delFV` fvs) })
224

batterseapower's avatar
batterseapower committed
225
newPatName (LetMk is_top fix_env) rdr_name
226
  = CpsRn (\ thing_inside -> 
227 228 229
        do { name <- case is_top of
                       NotTopLevel -> newLocalBndrRn rdr_name
                       TopLevel    -> newTopSrcBinder rdr_name
230
           ; bindLocalNames [name] $       -- Do *not* use bindLocalNameFV here
thoughtpolice's avatar
thoughtpolice committed
231
                                        -- See Note [View pattern usage]
232
             addLocalFixities fix_env [name] $
thoughtpolice's avatar
thoughtpolice committed
233 234
             thing_inside name })
                          
235
    -- Note: the bindLocalNames is somewhat suspicious
236 237 238 239 240 241 242
    --       because it binds a top-level name as a local name.
    --       however, this binding seems to work, and it only exists for
    --       the duration of the patterns and the continuation;
    --       then the top-level name is added to the global env
    --       before going on to the RHSes (see RnSource.lhs).
\end{code}

243 244 245 246 247 248
Note [View pattern usage]
~~~~~~~~~~~~~~~~~~~~~~~~~
Consider
  let (r, (r -> x)) = x in ...
Here the pattern binds 'r', and then uses it *only* in the view pattern.
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

%*********************************************************
thoughtpolice's avatar
thoughtpolice committed
253 254 255
%*                                                      *
        External entry points
%*                                                      *
256 257 258 259 260 261 262 263
%*********************************************************

There are various entry points to renaming patterns, depending on
 (1) whether the names created should be top-level names or local names
 (2) whether the scope of the names is entirely given in a continuation
     (e.g., in a case or lambda, but not in a let or at the top-level,
      because of the way mutually recursive bindings are handled)
 (3) whether the a type signature in the pattern can bind 
thoughtpolice's avatar
thoughtpolice committed
264 265
        lexically-scoped type variables (for unpacking existential 
        type vars in data constructors)
266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284
 (4) whether we do duplicate and unused variable checking
 (5) whether there are fixity declarations associated with the names
     bound by the patterns that need to be brought into scope with them.
     
 Rather than burdening the clients of this module with all of these choices,
 we export the three points in this design space that we actually need:

\begin{code}
-- ----------- Entry point 1: rnPats -------------------
-- Binds local names; the scope of the bindings is entirely in the thing_inside
--   * allows type sigs to bind type vars
--   * local namemaker
--   * unused and duplicate checking
--   * no fixities
rnPats :: HsMatchContext Name -- for error messages
       -> [LPat RdrName] 
       -> ([LPat Name] -> RnM (a, FreeVars))
       -> RnM (a, FreeVars)
rnPats ctxt pats thing_inside
thoughtpolice's avatar
thoughtpolice committed
285
  = do  { envs_before <- getRdrEnvs
286

thoughtpolice's avatar
thoughtpolice committed
287 288 289
          -- (1) rename the patterns, bringing into scope all of the term variables
          -- (2) then do the thing inside.
        ; unCpsRn (rnLPatsAndThen (matchNameMaker ctxt) pats) $ \ pats' -> do
290
        { -- Check for duplicated and shadowed names 
thoughtpolice's avatar
thoughtpolice committed
291 292
          -- Must do this *after* renaming the patterns
          -- See Note [Collect binders only after renaming] in HsUtils
293
          -- Because we don't bind the vars all at once, we can't
thoughtpolice's avatar
thoughtpolice committed
294 295 296
          --    check incrementally for duplicates; 
          -- Nor can we check incrementally for shadowing, else we'll
          --    complain *twice* about duplicates e.g. f (x,x) = ...
297 298 299
        ; addErrCtxt doc_pat $ 
          checkDupAndShadowedNames envs_before $
          collectPatsBinders pats'
300
        ; thing_inside pats' } }
301
  where
Ian Lynagh's avatar
Ian Lynagh committed
302
    doc_pat = ptext (sLit "In") <+> pprMatchContext ctxt
303

304 305 306
rnPat :: HsMatchContext Name -- for error messages
      -> LPat RdrName 
      -> (LPat Name -> RnM (a, FreeVars))
307
      -> RnM (a, FreeVars)     -- Variables bound by pattern do not 
thoughtpolice's avatar
thoughtpolice committed
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 Name
batterseapower's avatar
batterseapower committed
313
applyNameMaker mk rdr = do { (n, _fvs) <- runCps (newPatName mk rdr); return n }
314 315 316

-- ----------- Entry point 2: rnBindPat -------------------
-- Binds local names; in a recursive scope that involves other bound vars
thoughtpolice's avatar
thoughtpolice committed
317
--      e.g let { (x, Just y) = e1; ... } in ...
318 319 320 321
--   * does NOT allows type sig to bind type vars
--   * local namemaker
--   * no unused and duplicate checking
--   * fixities might be coming in
322 323
rnBindPat :: NameMaker
          -> LPat RdrName
324 325 326 327 328 329 330 331 332
          -> RnM (LPat Name, FreeVars)
   -- Returned FreeVars are the free variables of the pattern,
   -- of course excluding variables bound by this pattern 

rnBindPat name_maker pat = runCps (rnLPatAndThen name_maker pat)
\end{code}


%*********************************************************
thoughtpolice's avatar
thoughtpolice committed
333 334 335
%*                                                      *
        The main event
%*                                                      *
336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357
%*********************************************************

\begin{code}
-- ----------- Entry point 3: rnLPatAndThen -------------------
-- General version: parametrized by how you make new names

rnLPatsAndThen :: NameMaker -> [LPat RdrName] -> CpsRn [LPat Name]
rnLPatsAndThen mk = mapM (rnLPatAndThen mk)
  -- Despite the map, the monad ensures that each pattern binds
  -- variables that may be mentioned in subsequent patterns in the list

--------------------
-- The workhorse
rnLPatAndThen :: NameMaker -> LPat RdrName -> CpsRn (LPat Name)
rnLPatAndThen nm lpat = wrapSrcSpanCps (rnPatAndThen nm) lpat

rnPatAndThen :: NameMaker -> Pat RdrName -> CpsRn (Pat Name)
rnPatAndThen _  (WildPat _)   = return (WildPat placeHolderType)
rnPatAndThen mk (ParPat pat)  = do { pat' <- rnLPatAndThen mk pat; return (ParPat pat') }
rnPatAndThen mk (LazyPat pat) = do { pat' <- rnLPatAndThen mk pat; return (LazyPat pat') }
rnPatAndThen mk (BangPat pat) = do { pat' <- rnLPatAndThen mk pat; return (BangPat pat') }
rnPatAndThen mk (VarPat rdr)  = do { loc <- liftCps getSrcSpanM
batterseapower's avatar
batterseapower committed
358
                                   ; name <- newPatName mk (L loc rdr)
359 360 361
                                   ; return (VarPat name) }
     -- we need to bind pattern variables for view pattern expressions
     -- (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 365 366 367 368 369 370 371 372 373 374
  -- When renaming a pattern type signature (e.g. f (a :: T) = ...), it is
  -- important to rename its type signature _before_ renaming the rest of the
  -- pattern, so that type variables are first bound by the _outermost_ pattern
  -- type signature they occur in. This keeps the type checker happy when
  -- pattern type signatures happen to be nested (#7827)
  --
  -- f ((Just (x :: a) :: Maybe a)
  -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~^       `a' is first bound here
  -- ~~~~~~~~~~~~~~~^                   the same `a' then used here
  = do { sig' <- rnHsSigCps sig
       ; pat' <- rnLPatAndThen mk pat
375
       ; return (SigPatIn pat' sig') }
376
       
377 378
rnPatAndThen mk (LitPat lit)
  | HsString s <- lit
379
  = do { ovlStr <- liftCps (xoptM Opt_OverloadedStrings)
380 381 382 383 384 385 386 387 388 389
       ; if ovlStr 
         then rnPatAndThen mk (mkNPat (mkHsIsString s placeHolderType) Nothing)
         else normal_lit }
  | otherwise = normal_lit
  where
    normal_lit = do { liftCps (rnLit lit); return (LitPat lit) }

rnPatAndThen _ (NPat lit mb_neg _eq)
  = do { lit'    <- liftCpsFV $ rnOverLit lit
       ; mb_neg' <- liftCpsFV $ case mb_neg of
thoughtpolice's avatar
thoughtpolice committed
390 391 392
                      Nothing -> return (Nothing, emptyFVs)
                      Just _  -> do { (neg, fvs) <- lookupSyntaxName negateName
                                    ; return (Just neg, fvs) }
393 394 395 396
       ; eq' <- liftCpsFV $ lookupSyntaxName eqName
       ; return (NPat lit' mb_neg' eq') }

rnPatAndThen mk (NPlusKPat rdr lit _ _)
batterseapower's avatar
batterseapower committed
397
  = do { new_name <- newPatName mk rdr
398 399 400 401
       ; lit'  <- liftCpsFV $ rnOverLit lit
       ; minus <- liftCpsFV $ lookupSyntaxName minusName
       ; ge    <- liftCpsFV $ lookupSyntaxName geName
       ; return (NPlusKPat (L (nameSrcSpan new_name) new_name) lit' ge minus) }
thoughtpolice's avatar
thoughtpolice committed
402
                -- The Report says that n+k patterns must be in Integral
403

404
rnPatAndThen mk (AsPat rdr pat)
batterseapower's avatar
batterseapower committed
405
  = do { new_name <- newPatName mk rdr
406 407 408 409
       ; pat' <- rnLPatAndThen mk pat
       ; return (AsPat (L (nameSrcSpan new_name) new_name) pat') }

rnPatAndThen mk p@(ViewPat expr pat ty)
410
  = do { liftCps $ do { vp_flag <- xoptM Opt_ViewPatterns
411 412 413 414 415 416 417 418 419
                      ; checkErr vp_flag (badViewPat p) }
         -- Because of the way we're arranging the recursive calls,
         -- this will be in the right context 
       ; expr' <- liftCpsFV $ rnLExpr expr 
       ; pat' <- rnLPatAndThen mk pat
       ; return (ViewPat expr' pat' ty) }

rnPatAndThen mk (ConPatIn con stuff)
   -- rnConPatAndThen takes care of reconstructing the pattern
420 421 422 423 424 425 426 427 428 429 430 431 432 433
   -- The pattern for the empty list needs to be replaced by an empty explicit list pattern when overloaded lists is turned on.
  = case unLoc con == nameRdrName (dataConName nilDataCon) of
      True    -> do { ol_flag <- liftCps $ xoptM Opt_OverloadedLists
                    ; if ol_flag then rnPatAndThen mk (ListPat [] placeHolderType Nothing)
                                 else rnConPatAndThen mk con stuff} 
      False   -> rnConPatAndThen mk con stuff

rnPatAndThen mk (ListPat pats _ _)
  = do { opt_OverloadedLists <- liftCps $ xoptM Opt_OverloadedLists
       ; pats' <- rnLPatsAndThen mk pats
       ; case opt_OverloadedLists of
          True -> do   { (to_list_name,_) <- liftCps $ lookupSyntaxName toListName
                       ; return (ListPat pats' placeHolderType (Just (placeHolderType, to_list_name)))}
          False -> return (ListPat pats' placeHolderType Nothing) }
434 435 436 437 438 439 440 441 442 443

rnPatAndThen mk (PArrPat pats _)
  = do { pats' <- rnLPatsAndThen mk pats
       ; return (PArrPat pats' placeHolderType) }

rnPatAndThen mk (TuplePat pats boxed _)
  = do { liftCps $ checkTupSize (length pats)
       ; pats' <- rnLPatsAndThen mk pats
       ; return (TuplePat pats' boxed placeHolderType) }

gmainland's avatar
gmainland committed
444 445
rnPatAndThen _ (SplicePat splice)
  = do { -- XXX How to deal with free variables?
446
       ; (pat, _) <- liftCps $ rnSplicePat splice
gmainland's avatar
gmainland committed
447
       ; return pat }
448
rnPatAndThen mk (QuasiQuotePat qq)
449
  = do { pat <- liftCps $ runQuasiQuotePat qq
Edsko de Vries's avatar
Edsko de Vries committed
450 451 452
         -- Wrap the result of the quasi-quoter in parens so that we don't
         -- lose the outermost location set by runQuasiQuote (#7918) 
       ; rnPatAndThen mk (ParPat pat) }
453

454
rnPatAndThen _ pat = pprPanic "rnLPatAndThen" (ppr pat)
Ian Lynagh's avatar
Ian Lynagh committed
455

456

457
--------------------
458 459 460
rnConPatAndThen :: NameMaker
                -> Located RdrName          -- the constructor
                -> HsConPatDetails RdrName 
461 462 463
                -> CpsRn (Pat Name)

rnConPatAndThen mk con (PrefixCon pats)
thoughtpolice's avatar
thoughtpolice committed
464 465 466
  = do  { con' <- lookupConCps con
        ; pats' <- rnLPatsAndThen mk pats
        ; return (ConPatIn con' (PrefixCon pats')) }
467 468

rnConPatAndThen mk con (InfixCon pat1 pat2)
thoughtpolice's avatar
thoughtpolice committed
469 470 471 472 473
  = do  { con' <- lookupConCps con
        ; pat1' <- rnLPatAndThen mk pat1
        ; pat2' <- rnLPatAndThen mk pat2
        ; fixity <- liftCps $ lookupFixityRn (unLoc con')
        ; liftCps $ mkConOpPatRn con' fixity pat1' pat2' }
474 475

rnConPatAndThen mk con (RecCon rpats)
thoughtpolice's avatar
thoughtpolice committed
476 477 478
  = do  { con' <- lookupConCps con
        ; rpats' <- rnHsRecPatsAndThen mk con' rpats
        ; return (ConPatIn con' (RecCon rpats')) }
479 480 481

--------------------
rnHsRecPatsAndThen :: NameMaker
thoughtpolice's avatar
thoughtpolice committed
482 483 484
                   -> Located Name      -- Constructor
                   -> HsRecFields RdrName (LPat RdrName)
                   -> CpsRn (HsRecFields Name (LPat Name))
485 486 487 488 489 490 491 492 493
rnHsRecPatsAndThen mk (L _ con) hs_rec_fields@(HsRecFields { rec_dotdot = dd })
  = do { flds <- liftCpsFV $ rnHsRecFields1 (HsRecFieldPat con) VarPat hs_rec_fields
       ; flds' <- mapM rn_field (flds `zip` [1..])
       ; return (HsRecFields { rec_flds = flds', rec_dotdot = dd }) }
  where 
    rn_field (fld, n') = do { arg' <- rnLPatAndThen (nested_mk dd mk n') 
                                                    (hsRecFieldArg fld)
                            ; return (fld { hsRecFieldArg = arg' }) }

thoughtpolice's avatar
thoughtpolice committed
494
        -- Suppress unused-match reporting for fields introduced by ".."
495 496 497 498 499 500 501
    nested_mk Nothing  mk                    _  = mk
    nested_mk (Just _) mk@(LetMk {})         _  = mk
    nested_mk (Just n) (LamMk report_unused) n' = LamMk (report_unused && (n' <= n))
\end{code}


%************************************************************************
thoughtpolice's avatar
thoughtpolice committed
502 503 504
%*                                                                      *
        Record fields
%*                                                                      *
505 506 507 508 509 510 511 512 513
%************************************************************************

\begin{code}
data HsRecFieldContext 
  = HsRecFieldCon Name
  | HsRecFieldPat Name
  | HsRecFieldUpd

rnHsRecFields1 
514 515
    :: forall arg. 
       HsRecFieldContext
516 517 518 519 520 521 522 523 524 525 526
    -> (RdrName -> arg) -- When punning, use this to build a new field
    -> HsRecFields RdrName (Located arg)
    -> RnM ([HsRecField Name (Located arg)], FreeVars)

-- This supprisingly complicated pass
--   a) looks up the field name (possibly using disambiguation)
--   b) fills in puns and dot-dot stuff
-- When we we've finished, we've renamed the LHS, but not the RHS,
-- of each x=e binding

rnHsRecFields1 ctxt mk_arg (HsRecFields { rec_flds = flds, rec_dotdot = dotdot })
527 528
  = do { pun_ok      <- xoptM Opt_RecordPuns
       ; disambig_ok <- xoptM Opt_DisambiguateRecordFields
529 530 531
       ; parent <- check_disambiguation disambig_ok mb_con
       ; flds1 <- mapM (rn_fld pun_ok parent) flds
       ; mapM_ (addErr . dupFieldErr ctxt) dup_flds
532 533 534 535
       ; dotdot_flds <- rn_dotdot dotdot mb_con flds1
       ; let all_flds | null dotdot_flds = flds1
                      | otherwise        = flds1 ++ dotdot_flds
       ; return (all_flds, mkFVs (getFieldIds all_flds)) }
536 537
  where
    mb_con = case ctxt of
thoughtpolice's avatar
thoughtpolice committed
538 539 540 541 542 543 544
                HsRecFieldCon con | not (isUnboundName con) -> Just con
                HsRecFieldPat con | not (isUnboundName con) -> Just con
                _other -> Nothing
           -- The unbound name test is because if the constructor 
           -- isn't in scope the constructor lookup will add an error
           -- add an error, but still return an unbound name. 
           -- We don't want that to screw up the dot-dot fill-in stuff.
545

546 547 548 549 550
    doc = case mb_con of
            Nothing  -> ptext (sLit "constructor field name")
            Just con -> ptext (sLit "field of constructor") <+> quotes (ppr con)

    rn_fld pun_ok parent (HsRecField { hsRecFieldId = fld
thoughtpolice's avatar
thoughtpolice committed
551 552
                                     , hsRecFieldArg = arg
                                     , hsRecPun = pun })
553
      = do { fld'@(L loc fld_nm) <- wrapLocM (lookupSubBndrOcc True parent doc) fld
554 555
           ; arg' <- if pun 
                     then do { checkErr pun_ok (badPun fld)
556
                             ; return (L loc (mk_arg (mkRdrUnqual (nameOccName fld_nm)))) }
557 558 559 560 561
                     else return arg
           ; return (HsRecField { hsRecFieldId = fld'
                                , hsRecFieldArg = arg'
                                , hsRecPun = pun }) }

thoughtpolice's avatar
thoughtpolice committed
562 563 564 565 566
    rn_dotdot :: Maybe Int      -- See Note [DotDot fields] in HsPat
              -> Maybe Name     -- The constructor (Nothing for an update
                                --    or out of scope constructor)
              -> [HsRecField Name (Located arg)]   -- Explicit fields
              -> RnM [HsRecField Name (Located arg)]   -- Filled in .. fields
567 568 569 570
    rn_dotdot Nothing _mb_con _flds     -- No ".." at all
      = return []
    rn_dotdot (Just {}) Nothing _flds   -- ".." on record update
      = do { addErr (badDotDot ctxt); return [] }
571
    rn_dotdot (Just n) (Just con) flds -- ".." on record construction / pat match
572
      = ASSERT( n == length flds )
thoughtpolice's avatar
thoughtpolice committed
573
        do { loc <- getSrcSpanM -- Rather approximate
574
           ; dd_flag <- xoptM Opt_RecordWildCards
575
           ; checkErr dd_flag (needFlagDotDot ctxt)
thoughtpolice's avatar
thoughtpolice committed
576
           ; (rdr_env, lcl_env) <- getRdrEnvs
577 578
           ; con_fields <- lookupConstructorFields con
           ; let present_flds = getFieldIds flds
579 580
                 parent_tc = find_tycon rdr_env con

581 582
                   -- For constructor uses (but not patterns)
                   -- the arg should be in scope (unqualified)
thoughtpolice's avatar
thoughtpolice committed
583 584
                   -- ignoring the record field itself
                   -- Eg.  data R = R { x,y :: Int }
585
                   --      f x = R { .. }   -- Should expand to R {x=x}, not R{x=x,y=y}
thoughtpolice's avatar
thoughtpolice committed
586
                 arg_in_scope fld 
587 588 589 590 591 592 593 594
                   = rdr `elemLocalRdrEnv` lcl_env
                   || notNull [ gre | gre <- lookupGRE_RdrName rdr rdr_env
                                    , case gre_par gre of
                                        ParentIs p -> p /= parent_tc
                                        _          -> True ]
                   where
                     rdr = mkRdrUnqual (nameOccName fld)

595
                 dot_dot_gres = [ head gres
596 597
                                | fld <- con_fields
                                , not (fld `elem` present_flds)
598 599
                                , let gres = lookupGRE_Name rdr_env fld
                                , not (null gres)  -- Check field is in scope
600 601 602 603 604
                                , case ctxt of
                                    HsRecFieldCon {} -> arg_in_scope fld
                                    _other           -> True ] 

           ; addUsedRdrNames (map greRdrName dot_dot_gres)
605
           ; return [ HsRecField
606 607 608 609
                        { hsRecFieldId  = L loc fld
                        , hsRecFieldArg = L loc (mk_arg arg_rdr)
                        , hsRecPun      = False }
                    | gre <- dot_dot_gres
thoughtpolice's avatar
thoughtpolice committed
610 611
                    , let fld     = gre_name gre
                          arg_rdr = mkRdrUnqual (nameOccName fld) ] }
612 613

    check_disambiguation :: Bool -> Maybe Name -> RnM Parent
614
    -- When disambiguation is on, 
615 616
    check_disambiguation disambig_ok mb_con
      | disambig_ok, Just con <- mb_con
617
      = do { env <- getGlobalRdrEnv; return (ParentIs (find_tycon env con)) }
618 619
      | otherwise = return NoParent
 
620 621 622 623 624
    find_tycon :: GlobalRdrEnv -> Name {- DataCon -} -> Name {- TyCon -}
    -- Return the parent *type constructor* of the data constructor
    -- That is, the parent of the data constructor.  
    -- That's the parent to use for looking up record fields.
    find_tycon env con 
cactus's avatar
cactus committed
625
      | Just (AConLike (RealDataCon dc)) <- wiredInNameTyThing_maybe con
Simon Peyton Jones's avatar
Simon Peyton Jones committed
626 627 628 629 630 631 632
      = tyConName (dataConTyCon dc)   -- Special case for [], which is built-in syntax
                                      -- and not in the GlobalRdrEnv (Trac #8448)
      | [GRE { gre_par = ParentIs p }] <- lookupGRE_Name env con
      = p

      | otherwise
      = pprPanic "find_tycon" (ppr con $$ ppr (lookupGRE_Name env con))
633

634 635 636 637 638 639 640 641 642 643 644
    dup_flds :: [[RdrName]]
        -- Each list represents a RdrName that occurred more than once
        -- (the list contains all occurrences)
        -- Each list in dup_fields is non-empty
    (_, dup_flds) = removeDups compare (getFieldIds flds)

getFieldIds :: [HsRecField id arg] -> [id]
getFieldIds flds = map (unLoc . hsRecFieldId) flds

needFlagDotDot :: HsRecFieldContext -> SDoc
needFlagDotDot ctxt = vcat [ptext (sLit "Illegal `..' in record") <+> pprRFC ctxt,
645
                            ptext (sLit "Use RecordWildCards to permit this")]
646 647 648

badDotDot :: HsRecFieldContext -> SDoc
badDotDot ctxt = ptext (sLit "You cannot use `..' in a record") <+> pprRFC ctxt
649

Ian Lynagh's avatar
Ian Lynagh committed
650
badPun :: Located RdrName -> SDoc
Ian Lynagh's avatar
Ian Lynagh committed
651
badPun fld = vcat [ptext (sLit "Illegal use of punning for field") <+> quotes (ppr fld),
652
                   ptext (sLit "Use NamedFieldPuns to permit this")]
653

654 655 656 657
dupFieldErr :: HsRecFieldContext -> [RdrName] -> SDoc
dupFieldErr ctxt dups
  = hsep [ptext (sLit "duplicate field name"), 
          quotes (ppr (head dups)),
thoughtpolice's avatar
thoughtpolice committed
658
          ptext (sLit "in record"), pprRFC ctxt]
659

660 661 662 663
pprRFC :: HsRecFieldContext -> SDoc
pprRFC (HsRecFieldCon {}) = ptext (sLit "construction")
pprRFC (HsRecFieldPat {}) = ptext (sLit "pattern")
pprRFC (HsRecFieldUpd {}) = ptext (sLit "update")
664 665 666 667
\end{code}


%************************************************************************
thoughtpolice's avatar
thoughtpolice committed
668
%*                                                                      *
669
\subsubsection{Literals}
thoughtpolice's avatar
thoughtpolice committed
670
%*                                                                      *
671 672 673 674 675 676 677 678 679
%************************************************************************

When literals occur we have to make sure
that the types and classes they involve
are made available.

\begin{code}
rnLit :: HsLit -> RnM ()
rnLit (HsChar c) = checkErr (inCharRange c) (bogusCharError c)
Ian Lynagh's avatar
Ian Lynagh committed
680
rnLit _ = return ()
681

682 683 684 685 686 687 688
-- Turn a Fractional-looking literal which happens to be an integer into an
-- Integer-looking literal.
generalizeOverLitVal :: OverLitVal -> OverLitVal
generalizeOverLitVal (HsFractional (FL {fl_value=val}))
    | denominator val == 1 = HsIntegral (numerator val)
generalizeOverLitVal lit = lit

Ian Lynagh's avatar
Ian Lynagh committed
689
rnOverLit :: HsOverLit t -> RnM (HsOverLit Name, FreeVars)
690 691 692 693 694 695 696
rnOverLit origLit
  = do  { opt_NumDecimals <- xoptM Opt_NumDecimals
        ; let { lit@(OverLit {ol_val=val})
            | opt_NumDecimals = origLit {ol_val = generalizeOverLitVal (ol_val origLit)}
            | otherwise       = origLit
          }
        ; let std_name = hsOverLitName val
thoughtpolice's avatar
thoughtpolice committed
697 698 699 700 701 702
        ; (from_thing_name, fvs) <- lookupSyntaxName std_name
        ; let rebindable = case from_thing_name of
                                HsVar v -> v /= std_name
                                _       -> panic "rnOverLit"
        ; return (lit { ol_witness = from_thing_name
                      , ol_rebindable = rebindable }, fvs) }
703 704
\end{code}

705
%************************************************************************
thoughtpolice's avatar
thoughtpolice committed
706
%*                                                                      *
707
\subsubsection{Errors}
thoughtpolice's avatar
thoughtpolice committed
708
%*                                                                      *
709 710 711
%************************************************************************

\begin{code}
Ian Lynagh's avatar
Ian Lynagh committed
712
patSigErr :: Outputable a => a -> SDoc
713
patSigErr ty
Ian Lynagh's avatar
Ian Lynagh committed
714
  =  (ptext (sLit "Illegal signature in pattern:") <+> ppr ty)
715
        $$ nest 4 (ptext (sLit "Use ScopedTypeVariables to permit it"))
716

Ian Lynagh's avatar
Ian Lynagh committed
717
bogusCharError :: Char -> SDoc
718
bogusCharError c
Ian Lynagh's avatar
Ian Lynagh committed
719
  = ptext (sLit "character literal out of range: '\\") <> char c  <> char '\''
720

Ian Lynagh's avatar
Ian Lynagh committed
721
badViewPat :: Pat RdrName -> SDoc
Ian Lynagh's avatar
Ian Lynagh committed
722
badViewPat pat = vcat [ptext (sLit "Illegal view pattern: ") <+> ppr pat,
723
                       ptext (sLit "Use ViewPatterns to enable view patterns")]
724
\end{code}