PageRenderTime 62ms CodeModel.GetById 16ms RepoModel.GetById 1ms app.codeStats 0ms

/compiler/rename/RnEnv.lhs

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