diff --git a/compiler/rename/RnBinds.lhs b/compiler/rename/RnBinds.lhs index ed1343f..ba94a39 100644 --- a/compiler/rename/RnBinds.lhs +++ b/compiler/rename/RnBinds.lhs @@ -1,1031 +1,1038 @@ % % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998 % \section[RnBinds]{Renaming and dependency analysis of bindings} This module does renaming and dependency analysis on value bindings in the abstract syntax. It does {\em not} do cycle-checks on class or type-synonym declarations; those cannot be done at this stage because they may be affected by renaming (which isn't fully worked out yet). \begin{code} {-# OPTIONS -fno-warn-tabs #-} -- 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 -- http://ghc.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#TabsvsSpaces -- for details module RnBinds ( -- Renaming top-level bindings rnTopBindsLHS, rnTopBindsRHS, rnValBindsRHS, -- Renaming local bindings rnLocalBindsAndThen, rnLocalValBindsLHS, rnLocalValBindsRHS, -- Other bindings rnMethodBinds, renameSigs, mkSigTvFn, rnMatchGroup, rnGRHSs, rnGRHS, makeMiniFixityEnv, MiniFixityEnv, HsSigCtxt(..) ) where import {-# SOURCE #-} RnExpr( rnLExpr, rnStmts ) import HsSyn import TcRnMonad import TcEvidence ( emptyTcEvBinds ) import RnTypes ( bindSigTyVarsFV, rnHsSigType, rnLHsType, checkPrecMatch, rnContext ) import RnPat import RnNames import RnEnv import DynFlags import Module import Name import NameEnv import NameSet import RdrName ( RdrName, rdrNameOcc ) import SrcLoc import ListSetOps ( findDupsEq ) import BasicTypes ( RecFlag(..), Origin ) import Digraph ( SCC(..) ) import Bag import Outputable import FastString import Data.List ( partition, sort ) import Maybes ( orElse ) import Control.Monad import Data.Traversable ( traverse ) \end{code} -- ToDo: Put the annotations into the monad, so that they arrive in the proper -- place and can be used when complaining. The code tree received by the function @rnBinds@ contains definitions in where-clauses which are all apparently mutually recursive, but which may not really depend upon each other. For example, in the top level program \begin{verbatim} f x = y where a = x y = x \end{verbatim} the definitions of @a@ and @y@ do not depend on each other at all. Unfortunately, the typechecker cannot always check such definitions. \footnote{Mycroft, A. 1984. Polymorphic type schemes and recursive definitions. In Proceedings of the International Symposium on Programming, Toulouse, pp. 217-39. LNCS 167. Springer Verlag.} However, the typechecker usually can check definitions in which only the strongly connected components have been collected into recursive bindings. This is precisely what the function @rnBinds@ does. ToDo: deal with case where a single monobinds binds the same variable twice. The vertag tag is a unique @Int@; the tags only need to be unique within one @MonoBinds@, so that unique-Int plumbing is done explicitly (heavy monad machinery not needed). %************************************************************************ %* * %* naming conventions * %* * %************************************************************************ \subsection[name-conventions]{Name conventions} The basic algorithm involves walking over the tree and returning a tuple containing the new tree plus its free variables. Some functions, such as those walking polymorphic bindings (HsBinds) and qualifier lists in list comprehensions (@Quals@), return the variables bound in local environments. These are then used to calculate the free variables of the expression evaluated in these environments. Conventions for variable names are as follows: \begin{itemize} \item new code is given a prime to distinguish it from the old. \item a set of variables defined in @Exp@ is written @dvExp@ \item a set of variables free in @Exp@ is written @fvExp@ \end{itemize} %************************************************************************ %* * %* analysing polymorphic bindings (HsBindGroup, HsBind) %* * %************************************************************************ \subsubsection[dep-HsBinds]{Polymorphic bindings} Non-recursive expressions are reconstructed without any changes at top level, although their component expressions may have to be altered. However, non-recursive expressions are currently not expected as \Haskell{} programs, and this code should not be executed. Monomorphic bindings contain information that is returned in a tuple (a @FlatMonoBinds@) containing: \begin{enumerate} \item a unique @Int@ that serves as the ``vertex tag'' for this binding. \item the name of a function or the names in a pattern. These are a set referred to as @dvLhs@, the defined variables of the left hand side. \item the free variables of the body. These are referred to as @fvBody@. \item the definition's actual code. This is referred to as just @code@. \end{enumerate} The function @nonRecDvFv@ returns two sets of variables. The first is the set of variables defined in the set of monomorphic bindings, while the second is the set of free variables in those bindings. The set of variables defined in a non-recursive binding is just the union of all of them, as @union@ removes duplicates. However, the free variables in each successive set of cumulative bindings is the union of those in the previous set plus those of the newest binding after the defined variables of the previous set have been removed. @rnMethodBinds@ deals only with the declarations in class and instance declarations. It expects only to see @FunMonoBind@s, and it expects the global environment to contain bindings for the binders (which are all class operations). %************************************************************************ %* * \subsubsection{ Top-level bindings} %* * %************************************************************************ \begin{code} -- for top-level bindings, we need to make top-level names, -- so we have a different entry point than for local bindings rnTopBindsLHS :: MiniFixityEnv -> HsValBinds RdrName -> RnM (HsValBindsLR Name RdrName) rnTopBindsLHS fix_env binds = rnValBindsLHS (topRecNameMaker fix_env) binds rnTopBindsRHS :: NameSet -> HsValBindsLR Name RdrName -> RnM (HsValBinds Name, DefUses) rnTopBindsRHS bound_names binds = do { is_boot <- tcIsHsBoot ; if is_boot then rnTopBindsBoot binds else rnValBindsRHS (TopSigCtxt bound_names False) binds } rnTopBindsBoot :: HsValBindsLR Name RdrName -> RnM (HsValBinds Name, DefUses) -- A hs-boot file has no bindings. -- Return a single HsBindGroup with empty binds and renamed signatures rnTopBindsBoot (ValBindsIn mbinds sigs) = do { checkErr (isEmptyLHsBinds mbinds) (bindsInHsBootFile mbinds) ; (sigs', fvs) <- renameSigs HsBootCtxt sigs ; return (ValBindsOut [] sigs', usesOnly fvs) } rnTopBindsBoot b = pprPanic "rnTopBindsBoot" (ppr b) \end{code} %********************************************************* %* * HsLocalBinds %* * %********************************************************* \begin{code} rnLocalBindsAndThen :: HsLocalBinds RdrName -> (HsLocalBinds Name -> RnM (result, FreeVars)) -> RnM (result, FreeVars) -- This version (a) assumes that the binding vars are *not* already in scope -- (b) removes the binders from the free vars of the thing inside -- The parser doesn't produce ThenBinds rnLocalBindsAndThen EmptyLocalBinds thing_inside = thing_inside EmptyLocalBinds rnLocalBindsAndThen (HsValBinds val_binds) thing_inside = rnLocalValBindsAndThen val_binds $ \ val_binds' -> thing_inside (HsValBinds val_binds') rnLocalBindsAndThen (HsIPBinds binds) thing_inside = do (binds',fv_binds) <- rnIPBinds binds (thing, fvs_thing) <- thing_inside (HsIPBinds binds') return (thing, fvs_thing `plusFV` fv_binds) rnIPBinds :: HsIPBinds RdrName -> RnM (HsIPBinds Name, FreeVars) rnIPBinds (IPBinds ip_binds _no_dict_binds) = do (ip_binds', fvs_s) <- mapAndUnzipM (wrapLocFstM rnIPBind) ip_binds return (IPBinds ip_binds' emptyTcEvBinds, plusFVs fvs_s) rnIPBind :: IPBind RdrName -> RnM (IPBind Name, FreeVars) rnIPBind (IPBind ~(Left n) expr) = do (expr',fvExpr) <- rnLExpr expr return (IPBind (Left n) expr', fvExpr) \end{code} %************************************************************************ %* * ValBinds %* * %************************************************************************ \begin{code} -- Renaming local binding gropus -- Does duplicate/shadow check rnLocalValBindsLHS :: MiniFixityEnv -> HsValBinds RdrName -> RnM ([Name], HsValBindsLR Name RdrName) rnLocalValBindsLHS fix_env binds = do { binds' <- rnValBindsLHS (localRecNameMaker fix_env) binds -- Check for duplicates and shadowing -- Must do this *after* renaming the patterns -- See Note [Collect binders only after renaming] in HsUtils -- We need to check for dups here because we -- don't don't bind all of the variables from the ValBinds at once -- with bindLocatedLocals any more. -- -- Note that we don't want to do this at the top level, since -- sorting out duplicates and shadowing there happens elsewhere. -- The behavior is even different. For example, -- import A(f) -- f = ... -- should not produce a shadowing warning (but it will produce -- an ambiguity warning if you use f), but -- import A(f) -- g = let f = ... in f -- should. ; let bound_names = collectHsValBinders binds' ; envs <- getRdrEnvs ; checkDupAndShadowedNames envs bound_names ; return (bound_names, binds') } -- renames the left-hand sides -- generic version used both at the top level and for local binds -- does some error checking, but not what gets done elsewhere at the top level rnValBindsLHS :: NameMaker -> HsValBinds RdrName -> RnM (HsValBindsLR Name RdrName) rnValBindsLHS topP (ValBindsIn mbinds sigs) = do { mbinds' <- mapBagM (wrapOriginLocM (rnBindLHS topP doc)) mbinds ; return $ ValBindsIn mbinds' sigs } where bndrs = collectHsBindsBinders mbinds doc = text "In the binding group for:" <+> pprWithCommas ppr bndrs rnValBindsLHS _ b = pprPanic "rnValBindsLHSFromDoc" (ppr b) -- General version used both from the top-level and for local things -- Assumes the LHS vars are in scope -- -- Does not bind the local fixity declarations rnValBindsRHS :: HsSigCtxt -> HsValBindsLR Name RdrName -> RnM (HsValBinds Name, DefUses) rnValBindsRHS ctxt (ValBindsIn mbinds sigs) = do { (sigs', sig_fvs) <- renameSigs ctxt sigs ; binds_w_dus <- mapBagM (rnLBind (mkSigTvFn sigs')) mbinds ; case depAnalBinds binds_w_dus of (anal_binds, anal_dus) -> return (valbind', valbind'_dus) where valbind' = ValBindsOut anal_binds sigs' valbind'_dus = anal_dus `plusDU` usesOnly sig_fvs -- Put the sig uses *after* the bindings -- so that the binders are removed from -- the uses in the sigs } rnValBindsRHS _ b = pprPanic "rnValBindsRHS" (ppr b) -- Wrapper for local binds -- -- The *client* of this function is responsible for checking for unused binders; -- it doesn't (and can't: we don't have the thing inside the binds) happen here -- -- The client is also responsible for bringing the fixities into scope rnLocalValBindsRHS :: NameSet -- names bound by the LHSes -> HsValBindsLR Name RdrName -> RnM (HsValBinds Name, DefUses) rnLocalValBindsRHS bound_names binds = rnValBindsRHS (LocalBindCtxt bound_names) binds -- for local binds -- wrapper that does both the left- and right-hand sides -- -- here there are no local fixity decls passed in; -- the local fixity decls come from the ValBinds sigs rnLocalValBindsAndThen :: HsValBinds RdrName -> (HsValBinds Name -> RnM (result, FreeVars)) -> RnM (result, FreeVars) rnLocalValBindsAndThen binds@(ValBindsIn _ sigs) thing_inside = do { -- (A) Create the local fixity environment new_fixities <- makeMiniFixityEnv [L loc sig | L loc (FixSig sig) <- sigs] -- (B) Rename the LHSes ; (bound_names, new_lhs) <- rnLocalValBindsLHS new_fixities binds -- ...and bring them (and their fixities) into scope ; bindLocalNamesFV bound_names $ addLocalFixities new_fixities bound_names $ do { -- (C) Do the RHS and thing inside (binds', dus) <- rnLocalValBindsRHS (mkNameSet bound_names) new_lhs ; (result, result_fvs) <- thing_inside binds' -- Report unused bindings based on the (accurate) -- findUses. E.g. -- let x = x in 3 -- should report 'x' unused ; let real_uses = findUses dus result_fvs -- Insert fake uses for variables introduced implicitly by wildcards (#4404) implicit_uses = hsValBindsImplicits binds' ; warnUnusedLocalBinds bound_names (real_uses `unionNameSets` implicit_uses) ; let -- The variables "used" in the val binds are: -- (1) the uses of the binds (allUses) -- (2) the FVs of the thing-inside all_uses = allUses dus `plusFV` result_fvs -- Note [Unused binding hack] -- ~~~~~~~~~~~~~~~~~~~~~~~~~~ -- Note that *in contrast* to the above reporting of -- unused bindings, (1) above uses duUses to return *all* -- the uses, even if the binding is unused. Otherwise consider: -- x = 3 -- y = let p = x in 'x' -- NB: p not used -- If we don't "see" the dependency of 'y' on 'x', we may put the -- bindings in the wrong order, and the type checker will complain -- that x isn't in scope -- -- But note that this means we won't report 'x' as unused, -- whereas we would if we had { x = 3; p = x; y = 'x' } ; return (result, all_uses) }} -- The bound names are pruned out of all_uses -- by the bindLocalNamesFV call above rnLocalValBindsAndThen bs _ = pprPanic "rnLocalValBindsAndThen" (ppr bs) -- Process the fixity declarations, making a FastString -> (Located Fixity) map -- (We keep the location around for reporting duplicate fixity declarations.) -- -- Checks for duplicates, but not that only locally defined things are fixed. -- Note: for local fixity declarations, duplicates would also be checked in -- check_sigs below. But we also use this function at the top level. makeMiniFixityEnv :: [LFixitySig RdrName] -> RnM MiniFixityEnv makeMiniFixityEnv decls = foldlM add_one emptyFsEnv decls where add_one env (L loc (FixitySig (L name_loc name) fixity)) = do { -- this fixity decl is a duplicate iff -- the ReaderName's OccName's FastString is already in the env -- (we only need to check the local fix_env because -- definitions of non-local will be caught elsewhere) let { fs = occNameFS (rdrNameOcc name) ; fix_item = L loc fixity }; case lookupFsEnv env fs of Nothing -> return $ extendFsEnv env fs fix_item Just (L loc' _) -> do { setSrcSpan loc $ addErrAt name_loc (dupFixityDecl loc' name) ; return env} } dupFixityDecl :: SrcSpan -> RdrName -> SDoc dupFixityDecl loc rdr_name = vcat [ptext (sLit "Multiple fixity declarations for") <+> quotes (ppr rdr_name), ptext (sLit "also at ") <+> ppr loc] --------------------- -- renaming a single bind rnBindLHS :: NameMaker -> SDoc -> HsBind RdrName -- returns the renamed left-hand side, -- and the FreeVars *of the LHS* -- (i.e., any free variables of the pattern) -> RnM (HsBindLR Name RdrName) rnBindLHS name_maker _ bind@(PatBind { pat_lhs = pat }) = do -- we don't actually use the FV processing of rnPatsAndThen here (pat',pat'_fvs) <- rnBindPat name_maker pat return (bind { pat_lhs = pat', bind_fvs = pat'_fvs }) -- We temporarily store the pat's FVs in bind_fvs; -- gets updated to the FVs of the whole bind -- when doing the RHS below rnBindLHS name_maker _ bind@(FunBind { fun_id = name@(L nameLoc _) }) = do { newname <- applyNameMaker name_maker name ; return (bind { fun_id = L nameLoc newname }) } rnBindLHS name_maker _ bind@(PatSynBind{ patsyn_id = rdrname@(L nameLoc _) }) - = do { addLocM checkConName rdrname + = do { unless (isTopRecNameMaker name_maker) $ + addErr localPatternSynonymErr + ; addLocM checkConName rdrname ; name <- applyNameMaker name_maker rdrname ; return (bind{ patsyn_id = L nameLoc name }) } + where + localPatternSynonymErr :: SDoc + localPatternSynonymErr + = hang (ptext (sLit "Illegal pattern synonym declaration")) + 2 (ptext (sLit "Pattern synonym declarations are only valid in the top-level scope")) rnBindLHS _ _ b = pprPanic "rnBindHS" (ppr b) rnLBind :: (Name -> [Name]) -- Signature tyvar function -> (Origin, LHsBindLR Name RdrName) -> RnM ((Origin, LHsBind Name), [Name], Uses) rnLBind sig_fn (origin, (L loc bind)) = setSrcSpan loc $ do { (bind', bndrs, dus) <- rnBind sig_fn bind ; return ((origin, L loc bind'), bndrs, dus) } -- assumes the left-hands-side vars are in scope rnBind :: (Name -> [Name]) -- Signature tyvar function -> HsBindLR Name RdrName -> RnM (HsBind Name, [Name], Uses) rnBind _ bind@(PatBind { pat_lhs = pat , pat_rhs = grhss -- pat fvs were stored in bind_fvs -- after processing the LHS , bind_fvs = pat_fvs }) = do { mod <- getModule ; (grhss', rhs_fvs) <- rnGRHSs PatBindRhs rnLExpr grhss -- No scoped type variables for pattern bindings ; let all_fvs = pat_fvs `plusFV` rhs_fvs fvs' = filterNameSet (nameIsLocalOrFrom mod) all_fvs -- Keep locally-defined Names -- As well as dependency analysis, we need these for the -- MonoLocalBinds test in TcBinds.decideGeneralisationPlan bndrs = collectPatBinders pat bind' = bind { pat_rhs = grhss', bind_fvs = fvs' } is_wild_pat = case pat of L _ (WildPat {}) -> True _ -> False -- Warn if the pattern binds no variables, except for the -- entirely-explicit idiom _ = rhs -- which (a) is not that different from _v = rhs -- (b) is sometimes used to give a type sig for, -- or an occurrence of, a variable on the RHS ; whenWOptM Opt_WarnUnusedBinds $ when (null bndrs && not is_wild_pat) $ addWarn $ unusedPatBindWarn bind' ; fvs' `seq` -- See Note [Free-variable space leak] return (bind', bndrs, all_fvs) } rnBind sig_fn bind@(FunBind { fun_id = name , fun_infix = is_infix , fun_matches = matches }) -- invariant: no free vars here when it's a FunBind = do { let plain_name = unLoc name ; (matches', rhs_fvs) <- bindSigTyVarsFV (sig_fn plain_name) $ -- bindSigTyVars tests for Opt_ScopedTyVars rnMatchGroup (FunRhs plain_name is_infix) rnLExpr matches ; when is_infix $ checkPrecMatch plain_name matches' ; mod <- getModule ; let fvs' = filterNameSet (nameIsLocalOrFrom mod) rhs_fvs -- Keep locally-defined Names -- As well as dependency analysis, we need these for the -- MonoLocalBinds test in TcBinds.decideGeneralisationPlan ; fvs' `seq` -- See Note [Free-variable space leak] return (bind { fun_matches = matches' , bind_fvs = fvs' }, [plain_name], rhs_fvs) } rnBind _sig_fn bind@(PatSynBind { patsyn_id = L _ name , patsyn_args = details , patsyn_def = pat , patsyn_dir = dir }) -- invariant: no free vars here when it's a FunBind = do { pattern_synonym_ok <- xoptM Opt_PatternSynonyms ; unless pattern_synonym_ok (addErr patternSynonymErr) ; ((pat', details'), fvs) <- rnPat PatSyn pat $ \pat' -> do -- We check the 'RdrName's instead of the 'Name's -- so that the binding locations are reported -- from the left-hand side { (details', fvs) <- case details of PrefixPatSyn vars -> do { checkDupRdrNames vars ; names <- mapM lookupVar vars ; return (PrefixPatSyn names, mkFVs (map unLoc names)) } InfixPatSyn var1 var2 -> do { checkDupRdrNames [var1, var2] ; name1 <- lookupVar var1 ; name2 <- lookupVar var2 -- ; checkPrecMatch -- TODO ; return (InfixPatSyn name1 name2, mkFVs (map unLoc [name1, name2])) } ; return ((pat', details'), fvs) } ; dir' <- case dir of Unidirectional -> return Unidirectional ImplicitBidirectional -> return ImplicitBidirectional ; mod <- getModule ; let fvs' = filterNameSet (nameIsLocalOrFrom mod) fvs -- Keep locally-defined Names -- As well as dependency analysis, we need these for the -- MonoLocalBinds test in TcBinds.decideGeneralisationPlan ; let bind' = bind{ patsyn_args = details' , patsyn_def = pat' , patsyn_dir = dir' , bind_fvs = fvs' } ; fvs' `seq` -- See Note [Free-variable space leak] return (bind', [name], fvs) } where lookupVar = wrapLocM lookupOccRn patternSynonymErr :: SDoc patternSynonymErr = hang (ptext (sLit "Illegal pattern synonym declaration")) 2 (ptext (sLit "Use -XPatternSynonyms to enable this extension")) rnBind _ b = pprPanic "rnBind" (ppr b) {- Note [Free-variable space leak] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We have fvs' = trim fvs and we seq fvs' before turning it as part of a record. The reason is that trim is sometimes something like \xs -> intersectNameSet (mkNameSet bound_names) xs and we don't want to retain the list bound_names. This showed up in trac ticket #1136. -} --------------------- depAnalBinds :: Bag ((Origin, LHsBind Name), [Name], Uses) -> ([(RecFlag, LHsBinds Name)], DefUses) -- Dependency analysis; this is important so that -- unused-binding reporting is accurate depAnalBinds binds_w_dus = (map get_binds sccs, map get_du sccs) where sccs = depAnal (\(_, defs, _) -> defs) (\(_, _, uses) -> nameSetToList uses) (bagToList binds_w_dus) get_binds (AcyclicSCC (bind, _, _)) = (NonRecursive, unitBag bind) get_binds (CyclicSCC binds_w_dus) = (Recursive, listToBag [b | (b,_,_) <- binds_w_dus]) get_du (AcyclicSCC (_, bndrs, uses)) = (Just (mkNameSet bndrs), uses) get_du (CyclicSCC binds_w_dus) = (Just defs, uses) where defs = mkNameSet [b | (_,bs,_) <- binds_w_dus, b <- bs] uses = unionManyNameSets [u | (_,_,u) <- binds_w_dus] --------------------- -- Bind the top-level forall'd type variables in the sigs. -- E.g f :: a -> a -- f = rhs -- The 'a' scopes over the rhs -- -- NB: there'll usually be just one (for a function binding) -- but if there are many, one may shadow the rest; too bad! -- e.g x :: [a] -> [a] -- y :: [(a,a)] -> a -- (x,y) = e -- In e, 'a' will be in scope, and it'll be the one from 'y'! mkSigTvFn :: [LSig Name] -> (Name -> [Name]) -- Return a lookup function that maps an Id Name to the names -- of the type variables that should scope over its body.. mkSigTvFn sigs = \n -> lookupNameEnv env n `orElse` [] where env :: NameEnv [Name] env = mkNameEnv [ (name, hsLKiTyVarNames ltvs) -- Kind variables and type variables | L _ (TypeSig names (L _ (HsForAllTy Explicit ltvs _ _))) <- sigs , (L _ name) <- names] -- Note the pattern-match on "Explicit"; we only bind -- type variables from signatures with an explicit top-level for-all \end{code} @rnMethodBinds@ is used for the method bindings of a class and an instance declaration. Like @rnBinds@ but without dependency analysis. NOTA BENE: we record each {\em binder} of a method-bind group as a free variable. That's crucial when dealing with an instance decl: \begin{verbatim} instance Foo (T a) where op x = ... \end{verbatim} This might be the {\em sole} occurrence of @op@ for an imported class @Foo@, and unless @op@ occurs we won't treat the type signature of @op@ in the class decl for @Foo@ as a source of instance-decl gates. But we should! Indeed, in many ways the @op@ in an instance decl is just like an occurrence, not a binder. \begin{code} rnMethodBinds :: Name -- Class name -> (Name -> [Name]) -- Signature tyvar function -> LHsBinds RdrName -> RnM (LHsBinds Name, FreeVars) rnMethodBinds cls sig_fn binds = do { checkDupRdrNames meth_names -- Check that the same method is not given twice in the -- same instance decl instance C T where -- f x = ... -- g y = ... -- f x = ... -- We must use checkDupRdrNames because the Name of the -- method is the Name of the class selector, whose SrcSpan -- points to the class declaration; and we use rnMethodBinds -- for instance decls too ; foldlM do_one (emptyBag, emptyFVs) (bagToList binds) } where meth_names = collectMethodBinders binds do_one (binds,fvs) (origin,bind) = do { (bind', fvs_bind) <- rnMethodBind cls sig_fn bind ; let bind'' = mapBag (\bind -> (origin,bind)) bind' ; return (binds `unionBags` bind'', fvs_bind `plusFV` fvs) } rnMethodBind :: Name -> (Name -> [Name]) -> LHsBindLR RdrName RdrName -> RnM (Bag (LHsBindLR Name Name), FreeVars) rnMethodBind cls sig_fn (L loc bind@(FunBind { fun_id = name, fun_infix = is_infix , fun_matches = MG { mg_alts = matches } })) = setSrcSpan loc $ do sel_name <- wrapLocM (lookupInstDeclBndr cls (ptext (sLit "method"))) name let plain_name = unLoc sel_name -- We use the selector name as the binder (new_matches, fvs) <- bindSigTyVarsFV (sig_fn plain_name) $ mapFvRn (rnMatch (FunRhs plain_name is_infix) rnLExpr) matches let new_group = mkMatchGroup new_matches when is_infix $ checkPrecMatch plain_name new_group return (unitBag (L loc (bind { fun_id = sel_name , fun_matches = new_group , bind_fvs = fvs })), fvs `addOneFV` plain_name) -- The 'fvs' field isn't used for method binds -- Can't handle method pattern-bindings which bind multiple methods. rnMethodBind _ _ (L loc bind@(PatBind {})) = do addErrAt loc (methodBindErr bind) return (emptyBag, emptyFVs) rnMethodBind _ _ b = pprPanic "rnMethodBind" (ppr b) \end{code} %************************************************************************ %* * \subsubsection[dep-Sigs]{Signatures (and user-pragmas for values)} %* * %************************************************************************ @renameSigs@ checks for: \begin{enumerate} \item more than one sig for one thing; \item signatures given for things not bound here; \end{enumerate} % At the moment we don't gather free-var info from the types in signatures. We'd only need this if we wanted to report unused tyvars. \begin{code} renameSigs :: HsSigCtxt -> [LSig RdrName] -> RnM ([LSig Name], FreeVars) -- Renames the signatures and performs error checks renameSigs ctxt sigs = do { mapM_ dupSigDeclErr (findDupSigs sigs) ; checkDupMinimalSigs sigs ; (sigs', sig_fvs) <- mapFvRn (wrapLocFstM (renameSig ctxt)) sigs ; let (good_sigs, bad_sigs) = partition (okHsSig ctxt) sigs' ; mapM_ misplacedSigErr bad_sigs -- Misplaced ; return (good_sigs, sig_fvs) } ---------------------- -- We use lookupSigOccRn in the signatures, which is a little bit unsatisfactory -- because this won't work for: -- instance Foo T where -- {-# INLINE op #-} -- Baz.op = ... -- We'll just rename the INLINE prag to refer to whatever other 'op' -- is in scope. (I'm assuming that Baz.op isn't in scope unqualified.) -- Doesn't seem worth much trouble to sort this. renameSig :: HsSigCtxt -> Sig RdrName -> RnM (Sig Name, FreeVars) -- FixitySig is renamed elsewhere. renameSig _ (IdSig x) = return (IdSig x, emptyFVs) -- Actually this never occurs renameSig ctxt sig@(TypeSig vs ty) = do { new_vs <- mapM (lookupSigOccRn ctxt sig) vs ; (new_ty, fvs) <- rnHsSigType (ppr_sig_bndrs vs) ty ; return (TypeSig new_vs new_ty, fvs) } renameSig ctxt sig@(GenericSig vs ty) = do { defaultSigs_on <- xoptM Opt_DefaultSignatures ; unless defaultSigs_on (addErr (defaultSigErr sig)) ; new_v <- mapM (lookupSigOccRn ctxt sig) vs ; (new_ty, fvs) <- rnHsSigType (ppr_sig_bndrs vs) ty ; return (GenericSig new_v new_ty, fvs) } renameSig _ (SpecInstSig ty) = do { (new_ty, fvs) <- rnLHsType SpecInstSigCtx ty ; return (SpecInstSig new_ty,fvs) } -- {-# SPECIALISE #-} pragmas can refer to imported Ids -- so, in the top-level case (when mb_names is Nothing) -- we use lookupOccRn. If there's both an imported and a local 'f' -- then the SPECIALISE pragma is ambiguous, unlike all other signatures renameSig ctxt sig@(SpecSig v ty inl) = do { new_v <- case ctxt of TopSigCtxt {} -> lookupLocatedOccRn v _ -> lookupSigOccRn ctxt sig v ; (new_ty, fvs) <- rnHsSigType (quotes (ppr v)) ty ; return (SpecSig new_v new_ty inl, fvs) } renameSig ctxt sig@(InlineSig v s) = do { new_v <- lookupSigOccRn ctxt sig v ; return (InlineSig new_v s, emptyFVs) } renameSig ctxt sig@(FixSig (FixitySig v f)) = do { new_v <- lookupSigOccRn ctxt sig v ; return (FixSig (FixitySig new_v f), emptyFVs) } renameSig ctxt sig@(MinimalSig bf) = do new_bf <- traverse (lookupSigOccRn ctxt sig) bf return (MinimalSig new_bf, emptyFVs) renameSig ctxt sig@(PatSynSig v args ty prov req) = do v' <- lookupSigOccRn ctxt sig v let doc = quotes (ppr v) rn_type = rnHsSigType doc (ty', fvs1) <- rn_type ty (args', fvs2) <- case args of PrefixPatSyn tys -> do (tys, fvs) <- unzip <$> mapM rn_type tys return (PrefixPatSyn tys, plusFVs fvs) InfixPatSyn left right -> do (left', fvs1) <- rn_type left (right', fvs2) <- rn_type right return (InfixPatSyn left' right', fvs1 `plusFV` fvs2) (prov', fvs3) <- rnContext (TypeSigCtx doc) prov (req', fvs4) <- rnContext (TypeSigCtx doc) req let fvs = plusFVs [fvs1, fvs2, fvs3, fvs4] return (PatSynSig v' args' ty' prov' req', fvs) ppr_sig_bndrs :: [Located RdrName] -> SDoc ppr_sig_bndrs bs = quotes (pprWithCommas ppr bs) okHsSig :: HsSigCtxt -> LSig a -> Bool okHsSig ctxt (L _ sig) = case (sig, ctxt) of (GenericSig {}, ClsDeclCtxt {}) -> True (GenericSig {}, _) -> False (TypeSig {}, _) -> True (PatSynSig {}, TopSigCtxt{}) -> True (PatSynSig {}, _) -> False (FixSig {}, InstDeclCtxt {}) -> False (FixSig {}, _) -> True (IdSig {}, TopSigCtxt {}) -> True (IdSig {}, InstDeclCtxt {}) -> True (IdSig {}, _) -> False (InlineSig {}, HsBootCtxt) -> False (InlineSig {}, _) -> True (SpecSig {}, TopSigCtxt {}) -> True (SpecSig {}, LocalBindCtxt {}) -> True (SpecSig {}, InstDeclCtxt {}) -> True (SpecSig {}, _) -> False (SpecInstSig {}, InstDeclCtxt {}) -> True (SpecInstSig {}, _) -> False (MinimalSig {}, ClsDeclCtxt {}) -> True (MinimalSig {}, _) -> False ------------------- findDupSigs :: [LSig RdrName] -> [[(Located RdrName, Sig RdrName)]] -- Check for duplicates on RdrName version, -- because renamed version has unboundName for -- not-in-scope binders, which gives bogus dup-sig errors -- NB: in a class decl, a 'generic' sig is not considered -- equal to an ordinary sig, so we allow, say -- class C a where -- op :: a -> a -- default op :: Eq a => a -> a findDupSigs sigs = findDupsEq matching_sig (concatMap (expand_sig . unLoc) sigs) where expand_sig sig@(FixSig (FixitySig n _)) = [(n,sig)] expand_sig sig@(InlineSig n _) = [(n,sig)] expand_sig sig@(TypeSig ns _) = [(n,sig) | n <- ns] expand_sig sig@(GenericSig ns _) = [(n,sig) | n <- ns] expand_sig _ = [] matching_sig (L _ n1,sig1) (L _ n2,sig2) = n1 == n2 && mtch sig1 sig2 mtch (FixSig {}) (FixSig {}) = True mtch (InlineSig {}) (InlineSig {}) = True mtch (TypeSig {}) (TypeSig {}) = True mtch (GenericSig {}) (GenericSig {}) = True mtch _ _ = False -- Warn about multiple MINIMAL signatures checkDupMinimalSigs :: [LSig RdrName] -> RnM () checkDupMinimalSigs sigs = case filter isMinimalLSig sigs of minSigs@(_:_:_) -> dupMinimalSigErr minSigs _ -> return () \end{code} %************************************************************************ %* * \subsection{Match} %* * %************************************************************************ \begin{code} rnMatchGroup :: Outputable (body RdrName) => HsMatchContext Name -> (Located (body RdrName) -> RnM (Located (body Name), FreeVars)) -> MatchGroup RdrName (Located (body RdrName)) -> RnM (MatchGroup Name (Located (body Name)), FreeVars) rnMatchGroup ctxt rnBody (MG { mg_alts = ms }) = do { empty_case_ok <- xoptM Opt_EmptyCase ; when (null ms && not empty_case_ok) (addErr (emptyCaseErr ctxt)) ; (new_ms, ms_fvs) <- mapFvRn (rnMatch ctxt rnBody) ms ; return (mkMatchGroup new_ms, ms_fvs) } rnMatch :: Outputable (body RdrName) => HsMatchContext Name -> (Located (body RdrName) -> RnM (Located (body Name), FreeVars)) -> LMatch RdrName (Located (body RdrName)) -> RnM (LMatch Name (Located (body Name)), FreeVars) rnMatch ctxt rnBody = wrapLocFstM (rnMatch' ctxt rnBody) rnMatch' :: Outputable (body RdrName) => HsMatchContext Name -> (Located (body RdrName) -> RnM (Located (body Name), FreeVars)) -> Match RdrName (Located (body RdrName)) -> RnM (Match Name (Located (body Name)), FreeVars) rnMatch' ctxt rnBody match@(Match pats maybe_rhs_sig grhss) = do { -- Result type signatures are no longer supported case maybe_rhs_sig of Nothing -> return () Just (L loc ty) -> addErrAt loc (resSigErr ctxt match ty) -- Now the main event -- note that there are no local ficity decls for matches ; rnPats ctxt pats $ \ pats' -> do { (grhss', grhss_fvs) <- rnGRHSs ctxt rnBody grhss ; return (Match pats' Nothing grhss', grhss_fvs) }} emptyCaseErr :: HsMatchContext Name -> SDoc emptyCaseErr ctxt = hang (ptext (sLit "Empty list of alternatives in") <+> pp_ctxt) 2 (ptext (sLit "Use EmptyCase to allow this")) where pp_ctxt = case ctxt of CaseAlt -> ptext (sLit "case expression") LambdaExpr -> ptext (sLit "\\case expression") _ -> ptext (sLit "(unexpected)") <+> pprMatchContextNoun ctxt resSigErr :: Outputable body => HsMatchContext Name -> Match RdrName body -> HsType RdrName -> SDoc resSigErr ctxt match ty = vcat [ ptext (sLit "Illegal result type signature") <+> quotes (ppr ty) , nest 2 $ ptext (sLit "Result signatures are no longer supported in pattern matches") , pprMatchInCtxt ctxt match ] \end{code} %************************************************************************ %* * \subsubsection{Guarded right-hand sides (GRHSs)} %* * %************************************************************************ \begin{code} rnGRHSs :: HsMatchContext Name -> (Located (body RdrName) -> RnM (Located (body Name), FreeVars)) -> GRHSs RdrName (Located (body RdrName)) -> RnM (GRHSs Name (Located (body Name)), FreeVars) rnGRHSs ctxt rnBody (GRHSs grhss binds) = rnLocalBindsAndThen binds $ \ binds' -> do (grhss', fvGRHSs) <- mapFvRn (rnGRHS ctxt rnBody) grhss return (GRHSs grhss' binds', fvGRHSs) rnGRHS :: HsMatchContext Name -> (Located (body RdrName) -> RnM (Located (body Name), FreeVars)) -> LGRHS RdrName (Located (body RdrName)) -> RnM (LGRHS Name (Located (body Name)), FreeVars) rnGRHS ctxt rnBody = wrapLocFstM (rnGRHS' ctxt rnBody) rnGRHS' :: HsMatchContext Name -> (Located (body RdrName) -> RnM (Located (body Name), FreeVars)) -> GRHS RdrName (Located (body RdrName)) -> RnM (GRHS Name (Located (body Name)), FreeVars) rnGRHS' ctxt rnBody (GRHS guards rhs) = do { pattern_guards_allowed <- xoptM Opt_PatternGuards ; ((guards', rhs'), fvs) <- rnStmts (PatGuard ctxt) rnLExpr guards $ \ _ -> rnBody rhs ; unless (pattern_guards_allowed || is_standard_guard guards') (addWarn (nonStdGuardErr guards')) ; return (GRHS guards' rhs', fvs) } where -- Standard Haskell 1.4 guards are just a single boolean -- expression, rather than a list of qualifiers as in the -- Glasgow extension is_standard_guard [] = True is_standard_guard [L _ (BodyStmt _ _ _ _)] = True is_standard_guard _ = False \end{code} %************************************************************************ %* * \subsection{Error messages} %* * %************************************************************************ \begin{code} dupSigDeclErr :: [(Located RdrName, Sig RdrName)] -> RnM () dupSigDeclErr pairs@((L loc name, sig) : _) = addErrAt loc $ vcat [ ptext (sLit "Duplicate") <+> what_it_is <> ptext (sLit "s for") <+> quotes (ppr name) , ptext (sLit "at") <+> vcat (map ppr $ sort $ map (getLoc . fst) pairs) ] where what_it_is = hsSigDoc sig dupSigDeclErr [] = panic "dupSigDeclErr" misplacedSigErr :: LSig Name -> RnM () misplacedSigErr (L loc sig) = addErrAt loc $ sep [ptext (sLit "Misplaced") <+> hsSigDoc sig <> colon, ppr sig] defaultSigErr :: Sig RdrName -> SDoc defaultSigErr sig = vcat [ hang (ptext (sLit "Unexpected default signature:")) 2 (ppr sig) , ptext (sLit "Use DefaultSignatures to enable default signatures") ] methodBindErr :: HsBindLR RdrName RdrName -> SDoc methodBindErr mbind = hang (ptext (sLit "Pattern bindings (except simple variables) not allowed in instance declarations")) 2 (ppr mbind) bindsInHsBootFile :: LHsBindsLR Name RdrName -> SDoc bindsInHsBootFile mbinds = hang (ptext (sLit "Bindings in hs-boot files are not allowed")) 2 (ppr mbinds) nonStdGuardErr :: Outputable body => [LStmtLR Name Name body] -> SDoc nonStdGuardErr guards = hang (ptext (sLit "accepting non-standard pattern guards (use PatternGuards to suppress this message)")) 4 (interpp'SP guards) unusedPatBindWarn :: HsBind Name -> SDoc unusedPatBindWarn bind = hang (ptext (sLit "This pattern-binding binds no variables:")) 2 (ppr bind) dupMinimalSigErr :: [LSig RdrName] -> RnM () dupMinimalSigErr sigs@(L loc _ : _) = addErrAt loc $ vcat [ ptext (sLit "Multiple minimal complete definitions") , ptext (sLit "at") <+> vcat (map ppr $ sort $ map getLoc sigs) , ptext (sLit "Combine alternative minimal complete definitions with `|'") ] dupMinimalSigErr [] = panic "dupMinimalSigErr" \end{code} diff --git a/compiler/rename/RnPat.lhs b/compiler/rename/RnPat.lhs index 3fde563..3c48f34 100644 --- a/compiler/rename/RnPat.lhs +++ b/compiler/rename/RnPat.lhs @@ -1,719 +1,724 @@ % % (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} -- 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 -- http://ghc.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#TabsvsSpaces -- for details {-# LANGUAGE ScopedTypeVariables #-} module RnPat (-- main entry points rnPat, rnPats, rnBindPat, rnPatAndThen, NameMaker, applyNameMaker, -- a utility for making names: localRecNameMaker, topRecNameMaker, -- sometimes we want to make local names, -- sometimes we want to make top (qualified) names. + isTopRecNameMaker, rnHsRecFields1, HsRecFieldContext(..), -- CpsRn monad CpsRn, liftCps, -- Literals rnLit, rnOverLit, -- Pattern Error messages that are also used elsewhere checkTupSize, patSigErr ) where -- ENH: thin imports to only what is necessary for patterns import {-# SOURCE #-} RnExpr ( rnLExpr ) import {-# SOURCE #-} RnSplice ( rnSplicePat ) import {-# SOURCE #-} TcSplice ( runQuasiQuotePat ) #include "HsVersions.h" import HsSyn import TcRnMonad import TcHsSyn ( hsOverLitName ) import RnEnv import RnTypes import DynFlags import PrelNames import TyCon ( tyConName ) import ConLike import DataCon ( dataConTyCon ) import TypeRep ( TyThing(..) ) import Name import NameSet import RdrName import BasicTypes import Util import ListSetOps ( removeDups ) import Outputable import SrcLoc import FastString import Literal ( inCharRange ) import TysWiredIn ( nilDataCon ) import DataCon ( dataConName ) import Control.Monad ( when, liftM, ap ) import Data.Ratio \end{code} %********************************************************* %* * The CpsRn Monad %* * %********************************************************* Note [CpsRn monad] ~~~~~~~~~~~~~~~~~~ The CpsRn monad uses continuation-passing style to support this style of programming: do { ... ; 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. \begin{code} newtype CpsRn b = CpsRn { unCpsRn :: forall r. (b -> RnM (r, FreeVars)) -> RnM (r, FreeVars) } -- See Note [CpsRn monad] instance Functor CpsRn where fmap = liftM instance Applicative CpsRn where pure = return (<*>) = ap 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 ; (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] \end{code} Note [Patterns are uses] ~~~~~~~~~~~~~~~~~~~~~~~~ Consider module Foo( f, g ) where data T = T1 | T2 f T1 = True f T2 = False g _ = T1 Arguably we should report T2 as unused, even though it appears in a pattern, because it never occurs in a constructed position. See Trac #7336. 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 synonym. So for now, we do report conid occurrences in patterns as uses. %********************************************************* %* * Name makers %* * %********************************************************* Externally abstract type of name makers, which is how you go from a RdrName to a Name \begin{code} data NameMaker = LamMk -- Lambdas Bool -- True <=> report unused bindings -- (even if True, the warning only comes out -- if -fwarn-unused-matches is on) | LetMk -- Let bindings, incl top level -- Do *not* check for unused bindings TopLevelFlag MiniFixityEnv topRecNameMaker :: MiniFixityEnv -> NameMaker topRecNameMaker fix_env = LetMk TopLevel fix_env +isTopRecNameMaker :: NameMaker -> Bool +isTopRecNameMaker (LetMk TopLevel _) = True +isTopRecNameMaker _ = False + localRecNameMaker :: MiniFixityEnv -> NameMaker localRecNameMaker fix_env = LetMk NotTopLevel fix_env 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 StmtCtxt GhciStmtCtxt -> False _ -> True rnHsSigCps :: HsWithBndrs (LHsType RdrName) -> CpsRn (HsWithBndrs (LHsType Name)) rnHsSigCps sig = CpsRn (rnHsBndrSig PatCtx sig) newPatName :: NameMaker -> Located RdrName -> CpsRn Name newPatName (LamMk report_unused) rdr_name = CpsRn (\ thing_inside -> do { name <- newLocalBndrRn rdr_name ; (res, fvs) <- bindLocalNames [name] (thing_inside name) ; when report_unused $ warnUnusedMatches [name] fvs ; return (res, name `delFV` fvs) }) newPatName (LetMk is_top fix_env) rdr_name = CpsRn (\ thing_inside -> do { name <- case is_top of NotTopLevel -> newLocalBndrRn rdr_name TopLevel -> newTopSrcBinder rdr_name ; bindLocalNames [name] $ -- Do *not* use bindLocalNameFV here -- See Note [View pattern usage] addLocalFixities fix_env [name] $ thing_inside name }) -- Note: the bindLocalNames is somewhat suspicious -- 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} 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 report unused variables at the binding level. So we must use bindLocalNames here, *not* bindLocalNameFV. Trac #3943. %********************************************************* %* * External entry points %* * %********************************************************* 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 lexically-scoped type variables (for unpacking existential type vars in data constructors) (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 = do { envs_before <- getRdrEnvs -- (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 { -- Check for duplicated and shadowed names -- Must do this *after* renaming the patterns -- See Note [Collect binders only after renaming] in HsUtils -- Because we don't bind the vars all at once, we can't -- check incrementally for duplicates; -- Nor can we check incrementally for shadowing, else we'll -- complain *twice* about duplicates e.g. f (x,x) = ... ; addErrCtxt doc_pat $ checkDupAndShadowedNames envs_before $ collectPatsBinders pats' ; thing_inside pats' } } where doc_pat = ptext (sLit "In") <+> pprMatchContext ctxt rnPat :: HsMatchContext Name -- for error messages -> LPat RdrName -> (LPat Name -> RnM (a, FreeVars)) -> RnM (a, FreeVars) -- Variables bound by pattern do not -- appear in the result FreeVars rnPat ctxt pat thing_inside = rnPats ctxt [pat] (\pats' -> let [pat'] = pats' in thing_inside pat') applyNameMaker :: NameMaker -> Located RdrName -> RnM Name applyNameMaker mk rdr = do { (n, _fvs) <- runCps (newPatName mk rdr); return n } -- ----------- Entry point 2: rnBindPat ------------------- -- Binds local names; in a recursive scope that involves other bound vars -- e.g let { (x, Just y) = e1; ... } in ... -- * does NOT allows type sig to bind type vars -- * local namemaker -- * no unused and duplicate checking -- * fixities might be coming in rnBindPat :: NameMaker -> LPat RdrName -> 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} %********************************************************* %* * The main event %* * %********************************************************* \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 ; name <- newPatName mk (L loc rdr) ; 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) rnPatAndThen mk (SigPatIn pat sig) -- 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 ; return (SigPatIn pat' sig') } rnPatAndThen mk (LitPat lit) | HsString s <- lit = do { ovlStr <- liftCps (xoptM Opt_OverloadedStrings) ; 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 Nothing -> return (Nothing, emptyFVs) Just _ -> do { (neg, fvs) <- lookupSyntaxName negateName ; return (Just neg, fvs) } ; eq' <- liftCpsFV $ lookupSyntaxName eqName ; return (NPat lit' mb_neg' eq') } rnPatAndThen mk (NPlusKPat rdr lit _ _) = do { new_name <- newPatName mk rdr ; lit' <- liftCpsFV $ rnOverLit lit ; minus <- liftCpsFV $ lookupSyntaxName minusName ; ge <- liftCpsFV $ lookupSyntaxName geName ; return (NPlusKPat (L (nameSrcSpan new_name) new_name) lit' ge minus) } -- The Report says that n+k patterns must be in Integral rnPatAndThen mk (AsPat rdr pat) = do { new_name <- newPatName mk rdr ; pat' <- rnLPatAndThen mk pat ; return (AsPat (L (nameSrcSpan new_name) new_name) pat') } rnPatAndThen mk p@(ViewPat expr pat ty) = do { liftCps $ do { vp_flag <- xoptM Opt_ViewPatterns ; 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 -- 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) } 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) } rnPatAndThen _ (SplicePat splice) = do { -- XXX How to deal with free variables? ; (pat, _) <- liftCps $ rnSplicePat splice ; return pat } rnPatAndThen mk (QuasiQuotePat qq) = do { pat <- liftCps $ runQuasiQuotePat qq -- 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) } rnPatAndThen _ pat = pprPanic "rnLPatAndThen" (ppr pat) -------------------- rnConPatAndThen :: NameMaker -> Located RdrName -- the constructor -> HsConPatDetails RdrName -> CpsRn (Pat Name) rnConPatAndThen mk con (PrefixCon pats) = do { con' <- lookupConCps con ; pats' <- rnLPatsAndThen mk pats ; return (ConPatIn con' (PrefixCon pats')) } rnConPatAndThen mk con (InfixCon pat1 pat2) = do { con' <- lookupConCps con ; pat1' <- rnLPatAndThen mk pat1 ; pat2' <- rnLPatAndThen mk pat2 ; fixity <- liftCps $ lookupFixityRn (unLoc con') ; liftCps $ mkConOpPatRn con' fixity pat1' pat2' } rnConPatAndThen mk con (RecCon rpats) = do { con' <- lookupConCps con ; rpats' <- rnHsRecPatsAndThen mk con' rpats ; return (ConPatIn con' (RecCon rpats')) } -------------------- rnHsRecPatsAndThen :: NameMaker -> Located Name -- Constructor -> HsRecFields RdrName (LPat RdrName) -> CpsRn (HsRecFields Name (LPat Name)) 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' }) } -- Suppress unused-match reporting for fields introduced by ".." 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} %************************************************************************ %* * Record fields %* * %************************************************************************ \begin{code} data HsRecFieldContext = HsRecFieldCon Name | HsRecFieldPat Name | HsRecFieldUpd rnHsRecFields1 :: forall arg. HsRecFieldContext -> (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 }) = do { pun_ok <- xoptM Opt_RecordPuns ; disambig_ok <- xoptM Opt_DisambiguateRecordFields ; parent <- check_disambiguation disambig_ok mb_con ; flds1 <- mapM (rn_fld pun_ok parent) flds ; mapM_ (addErr . dupFieldErr ctxt) dup_flds ; 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)) } where mb_con = case ctxt of 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. 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 , hsRecFieldArg = arg , hsRecPun = pun }) = do { fld'@(L loc fld_nm) <- wrapLocM (lookupSubBndrOcc True parent doc) fld ; arg' <- if pun then do { checkErr pun_ok (badPun fld) ; return (L loc (mk_arg (mkRdrUnqual (nameOccName fld_nm)))) } else return arg ; return (HsRecField { hsRecFieldId = fld' , hsRecFieldArg = arg' , hsRecPun = pun }) } 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 rn_dotdot Nothing _mb_con _flds -- No ".." at all = return [] rn_dotdot (Just {}) Nothing _flds -- ".." on record update = do { addErr (badDotDot ctxt); return [] } rn_dotdot (Just n) (Just con) flds -- ".." on record construction / pat match = ASSERT( n == length flds ) do { loc <- getSrcSpanM -- Rather approximate ; dd_flag <- xoptM Opt_RecordWildCards ; checkErr dd_flag (needFlagDotDot ctxt) ; (rdr_env, lcl_env) <- getRdrEnvs ; con_fields <- lookupConstructorFields con ; let present_flds = getFieldIds flds parent_tc = find_tycon rdr_env con -- For constructor uses (but not patterns) -- the arg should be in scope (unqualified) -- ignoring the record field itself -- Eg. data R = R { x,y :: Int } -- f x = R { .. } -- Should expand to R {x=x}, not R{x=x,y=y} arg_in_scope fld = 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) dot_dot_gres = [ head gres | fld <- con_fields , not (fld `elem` present_flds) , let gres = lookupGRE_Name rdr_env fld , not (null gres) -- Check field is in scope , case ctxt of HsRecFieldCon {} -> arg_in_scope fld _other -> True ] ; addUsedRdrNames (map greRdrName dot_dot_gres) ; return [ HsRecField { hsRecFieldId = L loc fld , hsRecFieldArg = L loc (mk_arg arg_rdr) , hsRecPun = False } | gre <- dot_dot_gres , let fld = gre_name gre arg_rdr = mkRdrUnqual (nameOccName fld) ] } check_disambiguation :: Bool -> Maybe Name -> RnM Parent -- When disambiguation is on, check_disambiguation disambig_ok mb_con | disambig_ok, Just con <- mb_con = do { env <- getGlobalRdrEnv; return (ParentIs (find_tycon env con)) } | otherwise = return NoParent 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 | Just (AConLike (RealDataCon dc)) <- wiredInNameTyThing_maybe con = 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)) 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, ptext (sLit "Use RecordWildCards to permit this")] badDotDot :: HsRecFieldContext -> SDoc badDotDot ctxt = ptext (sLit "You cannot use `..' in a record") <+> pprRFC ctxt badPun :: Located RdrName -> SDoc badPun fld = vcat [ptext (sLit "Illegal use of punning for field") <+> quotes (ppr fld), ptext (sLit "Use NamedFieldPuns to permit this")] dupFieldErr :: HsRecFieldContext -> [RdrName] -> SDoc dupFieldErr ctxt dups = hsep [ptext (sLit "duplicate field name"), quotes (ppr (head dups)), ptext (sLit "in record"), pprRFC ctxt] pprRFC :: HsRecFieldContext -> SDoc pprRFC (HsRecFieldCon {}) = ptext (sLit "construction") pprRFC (HsRecFieldPat {}) = ptext (sLit "pattern") pprRFC (HsRecFieldUpd {}) = ptext (sLit "update") \end{code} %************************************************************************ %* * \subsubsection{Literals} %* * %************************************************************************ 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) rnLit _ = return () -- 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 rnOverLit :: HsOverLit t -> RnM (HsOverLit Name, FreeVars) 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 ; (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) } \end{code} %************************************************************************ %* * \subsubsection{Errors} %* * %************************************************************************ \begin{code} patSigErr :: Outputable a => a -> SDoc patSigErr ty = (ptext (sLit "Illegal signature in pattern:") <+> ppr ty) $$ nest 4 (ptext (sLit "Use ScopedTypeVariables to permit it")) bogusCharError :: Char -> SDoc bogusCharError c = ptext (sLit "character literal out of range: '\\") <> char c <> char '\'' badViewPat :: Pat RdrName -> SDoc badViewPat pat = vcat [ptext (sLit "Illegal view pattern: ") <+> ppr pat, ptext (sLit "Use ViewPatterns to enable view patterns")] \end{code} diff --git a/testsuite/tests/patsyn/should_fail/all.T b/testsuite/tests/patsyn/should_fail/all.T index e1708d2..0a07aed 100644 --- a/testsuite/tests/patsyn/should_fail/all.T +++ b/testsuite/tests/patsyn/should_fail/all.T @@ -1,3 +1,4 @@ test('mono', normal, compile_fail, ['']) test('unidir', normal, compile_fail, ['']) +test('local', normal, compile_fail, [''])