never executed always true always false
    1 {-
    2 
    3 This module contains helper functions for reporting and creating
    4 unbound variables.
    5 
    6 -}
    7 module GHC.Rename.Unbound
    8    ( mkUnboundName
    9    , mkUnboundNameRdr
   10    , isUnboundName
   11    , reportUnboundName
   12    , reportUnboundName'
   13    , unknownNameSuggestions
   14    , WhatLooking(..)
   15    , WhereLooking(..)
   16    , LookingFor(..)
   17    , unboundName
   18    , unboundNameX
   19    , notInScopeErr
   20    , nameSpacesRelated
   21    , exactNameErr
   22    )
   23 where
   24 
   25 import GHC.Prelude
   26 
   27 import GHC.Driver.Session
   28 import GHC.Driver.Ppr
   29 
   30 import GHC.Tc.Errors.Types
   31 import GHC.Tc.Utils.Monad
   32 import GHC.Builtin.Names ( mkUnboundName, isUnboundName, getUnique)
   33 import GHC.Utils.Outputable as Outputable
   34 import GHC.Utils.Misc
   35 
   36 import GHC.Data.Maybe
   37 import GHC.Data.FastString
   38 
   39 import qualified GHC.LanguageExtensions as LangExt
   40 
   41 import GHC.Types.Error
   42 import GHC.Types.SrcLoc as SrcLoc
   43 import GHC.Types.Name
   44 import GHC.Types.Name.Reader
   45 import GHC.Types.Unique.DFM (udfmToList)
   46 
   47 import GHC.Unit.Module
   48 import GHC.Unit.Module.Imported
   49 import GHC.Unit.Home.ModInfo
   50 
   51 import Data.List (sortBy, partition, nub)
   52 import Data.Function ( on )
   53 import GHC.Data.Bag
   54 
   55 {-
   56 ************************************************************************
   57 *                                                                      *
   58                What to do when a lookup fails
   59 *                                                                      *
   60 ************************************************************************
   61 -}
   62 
   63 -- What kind of suggestion are we looking for? #19843
   64 data WhatLooking = WL_Anything    -- Any binding
   65                  | WL_Constructor -- Constructors and pattern synonyms
   66                         -- E.g. in K { f1 = True }, if K is not in scope,
   67                         -- suggest only constructors
   68                  | WL_RecField    -- Record fields
   69                         -- E.g. in K { f1 = True, f2 = False }, if f2 is not in
   70                         -- scope, suggest only constructor fields
   71                  | WL_None        -- No suggestions
   72                         -- WS_None is used for rebindable syntax, where there
   73                         -- is no point in suggesting alternative spellings
   74                  deriving Eq
   75 
   76 data WhereLooking = WL_Anywhere   -- Any binding
   77                   | WL_Global     -- Any top-level binding (local or imported)
   78                   | WL_LocalTop   -- Any top-level binding in this module
   79                   | WL_LocalOnly
   80                         -- Only local bindings
   81                         -- (pattern synonyms declarations,
   82                         -- see Note [Renaming pattern synonym variables]
   83                         -- in GHC.Rename.Bind)
   84 
   85 data LookingFor = LF { lf_which :: WhatLooking
   86                      , lf_where :: WhereLooking
   87                      }
   88 
   89 mkUnboundNameRdr :: RdrName -> Name
   90 mkUnboundNameRdr rdr = mkUnboundName (rdrNameOcc rdr)
   91 
   92 reportUnboundName' :: WhatLooking -> RdrName -> RnM Name
   93 reportUnboundName' what_look rdr = unboundName (LF what_look WL_Anywhere) rdr
   94 
   95 reportUnboundName :: RdrName -> RnM Name
   96 reportUnboundName = reportUnboundName' WL_Anything
   97 
   98 unboundName :: LookingFor -> RdrName -> RnM Name
   99 unboundName lf rdr = unboundNameX lf rdr Outputable.empty
  100 
  101 unboundNameX :: LookingFor -> RdrName -> SDoc -> RnM Name
  102 unboundNameX looking_for rdr_name extra
  103   = do  { dflags <- getDynFlags
  104         ; let show_helpful_errors = gopt Opt_HelpfulErrors dflags
  105               err = notInScopeErr (lf_where looking_for) rdr_name $$ extra
  106         ; if not show_helpful_errors
  107           then addErr (TcRnUnknownMessage $ mkPlainError noHints err)
  108           else do { local_env  <- getLocalRdrEnv
  109                   ; global_env <- getGlobalRdrEnv
  110                   ; impInfo <- getImports
  111                   ; currmod <- getModule
  112                   ; hpt <- getHpt
  113                   ; let suggestions = unknownNameSuggestions_ looking_for
  114                           dflags hpt currmod global_env local_env impInfo
  115                           rdr_name
  116                   ; addErr (TcRnUnknownMessage $ mkPlainError noHints (err $$ suggestions)) }
  117         ; return (mkUnboundNameRdr rdr_name) }
  118 
  119 notInScopeErr :: WhereLooking -> RdrName -> SDoc
  120 notInScopeErr where_look rdr_name
  121   | Just name <- isExact_maybe rdr_name = exactNameErr name
  122   | WL_LocalTop <- where_look = hang (text "No top-level binding for")
  123       2 (what <+> quotes (ppr rdr_name) <+> text "in this module")
  124   | otherwise = hang (text "Not in scope:")
  125                  2 (what <+> quotes (ppr rdr_name))
  126   where
  127     what = pprNonVarNameSpace (occNameSpace (rdrNameOcc rdr_name))
  128 
  129 type HowInScope = Either SrcSpan ImpDeclSpec
  130      -- Left loc    =>  locally bound at loc
  131      -- Right ispec =>  imported as specified by ispec
  132 
  133 
  134 -- | Called from the typechecker ("GHC.Tc.Errors") when we find an unbound variable
  135 unknownNameSuggestions :: WhatLooking -> DynFlags
  136                        -> HomePackageTable -> Module
  137                        -> GlobalRdrEnv -> LocalRdrEnv -> ImportAvails
  138                        -> RdrName -> SDoc
  139 unknownNameSuggestions what_look = unknownNameSuggestions_ (LF what_look WL_Anywhere)
  140 
  141 unknownNameSuggestions_ :: LookingFor -> DynFlags
  142                        -> HomePackageTable -> Module
  143                        -> GlobalRdrEnv -> LocalRdrEnv -> ImportAvails
  144                        -> RdrName -> SDoc
  145 unknownNameSuggestions_ looking_for dflags hpt curr_mod global_env local_env
  146                           imports tried_rdr_name =
  147     similarNameSuggestions looking_for dflags global_env local_env tried_rdr_name $$
  148     importSuggestions looking_for global_env hpt
  149                       curr_mod imports tried_rdr_name $$
  150     extensionSuggestions tried_rdr_name $$
  151     fieldSelectorSuggestions global_env tried_rdr_name
  152 
  153 -- | When the name is in scope as field whose selector has been suppressed by
  154 -- NoFieldSelectors, display a helpful message explaining this.
  155 fieldSelectorSuggestions :: GlobalRdrEnv -> RdrName -> SDoc
  156 fieldSelectorSuggestions global_env tried_rdr_name
  157   | null gres = Outputable.empty
  158   | otherwise = text "NB:"
  159       <+> quotes (ppr tried_rdr_name)
  160       <+> text "is a field selector" <+> whose
  161       $$ text "that has been suppressed by NoFieldSelectors"
  162   where
  163     gres = filter isNoFieldSelectorGRE $
  164                lookupGRE_RdrName' tried_rdr_name global_env
  165     parents = [ parent | ParentIs parent <- map gre_par gres ]
  166 
  167     -- parents may be empty if this is a pattern synonym field without a selector
  168     whose | null parents = empty
  169           | otherwise    = text "belonging to the type" <> plural parents
  170                              <+> pprQuotedList parents
  171 
  172 similarNameSuggestions :: LookingFor -> DynFlags
  173                        -> GlobalRdrEnv -> LocalRdrEnv
  174                        -> RdrName -> SDoc
  175 similarNameSuggestions looking_for@(LF what_look where_look) dflags global_env
  176                        local_env tried_rdr_name
  177   = case suggest of
  178       []  -> Outputable.empty
  179       [p] -> perhaps <+> pp_item p
  180       ps  -> sep [ perhaps <+> text "one of these:"
  181                  , nest 2 (pprWithCommas pp_item ps) ]
  182   where
  183     all_possibilities :: [(String, (RdrName, HowInScope))]
  184     all_possibilities = case what_look of
  185       WL_None -> []
  186       _ -> [ (showPpr dflags r, (r, Left loc))
  187            | (r,loc) <- local_possibilities local_env ]
  188         ++ [ (showPpr dflags r, rp) | (r, rp) <- global_possibilities global_env ]
  189 
  190     suggest = fuzzyLookup (showPpr dflags tried_rdr_name) all_possibilities
  191     perhaps = text "Perhaps you meant"
  192 
  193     pp_item :: (RdrName, HowInScope) -> SDoc
  194     pp_item (rdr, Left loc) = pp_ns rdr <+> quotes (ppr rdr) <+> loc' -- Locally defined
  195         where loc' = case loc of
  196                      UnhelpfulSpan l -> parens (ppr l)
  197                      RealSrcSpan l _ -> parens (text "line" <+> int (srcSpanStartLine l))
  198     pp_item (rdr, Right is) = pp_ns rdr <+> quotes (ppr rdr) <+>   -- Imported
  199                               parens (text "imported from" <+> ppr (is_mod is))
  200 
  201     pp_ns :: RdrName -> SDoc
  202     pp_ns rdr | ns /= tried_ns = pprNameSpace ns
  203               | otherwise      = Outputable.empty
  204       where ns = rdrNameSpace rdr
  205 
  206     tried_occ     = rdrNameOcc tried_rdr_name
  207     tried_is_sym  = isSymOcc tried_occ
  208     tried_ns      = occNameSpace tried_occ
  209     tried_is_qual = isQual tried_rdr_name
  210 
  211     correct_name_space occ =
  212       (nameSpacesRelated dflags what_look tried_ns (occNameSpace occ))
  213       && isSymOcc occ == tried_is_sym
  214         -- Treat operator and non-operators as non-matching
  215         -- This heuristic avoids things like
  216         --      Not in scope 'f'; perhaps you meant '+' (from Prelude)
  217 
  218     local_ok = case where_look of { WL_Anywhere  -> True
  219                                   ; WL_LocalOnly -> True
  220                                   ; _            -> False }
  221 
  222     local_possibilities :: LocalRdrEnv -> [(RdrName, SrcSpan)]
  223     local_possibilities env
  224       | tried_is_qual = []
  225       | not local_ok  = []
  226       | otherwise     = [ (mkRdrUnqual occ, nameSrcSpan name)
  227                         | name <- localRdrEnvElts env
  228                         , let occ = nameOccName name
  229                         , correct_name_space occ]
  230 
  231     global_possibilities :: GlobalRdrEnv -> [(RdrName, (RdrName, HowInScope))]
  232     global_possibilities global_env
  233       | tried_is_qual = [ (rdr_qual, (rdr_qual, how))
  234                         | gre <- globalRdrEnvElts global_env
  235                         , isGreOk looking_for gre
  236                         , let occ = greOccName gre
  237                         , correct_name_space occ
  238                         , (mod, how) <- qualsInScope gre
  239                         , let rdr_qual = mkRdrQual mod occ ]
  240 
  241       | otherwise = [ (rdr_unqual, pair)
  242                     | gre <- globalRdrEnvElts global_env
  243                     , isGreOk looking_for gre
  244                     , let occ = greOccName gre
  245                           rdr_unqual = mkRdrUnqual occ
  246                     , correct_name_space occ
  247                     , pair <- case (unquals_in_scope gre, quals_only gre) of
  248                                 (how:_, _)    -> [ (rdr_unqual, how) ]
  249                                 ([],    pr:_) -> [ pr ]  -- See Note [Only-quals]
  250                                 ([],    [])   -> [] ]
  251 
  252               -- Note [Only-quals]
  253               -- The second alternative returns those names with the same
  254               -- OccName as the one we tried, but live in *qualified* imports
  255               -- e.g. if you have:
  256               --
  257               -- > import qualified Data.Map as Map
  258               -- > foo :: Map
  259               --
  260               -- then we suggest @Map.Map@.
  261 
  262     --------------------
  263     unquals_in_scope :: GlobalRdrElt -> [HowInScope]
  264     unquals_in_scope (gre@GRE { gre_lcl = lcl, gre_imp = is })
  265       | lcl       = [ Left (greDefinitionSrcSpan gre) ]
  266       | otherwise = [ Right ispec
  267                     | i <- bagToList is, let ispec = is_decl i
  268                     , not (is_qual ispec) ]
  269 
  270 
  271     --------------------
  272     quals_only :: GlobalRdrElt -> [(RdrName, HowInScope)]
  273     -- Ones for which *only* the qualified version is in scope
  274     quals_only (gre@GRE { gre_imp = is })
  275       = [ (mkRdrQual (is_as ispec) (greOccName gre), Right ispec)
  276         | i <- bagToList is, let ispec = is_decl i, is_qual ispec ]
  277 
  278 -- | Generate helpful suggestions if a qualified name Mod.foo is not in scope.
  279 importSuggestions :: LookingFor
  280                   -> GlobalRdrEnv
  281                   -> HomePackageTable -> Module
  282                   -> ImportAvails -> RdrName -> SDoc
  283 importSuggestions looking_for global_env hpt currMod imports rdr_name
  284   | WL_LocalOnly <- lf_where looking_for       = Outputable.empty
  285   | WL_LocalTop  <- lf_where looking_for       = Outputable.empty
  286   | not (isQual rdr_name || isUnqual rdr_name) = Outputable.empty
  287   | null interesting_imports
  288   , Just name <- mod_name
  289   , show_not_imported_line name
  290   = hsep
  291       [ text "No module named"
  292       , quotes (ppr name)
  293       , text "is imported."
  294       ]
  295   | is_qualified
  296   , null helpful_imports
  297   , [(mod,_)] <- interesting_imports
  298   = hsep
  299       [ text "Module"
  300       , quotes (ppr mod)
  301       , text "does not export"
  302       , quotes (ppr occ_name) <> dot
  303       ]
  304   | is_qualified
  305   , null helpful_imports
  306   , not (null interesting_imports)
  307   , mods <- map fst interesting_imports
  308   = hsep
  309       [ text "Neither"
  310       , quotedListWithNor (map ppr mods)
  311       , text "exports"
  312       , quotes (ppr occ_name) <> dot
  313       ]
  314   | [(mod,imv)] <- helpful_imports_non_hiding
  315   = fsep
  316       [ text "Perhaps you want to add"
  317       , quotes (ppr occ_name)
  318       , text "to the import list"
  319       , text "in the import of"
  320       , quotes (ppr mod)
  321       , parens (ppr (imv_span imv)) <> dot
  322       ]
  323   | not (null helpful_imports_non_hiding)
  324   = fsep
  325       [ text "Perhaps you want to add"
  326       , quotes (ppr occ_name)
  327       , text "to one of these import lists:"
  328       ]
  329     $$
  330     nest 2 (vcat
  331         [ quotes (ppr mod) <+> parens (ppr (imv_span imv))
  332         | (mod,imv) <- helpful_imports_non_hiding
  333         ])
  334   | [(mod,imv)] <- helpful_imports_hiding
  335   = fsep
  336       [ text "Perhaps you want to remove"
  337       , quotes (ppr occ_name)
  338       , text "from the explicit hiding list"
  339       , text "in the import of"
  340       , quotes (ppr mod)
  341       , parens (ppr (imv_span imv)) <> dot
  342       ]
  343   | not (null helpful_imports_hiding)
  344   = fsep
  345       [ text "Perhaps you want to remove"
  346       , quotes (ppr occ_name)
  347       , text "from the hiding clauses"
  348       , text "in one of these imports:"
  349       ]
  350     $$
  351     nest 2 (vcat
  352         [ quotes (ppr mod) <+> parens (ppr (imv_span imv))
  353         | (mod,imv) <- helpful_imports_hiding
  354         ])
  355   | otherwise
  356   = Outputable.empty
  357  where
  358   is_qualified = isQual rdr_name
  359   (mod_name, occ_name) = case rdr_name of
  360     Unqual occ_name        -> (Nothing, occ_name)
  361     Qual mod_name occ_name -> (Just mod_name, occ_name)
  362     _                      -> error "importSuggestions: dead code"
  363 
  364 
  365   -- What import statements provide "Mod" at all
  366   -- or, if this is an unqualified name, are not qualified imports
  367   interesting_imports = [ (mod, imp)
  368     | (mod, mod_imports) <- moduleEnvToList (imp_mods imports)
  369     , Just imp <- return $ pick (importedByUser mod_imports)
  370     ]
  371 
  372   -- We want to keep only one for each original module; preferably one with an
  373   -- explicit import list (for no particularly good reason)
  374   pick :: [ImportedModsVal] -> Maybe ImportedModsVal
  375   pick = listToMaybe . sortBy cmp . filter select
  376     where select imv = case mod_name of Just name -> imv_name imv == name
  377                                         Nothing   -> not (imv_qualified imv)
  378           cmp a b =
  379             (compare `on` imv_is_hiding) a b
  380               `thenCmp`
  381             (SrcLoc.leftmost_smallest `on` imv_span) a b
  382 
  383   -- Which of these would export a 'foo'
  384   -- (all of these are restricted imports, because if they were not, we
  385   -- wouldn't have an out-of-scope error in the first place)
  386   helpful_imports = filter helpful interesting_imports
  387     where helpful (_,imv)
  388             = any (isGreOk looking_for) $
  389               lookupGlobalRdrEnv (imv_all_exports imv) occ_name
  390 
  391   -- Which of these do that because of an explicit hiding list resp. an
  392   -- explicit import list
  393   (helpful_imports_hiding, helpful_imports_non_hiding)
  394     = partition (imv_is_hiding . snd) helpful_imports
  395 
  396   -- See note [When to show/hide the module-not-imported line]
  397   show_not_imported_line :: ModuleName -> Bool                    -- #15611
  398   show_not_imported_line modnam
  399       | modnam `elem` glob_mods               = False    -- #14225     -- 1
  400       | moduleName currMod == modnam          = False                  -- 2.1
  401       | is_last_loaded_mod modnam hpt_uniques = False                  -- 2.2
  402       | otherwise                             = True
  403     where
  404       hpt_uniques = map fst (udfmToList hpt)
  405       is_last_loaded_mod _ []         = False
  406       is_last_loaded_mod modnam uniqs = last uniqs == getUnique modnam
  407       glob_mods = nub [ mod
  408                      | gre <- globalRdrEnvElts global_env
  409                      , (mod, _) <- qualsInScope gre
  410                      ]
  411 
  412 extensionSuggestions :: RdrName -> SDoc
  413 extensionSuggestions rdrName
  414   | rdrName == mkUnqual varName (fsLit "mdo") ||
  415     rdrName == mkUnqual varName (fsLit "rec")
  416       = text "Perhaps you meant to use RecursiveDo"
  417   | otherwise = Outputable.empty
  418 
  419 qualsInScope :: GlobalRdrElt -> [(ModuleName, HowInScope)]
  420 -- Ones for which the qualified version is in scope
  421 qualsInScope gre@GRE { gre_lcl = lcl, gre_imp = is }
  422       | lcl = case greDefinitionModule gre of
  423                 Nothing -> []
  424                 Just m  -> [(moduleName m, Left (greDefinitionSrcSpan gre))]
  425       | otherwise = [ (is_as ispec, Right ispec)
  426                     | i <- bagToList is, let ispec = is_decl i ]
  427 
  428 isGreOk :: LookingFor -> GlobalRdrElt -> Bool
  429 isGreOk (LF what_look where_look) gre = what_ok && where_ok
  430   where
  431     -- when looking for record fields, what_ok checks whether the GRE is a
  432     -- record field. Otherwise, it checks whether the GRE is a record field
  433     -- defined in a module with -XNoFieldSelectors - it wouldn't be a useful
  434     -- suggestion in that case.
  435     what_ok  = case what_look of
  436                  WL_RecField -> isRecFldGRE gre
  437                  _           -> not (isNoFieldSelectorGRE gre)
  438 
  439     where_ok = case where_look of
  440                  WL_LocalTop  -> isLocalGRE gre
  441                  WL_LocalOnly -> False
  442                  _            -> True
  443 
  444 -- see Note [Related name spaces]
  445 nameSpacesRelated :: DynFlags    -- ^ to find out whether -XDataKinds is enabled
  446                   -> WhatLooking -- ^ What kind of name are we looking for
  447                   -> NameSpace   -- ^ Name space of the original name
  448                   -> NameSpace   -- ^ Name space of a name that might have been meant
  449                   -> Bool
  450 nameSpacesRelated dflags what_looking ns ns'
  451   = ns' `elem` ns : [ other_ns
  452                     | (orig_ns, others) <- other_namespaces
  453                     , ns == orig_ns
  454                     , (other_ns, wls) <- others
  455                     , what_looking `elem` WL_Anything : wls
  456                     ]
  457   where
  458     -- explanation:
  459     -- [(orig_ns, [(other_ns, what_looking_possibilities)])]
  460     -- A particular other_ns is related if the original namespace is orig_ns
  461     -- and what_looking is either WL_Anything or is one of
  462     -- what_looking_possibilities
  463     other_namespaces =
  464       [ (varName  , [(dataName, [WL_Constructor])])
  465       , (dataName , [(varName , [WL_RecField])])
  466       , (tvName   , (tcClsName, [WL_Constructor]) : promoted_datacons)
  467       , (tcClsName, (tvName   , []) : promoted_datacons)
  468       ]
  469     -- If -XDataKinds is enabled, the data constructor name space is also
  470     -- related to the type-level name spaces
  471     data_kinds = xopt LangExt.DataKinds dflags
  472     promoted_datacons = [(dataName, [WL_Constructor]) | data_kinds]
  473 
  474 {-
  475 Note [Related name space]
  476 ~~~~~~~~~~~~~~~~~~~~~~~~~
  477 Name spaces are related if there is a chance to mean the one when one writes
  478 the other, i.e. variables <-> data constructors and type variables <-> type
  479 constructors.
  480 
  481 In most contexts, this mistake can happen in both directions. Not so in
  482 patterns:
  483 
  484 When a user writes
  485         foo (just a) = ...
  486 It is possible that they meant to use `Just` instead. However, when they write
  487         foo (Map a) = ...
  488 It is unlikely that they mean to use `map`, since variables cannot be used here.
  489 
  490 Similarly, when we look for record fields, data constructors are not in a
  491 related namespace.
  492 
  493 Furthermore, with -XDataKinds, the data constructor name space is related to
  494 the type variable and type constructor name spaces.
  495 
  496 Note [When to show/hide the module-not-imported line]           -- #15611
  497 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  498 For the error message:
  499     Not in scope X.Y
  500     Module X does not export Y
  501     No module named ‘X’ is imported:
  502 there are 2 cases, where we hide the last "no module is imported" line:
  503 1. If the module X has been imported.
  504 2. If the module X is the current module. There are 2 subcases:
  505    2.1 If the unknown module name is in a input source file,
  506        then we can use the getModule function to get the current module name.
  507        (See test T15611a)
  508    2.2 If the unknown module name has been entered by the user in GHCi,
  509        then the getModule function returns something like "interactive:Ghci1",
  510        and we have to check the current module in the last added entry of
  511        the HomePackageTable. (See test T15611b)
  512 -}
  513 
  514 exactNameErr :: Name -> SDoc
  515 exactNameErr name =
  516   hang (text "The exact Name" <+> quotes (ppr name) <+> text "is not in scope")
  517     2 (vcat [ text "Probable cause: you used a unique Template Haskell name (NameU), "
  518             , text "perhaps via newName, but did not bind it"
  519             , text "If that's it, then -ddump-splices might be useful" ])