{-# LANGUAGE PatternGuards, RecordWildCards #-}

-- |  This module provides a way to apply HLint hints. If you want to just run @hlint@ in-process
--   and collect the results see 'hlint'.
--
--   If you want to approximate the @hlint@ experience with
--   a more structured API try:
--
-- @
-- (flags, classify, hint) <- 'autoSettings'
-- Right m <- 'parseModuleEx' flags \"MyFile.hs\" Nothing
-- print $ 'applyHints' classify hint [m]
-- @
module Language.Haskell.HLint(
    -- * Generate hints
    hlint, applyHints,
    -- * Idea data type
    Idea(..), Severity(..), Note(..), unpackSrcSpan, showIdeaANSI,
    -- * Settings
    Classify(..),
    getHLintDataDir, autoSettings, argsSettings,
    findSettings, readSettingsFile,
    -- * Hints
    Hint,
    -- * Modules
    ModuleEx, parseModuleEx, createModuleEx, ParseError(..),
    -- * Parse flags
    defaultParseFlags,
    ParseFlags(..), CppFlags(..), FixityInfo,
    parseFlagsAddFixities,
    ) where

import Config.Type
import Config.Read
import Idea
import qualified Apply as H
import HLint
import Fixity
import GHC.Data.FastString ( unpackFS )
import GHC.All
import Hint.All hiding (resolveHints)
import qualified Hint.All as H
import GHC.Types.SrcLoc
import CmdLine
import Paths_hlint

import Data.List.Extra
import Data.Maybe
import System.FilePath
import Data.Functor
import Prelude


-- | Get the Cabal configured data directory of HLint.
getHLintDataDir :: IO FilePath
getHLintDataDir :: IO FilePath
getHLintDataDir = IO FilePath
getDataDir


-- | The function produces a tuple containg 'ParseFlags' (for 'parseModuleEx'),
--   and 'Classify' and 'Hint' for 'applyHints'.
--   It approximates the normal HLint configuration steps, roughly:
--
-- 1. Use 'findSettings' with 'readSettingsFile' to find and load the HLint settings files.
--
-- 1. Use 'parseFlagsAddFixities' and 'resolveHints' to transform the outputs of 'findSettings'.
--
--   If you want to do anything custom (e.g. using a different data directory, storing intermediate outputs,
--   loading hints from a database) you are expected to copy and paste this function, then change it to your needs.
autoSettings :: IO (ParseFlags, [Classify], Hint)
autoSettings :: IO (ParseFlags, [Classify], Hint)
autoSettings = do
    ([FixityInfo]
fixities, [Classify]
classify, Hint
hints) <- (FilePath -> IO (FilePath, Maybe FilePath))
-> Maybe FilePath -> IO ([FixityInfo], [Classify], Hint)
findSettings (Maybe FilePath -> FilePath -> IO (FilePath, Maybe FilePath)
readSettingsFile Maybe FilePath
forall a. Maybe a
Nothing) Maybe FilePath
forall a. Maybe a
Nothing
    (ParseFlags, [Classify], Hint) -> IO (ParseFlags, [Classify], Hint)
forall (f :: * -> *) a. Applicative f => a -> f a
pure ([FixityInfo] -> ParseFlags -> ParseFlags
parseFlagsAddFixities [FixityInfo]
fixities ParseFlags
defaultParseFlags, [Classify]
classify, Hint
hints)


-- | A version of 'autoSettings' which respects some of the arguments supported by HLint.
--   If arguments unrecognised by HLint are used it will result in an error.
--   Arguments which have no representation in the return type are silently ignored.
argsSettings :: [String] -> IO (ParseFlags, [Classify], Hint)
argsSettings :: [FilePath] -> IO (ParseFlags, [Classify], Hint)
argsSettings [FilePath]
args = do
    cmd :: Cmd
cmd@CmdMain{Bool
Int
FilePath
[FilePath]
ColorMode
cmdTest :: Cmd -> Bool
cmdGenerateSummary :: Cmd -> [FilePath]
cmdIgnoreGlob :: Cmd -> [FilePath]
cmdWithRefactor :: Cmd -> FilePath
cmdRefactorOptions :: Cmd -> FilePath
cmdRefactor :: Cmd -> Bool
cmdSerialise :: Cmd -> Bool
cmdTiming :: Cmd -> Bool
cmdNoExitCode :: Cmd -> Bool
cmdOnly :: Cmd -> [FilePath]
cmdNoSummary :: Cmd -> Bool
cmdCC :: Cmd -> Bool
cmdJson :: Cmd -> Bool
cmdCppAnsi :: Cmd -> Bool
cmdCppSimple :: Cmd -> Bool
cmdCppFile :: Cmd -> [FilePath]
cmdCppInclude :: Cmd -> [FilePath]
cmdCppDefine :: Cmd -> [FilePath]
cmdPath :: Cmd -> [FilePath]
cmdDefault :: Cmd -> Bool
cmdDataDir :: Cmd -> FilePath
cmdFindHints :: Cmd -> [FilePath]
cmdCross :: Cmd -> Bool
cmdLanguage :: Cmd -> [FilePath]
cmdExtension :: Cmd -> [FilePath]
cmdShowAll :: Cmd -> Bool
cmdIgnore :: Cmd -> [FilePath]
cmdThreads :: Cmd -> Int
cmdColor :: Cmd -> ColorMode
cmdGit :: Cmd -> Bool
cmdWithGroups :: Cmd -> [FilePath]
cmdGivenHints :: Cmd -> [FilePath]
cmdReports :: Cmd -> [FilePath]
cmdFiles :: Cmd -> [FilePath]
cmdTest :: Bool
cmdGenerateSummary :: [FilePath]
cmdIgnoreGlob :: [FilePath]
cmdWithRefactor :: FilePath
cmdRefactorOptions :: FilePath
cmdRefactor :: Bool
cmdSerialise :: Bool
cmdTiming :: Bool
cmdNoExitCode :: Bool
cmdOnly :: [FilePath]
cmdNoSummary :: Bool
cmdCC :: Bool
cmdJson :: Bool
cmdCppAnsi :: Bool
cmdCppSimple :: Bool
cmdCppFile :: [FilePath]
cmdCppInclude :: [FilePath]
cmdCppDefine :: [FilePath]
cmdPath :: [FilePath]
cmdDefault :: Bool
cmdDataDir :: FilePath
cmdFindHints :: [FilePath]
cmdCross :: Bool
cmdLanguage :: [FilePath]
cmdExtension :: [FilePath]
cmdShowAll :: Bool
cmdIgnore :: [FilePath]
cmdThreads :: Int
cmdColor :: ColorMode
cmdGit :: Bool
cmdWithGroups :: [FilePath]
cmdGivenHints :: [FilePath]
cmdReports :: [FilePath]
cmdFiles :: [FilePath]
..} <- [FilePath] -> IO Cmd
getCmd [FilePath]
args
    -- FIXME: One thing that could be supported (but isn't) is 'cmdGivenHints'
    (Cmd
_,[Setting]
settings) <- [FilePath] -> Cmd -> IO (Cmd, [Setting])
readAllSettings [FilePath]
args Cmd
cmd
    let ([FixityInfo]
fixities, [Classify]
classify, Hint
hints) = [Setting] -> ([FixityInfo], [Classify], Hint)
splitSettings [Setting]
settings
    let flags :: ParseFlags
flags = (Maybe Language, ([Extension], [Extension]))
-> ParseFlags -> ParseFlags
parseFlagsSetLanguage (Cmd -> (Maybe Language, ([Extension], [Extension]))
cmdExtensions Cmd
cmd) (ParseFlags -> ParseFlags) -> ParseFlags -> ParseFlags
forall a b. (a -> b) -> a -> b
$ [FixityInfo] -> ParseFlags -> ParseFlags
parseFlagsAddFixities [FixityInfo]
fixities (ParseFlags -> ParseFlags) -> ParseFlags -> ParseFlags
forall a b. (a -> b) -> a -> b
$
                ParseFlags
defaultParseFlags{cppFlags :: CppFlags
cppFlags = Cmd -> CppFlags
cmdCpp Cmd
cmd}
    let ignore :: [Classify]
ignore = [Severity -> FilePath -> FilePath -> FilePath -> Classify
Classify Severity
Ignore FilePath
x FilePath
"" FilePath
"" | FilePath
x <- [FilePath]
cmdIgnore]
    (ParseFlags, [Classify], Hint) -> IO (ParseFlags, [Classify], Hint)
forall (f :: * -> *) a. Applicative f => a -> f a
pure (ParseFlags
flags, [Classify]
classify [Classify] -> [Classify] -> [Classify]
forall a. [a] -> [a] -> [a]
++ [Classify]
ignore, Hint
hints)


-- | Given a directory (or 'Nothing' to imply 'getHLintDataDir'), and a module name
--   (e.g. @HLint.Default@), find the settings file associated with it, returning the
--   name of the file, and (optionally) the contents.
--
--   This function looks for all settings files starting with @HLint.@ in the directory
--   argument, and all other files relative to the current directory.
readSettingsFile :: Maybe FilePath -> String -> IO (FilePath, Maybe String)
readSettingsFile :: Maybe FilePath -> FilePath -> IO (FilePath, Maybe FilePath)
readSettingsFile Maybe FilePath
dir FilePath
x
    | FilePath -> FilePath
takeExtension FilePath
x FilePath -> [FilePath] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` [FilePath
".yml",FilePath
".yaml"] = do
        FilePath
dir <- IO FilePath
-> (FilePath -> IO FilePath) -> Maybe FilePath -> IO FilePath
forall b a. b -> (a -> b) -> Maybe a -> b
maybe IO FilePath
getHLintDataDir FilePath -> IO FilePath
forall (f :: * -> *) a. Applicative f => a -> f a
pure Maybe FilePath
dir
        (FilePath, Maybe FilePath) -> IO (FilePath, Maybe FilePath)
forall (f :: * -> *) a. Applicative f => a -> f a
pure (FilePath
dir FilePath -> FilePath -> FilePath
</> FilePath
x, Maybe FilePath
forall a. Maybe a
Nothing)
    | Just FilePath
x <- FilePath
"HLint." FilePath -> FilePath -> Maybe FilePath
forall a. Eq a => [a] -> [a] -> Maybe [a]
`stripPrefix` FilePath
x = do
        FilePath
dir <- IO FilePath
-> (FilePath -> IO FilePath) -> Maybe FilePath -> IO FilePath
forall b a. b -> (a -> b) -> Maybe a -> b
maybe IO FilePath
getHLintDataDir FilePath -> IO FilePath
forall (f :: * -> *) a. Applicative f => a -> f a
pure Maybe FilePath
dir
        (FilePath, Maybe FilePath) -> IO (FilePath, Maybe FilePath)
forall (f :: * -> *) a. Applicative f => a -> f a
pure (FilePath
dir FilePath -> FilePath -> FilePath
</> FilePath
x FilePath -> FilePath -> FilePath
<.> FilePath
"hs", Maybe FilePath
forall a. Maybe a
Nothing)
    | Bool
otherwise = (FilePath, Maybe FilePath) -> IO (FilePath, Maybe FilePath)
forall (f :: * -> *) a. Applicative f => a -> f a
pure (FilePath
x FilePath -> FilePath -> FilePath
<.> FilePath
"hs", Maybe FilePath
forall a. Maybe a
Nothing)


-- | Given a function to load a module (typically 'readSettingsFile'), and a module to start from
--   (defaults to @hlint.yaml@) find the information from all settings files.
findSettings :: (String -> IO (FilePath, Maybe String)) -> Maybe String -> IO ([FixityInfo], [Classify], Hint)
findSettings :: (FilePath -> IO (FilePath, Maybe FilePath))
-> Maybe FilePath -> IO ([FixityInfo], [Classify], Hint)
findSettings FilePath -> IO (FilePath, Maybe FilePath)
load Maybe FilePath
start = do
    (FilePath
file,Maybe FilePath
contents) <- FilePath -> IO (FilePath, Maybe FilePath)
load (FilePath -> IO (FilePath, Maybe FilePath))
-> FilePath -> IO (FilePath, Maybe FilePath)
forall a b. (a -> b) -> a -> b
$ FilePath -> Maybe FilePath -> FilePath
forall a. a -> Maybe a -> a
fromMaybe FilePath
"hlint.yaml" Maybe FilePath
start
    [Setting] -> ([FixityInfo], [Classify], Hint)
splitSettings ([Setting] -> ([FixityInfo], [Classify], Hint))
-> IO [Setting] -> IO ([FixityInfo], [Classify], Hint)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> [(FilePath, Maybe FilePath)] -> IO [Setting]
readFilesConfig [(FilePath
file,Maybe FilePath
contents)]

-- | Split a list of 'Setting' for separate use in parsing and hint resolution
splitSettings :: [Setting] -> ([FixityInfo], [Classify], Hint)
splitSettings :: [Setting] -> ([FixityInfo], [Classify], Hint)
splitSettings [Setting]
xs =
    ([FixityInfo
x | Infix FixityInfo
x <- [Setting]
xs]
    ,[Classify
x | SettingClassify Classify
x <- [Setting]
xs]
    ,[Either HintBuiltin HintRule] -> Hint
H.resolveHints ([Either HintBuiltin HintRule] -> Hint)
-> [Either HintBuiltin HintRule] -> Hint
forall a b. (a -> b) -> a -> b
$ [HintRule -> Either HintBuiltin HintRule
forall a b. b -> Either a b
Right HintRule
x | SettingMatchExp HintRule
x <- [Setting]
xs] [Either HintBuiltin HintRule]
-> [Either HintBuiltin HintRule] -> [Either HintBuiltin HintRule]
forall a. [a] -> [a] -> [a]
++ (HintBuiltin -> Either HintBuiltin HintRule)
-> [HintBuiltin] -> [Either HintBuiltin HintRule]
forall a b. (a -> b) -> [a] -> [b]
map HintBuiltin -> Either HintBuiltin HintRule
forall a b. a -> Either a b
Left [HintBuiltin]
forall a. (Enum a, Bounded a) => [a]
enumerate)


-- | Given a way of classifying results, and a 'Hint', apply to a set of modules generating a list of 'Idea's.
--   The 'Idea' values will be ordered within a file.
--
--   Given a set of modules, it may be faster to pass each to 'applyHints' in a singleton list.
--   When given multiple modules at once this function attempts to find hints between modules,
--   which is slower and often pointless (by default HLint passes modules singularly, using
--   @--cross@ to pass all modules together).
applyHints :: [Classify] -> Hint -> [ModuleEx] -> [Idea]
applyHints :: [Classify] -> Hint -> [ModuleEx] -> [Idea]
applyHints = [Classify] -> Hint -> [ModuleEx] -> [Idea]
H.applyHints

-- | Snippet from the documentation, if this changes, update the documentation
_docs :: IO ()
_docs :: IO ()
_docs = do
    (ParseFlags
flags, [Classify]
classify, Hint
hint) <- IO (ParseFlags, [Classify], Hint)
autoSettings
    Right ModuleEx
m <- ParseFlags
-> FilePath -> Maybe FilePath -> IO (Either ParseError ModuleEx)
parseModuleEx ParseFlags
flags FilePath
"MyFile.hs" Maybe FilePath
forall a. Maybe a
Nothing
    [Idea] -> IO ()
forall a. Show a => a -> IO ()
print ([Idea] -> IO ()) -> [Idea] -> IO ()
forall a b. (a -> b) -> a -> b
$ [Classify] -> Hint -> [ModuleEx] -> [Idea]
applyHints [Classify]
classify Hint
hint [ModuleEx
m]

-- | Unpack a 'SrcSpan' value. Useful to allow using the 'Idea' information without
--   adding a dependency on @ghc@ or @ghc-lib-parser@. Unpacking gives:
--
-- > (filename, (startLine, startCol), (endLine, endCol))
--
--   Following the GHC API, he end column is the column /after/ the end of the error.
--   Lines and columns are 1-based. Returns 'Nothing' if there is no helpful location information.
unpackSrcSpan :: SrcSpan -> Maybe (FilePath, (Int, Int), (Int, Int))
unpackSrcSpan :: SrcSpan -> Maybe (FilePath, (Int, Int), (Int, Int))
unpackSrcSpan (RealSrcSpan RealSrcSpan
x Maybe BufSpan
_) = (FilePath, (Int, Int), (Int, Int))
-> Maybe (FilePath, (Int, Int), (Int, Int))
forall a. a -> Maybe a
Just
    (FastString -> FilePath
unpackFS (FastString -> FilePath) -> FastString -> FilePath
forall a b. (a -> b) -> a -> b
$ RealSrcSpan -> FastString
srcSpanFile RealSrcSpan
x
    ,(RealSrcSpan -> Int
srcSpanStartLine RealSrcSpan
x, RealSrcSpan -> Int
srcSpanStartCol RealSrcSpan
x)
    ,(RealSrcSpan -> Int
srcSpanEndLine RealSrcSpan
x, RealSrcSpan -> Int
srcSpanEndCol RealSrcSpan
x))
unpackSrcSpan SrcSpan
_ = Maybe (FilePath, (Int, Int), (Int, Int))
forall a. Maybe a
Nothing