PageRenderTime 34ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 0ms

/compiler/rename/RnEnv.lhs

https://bitbucket.org/khibino/ghc-hack
Haskell | 1488 lines | 1027 code | 196 blank | 265 comment | 54 complexity | 74fb4b939654924c6681caae24ef2185 MD5 | raw file
Possible License(s): BSD-3-Clause, BSD-2-Clause, LGPL-3.0
  1. %
  2. % (c) The GRASP/AQUA Project, Glasgow University, 1992-2006
  3. %
  4. \section[RnEnv]{Environment manipulation for the renamer monad}
  5. \begin{code}
  6. {-# OPTIONS -fno-warn-tabs #-}
  7. -- The above warning supression flag is a temporary kludge.
  8. -- While working on this module you are encouraged to remove it and
  9. -- detab the module (please do the detabbing in a separate patch). See
  10. -- http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#TabsvsSpaces
  11. -- for details
  12. module RnEnv (
  13. newTopSrcBinder,
  14. lookupLocatedTopBndrRn, lookupTopBndrRn,
  15. lookupLocatedOccRn, lookupOccRn, lookupLocalOccRn_maybe, lookupPromotedOccRn,
  16. lookupGlobalOccRn, lookupGlobalOccRn_maybe,
  17. HsSigCtxt(..), lookupLocalDataTcNames, lookupSigOccRn,
  18. lookupFixityRn, lookupTyFixityRn,
  19. lookupInstDeclBndr, lookupSubBndrOcc, greRdrName,
  20. lookupSubBndrGREs, lookupConstructorFields,
  21. lookupSyntaxName, lookupSyntaxTable, lookupIfThenElse,
  22. lookupGreRn, lookupGreLocalRn, lookupGreRn_maybe,
  23. getLookupOccRn, addUsedRdrNames,
  24. newLocalBndrRn, newLocalBndrsRn,
  25. bindLocalName, bindLocalNames, bindLocalNamesFV,
  26. MiniFixityEnv, emptyFsEnv, extendFsEnv, lookupFsEnv,
  27. addLocalFixities,
  28. bindLocatedLocalsFV, bindLocatedLocalsRn,
  29. bindSigTyVarsFV, bindPatSigTyVars, bindPatSigTyVarsFV,
  30. extendTyVarEnvFVRn,
  31. checkDupRdrNames, checkDupAndShadowedRdrNames,
  32. checkDupNames, checkDupAndShadowedNames,
  33. addFvRn, mapFvRn, mapMaybeFvRn, mapFvRnCPS,
  34. warnUnusedMatches,
  35. warnUnusedTopBinds, warnUnusedLocalBinds,
  36. dataTcOccs, unknownNameErr, kindSigErr, dataKindsErr, perhapsForallMsg,
  37. HsDocContext(..), docOfHsDocContext
  38. ) where
  39. #include "HsVersions.h"
  40. import LoadIface ( loadInterfaceForName, loadSrcInterface )
  41. import IfaceEnv
  42. import HsSyn
  43. import RdrHsSyn ( extractHsTyRdrTyVars )
  44. import RdrName
  45. import HscTypes
  46. import TcEnv ( tcLookupDataCon, tcLookupField, isBrackStage )
  47. import TcRnMonad
  48. import Id ( isRecordSelector )
  49. import Name
  50. import NameSet
  51. import NameEnv
  52. import Avail
  53. import Module ( ModuleName, moduleName )
  54. import UniqFM
  55. import DataCon ( dataConFieldLabels )
  56. import PrelNames ( mkUnboundName, rOOT_MAIN, forall_tv_RDR )
  57. import ErrUtils ( Message )
  58. import SrcLoc
  59. import Outputable
  60. import Util
  61. import Maybes
  62. import ListSetOps ( removeDups )
  63. import DynFlags
  64. import FastString
  65. import Control.Monad
  66. import Data.List
  67. import qualified Data.Set as Set
  68. \end{code}
  69. \begin{code}
  70. -- XXX
  71. thenM :: Monad a => a b -> (b -> a c) -> a c
  72. thenM = (>>=)
  73. \end{code}
  74. %*********************************************************
  75. %* *
  76. Source-code binders
  77. %* *
  78. %*********************************************************
  79. \begin{code}
  80. newTopSrcBinder :: Located RdrName -> RnM Name
  81. newTopSrcBinder (L loc rdr_name)
  82. | Just name <- isExact_maybe rdr_name
  83. = -- This is here to catch
  84. -- (a) Exact-name binders created by Template Haskell
  85. -- (b) The PrelBase defn of (say) [] and similar, for which
  86. -- the parser reads the special syntax and returns an Exact RdrName
  87. -- We are at a binding site for the name, so check first that it
  88. -- the current module is the correct one; otherwise GHC can get
  89. -- very confused indeed. This test rejects code like
  90. -- data T = (,) Int Int
  91. -- unless we are in GHC.Tup
  92. if isExternalName name then
  93. do { this_mod <- getModule
  94. ; unless (this_mod == nameModule name)
  95. (addErrAt loc (badOrigBinding rdr_name))
  96. ; return name }
  97. else -- See Note [Binders in Template Haskell] in Convert.hs
  98. do { let occ = nameOccName name
  99. ; occ `seq` return () -- c.f. seq in newGlobalBinder
  100. ; this_mod <- getModule
  101. ; updNameCache $ \ ns ->
  102. let name' = mkExternalName (nameUnique name) this_mod occ loc
  103. ns' = ns { nsNames = extendNameCache (nsNames ns) this_mod occ name' }
  104. in (ns', name') }
  105. | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name
  106. = do { this_mod <- getModule
  107. ; unless (rdr_mod == this_mod || rdr_mod == rOOT_MAIN)
  108. (addErrAt loc (badOrigBinding rdr_name))
  109. -- When reading External Core we get Orig names as binders,
  110. -- but they should agree with the module gotten from the monad
  111. --
  112. -- We can get built-in syntax showing up here too, sadly. If you type
  113. -- data T = (,,,)
  114. -- the constructor is parsed as a type, and then RdrHsSyn.tyConToDataCon
  115. -- uses setRdrNameSpace to make it into a data constructors. At that point
  116. -- the nice Exact name for the TyCon gets swizzled to an Orig name.
  117. -- Hence the badOrigBinding error message.
  118. --
  119. -- Except for the ":Main.main = ..." definition inserted into
  120. -- the Main module; ugh!
  121. -- Because of this latter case, we call newGlobalBinder with a module from
  122. -- the RdrName, not from the environment. In principle, it'd be fine to
  123. -- have an arbitrary mixture of external core definitions in a single module,
  124. -- (apart from module-initialisation issues, perhaps).
  125. ; newGlobalBinder rdr_mod rdr_occ loc }
  126. --TODO, should pass the whole span
  127. | otherwise
  128. = do { unless (not (isQual rdr_name))
  129. (addErrAt loc (badQualBndrErr rdr_name))
  130. -- Binders should not be qualified; if they are, and with a different
  131. -- module name, we we get a confusing "M.T is not in scope" error later
  132. ; stage <- getStage
  133. ; if isBrackStage stage then
  134. -- We are inside a TH bracket, so make an *Internal* name
  135. -- See Note [Top-level Names in Template Haskell decl quotes] in RnNames
  136. do { uniq <- newUnique
  137. ; return (mkInternalName uniq (rdrNameOcc rdr_name) loc) }
  138. else
  139. -- Normal case
  140. do { this_mod <- getModule
  141. ; newGlobalBinder this_mod (rdrNameOcc rdr_name) loc } }
  142. \end{code}
  143. %*********************************************************
  144. %* *
  145. Source code occurrences
  146. %* *
  147. %*********************************************************
  148. Looking up a name in the RnEnv.
  149. Note [Type and class operator definitions]
  150. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  151. We want to reject all of these unless we have -XTypeOperators (Trac #3265)
  152. data a :*: b = ...
  153. class a :*: b where ...
  154. data (:*:) a b = ....
  155. class (:*:) a b where ...
  156. The latter two mean that we are not just looking for a
  157. *syntactically-infix* declaration, but one that uses an operator
  158. OccName. We use OccName.isSymOcc to detect that case, which isn't
  159. terribly efficient, but there seems to be no better way.
  160. \begin{code}
  161. lookupTopBndrRn :: RdrName -> RnM Name
  162. lookupTopBndrRn n = do nopt <- lookupTopBndrRn_maybe n
  163. case nopt of
  164. Just n' -> return n'
  165. Nothing -> do traceRn $ text "lookupTopBndrRn"
  166. unboundName WL_LocalTop n
  167. lookupLocatedTopBndrRn :: Located RdrName -> RnM (Located Name)
  168. lookupLocatedTopBndrRn = wrapLocM lookupTopBndrRn
  169. lookupTopBndrRn_maybe :: RdrName -> RnM (Maybe Name)
  170. -- Look up a top-level source-code binder. We may be looking up an unqualified 'f',
  171. -- and there may be several imported 'f's too, which must not confuse us.
  172. -- For example, this is OK:
  173. -- import Foo( f )
  174. -- infix 9 f -- The 'f' here does not need to be qualified
  175. -- f x = x -- Nor here, of course
  176. -- So we have to filter out the non-local ones.
  177. --
  178. -- A separate function (importsFromLocalDecls) reports duplicate top level
  179. -- decls, so here it's safe just to choose an arbitrary one.
  180. --
  181. -- There should never be a qualified name in a binding position in Haskell,
  182. -- but there can be if we have read in an external-Core file.
  183. -- The Haskell parser checks for the illegal qualified name in Haskell
  184. -- source files, so we don't need to do so here.
  185. lookupTopBndrRn_maybe rdr_name
  186. | Just name <- isExact_maybe rdr_name
  187. = do { name' <- lookupExactOcc name; return (Just name') }
  188. | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name
  189. -- This deals with the case of derived bindings, where
  190. -- we don't bother to call newTopSrcBinder first
  191. -- We assume there is no "parent" name
  192. = do { loc <- getSrcSpanM
  193. ; n <- newGlobalBinder rdr_mod rdr_occ loc
  194. ; return (Just n)}
  195. | otherwise
  196. = do { -- Check for operators in type or class declarations
  197. -- See Note [Type and class operator definitions]
  198. let occ = rdrNameOcc rdr_name
  199. ; when (isTcOcc occ && isSymOcc occ)
  200. (do { op_ok <- xoptM Opt_TypeOperators
  201. ; unless op_ok (addErr (opDeclErr rdr_name)) })
  202. ; mb_gre <- lookupGreLocalRn rdr_name
  203. ; case mb_gre of
  204. Nothing -> return Nothing
  205. Just gre -> return (Just $ gre_name gre) }
  206. -----------------------------------------------
  207. lookupExactOcc :: Name -> RnM Name
  208. -- See Note [Looking up Exact RdrNames]
  209. lookupExactOcc name
  210. | isExternalName name
  211. = return name
  212. | otherwise
  213. = do { env <- getGlobalRdrEnv
  214. ; let gres = lookupGRE_Name env name
  215. ; case gres of
  216. [] -> return name
  217. [gre] -> return (gre_name gre)
  218. _ -> pprPanic "lookupExactOcc" (ppr name $$ ppr gres) }
  219. -----------------------------------------------
  220. lookupInstDeclBndr :: Name -> SDoc -> RdrName -> RnM Name
  221. -- This is called on the method name on the left-hand side of an
  222. -- instance declaration binding. eg. instance Functor T where
  223. -- fmap = ...
  224. -- ^^^^ called on this
  225. -- Regardless of how many unqualified fmaps are in scope, we want
  226. -- the one that comes from the Functor class.
  227. --
  228. -- Furthermore, note that we take no account of whether the
  229. -- name is only in scope qualified. I.e. even if method op is
  230. -- in scope as M.op, we still allow plain 'op' on the LHS of
  231. -- an instance decl
  232. --
  233. -- The "what" parameter says "method" or "associated type",
  234. -- depending on what we are looking up
  235. lookupInstDeclBndr cls what rdr
  236. = do { when (isQual rdr)
  237. (addErr (badQualBndrErr rdr))
  238. -- In an instance decl you aren't allowed
  239. -- to use a qualified name for the method
  240. -- (Although it'd make perfect sense.)
  241. ; lookupSubBndrOcc (ParentIs cls) doc rdr }
  242. where
  243. doc = what <+> ptext (sLit "of class") <+> quotes (ppr cls)
  244. -----------------------------------------------
  245. lookupConstructorFields :: Name -> RnM [Name]
  246. -- Look up the fields of a given constructor
  247. -- * For constructors from this module, use the record field env,
  248. -- which is itself gathered from the (as yet un-typechecked)
  249. -- data type decls
  250. --
  251. -- * For constructors from imported modules, use the *type* environment
  252. -- since imported modles are already compiled, the info is conveniently
  253. -- right there
  254. lookupConstructorFields con_name
  255. = do { this_mod <- getModule
  256. ; if nameIsLocalOrFrom this_mod con_name then
  257. do { RecFields field_env _ <- getRecFieldEnv
  258. ; return (lookupNameEnv field_env con_name `orElse` []) }
  259. else
  260. do { con <- tcLookupDataCon con_name
  261. ; return (dataConFieldLabels con) } }
  262. -----------------------------------------------
  263. -- Used for record construction and pattern matching
  264. -- When the -XDisambiguateRecordFields flag is on, take account of the
  265. -- constructor name to disambiguate which field to use; it's just the
  266. -- same as for instance decls
  267. --
  268. -- NB: Consider this:
  269. -- module Foo where { data R = R { fld :: Int } }
  270. -- module Odd where { import Foo; fld x = x { fld = 3 } }
  271. -- Arguably this should work, because the reference to 'fld' is
  272. -- unambiguous because there is only one field id 'fld' in scope.
  273. -- But currently it's rejected.
  274. lookupSubBndrOcc :: Parent -- NoParent => just look it up as usual
  275. -- ParentIs p => use p to disambiguate
  276. -> SDoc -> RdrName
  277. -> RnM Name
  278. lookupSubBndrOcc parent doc rdr_name
  279. | Just n <- isExact_maybe rdr_name -- This happens in derived code
  280. = lookupExactOcc n
  281. | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name
  282. = lookupOrig rdr_mod rdr_occ
  283. | otherwise -- Find all the things the rdr-name maps to
  284. = do { -- and pick the one with the right parent namep
  285. env <- getGlobalRdrEnv
  286. ; case lookupSubBndrGREs env parent rdr_name of
  287. -- NB: lookupGlobalRdrEnv, not lookupGRE_RdrName!
  288. -- The latter does pickGREs, but we want to allow 'x'
  289. -- even if only 'M.x' is in scope
  290. [gre] -> do { addUsedRdrName gre (used_rdr_name gre)
  291. -- Add a usage; this is an *occurrence* site
  292. ; return (gre_name gre) }
  293. [] -> do { addErr (unknownSubordinateErr doc rdr_name)
  294. ; return (mkUnboundName rdr_name) }
  295. gres -> do { addNameClashErrRn rdr_name gres
  296. ; return (gre_name (head gres)) } }
  297. where
  298. -- Note [Usage for sub-bndrs]
  299. used_rdr_name gre
  300. | isQual rdr_name = rdr_name
  301. | otherwise = greRdrName gre
  302. greRdrName :: GlobalRdrElt -> RdrName
  303. greRdrName gre
  304. = case gre_prov gre of
  305. LocalDef -> unqual_rdr
  306. Imported is -> used_rdr_name_from_is is
  307. where
  308. occ = nameOccName (gre_name gre)
  309. unqual_rdr = mkRdrUnqual occ
  310. used_rdr_name_from_is imp_specs -- rdr_name is unqualified
  311. | not (all (is_qual . is_decl) imp_specs)
  312. = unqual_rdr -- An unqualified import is available
  313. | otherwise
  314. = -- Only qualified imports available, so make up
  315. -- a suitable qualifed name from the first imp_spec
  316. ASSERT( not (null imp_specs) )
  317. mkRdrQual (is_as (is_decl (head imp_specs))) occ
  318. lookupSubBndrGREs :: GlobalRdrEnv -> Parent -> RdrName -> [GlobalRdrElt]
  319. -- If Parent = NoParent, just do a normal lookup
  320. -- If Parent = Parent p then find all GREs that
  321. -- (a) have parent p
  322. -- (b) for Unqual, are in scope qualified or unqualified
  323. -- for Qual, are in scope with that qualification
  324. lookupSubBndrGREs env parent rdr_name
  325. = case parent of
  326. NoParent -> pickGREs rdr_name gres
  327. ParentIs p
  328. | isUnqual rdr_name -> filter (parent_is p) gres
  329. | otherwise -> filter (parent_is p) (pickGREs rdr_name gres)
  330. where
  331. gres = lookupGlobalRdrEnv env (rdrNameOcc rdr_name)
  332. parent_is p (GRE { gre_par = ParentIs p' }) = p == p'
  333. parent_is _ _ = False
  334. \end{code}
  335. Note [Looking up Exact RdrNames]
  336. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  337. Exact RdrNames are generated by Template Haskell. See Note [Binders
  338. in Template Haskell] in Convert.
  339. For data types and classes have Exact system Names in the binding
  340. positions for constructors, TyCons etc. For example
  341. [d| data T = MkT Int |]
  342. when we splice in and Convert to HsSyn RdrName, we'll get
  343. data (Exact (system Name "T")) = (Exact (system Name "MkT")) ...
  344. But, constructors and the like need External Names, not System Names!
  345. So we do the following
  346. * In RnEnv.newGlobalBinder we spot Exact RdrNames that wrap a
  347. non-External Name, and make an External name for it. This is
  348. the name that goes in the GlobalRdrEnv
  349. * When looking up an occurrence of an Exact name, done in
  350. RnEnv.lookupExactOcc, we find the Name with the right unique in the
  351. GlobalRdrEnv, and use the on from the envt -- it will be an
  352. External Name in the case of the data type/constructor above.
  353. * Exact names are also use for purely local binders generated
  354. by TH, such as \x_33. x_33
  355. Both binder and occurrence are Exact RdrNames. The occurrence
  356. gets looked up in the LocalRdrEnv by RnEnv.lookupOccRn, and
  357. misses, because lookupLocalRdrEnv always returns Nothing for
  358. an Exact Name. Now we fall through to lookupExactOcc, which
  359. will find the Name is not in the GlobalRdrEnv, so we just use
  360. the Exact supplied Name.
  361. Note [Usage for sub-bndrs]
  362. ~~~~~~~~~~~~~~~~~~~~~~~~~~
  363. If you have this
  364. import qualified M( C( f ) )
  365. instance M.C T where
  366. f x = x
  367. then is the qualified import M.f used? Obviously yes.
  368. But the RdrName used in the instance decl is unqualified. In effect,
  369. we fill in the qualification by looking for f's whose class is M.C
  370. But when adding to the UsedRdrNames we must make that qualification
  371. explicit (saying "used M.f"), otherwise we get "Redundant import of M.f".
  372. So we make up a suitable (fake) RdrName. But be careful
  373. import qualifed M
  374. import M( C(f) )
  375. instance C T where
  376. f x = x
  377. Here we want to record a use of 'f', not of 'M.f', otherwise
  378. we'll miss the fact that the qualified import is redundant.
  379. --------------------------------------------------
  380. -- Occurrences
  381. --------------------------------------------------
  382. \begin{code}
  383. getLookupOccRn :: RnM (Name -> Maybe Name)
  384. getLookupOccRn
  385. = getLocalRdrEnv `thenM` \ local_env ->
  386. return (lookupLocalRdrOcc local_env . nameOccName)
  387. lookupLocatedOccRn :: Located RdrName -> RnM (Located Name)
  388. lookupLocatedOccRn = wrapLocM lookupOccRn
  389. lookupLocalOccRn_maybe :: RdrName -> RnM (Maybe Name)
  390. -- Just look in the local environment
  391. lookupLocalOccRn_maybe rdr_name
  392. = do { local_env <- getLocalRdrEnv
  393. ; return (lookupLocalRdrEnv local_env rdr_name) }
  394. -- lookupOccRn looks up an occurrence of a RdrName
  395. lookupOccRn :: RdrName -> RnM Name
  396. lookupOccRn rdr_name = do
  397. opt_name <- lookupOccRn_maybe rdr_name
  398. maybe (unboundName WL_Any rdr_name) return opt_name
  399. -- lookupPromotedOccRn looks up an optionally promoted RdrName.
  400. lookupPromotedOccRn :: RdrName -> RnM Name
  401. -- see Note [Demotion] in OccName
  402. lookupPromotedOccRn rdr_name = do {
  403. -- 1. lookup the name
  404. opt_name <- lookupOccRn_maybe rdr_name
  405. ; case opt_name of
  406. -- 1.a. we found it!
  407. Just name -> return name
  408. -- 1.b. we did not find it -> 2
  409. Nothing -> do {
  410. ; -- 2. maybe it was implicitly promoted
  411. case demoteRdrName rdr_name of
  412. -- 2.a it was not in a promoted namespace
  413. Nothing -> err
  414. -- 2.b let's try every thing again -> 3
  415. Just demoted_rdr_name -> do {
  416. ; data_kinds <- xoptM Opt_DataKinds
  417. -- 3. lookup again
  418. ; opt_demoted_name <- lookupOccRn_maybe demoted_rdr_name ;
  419. ; case opt_demoted_name of
  420. -- 3.a. it was implicitly promoted, but confirm that we can promote
  421. -- JPM: We could try to suggest turning on DataKinds here
  422. Just demoted_name -> if data_kinds then return demoted_name else err
  423. -- 3.b. use rdr_name to have a correct error message
  424. Nothing -> err } } }
  425. where err = unboundName WL_Any rdr_name
  426. -- lookupOccRn looks up an occurrence of a RdrName
  427. lookupOccRn_maybe :: RdrName -> RnM (Maybe Name)
  428. lookupOccRn_maybe rdr_name
  429. = do { local_env <- getLocalRdrEnv
  430. ; case lookupLocalRdrEnv local_env rdr_name of {
  431. Just name -> return (Just name) ;
  432. Nothing -> do
  433. { mb_name <- lookupGlobalOccRn_maybe rdr_name
  434. ; case mb_name of {
  435. Just name -> return (Just name) ;
  436. Nothing -> do
  437. { -- We allow qualified names on the command line to refer to
  438. -- *any* name exported by any module in scope, just as if there
  439. -- was an "import qualified M" declaration for every module.
  440. allow_qual <- doptM Opt_ImplicitImportQualified
  441. ; is_ghci <- getIsGHCi
  442. -- This test is not expensive,
  443. -- and only happens for failed lookups
  444. ; if isQual rdr_name && allow_qual && is_ghci
  445. then lookupQualifiedName rdr_name
  446. else do { traceRn (text "lookupOccRn" <+> ppr rdr_name)
  447. ; return Nothing } } } } } }
  448. lookupGlobalOccRn :: RdrName -> RnM Name
  449. -- lookupGlobalOccRn is like lookupOccRn, except that it looks in the global
  450. -- environment. Adds an error message if the RdrName is not in scope.
  451. lookupGlobalOccRn rdr_name
  452. = do { mb_name <- lookupGlobalOccRn_maybe rdr_name
  453. ; case mb_name of
  454. Just n -> return n
  455. Nothing -> do { traceRn (text "lookupGlobalOccRn" <+> ppr rdr_name)
  456. ; unboundName WL_Global rdr_name } }
  457. lookupGlobalOccRn_maybe :: RdrName -> RnM (Maybe Name)
  458. -- No filter function; does not report an error on failure
  459. lookupGlobalOccRn_maybe rdr_name
  460. | Just n <- isExact_maybe rdr_name -- This happens in derived code
  461. = do { n' <- lookupExactOcc n; return (Just n') }
  462. | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name
  463. = do { n <- lookupOrig rdr_mod rdr_occ
  464. ; return (Just n) }
  465. | otherwise
  466. = do { mb_gre <- lookupGreRn_maybe rdr_name
  467. ; case mb_gre of
  468. Nothing -> return Nothing
  469. Just gre -> return (Just (gre_name gre)) }
  470. --------------------------------------------------
  471. -- Lookup in the Global RdrEnv of the module
  472. --------------------------------------------------
  473. lookupGreRn_maybe :: RdrName -> RnM (Maybe GlobalRdrElt)
  474. -- Just look up the RdrName in the GlobalRdrEnv
  475. lookupGreRn_maybe rdr_name
  476. = lookupGreRn_help rdr_name (lookupGRE_RdrName rdr_name)
  477. lookupGreRn :: RdrName -> RnM GlobalRdrElt
  478. -- If not found, add error message, and return a fake GRE
  479. lookupGreRn rdr_name
  480. = do { mb_gre <- lookupGreRn_maybe rdr_name
  481. ; case mb_gre of {
  482. Just gre -> return gre ;
  483. Nothing -> do
  484. { traceRn (text "lookupGreRn" <+> ppr rdr_name)
  485. ; name <- unboundName WL_Global rdr_name
  486. ; return (GRE { gre_name = name, gre_par = NoParent,
  487. gre_prov = LocalDef }) }}}
  488. lookupGreLocalRn :: RdrName -> RnM (Maybe GlobalRdrElt)
  489. -- Similar, but restricted to locally-defined things
  490. lookupGreLocalRn rdr_name
  491. = lookupGreRn_help rdr_name lookup_fn
  492. where
  493. lookup_fn env = filter isLocalGRE (lookupGRE_RdrName rdr_name env)
  494. lookupGreRn_help :: RdrName -- Only used in error message
  495. -> (GlobalRdrEnv -> [GlobalRdrElt]) -- Lookup function
  496. -> RnM (Maybe GlobalRdrElt)
  497. -- Checks for exactly one match; reports deprecations
  498. -- Returns Nothing, without error, if too few
  499. lookupGreRn_help rdr_name lookup
  500. = do { env <- getGlobalRdrEnv
  501. ; case lookup env of
  502. [] -> return Nothing
  503. [gre] -> do { addUsedRdrName gre rdr_name
  504. ; return (Just gre) }
  505. gres -> do { addNameClashErrRn rdr_name gres
  506. ; return (Just (head gres)) } }
  507. addUsedRdrName :: GlobalRdrElt -> RdrName -> RnM ()
  508. -- Record usage of imported RdrNames
  509. addUsedRdrName gre rdr
  510. | isLocalGRE gre = return ()
  511. | otherwise = do { env <- getGblEnv
  512. ; updMutVar (tcg_used_rdrnames env)
  513. (\s -> Set.insert rdr s) }
  514. addUsedRdrNames :: [RdrName] -> RnM ()
  515. -- Record used sub-binders
  516. -- We don't check for imported-ness here, because it's inconvenient
  517. -- and not stritly necessary.
  518. addUsedRdrNames rdrs
  519. = do { env <- getGblEnv
  520. ; updMutVar (tcg_used_rdrnames env)
  521. (\s -> foldr Set.insert s rdrs) }
  522. ------------------------------
  523. -- GHCi support
  524. ------------------------------
  525. -- A qualified name on the command line can refer to any module at all: we
  526. -- try to load the interface if we don't already have it.
  527. lookupQualifiedName :: RdrName -> RnM (Maybe Name)
  528. lookupQualifiedName rdr_name
  529. | Just (mod,occ) <- isQual_maybe rdr_name
  530. -- Note: we want to behave as we would for a source file import here,
  531. -- and respect hiddenness of modules/packages, hence loadSrcInterface.
  532. = loadSrcInterface doc mod False Nothing `thenM` \ iface ->
  533. case [ name
  534. | avail <- mi_exports iface,
  535. name <- availNames avail,
  536. nameOccName name == occ ] of
  537. (n:ns) -> ASSERT (null ns) return (Just n)
  538. _ -> do { traceRn (text "lookupQualified" <+> ppr rdr_name)
  539. ; return Nothing }
  540. | otherwise
  541. = pprPanic "RnEnv.lookupQualifiedName" (ppr rdr_name)
  542. where
  543. doc = ptext (sLit "Need to find") <+> ppr rdr_name
  544. \end{code}
  545. Note [Looking up signature names]
  546. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  547. lookupSigOccRn is used for type signatures and pragmas
  548. Is this valid?
  549. module A
  550. import M( f )
  551. f :: Int -> Int
  552. f x = x
  553. It's clear that the 'f' in the signature must refer to A.f
  554. The Haskell98 report does not stipulate this, but it will!
  555. So we must treat the 'f' in the signature in the same way
  556. as the binding occurrence of 'f', using lookupBndrRn
  557. However, consider this case:
  558. import M( f )
  559. f :: Int -> Int
  560. g x = x
  561. We don't want to say 'f' is out of scope; instead, we want to
  562. return the imported 'f', so that later on the reanamer will
  563. correctly report "misplaced type sig".
  564. \begin{code}
  565. data HsSigCtxt
  566. = HsBootCtxt -- Top level of a hs-boot file
  567. | TopSigCtxt -- At top level
  568. | LocalBindCtxt NameSet -- In a local binding, binding these names
  569. | ClsDeclCtxt Name -- Class decl for this class
  570. | InstDeclCtxt Name -- Intsance decl for this class
  571. lookupSigOccRn :: HsSigCtxt
  572. -> Sig RdrName
  573. -> Located RdrName -> RnM (Located Name)
  574. lookupSigOccRn ctxt sig
  575. = wrapLocM $ \ rdr_name ->
  576. do { mb_name <- lookupBindGroupOcc ctxt (hsSigDoc sig) rdr_name
  577. ; case mb_name of
  578. Left err -> do { addErr err; return (mkUnboundName rdr_name) }
  579. Right name -> return name }
  580. lookupBindGroupOcc :: HsSigCtxt
  581. -> SDoc
  582. -> RdrName -> RnM (Either Message Name)
  583. -- Looks up the RdrName, expecting it to resolve to one of the
  584. -- bound names passed in. If not, return an appropriate error message
  585. --
  586. -- See Note [Looking up signature names]
  587. lookupBindGroupOcc ctxt what rdr_name
  588. | Just n <- isExact_maybe rdr_name
  589. = do { n' <- lookupExactOcc n
  590. ; return (Right n') } -- Maybe we should check the side conditions
  591. -- but it's a pain, and Exact things only show
  592. -- up when you know what you are doing
  593. | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name
  594. = do { n' <- lookupOrig rdr_mod rdr_occ
  595. ; return (Right n') }
  596. | otherwise
  597. = case ctxt of
  598. HsBootCtxt -> lookup_top
  599. TopSigCtxt -> lookup_top
  600. LocalBindCtxt ns -> lookup_group ns
  601. ClsDeclCtxt cls -> lookup_cls_op cls
  602. InstDeclCtxt cls -> lookup_cls_op cls
  603. where
  604. lookup_cls_op cls
  605. = do { env <- getGlobalRdrEnv
  606. ; let gres = lookupSubBndrGREs env (ParentIs cls) rdr_name
  607. ; case gres of
  608. [] -> return (Left (unknownSubordinateErr doc rdr_name))
  609. (gre:_) -> return (Right (gre_name gre)) }
  610. -- If there is more than one local GRE for the
  611. -- same OccName 'f', that will be reported separately
  612. -- as a duplicate top-level binding for 'f'
  613. where
  614. doc = ptext (sLit "method of class") <+> quotes (ppr cls)
  615. lookup_top
  616. = do { env <- getGlobalRdrEnv
  617. ; let gres = lookupGlobalRdrEnv env (rdrNameOcc rdr_name)
  618. ; case filter isLocalGRE gres of
  619. [] | null gres -> bale_out_with empty
  620. | otherwise -> bale_out_with (bad_msg (ptext (sLit "an imported value")))
  621. (gre:_)
  622. | ParentIs {} <- gre_par gre
  623. -> bale_out_with (bad_msg (ptext (sLit "a record selector or class method")))
  624. | otherwise
  625. -> return (Right (gre_name gre)) }
  626. lookup_group bound_names
  627. = do { mb_name <- lookupOccRn_maybe rdr_name
  628. ; case mb_name of
  629. Just n
  630. | n `elemNameSet` bound_names -> return (Right n)
  631. | otherwise -> bale_out_with local_msg
  632. Nothing -> bale_out_with empty }
  633. bale_out_with msg
  634. = return (Left (sep [ ptext (sLit "The") <+> what
  635. <+> ptext (sLit "for") <+> quotes (ppr rdr_name)
  636. , nest 2 $ ptext (sLit "lacks an accompanying binding")]
  637. $$ nest 2 msg))
  638. local_msg = parens $ ptext (sLit "The") <+> what <+> ptext (sLit "must be given where")
  639. <+> quotes (ppr rdr_name) <+> ptext (sLit "is declared")
  640. bad_msg thing = parens $ ptext (sLit "You cannot give a") <+> what
  641. <+> ptext (sLit "for") <+> thing
  642. ---------------
  643. lookupLocalDataTcNames :: NameSet -> SDoc -> RdrName -> RnM [Name]
  644. -- GHC extension: look up both the tycon and data con
  645. -- for con-like things. Used for top-level fixity signatures
  646. -- Complain if neither is in scope
  647. lookupLocalDataTcNames bndr_set what rdr_name
  648. | Just n <- isExact_maybe rdr_name
  649. -- Special case for (:), which doesn't get into the GlobalRdrEnv
  650. = do { n' <- lookupExactOcc n; return [n'] } -- For this we don't need to try the tycon too
  651. | otherwise
  652. = do { mb_gres <- mapM (lookupBindGroupOcc (LocalBindCtxt bndr_set) what)
  653. (dataTcOccs rdr_name)
  654. ; let (errs, names) = splitEithers mb_gres
  655. ; when (null names) (addErr (head errs)) -- Bleat about one only
  656. ; return names }
  657. dataTcOccs :: RdrName -> [RdrName]
  658. -- If the input is a data constructor, return both it and a type
  659. -- constructor. This is useful when we aren't sure which we are
  660. -- looking at.
  661. dataTcOccs rdr_name
  662. | isDataOcc occ = [rdr_name, rdr_name_tc]
  663. | otherwise = [rdr_name]
  664. where
  665. occ = rdrNameOcc rdr_name
  666. rdr_name_tc = setRdrNameSpace rdr_name tcName
  667. \end{code}
  668. %*********************************************************
  669. %* *
  670. Fixities
  671. %* *
  672. %*********************************************************
  673. \begin{code}
  674. --------------------------------
  675. type FastStringEnv a = UniqFM a -- Keyed by FastString
  676. emptyFsEnv :: FastStringEnv a
  677. lookupFsEnv :: FastStringEnv a -> FastString -> Maybe a
  678. extendFsEnv :: FastStringEnv a -> FastString -> a -> FastStringEnv a
  679. emptyFsEnv = emptyUFM
  680. lookupFsEnv = lookupUFM
  681. extendFsEnv = addToUFM
  682. --------------------------------
  683. type MiniFixityEnv = FastStringEnv (Located Fixity)
  684. -- Mini fixity env for the names we're about
  685. -- to bind, in a single binding group
  686. --
  687. -- It is keyed by the *FastString*, not the *OccName*, because
  688. -- the single fixity decl infix 3 T
  689. -- affects both the data constructor T and the type constrctor T
  690. --
  691. -- We keep the location so that if we find
  692. -- a duplicate, we can report it sensibly
  693. --------------------------------
  694. -- Used for nested fixity decls to bind names along with their fixities.
  695. -- the fixities are given as a UFM from an OccName's FastString to a fixity decl
  696. addLocalFixities :: MiniFixityEnv -> [Name] -> RnM a -> RnM a
  697. addLocalFixities mini_fix_env names thing_inside
  698. = extendFixityEnv (mapCatMaybes find_fixity names) thing_inside
  699. where
  700. find_fixity name
  701. = case lookupFsEnv mini_fix_env (occNameFS occ) of
  702. Just (L _ fix) -> Just (name, FixItem occ fix)
  703. Nothing -> Nothing
  704. where
  705. occ = nameOccName name
  706. \end{code}
  707. --------------------------------
  708. lookupFixity is a bit strange.
  709. * Nested local fixity decls are put in the local fixity env, which we
  710. find with getFixtyEnv
  711. * Imported fixities are found in the HIT or PIT
  712. * Top-level fixity decls in this module may be for Names that are
  713. either Global (constructors, class operations)
  714. or Local/Exported (everything else)
  715. (See notes with RnNames.getLocalDeclBinders for why we have this split.)
  716. We put them all in the local fixity environment
  717. \begin{code}
  718. lookupFixityRn :: Name -> RnM Fixity
  719. lookupFixityRn name
  720. = getModule `thenM` \ this_mod ->
  721. if nameIsLocalOrFrom this_mod name
  722. then do -- It's defined in this module
  723. local_fix_env <- getFixityEnv
  724. traceRn (text "lookupFixityRn: looking up name in local environment:" <+>
  725. vcat [ppr name, ppr local_fix_env])
  726. return $ lookupFixity local_fix_env name
  727. else -- It's imported
  728. -- For imported names, we have to get their fixities by doing a
  729. -- loadInterfaceForName, and consulting the Ifaces that comes back
  730. -- from that, because the interface file for the Name might not
  731. -- have been loaded yet. Why not? Suppose you import module A,
  732. -- which exports a function 'f', thus;
  733. -- module CurrentModule where
  734. -- import A( f )
  735. -- module A( f ) where
  736. -- import B( f )
  737. -- Then B isn't loaded right away (after all, it's possible that
  738. -- nothing from B will be used). When we come across a use of
  739. -- 'f', we need to know its fixity, and it's then, and only
  740. -- then, that we load B.hi. That is what's happening here.
  741. --
  742. -- loadInterfaceForName will find B.hi even if B is a hidden module,
  743. -- and that's what we want.
  744. loadInterfaceForName doc name `thenM` \ iface -> do {
  745. traceRn (text "lookupFixityRn: looking up name in iface cache and found:" <+>
  746. vcat [ppr name, ppr $ mi_fix_fn iface (nameOccName name)]);
  747. return (mi_fix_fn iface (nameOccName name))
  748. }
  749. where
  750. doc = ptext (sLit "Checking fixity for") <+> ppr name
  751. ---------------
  752. lookupTyFixityRn :: Located Name -> RnM Fixity
  753. lookupTyFixityRn (L _ n) = lookupFixityRn n
  754. \end{code}
  755. %************************************************************************
  756. %* *
  757. Rebindable names
  758. Dealing with rebindable syntax is driven by the
  759. Opt_RebindableSyntax dynamic flag.
  760. In "deriving" code we don't want to use rebindable syntax
  761. so we switch off the flag locally
  762. %* *
  763. %************************************************************************
  764. Haskell 98 says that when you say "3" you get the "fromInteger" from the
  765. Standard Prelude, regardless of what is in scope. However, to experiment
  766. with having a language that is less coupled to the standard prelude, we're
  767. trying a non-standard extension that instead gives you whatever "Prelude.fromInteger"
  768. happens to be in scope. Then you can
  769. import Prelude ()
  770. import MyPrelude as Prelude
  771. to get the desired effect.
  772. At the moment this just happens for
  773. * fromInteger, fromRational on literals (in expressions and patterns)
  774. * negate (in expressions)
  775. * minus (arising from n+k patterns)
  776. * "do" notation
  777. We store the relevant Name in the HsSyn tree, in
  778. * HsIntegral/HsFractional/HsIsString
  779. * NegApp
  780. * NPlusKPat
  781. * HsDo
  782. respectively. Initially, we just store the "standard" name (PrelNames.fromIntegralName,
  783. fromRationalName etc), but the renamer changes this to the appropriate user
  784. name if Opt_NoImplicitPrelude is on. That is what lookupSyntaxName does.
  785. We treat the orignal (standard) names as free-vars too, because the type checker
  786. checks the type of the user thing against the type of the standard thing.
  787. \begin{code}
  788. lookupIfThenElse :: RnM (Maybe (SyntaxExpr Name), FreeVars)
  789. -- Different to lookupSyntaxName because in the non-rebindable
  790. -- case we desugar directly rather than calling an existing function
  791. -- Hence the (Maybe (SyntaxExpr Name)) return type
  792. lookupIfThenElse
  793. = do { rebind <- xoptM Opt_RebindableSyntax
  794. ; if not rebind
  795. then return (Nothing, emptyFVs)
  796. else do { ite <- lookupOccRn (mkVarUnqual (fsLit "ifThenElse"))
  797. ; return (Just (HsVar ite), unitFV ite) } }
  798. lookupSyntaxName :: Name -- The standard name
  799. -> RnM (SyntaxExpr Name, FreeVars) -- Possibly a non-standard name
  800. lookupSyntaxName std_name
  801. = xoptM Opt_RebindableSyntax `thenM` \ rebindable_on ->
  802. if not rebindable_on then normal_case
  803. else
  804. -- Get the similarly named thing from the local environment
  805. lookupOccRn (mkRdrUnqual (nameOccName std_name)) `thenM` \ usr_name ->
  806. return (HsVar usr_name, unitFV usr_name)
  807. where
  808. normal_case = return (HsVar std_name, emptyFVs)
  809. lookupSyntaxTable :: [Name] -- Standard names
  810. -> RnM (SyntaxTable Name, FreeVars) -- See comments with HsExpr.ReboundNames
  811. lookupSyntaxTable std_names
  812. = xoptM Opt_RebindableSyntax `thenM` \ rebindable_on ->
  813. if not rebindable_on then normal_case
  814. else
  815. -- Get the similarly named thing from the local environment
  816. mapM (lookupOccRn . mkRdrUnqual . nameOccName) std_names `thenM` \ usr_names ->
  817. return (std_names `zip` map HsVar usr_names, mkFVs usr_names)
  818. where
  819. normal_case = return (std_names `zip` map HsVar std_names, emptyFVs)
  820. \end{code}
  821. %*********************************************************
  822. %* *
  823. \subsection{Binding}
  824. %* *
  825. %*********************************************************
  826. \begin{code}
  827. newLocalBndrRn :: Located RdrName -> RnM Name
  828. -- Used for non-top-level binders. These should
  829. -- never be qualified.
  830. newLocalBndrRn (L loc rdr_name)
  831. | Just name <- isExact_maybe rdr_name
  832. = return name -- This happens in code generated by Template Haskell
  833. -- See Note [Binders in Template Haskell] in Convert.lhs
  834. | otherwise
  835. = do { unless (isUnqual rdr_name)
  836. (addErrAt loc (badQualBndrErr rdr_name))
  837. ; uniq <- newUnique
  838. ; return (mkInternalName uniq (rdrNameOcc rdr_name) loc) }
  839. newLocalBndrsRn :: [Located RdrName] -> RnM [Name]
  840. newLocalBndrsRn = mapM newLocalBndrRn
  841. ---------------------
  842. bindLocatedLocalsRn :: [Located RdrName]
  843. -> ([Name] -> RnM a)
  844. -> RnM a
  845. bindLocatedLocalsRn rdr_names_w_loc enclosed_scope
  846. = do { checkDupAndShadowedRdrNames rdr_names_w_loc
  847. -- Make fresh Names and extend the environment
  848. ; names <- newLocalBndrsRn rdr_names_w_loc
  849. ; bindLocalNames names (enclosed_scope names) }
  850. bindLocalNames :: [Name] -> RnM a -> RnM a
  851. bindLocalNames names enclosed_scope
  852. = do { name_env <- getLocalRdrEnv
  853. ; setLocalRdrEnv (extendLocalRdrEnvList name_env names)
  854. enclosed_scope }
  855. bindLocalName :: Name -> RnM a -> RnM a
  856. bindLocalName name enclosed_scope
  857. = do { name_env <- getLocalRdrEnv
  858. ; setLocalRdrEnv (extendLocalRdrEnv name_env name)
  859. enclosed_scope }
  860. bindLocalNamesFV :: [Name] -> RnM (a, FreeVars) -> RnM (a, FreeVars)
  861. bindLocalNamesFV names enclosed_scope
  862. = do { (result, fvs) <- bindLocalNames names enclosed_scope
  863. ; return (result, delFVs names fvs) }
  864. -------------------------------------
  865. -- binLocalsFVRn is the same as bindLocalsRn
  866. -- except that it deals with free vars
  867. bindLocatedLocalsFV :: [Located RdrName]
  868. -> ([Name] -> RnM (a,FreeVars)) -> RnM (a, FreeVars)
  869. bindLocatedLocalsFV rdr_names enclosed_scope
  870. = bindLocatedLocalsRn rdr_names $ \ names ->
  871. enclosed_scope names `thenM` \ (thing, fvs) ->
  872. return (thing, delFVs names fvs)
  873. -------------------------------------
  874. bindPatSigTyVars :: [LHsType RdrName] -> ([Name] -> RnM a) -> RnM a
  875. -- Find the type variables in the pattern type
  876. -- signatures that must be brought into scope
  877. bindPatSigTyVars tys thing_inside
  878. = do { scoped_tyvars <- xoptM Opt_ScopedTypeVariables
  879. ; if not scoped_tyvars then
  880. thing_inside []
  881. else
  882. do { name_env <- getLocalRdrEnv
  883. ; let locd_tvs = [ tv | ty <- tys
  884. , tv <- extractHsTyRdrTyVars ty
  885. , not (unLoc tv `elemLocalRdrEnv` name_env) ]
  886. nubbed_tvs = nubBy eqLocated locd_tvs
  887. -- The 'nub' is important. For example:
  888. -- f (x :: t) (y :: t) = ....
  889. -- We don't want to complain about binding t twice!
  890. ; bindLocatedLocalsRn nubbed_tvs thing_inside }}
  891. bindPatSigTyVarsFV :: [LHsType RdrName]
  892. -> RnM (a, FreeVars)
  893. -> RnM (a, FreeVars)
  894. bindPatSigTyVarsFV tys thing_inside
  895. = bindPatSigTyVars tys $ \ tvs ->
  896. thing_inside `thenM` \ (result,fvs) ->
  897. return (result, fvs `delListFromNameSet` tvs)
  898. bindSigTyVarsFV :: [Name]
  899. -> RnM (a, FreeVars)
  900. -> RnM (a, FreeVars)
  901. bindSigTyVarsFV tvs thing_inside
  902. = do { scoped_tyvars <- xoptM Opt_ScopedTypeVariables
  903. ; if not scoped_tyvars then
  904. thing_inside
  905. else
  906. bindLocalNamesFV tvs thing_inside }
  907. extendTyVarEnvFVRn :: [Name] -> RnM (a, FreeVars) -> RnM (a, FreeVars)
  908. -- This function is used only in rnSourceDecl on InstDecl
  909. extendTyVarEnvFVRn tyvars thing_inside = bindLocalNamesFV tyvars thing_inside
  910. -------------------------------------
  911. checkDupRdrNames :: [Located RdrName] -> RnM ()
  912. -- Check for duplicated names in a binding group
  913. checkDupRdrNames rdr_names_w_loc
  914. = mapM_ (dupNamesErr getLoc) dups
  915. where
  916. (_, dups) = removeDups (\n1 n2 -> unLoc n1 `compare` unLoc n2) rdr_names_w_loc
  917. checkDupNames :: [Name] -> RnM ()
  918. -- Check for duplicated names in a binding group
  919. checkDupNames names
  920. = mapM_ (dupNamesErr nameSrcSpan) dups
  921. where
  922. (_, dups) = removeDups (\n1 n2 -> nameOccName n1 `compare` nameOccName n2) $
  923. filterOut isSystemName names
  924. -- See Note [Binders in Template Haskell] in Convert
  925. ---------------------
  926. checkDupAndShadowedRdrNames :: [Located RdrName] -> RnM ()
  927. checkDupAndShadowedRdrNames loc_rdr_names
  928. = do { checkDupRdrNames loc_rdr_names
  929. ; envs <- getRdrEnvs
  930. ; checkShadowedOccs envs loc_occs }
  931. where
  932. loc_occs = [(loc,rdrNameOcc rdr) | L loc rdr <- loc_rdr_names]
  933. checkDupAndShadowedNames :: (GlobalRdrEnv, LocalRdrEnv) -> [Name] -> RnM ()
  934. checkDupAndShadowedNames envs names
  935. = do { checkDupNames names
  936. ; checkShadowedOccs envs loc_occs }
  937. where
  938. loc_occs = [(nameSrcSpan name, nameOccName name) | name <- names]
  939. -------------------------------------
  940. checkShadowedOccs :: (GlobalRdrEnv, LocalRdrEnv) -> [(SrcSpan,OccName)] -> RnM ()
  941. checkShadowedOccs (global_env,local_env) loc_occs
  942. = ifWOptM Opt_WarnNameShadowing $
  943. do { traceRn (text "shadow" <+> ppr loc_occs)
  944. ; mapM_ check_shadow loc_occs }
  945. where
  946. check_shadow (loc, occ)
  947. | startsWithUnderscore occ = return () -- Do not report shadowing for "_x"
  948. -- See Trac #3262
  949. | Just n <- mb_local = complain [ptext (sLit "bound at") <+> ppr (nameSrcLoc n)]
  950. | otherwise = do { gres' <- filterM is_shadowed_gre gres
  951. ; complain (map pprNameProvenance gres') }
  952. where
  953. complain [] = return ()
  954. complain pp_locs = addWarnAt loc (shadowedNameWarn occ pp_locs)
  955. mb_local = lookupLocalRdrOcc local_env occ
  956. gres = lookupGRE_RdrName (mkRdrUnqual occ) global_env
  957. -- Make an Unqualified RdrName and look that up, so that
  958. -- we don't find any GREs that are in scope qualified-only
  959. is_shadowed_gre :: GlobalRdrElt -> RnM Bool
  960. -- Returns False for record selectors that are shadowed, when
  961. -- punning or wild-cards are on (cf Trac #2723)
  962. is_shadowed_gre gre@(GRE { gre_par = ParentIs _ })
  963. = do { dflags <- getDOpts
  964. ; if (xopt Opt_RecordPuns dflags || xopt Opt_RecordWildCards dflags)
  965. then do { is_fld <- is_rec_fld gre; return (not is_fld) }
  966. else return True }
  967. is_shadowed_gre _other = return True
  968. is_rec_fld gre -- Return True for record selector ids
  969. | isLocalGRE gre = do { RecFields _ fld_set <- getRecFieldEnv
  970. ; return (gre_name gre `elemNameSet` fld_set) }
  971. | otherwise = do { sel_id <- tcLookupField (gre_name gre)
  972. ; return (isRecordSelector sel_id) }
  973. \end{code}
  974. %************************************************************************
  975. %* *
  976. What to do when a lookup fails
  977. %* *
  978. %************************************************************************
  979. \begin{code}
  980. data WhereLooking = WL_Any -- Any binding
  981. | WL_Global -- Any top-level binding (local or imported)
  982. | WL_LocalTop -- Any top-level binding in this module
  983. unboundName :: WhereLooking -> RdrName -> RnM Name
  984. unboundName where_look rdr_name
  985. = do { show_helpful_errors <- doptM Opt_HelpfulErrors
  986. ; let err = unknownNameErr rdr_name
  987. ; if not show_helpful_errors
  988. then addErr err
  989. else do { extra_err <- unknownNameSuggestErr where_look rdr_name
  990. ; addErr (err $$ extra_err) }
  991. ; env <- getGlobalRdrEnv;
  992. ; traceRn (vcat [unknownNameErr rdr_name,
  993. ptext (sLit "Global envt is:"),
  994. nest 3 (pprGlobalRdrEnv env)])
  995. ; return (mkUnboundName rdr_name) }
  996. unknownNameErr :: RdrName -> SDoc
  997. unknownNameErr rdr_name
  998. = vcat [ hang (ptext (sLit "Not in scope:"))
  999. 2 (pprNonVarNameSpace (occNameSpace (rdrNameOcc rdr_name))
  1000. <+> quotes (ppr rdr_name))
  1001. , extra ]
  1002. where
  1003. extra | rdr_name == forall_tv_RDR = perhapsForallMsg
  1004. | otherwise = empty
  1005. type HowInScope = Either SrcSpan ImpDeclSpec
  1006. -- Left loc => locally bound at loc
  1007. -- Right ispec => imported as specified by ispec
  1008. unknownNameSuggestErr :: WhereLooking -> RdrName -> RnM SDoc
  1009. unknownNameSuggestErr where_look tried_rdr_name
  1010. = do { local_env <- getLocalRdrEnv
  1011. ; global_env <- getGlobalRdrEnv
  1012. ; let all_possibilities :: [(String, (RdrName, HowInScope))]
  1013. all_possibilities
  1014. = [ (showSDoc (ppr r), (r, Left loc))
  1015. | (r,loc) <- local_possibilities local_env ]
  1016. ++ [ (showSDoc (ppr r), rp) | (r,rp) <- global_possibilities global_env ]
  1017. suggest = fuzzyLookup (showSDoc (ppr tried_rdr_name)) all_possibilities
  1018. perhaps = ptext (sLit "Perhaps you meant")
  1019. extra_err = case suggest of
  1020. [] -> empty
  1021. [p] -> perhaps <+> pp_item p
  1022. ps -> sep [ perhaps <+> ptext (sLit "one of these:")
  1023. , nest 2 (pprWithCommas pp_item ps) ]
  1024. ; return extra_err }
  1025. where
  1026. pp_item :: (RdrName, HowInScope) -> SDoc
  1027. pp_item (rdr, Left loc) = quotes (ppr rdr) <+> loc' -- Locally defined
  1028. where loc' = case loc of
  1029. UnhelpfulSpan l -> parens (ppr l)
  1030. RealSrcSpan l -> parens (ptext (sLit "line") <+> int (srcSpanStartLine l))
  1031. pp_item (rdr, Right is) = quotes (ppr rdr) <+> -- Imported
  1032. parens (ptext (sLit "imported from") <+> ppr (is_mod is))
  1033. tried_occ = rdrNameOcc tried_rdr_name
  1034. tried_is_sym = isSymOcc tried_occ
  1035. tried_ns = occNameSpace tried_occ
  1036. tried_is_qual = isQual tried_rdr_name
  1037. correct_name_space occ = occNameSpace occ == tried_ns
  1038. && isSymOcc occ == tried_is_sym
  1039. -- Treat operator and non-operators as non-matching
  1040. -- This heuristic avoids things like
  1041. -- Not in scope 'f'; perhaps you meant '+' (from Prelude)
  1042. local_ok = case where_look of { WL_Any -> True; _ -> False }
  1043. local_possibilities :: LocalRdrEnv -> [(RdrName, SrcSpan)]
  1044. local_possibilities env
  1045. | tried_is_qual = []
  1046. | not local_ok = []
  1047. | otherwise = [ (mkRdrUnqual occ, nameSrcSpan name)
  1048. | name <- occEnvElts env
  1049. , let occ = nameOccName name
  1050. , correct_name_space occ]
  1051. gre_ok :: GlobalRdrElt -> Bool
  1052. gre_ok = case where_look of
  1053. WL_LocalTop -> isLocalGRE
  1054. _ -> \_ -> True
  1055. global_possibilities :: GlobalRdrEnv -> [(RdrName, (RdrName, HowInScope))]
  1056. global_possibilities global_env
  1057. | tried_is_qual = [ (rdr_qual, (rdr_qual, how))
  1058. | gre <- globalRdrEnvElts global_env
  1059. , gre_ok gre
  1060. , let name = gre_name gre
  1061. occ = nameOccName name
  1062. , correct_name_space occ
  1063. , (mod, how) <- quals_in_scope name (gre_prov gre)
  1064. , let rdr_qual = mkRdrQual mod occ ]
  1065. | otherwise = [ (rdr_unqual, pair)
  1066. | gre <- globalRdrEnvElts global_env
  1067. , gre_ok gre
  1068. , let name = gre_name gre
  1069. prov = gre_prov gre
  1070. occ = nameOccName name
  1071. rdr_unqual = mkRdrUnqual occ
  1072. , correct_name_space occ
  1073. , pair <- case (unquals_in_scope name prov, quals_only occ prov) of
  1074. (how:_, _) -> [ (rdr_unqual, how) ]
  1075. ([], pr:_) -> [ pr ] -- See Note [Only-quals]
  1076. ([], []) -> [] ]
  1077. -- Note [Only-quals]
  1078. -- The second alternative returns those names with the same
  1079. -- OccName as the one we tried, but live in *qualified* imports
  1080. -- e.g. if you have:
  1081. --
  1082. -- > import qualified Data.Map as Map
  1083. -- > foo :: Map
  1084. --
  1085. -- then we suggest @Map.Map@.
  1086. --------------------
  1087. unquals_in_scope :: Name -> Provenance -> [HowInScope]
  1088. unquals_in_scope n LocalDef = [ Left (nameSrcSpan n) ]
  1089. unquals_in_scope _ (Imported is) = [ Right ispec
  1090. | i <- is, let ispec = is_decl i
  1091. , not (is_qual ispec) ]
  1092. --------------------
  1093. quals_in_scope :: Name -> Provenance -> [(ModuleName, HowInScope)]
  1094. -- Ones for which the qualified version is in scope
  1095. quals_in_scope n LocalDef = case nameModule_maybe n of
  1096. Nothing -> []
  1097. Just m -> [(moduleName m, Left (nameSrcSpan n))]
  1098. quals_in_scope _ (Imported is) = [ (is_as ispec, Right ispec)
  1099. | i <- is, let ispec = is_decl i ]
  1100. --------------------
  1101. quals_only :: OccName -> Provenance -> [(RdrName, HowInScope)]
  1102. -- Ones for which *only* the qualified version is in scope
  1103. quals_only _ LocalDef = []
  1104. quals_only occ (Imported is) = [ (mkRdrQual (is_as ispec) occ, Right ispec)
  1105. | i <- is, let ispec = is_decl i, is_qual ispec ]
  1106. \end{code}
  1107. %************************************************************************
  1108. %* *
  1109. \subsection{Free variable manipulation}
  1110. %* *
  1111. %************************************************************************
  1112. \begin{code}
  1113. -- A useful utility
  1114. addFvRn :: FreeVars -> RnM (thing, FreeVars) -> RnM (thing, FreeVars)
  1115. addFvRn fvs1 thing_inside = do { (res, fvs2) <- thing_inside
  1116. ; return (res, fvs1 `plusFV` fvs2) }
  1117. mapFvRn :: (a -> RnM (b, FreeVars)) -> [a] -> RnM ([b], FreeVars)
  1118. mapFvRn f xs = do stuff <- mapM f xs
  1119. case unzip stuff of
  1120. (ys, fvs_s) -> return (ys, plusFVs fvs_s)
  1121. mapMaybeFvRn :: (a -> RnM (b, FreeVars)) -> Maybe a -> RnM (Maybe b, FreeVars)
  1122. mapMaybeFvRn _ Nothing = return (Nothing, emptyFVs)
  1123. mapMaybeFvRn f (Just x) = do { (y, fvs) <- f x; return (Just y, fvs) }
  1124. -- because some of the rename functions are CPSed:
  1125. -- maps the function across the list from left to right;
  1126. -- collects all the free vars into one set
  1127. mapFvRnCPS :: (a -> (b -> RnM c) -> RnM c)
  1128. -> [a] -> ([b] -> RnM c) -> RnM c
  1129. mapFvRnCPS _ [] cont = cont []
  1130. mapFvRnCPS f (x:xs) cont = f x $ \ x' ->
  1131. mapFvRnCPS f xs $ \ xs' ->
  1132. cont (x':xs')
  1133. \end{code}
  1134. %************************************************************************
  1135. %* *
  1136. \subsection{Envt utility functions}
  1137. %* *
  1138. %************************************************************************
  1139. \begin{code}
  1140. warnUnusedTopBinds :: [GlobalRdrElt] -> RnM ()
  1141. warnUnusedTopBinds gres
  1142. = ifWOptM Opt_WarnUnusedBinds
  1143. $ do isBoot <- tcIsHsBoot
  1144. let noParent gre = case gre_par gre of
  1145. NoParent -> True
  1146. ParentIs _ -> False
  1147. -- Don't warn about unused bindings with parents in
  1148. -- .hs-boot files, as you are sometimes required to give
  1149. -- unused bindings (trac #3449).
  1150. gres' = if isBoot then filter noParent gres
  1151. else gres
  1152. warnUnusedGREs gres'
  1153. warnUnusedLocalBinds, warnUnusedMatches :: [Name] -> FreeVars -> RnM ()
  1154. warnUnusedLocalBinds = check_unused Opt_WarnUnusedBinds
  1155. warnUnusedMatches = check_unused Opt_WarnUnusedMatches
  1156. check_unused :: WarningFlag -> [Name] -> FreeVars -> RnM ()
  1157. check_unused flag bound_names used_names
  1158. = ifWOptM flag (warnUnusedLocals (filterOut (`elemNameSet` used_names) bound_names))
  1159. -------------------------
  1160. -- Helpers
  1161. warnUnusedGREs :: [GlobalRdrElt] -> RnM ()
  1162. warnUnusedGREs gres
  1163. = warnUnusedBinds [(n,p) | GRE {gre_name = n, gre_prov = p} <- gres]
  1164. warnUnusedLocals :: [Name] -> RnM ()
  1165. warnUnusedLocals names
  1166. = warnUnusedBinds [(n,LocalDef) | n<-names]
  1167. warnUnusedBinds :: [(Name,Provenance)] -> RnM ()
  1168. warnUnusedBinds names = mapM_ warnUnusedName (filter reportable names)
  1169. where reportable (name,_)
  1170. | isWiredInName name = False -- Don't report unused wired-in names
  1171. -- Otherwise we get a zillion warnings
  1172. -- from Data.Tuple
  1173. | otherwise = not (startsWithUnderscore (nameOccName name))
  1174. -------------------------
  1175. warnUnusedName :: (Name, Provenance) -> RnM ()
  1176. warnUnusedName (name, LocalDef)
  1177. = addUnusedWarning name (nameSrcSpan name)
  1178. (ptext (sLit "Defined but not used"))
  1179. warnUnusedName (name, Imported is)
  1180. = mapM_ warn is
  1181. where
  1182. warn spec = addUnusedWarning name span msg
  1183. where
  1184. span = importSpecLoc spec
  1185. pp_mod = quotes (ppr (importSpecModule spec))
  1186. msg = ptext (sLit "Imported from") <+> pp_mod <+> ptext (sLit "but not used")
  1187. addUnusedWarning :: Name -> SrcSpan -> SDoc -> RnM ()
  1188. addUnusedWarning name span msg
  1189. = addWarnAt span $
  1190. sep [msg <> colon,
  1191. nest 2 $ pprNonVarNameSpace (occNameSpace (nameOccName name))
  1192. <+> quotes (ppr name)]
  1193. \end{code}
  1194. \begin{code}
  1195. addNameClashErrRn :: RdrName -> [GlobalRdrElt] -> RnM ()
  1196. addNameClashErrRn rdr_name names
  1197. = addErr (vcat [ptext (sLit "Ambiguous occurrence") <+> quotes (ppr rdr_name),
  1198. ptext (sLit "It could refer to") <+> vcat (msg1 : msgs)])
  1199. where
  1200. (np1:nps) = names
  1201. msg1 = ptext (sLit "either") <+> mk_ref np1
  1202. msgs = [ptext (sLit " or") <+> mk_ref np | np <- nps]
  1203. mk_ref gre = sep [quotes (ppr (gre_name gre)) <> comma, pprNameProvenance gre]
  1204. shadowedNameWarn :: OccName -> [SDoc] -> SDoc
  1205. shadowedNameWarn occ shadowed_locs
  1206. = sep [ptext (sLit "This binding for") <+> quotes (ppr occ)
  1207. <+> ptext (sLit "shadows the existing binding") <> plural shadowed_locs,
  1208. nest 2 (vcat shadowed_locs)]
  1209. perhapsForallMsg :: SDoc
  1210. perhapsForallMsg
  1211. = vcat [ ptext (sLit "Perhaps you intended to use -XExplicitForAll or similar flag")
  1212. , ptext (sLit "to enable explicit-forall syntax: forall <tvs>. <type>")]
  1213. unknownSubordinateErr :: SDoc -> RdrName -> SDoc
  1214. unknownSubordinateErr doc op -- Doc is "method of class" or
  1215. -- "field of constructor"
  1216. = quotes (ppr op) <+> ptext (sLit "is not a (visible)") <+> doc
  1217. badOrigBinding :: RdrName -> SDoc
  1218. badOrigBinding name
  1219. = ptext (sLit "Illegal binding of built-in syntax:") <+> ppr (rdrNameOcc name)
  1220. -- The rdrNameOcc is because we don't want to print Prelude.(,)
  1221. dupNamesErr :: Outputable n => (n -> SrcSpan) -> [n] -> RnM ()
  1222. dupNamesErr get_loc names
  1223. = addErrAt big_loc $
  1224. vcat [ptext (sLit "Conflicting definitions for") <+> quotes (ppr (head names)),
  1225. locations]
  1226. where
  1227. locs = map get_loc names
  1228. big_loc = foldr1 combineSrcSpans locs
  1229. locations = ptext (sLit "Bound at:") <+> vcat (map ppr (sortLe (<=) locs))
  1230. kindSigErr :: Outputable a => a -> SDoc
  1231. kindSigErr thing
  1232. = hang (ptext (sLit "Illegal kind signature for") <+> quotes (ppr thing))
  1233. 2 (ptext (sLit "Perhaps you intended to use -XKindSignatures"))
  1234. dataKindsErr :: Outputable a => a -> SDoc
  1235. dataKindsErr thing
  1236. = hang (ptext (sLit "Illegal kind:") <+> quotes (ppr thing))
  1237. 2 (ptext (sLit "Perhaps you intended to use -XDataKinds"))
  1238. badQualBndrErr :: RdrName -> SDoc
  1239. badQualBndrErr rdr_name
  1240. = ptext (sLit "Qualified name in binding position:") <+> ppr rdr_name
  1241. opDeclErr :: RdrName -> SDoc
  1242. opDeclErr n
  1243. = hang (ptext (sLit "Illegal declaration of a type or class operator") <+> quotes (ppr n))
  1244. 2 (ptext (sLit "Use -XTypeOperators to declare operators in type and declarations"))
  1245. \end{code}
  1246. %************************************************************************
  1247. %* *
  1248. \subsection{Contexts for renaming errors}
  1249. %* *
  1250. %************************************************************************
  1251. \begin{code}
  1252. data HsDocContext
  1253. = TypeSigCtx SDoc
  1254. | PatCtx
  1255. | SpecInstSigCtx
  1256. | DefaultDeclCtx
  1257. | ForeignDeclCtx (Located RdrName)
  1258. | DerivDeclCtx
  1259. | RuleCtx FastString
  1260. | TyDataCtx (Located RdrName)
  1261. | TySynCtx (Located RdrName)
  1262. | TyFamilyCtx (Located RdrName)
  1263. | ConDeclCtx (Located RdrName)
  1264. | ClassDeclCtx (Located RdrName)
  1265. | ExprWithTySigCtx
  1266. | TypBrCtx
  1267. | HsTypeCtx
  1268. | GHCiCtx
  1269. | SpliceTypeCtx (LHsType RdrName)
  1270. | ClassInstanceCtx
  1271. | VectDeclCtx (Located RdrName)
  1272. docOfHsDocContext :: HsDocContext -> SDoc
  1273. docOfHsDocContext (TypeSigCtx doc) = text "In the type signature for" <+> doc
  1274. docOfHsDocContext PatCtx = text "In a pattern type-signature"
  1275. docOfHsDocContext SpecInstSigCtx = text "In a SPECIALISE instance pragma"
  1276. docOfHsDocContext DefaultDeclCtx = text "In a `default' declaration"
  1277. docOfHsDocContext (ForeignDeclCtx name) = ptext (sLit "In the foreign declaration for") <+> ppr name
  1278. docOfHsDocContext DerivDeclCtx = text "In a deriving declaration"
  1279. docOfHsDocContext (RuleCtx name) = text "In the transformation rule" <+> ftext name
  1280. docOfHsDocContext (TyDataCtx tycon) = text "In the data type declaration for" <+> quotes (ppr tycon)
  1281. docOfHsDocContext (TySynCtx name) = text "In the declaration for type synonym" <+> quotes (ppr name)
  1282. docOfHsDocContext (TyFamilyCtx name) = text "In the declaration for type family" <+> quotes (ppr name)
  1283. docOfHsDocContext (ConDeclCtx name) = text "In the definition of data constructor" <+> quotes (ppr name)
  1284. docOfHsDocContext (ClassDeclCtx name) = text "In the declaration for class" <+> ppr name
  1285. docOfHsDocContext ExprWithTySigCtx = text "In an expression type signature"
  1286. docOfHsDocContext TypBrCtx = ptext (sLit "In a Template-Haskell quoted type")
  1287. docOfHsDocContext HsTypeCtx = text "In a type argument"
  1288. docOfHsDocContext GHCiCtx = ptext (sLit "In GHCi input")
  1289. docOfHsDocContext (SpliceTypeCtx hs_ty) = ptext (sLit "In the spliced type") <+> ppr hs_ty
  1290. docOfHsDocContext ClassInstanceCtx = ptext (sLit "TcSplice.reifyInstances")
  1291. docOfHsDocContext (VectDeclCtx tycon) = ptext (sLit "In the VECTORISE pragma for type constructor") <+> quotes (ppr tycon)
  1292. \end{code}