hlint 1.8.55 → 1.8.56
raw patch · 21 files changed
+711/−417 lines, 21 files
Files
- CHANGES.txt +389/−0
- LICENSE +1/−1
- README.md +204/−0
- data/Default.hs +27/−8
- data/Test.hs +18/−1
- hlint.cabal +4/−3
- hlint.htm +0/−340
- src/Apply.hs +3/−2
- src/CmdLine.hs +3/−2
- src/HLint.hs +3/−2
- src/HSE/All.hs +2/−1
- src/HSE/Util.hs +1/−1
- src/Hint/Extensions.hs +1/−1
- src/Hint/Import.hs +3/−2
- src/Hint/List.hs +3/−3
- src/Hint/Match.hs +19/−6
- src/Hint/Monad.hs +6/−5
- src/Proof.hs +2/−1
- src/Settings.hs +12/−13
- src/Test.hs +7/−9
- src/Util.hs +3/−16
+ CHANGES.txt view
@@ -0,0 +1,389 @@+Changelog for HLint++1.8.56+ Remove support for GHC 6.12 and below+ #317, tone down the void hint+ #16, match not . not (and reverse . reverse etc)+ Suggest <$> instead of fmap f $ ...+ Tweak some priorities, make >=> a warn and void an error+ #3, make top of the file ANN pragmas work+ #10, add a suggestion to use unlines+ #11, add a few hints about characters+ #8, add CHANGES.txt to the Cabal package+1.8.55+ #627, fix the UnboxedTuples extension warning+1.8.54+ Fix a bug when suggesting const+1.8.53+ Fix some corner cases when suggesting foldr etc.+ #517, don't introduce new free variables in a replacement+1.8.52+ #2, Generic is not newtype derivable+1.8.51+ Upgrade to haskell-src-exts-1.14+1.8.50+ Eliminate upper bounds on all dependencies+ #617, fix up notIn to take account of Template Haskell variables+ #573, suggest removing various deriving language extensions+1.8.49+ Remove ^^ ==> ** hint+ Remove a duplicate sqrt hint+ Ensure that --test failures throws an error+ Fix up the copyright year in --help+1.8.48+ Brackets at the root of annotations are fine+ Reduce a few more lambda expressions+1.8.47+ #613, compatibility with base-4.7+1.8.46+ Remove incorrect isPrefixOf hints+ #586, add span/break/takeWhile/dropWhile hints+ #588, add sort/reverse hints+ #601, add replicate/map/repeat hints+ Add a hint about reverse/reverse+ Add side as an alias for _+ Add hint as an alias for error+1.8.45+ #600, hints for unnecessary lazy annotations+1.8.44+ #598, warn on unnecessary bang patterns+1.8.43+ Change some hint error/warning levels+1.8.42+ Allow cpphs-1.16+1.8.41+ #586, add a rule for takeWhile/dropWhile ==> span+ #522, add hints for the state monad+ #499, fix up the test suite+ Fix the side conditions for the `isPrefixOf` hint+ Add hints about take/drop on non positive numbers+ Add isNat/isPos/isNeg/isNegPos as notes+ Make the notes a structured type+ Add --proof feature+ Retire the Prelude.catch hint+ Additional boolean equality hints+1.8.40+ #585, lots of additional list based hints+1.8.39+ #582, don't suggest renaming with trailingHashes#+1.8.38+ #578, treat _ bindings differently in lambdas+1.8.37+ #575, allow cpphs-1.15+1.8.36+ Make --with imply no default Hint files+1.8.35+ #567, avoid duplicate hints around (.) hints+1.8.34+ Switch license from GPL to BSD3+1.8.33+ Lots more hints on laziness, foldable and a few others+ Use mapM_ etc in more situations, when using explicit >>=+1.8.32+ Add notes about how to deal with imported fixites+ Add a --with flag for passing settings on the command line+ #563, make sure TypeSig hints get the right function name+ Update the copyright year to 2012+ #564, allow brackets and type signatures on annotations+ Add a note that about using !! if the index is negative+1.8.31+ Avoid incomplete patterns when reading ANN pragmas+ #555, top-level expressions require TemplateHaskell+1.8.30+ Add elemIndex/elemIndices hints+ Allow cpphs-1.14+ #551, allow case_ as a name with an underscore+1.8.29+ Allow hscolor-1.20.*+ #574, add a hint to for mapM/zip ==> zipWithM+1.8.28+ Fix a bug, >=> hint was missing check about removal of free var+1.8.27+ Allow haskell-src-exts-1.13.*+1.8.26+ Allow haskell-src-exts-1.12.*+ Don't suggest redundant brackets when turning ++ into :+ Add hints suggesting >=> and <=<+1.8.25+ Update the copyright year in the Cabal file+ Allow transformers-0.3.*+1.8.24+ #531, Make hlint.ghci well formed again+1.8.23+ Add hints for redundant seq/evaluate using isWHNF+ #526, don't hint for return $! (x :: Int)+1.8.22+ Add hint for $! where the RHS is not a variable+1.8.21+ #508, add lots of hints from the base library+ #317, add hints for a >> return () to void+ Add a fromMaybe/fmap ==> maybe hint+ #304, don't backet tuple sections+ Add foldl (++) [] ==> concat+ #512, detect unnecessary case construct+ When finding hints, don't abort on a parse error+ #507, add exitSuccess hint+ #505, suggest record patterns+1.8.20+ #500, make sure eta reduction has position information+1.8.19+ #498, eta reduce even if there is a where block+ #497, don't produce an incorrect lambda when suggesting flip+1.8.18+ #438, use Foo.Bar to mean Foo/Bar.hs+ Add a --path command line option to say where files live+ #441, avoid bad matches due to automatically eta reducing rules+ #489, import Foo as Foo is redundant+ #481, suggest liftM instead of fmap when using the Monad laws+1.8.17+ #479, allow - as the file to specify using stdin+1.8.16+ #478, allow cpphs-1.13.1+ Never suggest view patterns (they aren't sufficiently better)+ Don't suggest use of Data.Ord.comparing, using `on` is better+ Only suggest elem/notElem on 3 or more items+1.8.15+ Add --cpp-ansi to turn on ANSI compat in cpphs+1.8.14+ #455, GHC 7.2 compatibility+ Add lots of hints from Lennart Augustsson+1.8.13+ #302, add a backup fixity analysis, if the HSE one fails+ Fix x /= y || x /= z ==> x `notElem` [y,z], should be &&+1.8.12+ Allow cpphs-1.12+1.8.11+ #440, suggest removing redundant brackets under do+ #439, don't add redundant brackets under do+1.8.10+ Upgrade to hscolour-1.19+1.8.9+ #436, add a hint about mapMaybe/map+ Upgrade to haskell-src-exts-1.11.1+ Add a --cross flag, to detect hints between multiple modules+ #428, don't suggest using String in an instance head+1.8.8+ #384, suggest collapsing multiple imports/exports+ #374, don't suggest the removal of necessary brackets+ #337, suggest Control.Exception.catch instead of Prelude.catch+ #412, add hints based on Control.Exception+ #378, suggest removing fromInteger/fromIntegral on literals+ #369, add notes to a few hints about possible pitfalls+ #409, fix a few cases where definitions suggested themselves+ #410, Support test* as ignored items in settings files+ #414, add isLit* pattern, and hint about ^^ ==> **+ #420, make the suggestion to use let a warning+ #408, rework the when/unless hints, don't suggest on itself+ Add duplicate detector, for copy/pasted code+ #285, don't show duplicate filepath separators+ If the user enters directories containing no files then say+ Make suggesting curry/uncurry a warning instead of an error+1.8.7+ Relax the transformers dependency, works with 0.0.* and 0.1.*+1.8.6+ Export suggestionSeverity/Severity from the API+ Allow hint imports with "hlint", as well as the existing "hint"+1.8.5+ Update the copyright year to 2011+ #400, support more encoding strings, give useful errors+ #401, rename the report template to report_template.html+ Replace filter f x /= [] with any f x, and 2 more similar+1.8.4+ #308, allow haskell-src-exts-1.10.1, which parses Unicode better+ import qualified Char ==> import qualified Data.Char as Char+ #393, fix suggestion for import IO, requires more than System.IO+ #376, note that RecordWildCards implies DisambiguateRecordFields+1.8.3+ Allow uniplate-1.6+ Switch from mtl to transformers+ #373, require haskell-src-exts-1.9.6+ Add a type signature for GHC 7+ Suggest [x | x <- xs] ==> xs, if x is a variable+1.8.2+ #371, foo (\x -> y :: Int -> Int) is not a redundant bracket+ Add a hint to use just equality rather than isJust/fromJust+1.8.1+ Massive speed up for files with many naming hints+ #361, keep module names when suggesting infix+ Add support for wildcard matching on module names+ #357, don't camel case suggest on FOO_A+ #370, fix building with GHC 6.10.4+ #313, upgrade to haskell-src-exts-1.9.4+ Workaround for #358, disable empty where hints+ #355, make "--ignore=Parse error" work+ Add --cpp-simple to run a simple CPP to strip lines begining #+ Add bracketing information if the parent is a case+ Suggest intercalate+1.8+ Make --test --hint=file typecheck a file for valid hints+ #347, Suggest use of otherwise, instead of True, in pattern guards+ Add hints about redundant where statements+ Suggest removal of redundant guards+ Make hints about guards work on patterns/infix matches/case alts+ Make finding guards look a child functions+ Correctly collapse functions and lambdas using the same patterns+ Suggest promoting patterns bound to lambdas to functions+ Allow collapsing lambdas sharing pattern variables correctly+ #344, only give one warning for multiple collapsable lambdas+ #300, substantially improve module name resolution with imports+ BREAKING: imports in hint files require import "hint" HintFile+ #335, redundant id should only generate one warning+ Add a hint for using map (f &&& g)+ #328, for foo'bar suggest the naming fooBar+ #323, detect redundant brackets in field declarations+ #321, force the whole file before displaying a parse error+ Make --find more robust, fixes a potential parse error+1.7.3+ Upgrade to hscolour-1.17+1.7.2+ #318, match rules by expanding out (.)+ #319, don't remove lambdas on the right of infix operators+1.7.1+ Add a --quiet flag, to supress stdout (mainly for API users)+1.7+ Add support for HLint.Builtin.All+ Fix crash on (\x -> x)+ Make the library correctly honour the data directory+ Improve the manual, mainly language changes and hyperlinking+ Fix a bug in ListRec, could have _recursive_ in the result+ #315, spot list rec hints through $ and let+ Add hints based on (f $) ==> f, and change in ListRec hints+ Changes to the lambda suggestions, now gives a few more hints+ Don't suggest importing modules in old-locale/old-time+ Make the API return the suggestions, rather than just the count+ #278, add -XNoCpp to disable the C preprocessor+ #279, add -XExt/-XNoExt to choose extensions+ Remove some redundant brackets in type replacements+ #286, remove redundant brackets in match+ Additional bracket removal, application under sections+ #299, rework hints to use flip (suggest infix in some cases)+ Add some fromMaybe hints+ Fix bug where hints didn't always get names+ #306, make --find use the hints if there are files specified+ Upgrade to haskell-src-exts-1.9+ #303, allow fixities to be specified in hint files+1.6.21+ #287, warn about Haskell 98 imports+ #297, add a hint to use mplus+ #288, detect redundant brackets under a lambda+ #302, remove error about ambiguous fixities+ #281, enhance the redundant monad return warnings+ #293, eliminate _noParen_ from the result+ #284, eliminate ViewPatterns from FindHints, hits compiler bug+ #283, don't suggest removal of RecordWildCards+ Add some hints about concat and (++)+ #273, require haskell-src-exts >= 1.8.2+1.6.20+ #275, add more acknowledgements (still very incomplete)+ #254, remove the foldr1/map hint+ Compress nested lambdas, \x -> \y -> ... ==> \x y -> ...+ Fix minor bug on \x -> \x -> foo x x+ #274, add redundant bracket inside record update/construct+ #272, don't mess up creating sections from qualified names+ Add some hints to suggest elem+ Add Paths_hlint to the .cabal file, or the library doesn't link+ #271, rewrite the match engine in terms of SYB+1.6.19+ #251, add automatic definition hunting with --find+ #268, rewrite the (.) expansion in hints to fix various bugs+ #269, replacing a case with an if should generate one hint+ Document the ANN pragmas+ Require haskell-src-exts-1.8.1+1.6.18+ Remove a hint replacing do x <- foo; bar x with foo >>= bar+ #263, support CPP files more fully+ Upgrade to hscolour-1.16+ Upgrade to cpphs-1.11+1.6.17+ Force cpphs-1.10, since 1.11 breaks the interface+ More hints from the Data.Maybe module+ #262, add support for the TupleSections extension+ #264, upgrade to haskell-src-exts-1.8.*, fixes QuasiQuote pos+ Upgrade to cpphs 1.10+ #266, don't match hints that appear to be the definitions+ #248, tone down the eta reduction hints+ Add support for WARNING pragma's to reclassify hints+ Support ignoring hints on types+ Give better error messages on incorrect settings files+ Add temporary haskell-src-exts 1.5/1.6 compatibility+ #327, add hints to use expressions infix+ #240, if a then True else False no longer suggests a || False+ Upgrade to haskell-src-exts-1.7.*+ #236, support changing the text encoding with --encoding/--utf8+ #260, generate nicer lambdas for (($) . f)+ Add the hint (($) . f) ==> (f $)+1.6.16+ Further performance enhancements (for details see my blog)+ Update to uniplate 1.5.* (fixes performance bug)+ Improve speed based on profiling (roughly twice as fast)+ #245, add hints for excess brackets in types and patterns+ Make 100% redundant brackets an error+ Fix bug where qualified names did not match+ Remove dependency on SYB+ #234, allow TH top-level splices for ignore+ #110, add tests for ignoring commands+1.6.15+ Upgrade to uniplate 1.4.* (fixes performance bug)+ #192, make HLint into a fairly basic library+ Add --datadir to allow running with a different data directory+ #254, eliminate foldl/map fusion rules (which were untrue)+ Fix a few typos in the hint rules+ Upgrade to uniplate 1.3.*+ Upgrade to haskell-src-exts 1.6.*+ Add a .ghci file snippet+ #247, Fix bug matching expressions containing position info+1.6.14+ Upgrade to haskell-src-exts 1.5.*+1.6.13+ #246, redundant brackets in [(...)]+ Add fold/map fusion hints+ Don't suggest namings that are already used in the module+ #239, Add suggestions of and/or on foldl+ Add --extension flag, to find files not named .hs/.lhs+ Only activate the builtin hints when they are imported+ Fix matching bug, said "Use flip" on "\v -> f v . g"+ Suggest changing some pattern guards to view patterns+1.6.12+ Fix a bug with ignored hints being written to reports+ Upgrade to haskell-src-exts 1.3.*+ #228, suggest let instead of <- return in do statements+ #229, suggest comparing+ Qualify all non-Prelude function suggestions+ #225, Add redundant flip hint+ #226, Add ((+) x) ==> (x +)+ #223, TemplateHaskell may allow other extensions via code+ Fix incorrect suggestion on do x <- f ; g x x+ A few small additional hints (use flip, redundant id)+1.6.11+ Don't perform type eta reduction+1.6.10+ Fix bug, eta reduction on chained infix operators, i.e. x#y#z+1.6.9+ #217, don't suggest eta reduction on - or ++ Fix bug, PatternGuards under case alternatives were ignored+1.6.8+ #213, upgrade to cpphs 1.9+ Add suggestion to replace lambda with operator sections+ Fix bug, ''Name decided TemplateHaskell was unnecessary+ HPC statistics, and increase in test coverage+ Fix bug, import A as Y; import A gave import A, missing the as Y+ Fix bug, type Foo a = Bar a a incorrectly suggested eta reduce+1.6.7+ NOTE: #213 has not been fixed, cpphs can cause hangs+ Add threaded flag to Cabal to disable -threaded mode+ #212, fix crash+ Fix bug, incorrectly decided TemplateHaskell was unnecessary+1.6.6+ Upgrade to hscolour 1.15+ Add a hint for using unless+ #211, add hints for unused extensions+ #188, add pragma hints+ Add a few additional hints (Functor laws)+ #137, add cpphs support+ #189, give hints for redundant imports+ Upgrade to haskell-src-exts 1.1.*+1.6.5+ #206, better presentation of parse errors+ #208, give the correct precedence to ==> in source files+1.6.4+ Start of changelog
LICENSE view
@@ -1,4 +1,4 @@-Copyright Neil Mitchell 2006-2013.+Copyright Neil Mitchell 2006-2014. All rights reserved. Redistribution and use in source and binary forms, with or without
+ README.md view
@@ -0,0 +1,204 @@+# HLint [](https://travis-ci.org/ndmitchell/hlint)++HLint is a tool for suggesting possible improvements to Haskell code. These suggestions include ideas such as using alternative functions, simplifying code and spotting redundancies. This document is structured as follows:++* [Installing and running HLint](#installing-and-running-hlint)+* [FAQ](#faq)+* [Customizing the hints](#customizing-the-hints)++### Acknowledgements++This program has only been made possible by the presence of the [haskell-src-exts](http://www.cs.chalmers.se/~d00nibro/haskell-src-exts/) package, and many improvements have been made by [Niklas Broberg](http://www.cs.chalmers.se/~d00nibro/) in response to feature requests. Additionally, many people have provided help and patches, including Lennart Augustsson, Malcolm Wallace, Henk-Jan van Tuyl, Gwern Branwen, Alex Ott, Andy Stewart, Roman Leshchinskiy and others.++### Bugs and limitations++Bugs can be reported [on the bug tracker](https://github.com/ndmitchell/hlint/issues). There are three common issues that I do not intend to fix:++* The presence of `seq` may cause some hints (i.e. eta-reduction) to change the semantics of a program.+* Either the monomorphism restriction, or rank-2 types, may cause transformed programs to require type signatures to be manually inserted.+* HLint operates on each module at a time in isolation, as a result HLint does not know about types or which names are in scope.++## Installing and running HLint++Installation follows the standard pattern of any Haskell library or program, type `cabal update` to update your local hackage database, then `cabal install hlint` to install HLint.++Once HLint is installed, run hlint source where source is either a Haskell file, or a directory containing Haskell files. A directory will be searched recursively for any files ending with .hs or .lhs. For example, running HLint over darcs would give:+++ $ hlint darcs-2.1.2++ darcs-2.1.2\src\CommandLine.lhs:94:1: Error: Use concatMap+ Found:+ concat $ map escapeC s+ Why not:+ concatMap escapeC s++ darcs-2.1.2\src\CommandLine.lhs:103:1: Warning: Use fewer brackets+ Found:+ ftable ++ (map (\ (c, x) -> (toUpper c, urlEncode x)) ftable)+ Why not:+ ftable ++ map (\ (c, x) -> (toUpper c, urlEncode x)) ftable++ darcs-2.1.2\src\Darcs\Patch\Test.lhs:306:1: Error: Use a more efficient monadic variant+ Found:+ mapM (delete_line (fn2fp f) line) old+ Why not:+ mapM_ (delete_line (fn2fp f) line) old++ ... lots more suggestions ...++Each suggestion says which file/line the suggestion relates to, how serious the issue is, a description of the issue, what it found, and what you might want to replace it with. In the case of the first hint, it has suggested that instead of applying `concat` and `map` separately, it would be better to use the combination function `concatMap`.++The first suggestion is marked as an error, because using `concatMap` in preference to the two separate functions is always desirable. In contrast, the removal of brackets is probably a good idea, but not always. Reasons that a hint might be a warning include requiring an additional import, something not everyone agrees on, and functions only available in more recent versions of the base library.++**Bug reports:** The suggested replacement should be equivalent - please report all incorrect suggestions not mentioned as known limitations.++### Reports++HLint can generate a lot of information, making it difficult to search for particular types of errors. The `--report` flag will cause HLint to generate a report file in HTML, which can be viewed interactively. Reports are recommended when there are more than a handlful of hints.++### Language Extensions++HLint enables most Haskell extensions, disabling only those which steal too much syntax (currently Arrows, TransformListComp, XmlSyntax and RegularPatterns). Individual extensions can be enabled or disabled with, for instance, `-XArrows`, or `-XNoMagicHash`. The flag `-XHaskell98` selects Haskell 98 compatibility.++### Emacs Integration++Emacs integration has been provided by [Alex Ott](http://xtalk.msk.su/~ott/). The integration is similar to compilation-mode, allowing navigation between errors. The script is at [hs-lint.el](http://community.haskell.org/~ndm/darcs/hlint/data/hs-lint.el), and a copy is installed locally in the data directory. To use, add the following code to the Emacs init file:++ (require 'hs-lint)+ (defun my-haskell-mode-hook ()+ (local-set-key "\C-cl" 'hs-lint))+ (add-hook 'haskell-mode-hook 'my-haskell-mode-hook)++### GHCi Integration++GHCi integration has been provided by Gwern Branwen. The integration allows running `:hlint` from the GHCi prompt. The script is at [hlint.ghci](http://community.haskell.org/~ndm/darcs/hlint/data/hlint.ghci), and a copy is installed locally in the data directory. To use, add the contents to your [GHCi startup file](http://www.haskell.org/ghc/docs/latest/html/users_guide/ghci-dot-files.html).++### Parallel Operation++To run HLint on n processors append the flags `+RTS -Nn`, as described in the [GHC user manual](http://www.haskell.org/ghc/docs/latest/html/users_guide/runtime-control.html). HLint will usually perform fastest if n is equal to the number of physical processors.++If your version of GHC does not support the GHC threaded runtime then install with the command: `cabal install --flags="-threaded"`++### C preprocessor support++HLint runs the [cpphs C preprocessor](http://hackage.haskell.org/package/cpphs) over all input files, by default using the current directory as the include path with no defined macros. These settings can be modified using the flags `--cpp-include` and `--cpp-define`. To disable the C preprocessor use the flag `-XNoCPP`. There are a number of limitations to the C preprocessor support:++* HLint will only check one branch of an `#if`, based on which macros have been defined.+* Any missing `#include` files will produce a warning on the console, but no information in the reports.++### Unicode support++By default, HLint uses the current locale encoding. The encoding can be overriden with either `--utf8` or `--encoding=value`. For descriptions of some valid [encodings see the mkTextEncoding documentation](http://haskell.org/ghc/docs/latest/html/libraries/base/System-IO.html#v%3AmkTextEncoding).++## FAQ++### Why are suggestions not applied recursively?++Consider:++ foo xs = concat (map op xs)++This will suggest eta reduction to `concat . map op`, and then after making that change and running HLint again, will suggest use of `concatMap`. Many people wonder why HLint doesn't directly suggest `concatMap op`. There are a number of reasons:++* HLint aims to both improve code, and to teach the author better style. Doing modifications individually helps this process.+* Sometimes the steps are reasonably complex, by automatically composing them the user may become confused.+* Sometimes HLint gets transformations wrong. If suggestions are applied recursively, one error will cascade.+* Some people only make use of some of the suggestions. In the above example using concatMap is a good idea, but sometimes eta reduction isn't. By suggesting them separately, people can pick and choose.+* Sometimes a transformed expression will be large, and a further hint will apply to some small part of the result, which appears confusing.+* Consider `f $ (a b)`. There are two valid hints, either remove the $ or remove the brackets, but only one can be applied.++### Why aren't the suggestions automatically applied?++If you want to automatically apply suggestions, the [Emacs integration](https://rawgithub.com/ndmitchell/hlint/master/hlint.htm#emacs) offers such a feature. However, there are a number of reasons that HLint itself doesn't have an option to automatically apply suggestions:++* The underlying Haskell parser library makes it hard to modify the code, then print it similarly to the original.+* Sometimes multiple transformations may apply.+* After applying one transformation, others that were otherwise suggested may become inappropriate.++I am intending to develop such a feature, but the above reasons mean it is likely to take some time.++### Why doesn't the compiler automatically apply the optimisations?++HLint doesn't suggest optimisations, it suggests code improvements - the intention is to make the code simpler, rather than making the code perform faster. The [GHC compiler](http://haskell.org/ghc/) automatically applies many of the rules suggested by HLint, so HLint suggestions will rarely improve performance.++### Why doesn't HLint know the fixity for my custom !@%$ operator?++HLint knows the fixities for all the operators in the base library, but no others. HLint works on a single file at a time, and does not resolve imports, so cannot see fixity declarations from imported modules. You can tell HLint about fixities by putting them in a hint file, or passing them on the command line. For example, pass `--with=infixr 5 !@%$`, or put all the fixity declarations in a file and pass `--hint=fixities.hs`. You can also use [--find](https://rawgithub.com/ndmitchell/hlint/master/hlint.htm#find) to automatically produce a list of fixity declarations in a file.++### How can I use `--with` or `--hint` with the default hints?++HLint does not use the default set of hints if custom hints are specified on the command line using `--with` or `--hint`. To include the default hints either pass `--hint=HLint` on the command line, or add import `"hint" HLint.HLint` in one of the hint files you specify with `--hint`.++### Why do I sometimes get a "Note" with my hint?++Most hints are perfect substitutions, and these are displayed without any notes. However, some hints change the semantics of your program - typically in irrelevant ways - but HLint shows a warning note. HLint does not warn when assuming typeclass laws (such as `==` being symmetric). Some notes you may see include:++* __Increases laziness__ - for example `foldl (&&) True` suggests `and` including this note. The new code will work on infinite lists, while the old code would not. Increasing laziness is usually a good idea.+* __Decreases laziness__ - for example `(fst a, snd a)` suggests a including this note. On evaluation the new code will raise an error if a is an error, while the old code would produce a pair containing two error values. Only a small number of hints decrease laziness, and anyone relying on the laziness of the original code would be advised to include a comment.+* __Removes error__ - for example foldr1 (&&) suggests and including the note "Removes error on []". The new code will produce `True` on the empty list, while the old code would raise an error. Unless you are relying on the exception thrown by the empty list, this hint is safe - and if you do rely on the exception, you would be advised to add a comment. ++### What is the difference between error and warning?++Every hint has a severity level:++* __Error__ - for example `concat (map f x)` suggests `concatMap f x` as an "error" severity hint. From a style point of view, you should always replace a combination of `concat` and `map` with `concatMap`. Note that both expressions are equivalent - HLint is reporting an error in style, not an actual error in the code.+* __Warning__ - for example `x !! 0` suggests head x as a "warning" severity hint. Typically head is a simpler way of expressing the first element of a list, especially if you are treating the list inductively. However, in the expression `f (x !! 4) (x !! 0) (x !! 7)`, replacing the middle argument with `head` makes it harder to follow the pattern, and is probably a bad idea. Warning hints are often worthwhile, but should not be applied blindly.++The difference between error and warning is one of personal taste, typically my personal taste. If you already have a well developed sense of Haskell style, you should ignore the difference. If you are a beginner Haskell programmer you may wish to focus on error hints before warning hints.++## Customizing the hints++Many of the hints that are applied by HLint are contained in Haskell source files which are installed in the data directory by Cabal. These files may be edited, to add library specific knowledge, to include hints that may have been missed, or to ignore unwanted hints.++### Choosing a package of hints++By default, HLint will use the `HLint.hs` file either from the current working directory, or from the data directory. Alternatively, hint files can be specified with the `--hint` flag. HLint comes with a number of hint packages:++* __Default__ - these are the hints that are used by default, covering most of the base libraries.+* __Dollar__ - suggests the replacement `a $ b $ c` with `a . b $ c`. This hint is especially popular on the [\#haskell IRC channel](http://www.haskell.org/haskellwiki/IRC_channel).+* __Generalise__ - suggests replacing specific variants of functions (i.e. `map`) with more generic functions (i.e. `fmap`).++As an example, to check the file `Example.hs` with both the default hints and the dollar hint, I could type: `hlint Example.hs --hint=Default --hint=Dollar`. Alternatively, I could create the file `HLint.hs` in the working directory and give it the contents:++ import "hint" HLint.Default+ import "hint" HLint.Dollar++### Ignoring hints++Some of the hints are subjective, and some users believe they should be ignored. Some hints are applicable usually, but occasionally don't always make sense. The ignoring mechanism provides features for supressing certain hints. Ignore directives can either be written as pragmas in the file being analysed, or in the hint files. Examples of pragmas are:++* `{-# ANN module "HLint: ignore Eta reduce" #-}` - ignore all eta reduction suggestions in this module (use `module` literally, not the name of the module).+* `{-# ANN myFunction "HLint: ignore" #-}` - don't give any hints in the function `myFunction`.+* `{-# ANN myFunction "HLint: error" #-}` - any hint in the function `myFunction` is an error.+* `{-# ANN module "HLint: error Use concatMap" #-}` - the hint to use concatMap is an error.+* `{-# ANN module "HLint: warn Use concatMap" #-}` - the hint to use concatMap is a warning.++Ignore directives can also be written in the hint files:++* `ignore "Eta reduce"` - supress all eta reduction suggestions.+* `ignore "Eta reduce" = MyModule1 MyModule2` - supress eta reduction hints in the `MyModule1` and `MyModule2` modules.+* `ignore = MyModule.myFunction` - don't give any hints in the function `MyModule.myFunction`.+* `error = MyModule.myFunction` - any hint in the function `MyModule.myFunction` is an error.+* `error "Use concatMap"` - the hint to use `concatMap` is an error.+* `warn "Use concatMap"` - the hint to use `concatMap` is a warning.++These directives are applied in the order they are given, with later hints overriding earlier ones.++### Adding hints++The hint suggesting `concatMap` is defined as:++ error = concat (map f x) ==> concatMap f x++The line can be read as replace `concat (map f x)` with `concatMap f x`. All single-letter variables are treated as substitution parameters. For examples of more complex hints see the supplied hints file. In general, hints should not be given in point free style, as this reduces the power of the matching. Hints may start with `error` or `warn` to denote how severe they are by default. If you come up with interesting hints, please submit them for inclusion.++You can search for possible hints to add from a source file with the `--find` flag, for example:++ $ hlint --find=src/Utils.hs+ -- hints found in src/Util.hs+ warn = null (intersect a b) ==> disjoint a b+ warn = dropWhile isSpace ==> ltrim+ infixr 5 !:++These hints are suitable for inclusion in a custom hint file. You can also include Haskell fixity declarations in a hint file, and these will also be extracted. If you pass only `--find` flags then the hints will be written out, if you also pass files/folders to check, then the found hints will be automatically used when checking.
data/Default.hs view
@@ -4,7 +4,7 @@ import Control.Arrow import Control.Exception import Control.Monad-import Control.Monad.State+import Control.Monad.Trans.State import qualified Data.Foldable import Data.Foldable(asum, sequenceA_, traverse_, for_) import Data.Traversable(traverse, for)@@ -108,6 +108,7 @@ error = fst (break p x) ==> takeWhile (not . p) x error = snd (break p x) ==> dropWhile (not . p) x error = concatMap (++ "\n") ==> unlines+error = intercalate "\n" x ++ "\n" ==> unlines x error = map id ==> id error = or (map p x) ==> any p x error = and (map p x) ==> all p x@@ -190,6 +191,9 @@ warn = (\x -> y) ==> const y where _ = isAtom y && notIn x y error "Redundant flip" = flip f x y ==> f y x where _ = isApp original warn = (\a b -> g (f a) (f b)) ==> g `Data.Function.on` f+error "Evaluate" = id x ==> x+error "Redundant id" = id . x ==> x+error "Redundant id" = x . id ==> x -- CHAR @@ -199,7 +203,9 @@ error = a >= '0' && a <= '7' ==> isOctDigit a error = not (isControl a) ==> isPrint a error = isLower a || isUpper a ==> isAlpha a+error = isUpper a || isLower a ==> isAlpha a error = isAlpha a || isDigit a ==> isAlphaNum a+error = isDigit a || isAlpha a ==> isAlphaNum a -- BOOL @@ -249,6 +255,8 @@ error "Functor law" = fmap f (fmap g x) ==> fmap (f . g) x error "Functor law" = fmap id ==> id+warn = fmap f $ x ==> f Control.Applicative.<$> x+ where _ = isApp x || isAtom x -- MONAD @@ -269,14 +277,15 @@ error = x >>= id ==> Control.Monad.join x error = liftM f (liftM g x) ==> liftM (f . g) x error = fmap f (fmap g x) ==> fmap (f . g) x-warn = a >> return () ==> void a-warn = fmap (const ()) ==> void+warn = a >> return () ==> Control.Monad.void a+ where _ = isAtom a || isApp a+error = fmap (const ()) ==> Control.Monad.void error = flip (>=>) ==> (<=<) error = flip (<=<) ==> (>=>)-error = (\x -> f x >>= g) ==> f Control.Monad.>=> g-error = (\x -> f =<< g x) ==> f Control.Monad.<=< g+warn = (\x -> f x >>= g) ==> f Control.Monad.>=> g+warn = (\x -> f =<< g x) ==> f Control.Monad.<=< g error = a >> forever a ==> forever a-warn = liftM2 id ==> ap+warn = liftM2 id ==> ap error = mapM (uncurry f) (zip l m) ==> zipWithM f l m -- STATE MONAD@@ -452,7 +461,6 @@ error "Evaluate" = concat [a] ==> a error "Evaluate" = concat [] ==> [] error "Evaluate" = zip [] [] ==> []-error "Evaluate" = id x ==> x error "Evaluate" = const x y ==> x -- COMPLEX@@ -489,7 +497,7 @@ yes = not (a /= b) -- a == b yes = if a then 1 else if b then 1 else 2 -- if a || b then 1 else 2 no = if a then 1 else if b then 3 else 2-yes = a >>= return . id -- Control.Monad.liftM id a+yes = a >>= return . bob -- Control.Monad.liftM bob a yes = (x !! 0) + (x !! 2) -- head x yes = if b < 42 then [a] else [] -- [a | b < 42] no = take n (foo xs) == "hello"@@ -565,6 +573,17 @@ main = let (first, rest) = (takeWhile p l, dropWhile p l) in rest -- span p l main = map $ \ d -> ([| $d |], [| $d |]) pairs (x:xs) = map (\y -> (x,y)) xs ++ pairs xs+{-# ANN foo "HLint: ignore" #-};foo = map f (map g x) -- @Ignore ???+yes = fmap lines $ abc 123 -- lines Control.Applicative.<$> abc 123+no = fmap lines $ abc $ def 123+test = foo . not . not -- id+test = map (not . not) xs -- id+used = not . not . any (`notElem` special) . fst . derives -- any (`notElem` special) . fst . derives+test = foo . id . map -- map+test = food id xs+yes = baz baz >> return () -- Control.Monad.void (baz baz)+no = foo >>= bar >>= something >>= elsee >> return ()+ import Prelude \ yes = flip mapM -- Control.Monad.forM
data/Test.hs view
@@ -5,7 +5,7 @@ -- things without them overlapping module HLint.Test where -import "hint" HLint.Builtin.Naming+import "hint" HLint.Builtin.All error = Prelude.readFile ==> bad@@ -88,5 +88,22 @@ import qualified Array as B; test = tail -- B.tail zip [1..length x] zip [1..length x] x -- zipFrom 1 x++{-# ANN module "HLint: ignore Unused LANGUAGE pragma" #-} \+{-# LANGUAGE RecordWildCards #-} -- @Ignore ???++{-# ANN module "HLint: ignore Unused LANGUAGE pragma" #-} \+{-# LANGUAGE RecordWildCards #-} -- @Ignore ???++{-# ANN module "HLint: ignore Use import/export shortcut" #-} \+module ABCD(module A, module B, module C) where \+import A; import B; import C -- @Ignore ???++{-# ANN lam "HLint: ignore Redundant lambda" #-} \+lam = \x -> x x x -- @Ignore ???++{-# ANN module "HLint: ignore Reduce duplication" #-} \+dup = do a; a; a; a; a; a -- @Ignore ???+ </TEST> -}
hlint.cabal view
@@ -1,13 +1,13 @@ cabal-version: >= 1.6 build-type: Simple name: hlint-version: 1.8.55+version: 1.8.56 license: BSD3 license-file: LICENSE category: Development author: Neil Mitchell <ndmitchell@gmail.com> maintainer: Neil Mitchell <ndmitchell@gmail.com>-copyright: Neil Mitchell 2006-2013+copyright: Neil Mitchell 2006-2014 synopsis: Source code suggestions description: HLint gives suggestions on how to improve your source code.@@ -24,7 +24,8 @@ hlint.1 hlint.ghci extra-source-files:- hlint.htm+ README.md+ CHANGES.txt tested-with: GHC==7.6.3, GHC==7.4.2, GHC==7.2.2 source-repository head
− hlint.htm
@@ -1,340 +0,0 @@-<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"- "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">-<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">- <head>- <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />- <title>HLint Manual</title>- <style type="text/css">-pre {- border: 2px solid gray;- padding: 1px;- padding-left: 5px;- margin-left: 10px;- background-color: #eee;-}--pre.define {- background-color: #ffb;- border-color: #cc0;-}--body {- font-family: sans-serif;-}--h1, h2, h3 {- font-family: serif;-}--h1 {- color: rgb(23,54,93);- border-bottom: 1px solid rgb(79,129,189);- padding-bottom: 2px;- font-variant: small-caps;- text-align: center;-}--a {- color: rgb(54,95,145);-}--h2 {- color: rgb(54,95,145);-}--h3 {- color: rgb(79,129,189);-}--p.rule {- background-color: #ffb;- padding: 3px;- margin-left: 50px;- margin-right: 50px;-}- </style>- </head>- <body>--<h1>HLint Manual</h1>--<p style="text-align:right;margin-bottom:25px;">- by <a href="http://community.haskell.org/~ndm/">Neil Mitchell</a>-</p>--<p>- <a href="http://community.haskell.org/~ndm/hlint/">HLint</a> is a tool for suggesting possible improvements to Haskell code. These suggestions include ideas such as using alternative functions, simplifying code and spotting redundancies. This document is structured as follows:-</p>-<ol>- <li><a href="#installation">Installing and running HLint</a></li>- <li><a href="#faq">FAQ</a></li>- <li><a href="#customization">Customizing the hints</a></li>-</ol>--<h3>Acknowledgements</h3>--<p>- This program has only been made possible by the presence of the <a href="http://www.cs.chalmers.se/~d00nibro/haskell-src-exts/">haskell-src-exts</a> package, and many improvements have been made by <a href="http://www.cs.chalmers.se/~d00nibro/">Niklas Broberg</a> in response to feature requests. Additionally, many people have provided help and patches, including Lennart Augustsson, Malcolm Wallace, Henk-Jan van Tuyl, Gwern Branwen, Alex Ott, Andy Stewart, Roman Leshchinskiy and others.-</p>--<h3 id="limitations">Bugs and limitations</h3>--<p>- To report a bug either <a href="http://community.haskell.org/~ndm/contact/">email me</a>, or add the issue directly to <a href="http://code.google.com/p/ndmitchell/issues/list?q=proj:HLint">the bug tracker</a>. There are three common issues that I do not intend to fix:-</p>-<ul>- <li>The presence of <tt>seq</tt> may cause some hints (i.e. eta-reduction) to change the semantics of a program.</li>- <li>Either the monomorphism restriction, or rank-2 types, may cause transformed programs to require type signatures to be manually inserted.</li>- <li>HLint operates on each module at a time in isolation, as a result HLint does not know about types or which names are in scope.</li>-</ul>--<h2 id="installation">Installing and running HLint</h2>--<p>- Installation follows the standard pattern of any Haskell library or program, type <tt>cabal update</tt> to update your local hackage database, then <tt>cabal install hlint</tt> to install HLint.-</p><p>- Once HLint is installed, run <tt>hlint <i>source</i></tt> where <i>source</i> is either a Haskell file, or a directory containing Haskell files. A directory will be searched recursively for any files ending with <tt>.hs</tt> or <tt>.lhs</tt>. For example, running HLint over darcs would give:-</p>-<pre>--$ hlint darcs-2.1.2--darcs-2.1.2\src\CommandLine.lhs:94:1: Error: Use concatMap-Found:- concat $ map escapeC s-Why not:- concatMap escapeC s--darcs-2.1.2\src\CommandLine.lhs:103:1: Warning: Use fewer brackets-Found:- ftable ++ (map (\ (c, x) -> (toUpper c, urlEncode x)) ftable)-Why not:- ftable ++ map (\ (c, x) -> (toUpper c, urlEncode x)) ftable--darcs-2.1.2\src\Darcs\Patch\Test.lhs:306:1: Error: Use a more efficient monadic variant-Found:- mapM (delete_line (fn2fp f) line) old-Why not:- mapM_ (delete_line (fn2fp f) line) old--... lots more suggestions ...-</pre>-<p>- Each suggestion says which file/line the suggestion relates to, how serious the issue is, a description of the issue, what it found, and what you might want to replace it with. In the case of the first hint, it has suggested that instead of applying <tt>concat</tt> and <tt>map</tt> separately, it would be better to use the combination function <tt>concatMap</tt>.-</p><p>- The first suggestion is marked as an error, because using <tt>concatMap</tt> in preference to the two separate functions is always desirable. In contrast, the removal of brackets is probably a good idea, but not always. Reasons that a hint might be a warning include requiring an additional import, something not everyone agrees on, and functions only available in more recent versions of the base library.-</p>-<p class="rule">- <b>Bug reports:</b> The suggested replacement should be equivalent - please report all incorrect suggestions not mentioned as <a href="#limitations">known limitations</a>.-</p>--<h3>Reports</h3>--<p>- HLint can generate a lot of information, making it difficult to search for particular types of errors. The <tt>--report</tt> flag will cause HLint to generate a report file in HTML, which can be viewed interactively. Reports are recommended when there are more than a handlful of hints.-</p>--<h3>Language Extensions</h3>--<p>- HLint enables most Haskell extensions, disabling only those which steal too much syntax (currently Arrows, TransformListComp, XmlSyntax and RegularPatterns). Individual extensions can be enabled or disabled with, for instance, <tt>-XArrows</tt>, or <tt>-XNoMagicHash</tt>. The flag <tt>-XHaskell98</tt> selects Haskell 98 compatibility.-</p>--<h3 id="emacs">Emacs Integration</h3>--<p>- Emacs integration has been provided by <a href="http://xtalk.msk.su/~ott/">Alex Ott</a>. The integration is similar to compilation-mode, allowing navigation between errors. The script is at <a href="http://community.haskell.org/~ndm/darcs/hlint/data/hs-lint.el">hs-lint.el</a>, and a copy is installed locally in the data directory. To use, add the following code to the Emacs init file:-</p>-<pre>-(require 'hs-lint)-(defun my-haskell-mode-hook ()- (local-set-key "\C-cl" 'hs-lint))-(add-hook 'haskell-mode-hook 'my-haskell-mode-hook)-</pre>--<h3>GHCi Integration</h3>--<p>- GHCi integration has been provided by Gwern Branwen. The integration allows running <tt>:hlint</tt> from the GHCi prompt. The script is at <a href="http://community.haskell.org/~ndm/darcs/hlint/data/hlint.ghci">hlint.ghci</a>, and a copy is installed locally in the data directory. To use, add the contents to your <a href="http://www.haskell.org/ghc/docs/latest/html/users_guide/ghci-dot-files.html">GHCi startup file</a>.-</p>--<h3>Parallel Operation</h3>--<p>- To run HLint on <i>n</i> processors append the flags <tt>+RTS -N<i>n</i></tt>, as described in the <a href="http://www.haskell.org/ghc/docs/latest/html/users_guide/runtime-control.html">GHC user manual</a>. HLint will usually perform fastest if <i>n</i> is equal to the number of physical processors.-</p><p>- If your version of GHC does not support the GHC threaded runtime then install with the command: <tt>cabal install --flags="-threaded"</tt>-</p>--<h3>C preprocessor support</h3>--<p>- HLint runs the <a href="http://hackage.haskell.org/package/cpphs">cpphs C preprocessor</a> over all input files, by default using the current directory as the include path with no defined macros. These settings can be modified using the flags <tt>--cpp-include</tt> and <tt>--cpp-define</tt>. To disable the C preprocessor use the flag <tt>-XNoCPP</tt>. There are a number of limitations to the C preprocessor support:-</p>-<ul>- <li>HLint will only check one branch of an <tt>#if</tt>, based on which macros have been defined.</li>- <li>Any missing <tt>#include</tt> files will produce a warning on the console, but no information in the reports.</li>-</ul>--<h3>Unicode support</h3>--<p>- When compiled with GHC 6.10, HLint only supports ASCII. When compiled with GHC 6.12 or above, HLint uses the current locale encoding. The encoding can be overriden with either <tt>--utf8</tt> or <tt>--encoding=<i>value</i></tt>. For descriptions of some valid encodings see <a href="http://haskell.org/ghc/docs/latest/html/libraries/base-4.2.0.0/System-IO.html#v%3AmkTextEncoding">the mkTextEncoding documentation</a>.-</p>--<h2 id="faq">FAQ</h2>--<h3>Why are suggestions not applied recursively?</h3>--<p>- Consider:-</p>-<pre>-foo xs = concat (map op xs)-</pre>-<p>- This will suggest eta reduction to <tt>concat . map op</tt>, and then after making that change and running HLint again, will suggest use of <tt>concatMap</tt>. Many people wonder why HLint doesn't directly suggest <tt>concatMap op</tt>. There are a number of reasons:-</p>-<ul>- <li>HLint aims to both improve code, and to teach the author better style. Doing modifications individually helps this process.</li>- <li>Sometimes the steps are reasonably complex, by automatically composing them the user may become confused.</li>- <li>Sometimes HLint gets transformations wrong. If suggestions are applied recursively, one error will cascade.</li>- <li>Some people only make use of some of the suggestions. In the above example using concatMap is a good idea, but sometimes eta reduction isn't. By suggesting them separately, people can pick and choose.</li>- <li>Sometimes a transformed expression will be large, and a further hint will apply to some small part of the result, which appears confusing.</li>- <li>Consider <tt>f $ (a b)</tt>. There are two valid hints, either remove the <tt>$</tt> or remove the brackets, but only one can be applied.</li>-</ul>--<h3>Why aren't the suggestions automatically applied?</h3>--<p>- If you want to automatically apply suggestions, the <a href="#emacs">Emacs integration</a> offers such a feature. However, there are a number of reasons that HLint itself doesn't have an option to automatically apply suggestions:-</p>-<ul>- <li>The underlying Haskell parser library makes it hard to modify the code, then print it similarly to the original.</li>- <li>Sometimes multiple transformations may apply.</li>- <li>After applying one transformation, others that were otherwise suggested may become inappropriate.</li>-</ul>-<p>- I am intending to develop such a feature, but the above reasons mean it is likely to take some time.-</p>--<h3>Why doesn't the compiler automatically apply the optimisations?</h3>--<p>- HLint doesn't suggest optimisations, it suggests code improvements - the intention is to make the code simpler, rather than making the code perform faster. The <a href="http://haskell.org/ghc/">GHC compiler</a> automatically applies many of the rules suggested by HLint, so HLint suggestions will rarely improve performance.-</p>--<h3>Why doesn't HLint know the fixity for my custom <tt>!@%$</tt> operator?</h3>--<p>- HLint knows the fixities for all the operators in the base library, but no others. HLint works on a single file at a time, and does not resolve imports, so cannot see fixity declarations from imported modules. You can tell HLint about fixities by putting them in a hint file, or passing them on the command line. For example, pass <tt>"--with=infixr 5 !@%$"</tt>, or put all the fixity declarations in a file and pass <tt>--hint=fixities.hs</tt>. You can also use <tt><a href="#find">--find</a></tt> to automatically produce a list of fixity declarations in a file.-</p>--<h3>How can I use <tt>--with</tt> or <tt>--hint</tt> with the default hints?</h3>--<p>- HLint does not use the default set of hints if custom hints are specified on the command line using <tt>--with</tt> or <tt>--hint</tt>. To include the default hints either pass <tt>--hint=HLint</tt> on the command line, or add <tt>import "hint" HLint.HLint</tt> in one of the hint files you specify with <tt>--hint</tt>.-</p>--<h3>Why do I sometimes get a "Note" with my hint?</h3>--<p>- Most hints are perfect substitutions, and these are displayed without any notes. However, some hints change the semantics of your program - typically in irrelevant ways - but HLint shows a warning note. HLint does not warn when assuming typeclass laws (such as <tt>==</tt> being symmetric). Some notes you may see include:-</p>-<ul>- <li><b>Increases laziness</b> - for example <tt>foldl (&&) True</tt> suggests <tt>and</tt> including this note. The new code will work on infinite lists, while the old code would not. Increasing laziness is usually a good idea.</li>- <li><b>Decreases laziness</b> - for example <tt>(fst a, snd a)</tt> suggests <tt>a</tt> including this note. On evaluation the new code will raise an error if <tt>a</tt> is an error, while the old code would produce a pair containing two error values. Only a small number of hints decrease laziness, and anyone relying on the laziness of the original code would be advised to include a comment.</li>- <li><b>Removes error</b> - for example <tt>foldr1 (&&)</tt> suggests <tt>and</tt> including the note "Removes error on []". The new code will produce <tt>True</tt> on the empty list, while the old code would raise an error. Unless you are relying on the exception thrown by the empty list, this hint is safe - and if you do rely on the exception, you would be advised to add a comment.-</ul>--<h3 id="error_vs_warning">What is the difference between error and warning?</h3>--<p>- Every hint has a severity level:-</p>-<ul>- <li><b>Error</b> - for example <tt>concat (map f x)</tt> suggests <tt>concatMap f x</tt> as an "error" severity hint. From a style point of view, you should always replace a combination of <tt>concat</tt> and <tt>map</tt> with <tt>concatMap</tt>. Note that both expressions are equivalent - HLint is reporting an error in style, <i>not</i> an actual error in the code.</li>- <li><b>Warning</b> - for example <tt>x !! 0</tt> suggests <tt>head x</tt> as a "warning" severity hint. Typically <tt>head</tt> is a simpler way of expressing the first element of a list, especially if you are treating the list inductively. However, in the expression <tt>f (x !! 4) (x !! 0) (x !! 7)</tt>, replacing the middle argument with <tt>head</tt> makes it harder to follow the pattern, and is probably a bad idea. Warning hints are often worthwhile, but should not be applied blindly.</li>-</ul>-<p>- The difference between error and warning is one of personal taste, typically my personal taste. If you already have a well developed sense of Haskell style, you should ignore the difference. If you are a beginner Haskell programmer you may wish to focus on error hints before warning hints.-</p>--<h2 id="customization">Customizing the hints</h2>--<p>- Many of the hints that are applied by HLint are contained in Haskell source files which are installed in the data directory by Cabal. These files may be edited, to add library specific knowledge, to include hints that may have been missed, or to ignore unwanted hints.-</p>--<h3>Choosing a package of hints</h3>--<p>- By default, HLint will use the <tt>HLint.hs</tt> file either from the current working directory, or from the data directory. Alternatively, hint files can be specified with the <tt>--hint</tt> flag. HLint comes with a number of hint packages:-</p>-<ul>- <li><b>Default</b> - these are the hints that are used by default, covering most of the base libraries.</li>- <li><b>Dollar</b> - suggests the replacement <tt>a $ b $ c</tt> with <tt>a . b $ c</tt>. This hint is especially popular on the <a href="http://www.haskell.org/haskellwiki/IRC_channel"><tt>#haskell</tt> IRC channel</a>.</li>- <li><b>Generalise</b> - suggests replacing specific variants of functions (i.e. <tt>map</tt>) with more generic functions (i.e. <tt>fmap</tt>).</li>-</ul>-<p>- As an example, to check the file <tt>Example.hs</tt> with both the default hints and the dollar hint, I could type: <tt>hlint Example.hs --hint=Default --hint=Dollar</tt>. Alternatively, I could create the file <tt>HLint.hs</tt> in the working directory and give it the contents:-</p>-<pre>-import "hint" HLint.Default-import "hint" HLint.Dollar-</pre>--<h3>Ignoring hints</h3>--<p>- Some of the hints are subjective, and some users believe they should be ignored. Some hints are applicable usually, but occasionally don't always make sense. The ignoring mechanism provides features for supressing certain hints. Ignore directives can either be written as pragmas in the file being analysed, or in the hint files. Examples of pragmas are:-</p>-<ul>- <li><tt>{-# ANN module "HLint: ignore Eta reduce" #-}</tt> - ignore all eta reduction suggestions in this module (use <tt>module</tt> literally, not the name of the module).</li>- <li><tt>{-# ANN <i>myFunction</i> "HLint: ignore" #-}</tt> - don't give any hints in the function <tt><i>myFunction</i></tt>.</li>- <li><tt>{-# ANN <i>myFunction</i> "HLint: error" #-}</tt> - any hint in the function <tt><i>myFunction</i></tt> is an error.</li>- <li><tt>{-# ANN module "HLint: error Use concatMap" #-}</tt> - the hint to use concatMap is an error.</li>- <li><tt>{-# ANN module "HLint: warn Use concatMap" #-}</tt> - the hint to use concatMap is a warning.</li>-</ul>-<p>- Ignore directives can also be written in the hint files:-</p>-<ul>- <li><tt>ignore "Eta reduce"</tt> - supress all eta reduction suggestions.</li>- <li><tt>ignore "Eta reduce" = MyModule1 MyModule2</tt> - supress eta reduction hints in the <tt>MyModule1</tt> and <tt>MyModule2</tt> modules.</li>- <li><tt>ignore = MyModule.myFunction</tt> - don't give any hints in the function <tt>MyModule.myFunction</tt>.</li>- <li><tt>error = MyModule.myFunction</tt> - any hint in the function <tt>MyModule.myFunction</tt> is an error.</li>- <li><tt>error "Use concatMap"</tt> - the hint to use concatMap is an error.</li>- <li><tt>warn "Use concatMap"</tt> - the hint to use concatMap is a warning.</li>-</ul>-<p>- These directives are applied in the order they are given, with later hints overriding earlier ones.-</p>--<h3>Adding hints</h3>--<p>- The hint suggesting <tt>concatMap</tt> is defined as:-</p>-<pre>-error = concat (map f x) ==> concatMap f x-</pre>-<p>- The line can be read as replace <tt>concat (map <i>f</i> <i>x</i>)</tt> with <tt>concatMap <i>f</i> <i>x</i></tt>. All single-letter variables are treated as substitution parameters. For examples of more complex hints see the supplied hints file. In general, hints should <i>not</i> be given in point free style, as this reduces the power of the matching. Hints may start with <tt>error</tt> or <tt>warn</tt> to denote how severe they are by default. If you come up with interesting hints, please submit them for inclusion.-</p>-<p>- <a name="find"></a>You can search for possible hints to add from a source file with the <tt>--find</tt> flag, for example:-</p>-<pre>-$ hlint --find=src/Utils.hs--- hints found in src/Util.hs-warn = null (intersect a b) ==> disjoint a b-warn = dropWhile isSpace ==> ltrim-infixr 5 !:-</pre>-<p>- These hints are suitable for inclusion in a custom hint file. You can also include Haskell fixity declarations in a hint file, and these will also be extracted. If you pass only <tt>--find</tt> flags then the hints will be written out, if you also pass files/folders to check, then the found hints will be automatically used when checking.-</p>-- </body>-</html>
src/Apply.hs view
@@ -3,6 +3,7 @@ import HSE.All import Hint.All+import Control.Applicative import Control.Arrow import Data.Char import Data.List@@ -34,14 +35,14 @@ -- | Apply hints to multiple files, allowing cross-file hints to fire. applyHintFiles :: ParseFlags -> [Setting] -> [FilePath] -> IO [Idea] applyHintFiles flags s files = do- (err, ms) <- fmap unzipEither $ mapM (parseModuleFile flags s) files+ (err, ms) <- unzipEither <$> mapM (parseModuleFile flags s) files return $ err ++ executeHints s ms -- | Given a list of settings (a way to classify) and a list of hints, run them over a list of modules. executeHints :: [Setting] -> [Module_] -> [Idea] executeHints s ms = concat $- [ map (classify $ s ++ mapMaybe readPragma (moduleDecls m)) $+ [ map (classify $ s ++ mapMaybe readPragma (universeBi m)) $ order "" [i | ModuHint h <- hints, i <- h nm m] ++ concat [order (fromNamed d) [i | h <- decHints, i <- h d] | d <- moduleDecls m] | (nm,m) <- mns
src/CmdLine.hs view
@@ -2,6 +2,7 @@ module CmdLine(Cmd(..), CppFlags(..), getCmd, exitWithHelp) where +import Control.Applicative import Control.Monad import Data.Char import Data.List@@ -117,7 +118,7 @@ let exts = [x | Ext x <- opt] exts2 = if null exts then ["hs","lhs"] else exts let path = [x | Path x <- opt] ++ ["."]- files <- if null files then return Nothing else fmap Just $ concatMapM (getFile path exts2) files+ files <- if null files then return Nothing else Just <$> concatMapM (getFile path exts2) files findHints <- concatMapM (getFile path exts2) [x | FindHints x <- opt] let hintFiles = [x | Hints x <- opt]@@ -166,7 +167,7 @@ versionText :: String-versionText = "HLint v" ++ showVersion version ++ ", (C) Neil Mitchell 2006-2013\n"+versionText = "HLint v" ++ showVersion version ++ ", (C) Neil Mitchell 2006-2014\n" helpText :: String
src/HLint.hs view
@@ -2,6 +2,7 @@ module HLint(hlint, Suggestion, suggestionLocation, suggestionSeverity, Severity(..)) where +import Control.Applicative import Control.Monad import Data.List import Data.Maybe@@ -50,7 +51,7 @@ cmd@Cmd{..} <- getCmd args let flags = parseFlags{cppFlags=cmdCpp, encoding=cmdEncoding, language=cmdLanguage} if cmdTest then do- failed <- test (\x -> hlint x >> return ()) cmdDataDir cmdGivenHints+ failed <- test (void . hlint) cmdDataDir cmdGivenHints when (failed > 0) exitFailure return [] else if notNull cmdProof then do@@ -83,7 +84,7 @@ let files = fromMaybe [] cmdFiles ideas <- if cmdCross then applyHintFiles flags settings files- else fmap concat $ parallel [listM' =<< applyHintFile flags settings x | x <- files]+ else concat <$> parallel [listM' =<< applyHintFile flags settings x | x <- files] let (showideas,hideideas) = partition (\i -> cmdShowAll || severity i /= Ignore) ideas showItem <- if cmdColor then showANSI else return show mapM_ (outStrLn . showItem) showideas
src/HSE/All.hs view
@@ -14,6 +14,7 @@ import HSE.FreeVars as X import Util import CmdLine+import Control.Applicative import Data.List import Data.Maybe import Language.Preprocessor.Cpphs@@ -48,7 +49,7 @@ parseString :: ParseFlags -> FilePath -> String -> IO (String, ParseResult Module_) parseString flags file str = do ppstr <- runCpp (cppFlags flags) file str- return (ppstr, fmap (applyFixity fixity) $ parseFileContentsWithMode mode ppstr)+ return (ppstr, applyFixity fixity <$> parseFileContentsWithMode mode ppstr) where fixity = infixes flags ++ baseFixities mode = defaultParseMode
src/HSE/Util.hs view
@@ -271,7 +271,7 @@ an = toSrcInfo nullSrcLoc [] nullSrcLoc dropAnn :: Functor f => f s -> f ()-dropAnn = fmap (const ())+dropAnn = void ---------------------------------------------------------------------
src/Hint/Extensions.hs view
@@ -132,7 +132,7 @@ used DeriveFunctor = hasDerive False ["Functor"] used DeriveFoldable = hasDerive False ["Foldable"] used DeriveTraversable = hasDerive False ["Traversable"]-used GeneralizedNewtypeDeriving = not . null . filter (`notElem` special) . fst . derives+used GeneralizedNewtypeDeriving = any (`notElem` special) . fst . derives where special = ["Read","Show","Data","Typeable","Generic","Generic1"] -- these classes cannot use generalised deriving -- FIXME: This special list is duplicated here, and as booleans to hasDerive used Arrows = hasS f
src/Hint/Import.hs view
@@ -44,6 +44,7 @@ import Hint.Type import Util+import Control.Applicative import Data.List import Data.Maybe @@ -64,14 +65,14 @@ simplify :: [ImportDecl S] -> Maybe [ImportDecl S] simplify [] = Nothing simplify (x:xs) = case simplifyHead x xs of- Nothing -> fmap (x:) $ simplify xs+ Nothing -> (x:) <$> simplify xs Just xs -> Just $ fromMaybe xs $ simplify xs simplifyHead :: ImportDecl S -> [ImportDecl S] -> Maybe [ImportDecl S] simplifyHead x [] = Nothing simplifyHead x (y:ys) = case reduce x y of- Nothing -> fmap (y:) $ simplifyHead x ys+ Nothing -> (y:) <$> simplifyHead x ys Just xy -> Just $ xy : ys
src/Hint/List.hs view
@@ -9,7 +9,7 @@ -- [a]++b -> a : b, but only if not in a chain of ++'s yes = [x] ++ xs -- x : xs-yes = "x" ++ xs -- 'x' : xs+no = "x" ++ xs no = [x] ++ xs ++ ys no = xs ++ [x] ++ ys yes = [if a then b else c] ++ xs -- (if a then b else c) : xs@@ -25,6 +25,7 @@ module Hint.List where +import Control.Applicative import Hint.Type @@ -60,13 +61,12 @@ useList b = fmap (List an) . f True where f first x | x ~= "[]" = if first then Nothing else Just []- f first (view -> App2 c a b) | c ~= ":" = fmap (a:) $ f False b+ f first (view -> App2 c a b) | c ~= ":" = (a:) <$> f False b f first _ = Nothing useCons False (view -> App2 op x y) | op ~= "++", Just x2 <- f x, not $ isAppend y = Just $ InfixApp an x2 (QConOp an $ list_cons_name an) y where- f (Lit _ (String _ [x] _)) = Just $ Lit an $ Char an x (show x) f (List _ [x]) = Just $ if isApp x then x else paren x f _ = Nothing useCons _ _ = Nothing
src/Hint/Match.hs view
@@ -29,6 +29,12 @@ -- we use the associativity of (.) to add concat . map f . x ==> concatMap f . x -- currently 36 of 169 rules have (.) equivalents++We see through (.) if the RHS is dull using id, e.g.++not (not x) ==> x+not . not ==> id+not . not . x ==> x -} module Hint.Match(readMatch) where@@ -40,6 +46,7 @@ import Settings import Hint.Type import Control.Monad+import Control.Applicative import Control.Arrow import Util import qualified Data.Set as Set@@ -60,16 +67,22 @@ (:) m{lhs=lhs,side=side,rhs=rhs} $ fromMaybe [] $ do (l,v1) <- dotVersion lhs (r,v2) <- dotVersion rhs- guard $ v1 == v2 && l /= [] && r /= [] && Set.notMember v1 (freeVars $ maybeToList side ++ l ++ r)- return [m{lhs=dotApps l, rhs=dotApps r, side=side}- ,m{lhs=dotApps (l++[toNamed v1]), rhs=dotApps (r++[toNamed v1]), side=side}]+ guard $ v1 == v2 && l /= [] && Set.notMember v1 (freeVars $ maybeToList side ++ l ++ r)+ if r /= [] then return+ [m{lhs=dotApps l, rhs=dotApps r, side=side}+ ,m{lhs=dotApps (l++[toNamed v1]), rhs=dotApps (r++[toNamed v1]), side=side}]+ else if length l > 1 then return+ [m{lhs=dotApps l, rhs=toNamed "id", side=side}+ ,m{lhs=dotApps (l++[toNamed v1]), rhs=toNamed v1, side=side}]+ else+ Nothing readRule _ = [] -- find a dot version of this rule, return the sequence of app prefixes, and the var dotVersion :: Exp_ -> Maybe ([Exp_], String) dotVersion (view -> Var_ v) | isUnifyVar v = Just ([], v)-dotVersion (fromApps -> xs) | length xs > 1 = fmap (first (apps (init xs) :)) $ dotVersion (fromParen $ last xs)+dotVersion (fromApps -> xs) | length xs > 1 = first (apps (init xs) :) <$> dotVersion (fromParen $ last xs) dotVersion _ = Nothing @@ -198,7 +211,7 @@ asInt :: Exp_ -> Maybe Integer asInt (Paren _ x) = asInt x- asInt (NegApp _ x) = fmap negate $ asInt x+ asInt (NegApp _ x) = negate <$> asInt x asInt (Lit _ (Int _ x _)) = Just x asInt _ = Nothing @@ -232,7 +245,7 @@ unqualify :: Scope -> Scope -> [(String,Exp_)] -> Exp_ -> Exp_ unqualify from to subs = transformBi f where- f (Qual _ (ModuleName _ [m]) x) | Just y <- fmap fromNamed $ lookup [m] subs+ f (Qual _ (ModuleName _ [m]) x) | Just y <- fromNamed <$> lookup [m] subs = if null y then UnQual an x else Qual an (ModuleName an y) x f x = nameQualify from to x
src/Hint/Monad.hs view
@@ -37,6 +37,7 @@ module Hint.Monad where import Control.Arrow+import Control.Applicative import Data.Maybe import Data.List import Hint.Type@@ -64,11 +65,11 @@ -- see through Paren and down if/case etc -- return the name to use in the hint, and the revised expression monadCall :: Exp_ -> Maybe (String,Exp_)-monadCall (Paren _ x) = fmap (second $ Paren an) $ monadCall x-monadCall (App _ x y) = fmap (second $ \x -> App an x y) $ monadCall x+monadCall (Paren _ x) = second (Paren an) <$> monadCall x+monadCall (App _ x y) = second (\x -> App an x y) <$> monadCall x monadCall (InfixApp _ x op y)- | isDol op = fmap (second $ \x -> InfixApp an x op y) $ monadCall x- | op ~= ">>=" = fmap (second $ \y -> InfixApp an x op y) $ monadCall y+ | isDol op = second (\x -> InfixApp an x op y) <$> monadCall x+ | op ~= ">>=" = second (\y -> InfixApp an x op y) <$> monadCall y monadCall (replaceBranches -> (bs@(_:_), gen)) | all isJust res = Just (fst $ fromJust $ head res, gen $ map (snd . fromJust) res) where res = map monadCall bs@@ -85,7 +86,7 @@ monadJoin (Generator _ (view -> PVar_ p) x:Qualifier _ (view -> Var_ v):xs) | p == v && v `notElem` varss xs = Just $ Qualifier an (rebracket1 $ App an (toNamed "join") x) : fromMaybe xs (monadJoin xs)-monadJoin (x:xs) = fmap (x:) $ monadJoin xs+monadJoin (x:xs) = (x:) <$> monadJoin xs monadJoin [] = Nothing
src/Proof.hs view
@@ -2,6 +2,7 @@ module Proof(proof) where +import Control.Applicative import Control.Arrow import Control.Monad import Control.Monad.Trans.State@@ -29,7 +30,7 @@ proof :: [FilePath] -> [Setting] -> FilePath -> IO () proof reports hints thy = do- got <- fmap (isabelleTheorems (takeFileName thy)) $ readFile thy+ got <- isabelleTheorems (takeFileName thy) <$> readFile thy let want = nub $ hintTheorems hints let unused = got \\ want let missing = want \\ got
src/Settings.hs view
@@ -90,7 +90,8 @@ readSettings :: FilePath -> [FilePath] -> [String] -> IO [Setting] readSettings dataDir files hints = do (builtin,mods) <- fmap unzipEither $ concatMapM (readHints dataDir) $ map Right files ++ map Left hints- let f m = concatMap (readSetting $ moduleScope m) $ concatMap getEquations $ moduleDecls m+ let f m = concatMap (readSetting $ moduleScope m) $ concatMap getEquations $+ [AnnPragma l x | AnnModulePragma l x <- modulePragmas m] ++ moduleDecls m return $ map Builtin builtin ++ concatMap f mods @@ -118,7 +119,7 @@ names2 = ["" | null names] ++ names readSetting s x | "test" `isPrefixOf` map toLower (fromNamed x) = []-readSetting s x@AnnPragma{} | Just y <- readPragma x = [y]+readSetting s (AnnPragma _ x) | Just y <- readPragma x = [y] readSetting s (PatBind an (PVar _ name) _ bod bind) = readSetting s $ FunBind an [Match an name [] bod bind] readSetting s (FunBind an xs) | length xs /= 1 = concatMap (readSetting s . FunBind an . return) xs readSetting s (SpliceDecl an (App _ (Var _ x) (Lit _ y))) = readSetting s $ FunBind an [Match an (toNamed $ fromNamed x) [PLit an y] (UnGuardedRhs an $ Lit an $ String an "" "") Nothing]@@ -127,22 +128,20 @@ -- return Nothing if it is not an HLint pragma, otherwise all the settings-readPragma :: Decl_ -> Maybe Setting-readPragma o@(AnnPragma _ p) = f p+readPragma :: Annotation S -> Maybe Setting+readPragma o = case o of+ Ann _ name x -> f (fromNamed name) x+ TypeAnn _ name x -> f (fromNamed name) x+ ModuleAnn _ x -> f "" x where- f (Ann _ name x) = g (fromNamed name) x- f (TypeAnn _ name x) = g (fromNamed name) x- f (ModuleAnn _ x) = g "" x-- g name (Lit _ (String _ s _)) | "hlint:" `isPrefixOf` map toLower s =+ f name (Lit _ (String _ s _)) | "hlint:" `isPrefixOf` map toLower s = case getSeverity a of Nothing -> errorOn o "bad classify pragma" Just severity -> Just $ Classify severity (ltrim b) ("",name) where (a,b) = break isSpace $ ltrim $ drop 6 s- g name (Paren _ x) = g name x- g name (ExpTypeSig _ x _) = g name x- g _ _ = Nothing-readPragma _ = Nothing+ f name (Paren _ x) = f name x+ f name (ExpTypeSig _ x _) = f name x+ f _ _ = Nothing readSide :: [Decl_] -> (Maybe Exp_, [Note])
src/Test.hs view
@@ -2,6 +2,7 @@ module Test(test) where +import Control.Applicative import Control.Exception import Control.Monad import Data.Char@@ -73,7 +74,7 @@ testSourceFiles :: IO Result-testSourceFiles = fmap mconcat $ sequence+testSourceFiles = mconcat <$> sequence [checkAnnotations [Builtin name] ("src/Hint" </> name <.> "hs") | (name,h) <- staticHints] @@ -207,22 +208,19 @@ reader x = readFile' $ "tests" </> pre <.> x flags <-- if has "flags" then fmap lines $ reader "flags"+ if has "flags" then lines <$> reader "flags" else if has "hs" then return ["tests/" ++ pre <.> "hs"] else if has "lhs" then return ["tests/" ++ pre <.> "lhs"] else error "checkInputOutput, couldn't find or figure out flags" - got <- fmap (fmap lines) $ captureOutput $+ got <- fmap lines $ captureOutput $ handle (\(e::SomeException) -> print e) $ handle (\(e::ExitCode) -> return ()) $ main flags- let gotValid = isJust got- want <- fmap lines $ reader "output"- (want,got) <- return $ matchStarStar want $ fromMaybe [] got+ want <- lines <$> reader "output"+ (want,got) <- return $ matchStarStar want got - if not gotValid then- putStrLn "Warning: failed to capture output (GHC too old?)" >> return pass- else if length got == length want && and (zipWith matchStar want got) then+ if length got == length want && and (zipWith matchStar want got) then return pass else do let trail = replicate (max (length got) (length want)) "<EOF>"
src/Util.hs view
@@ -1,4 +1,4 @@-{-# LANGUAGE CPP, ExistentialQuantification, Rank2Types, PatternGuards #-}+{-# LANGUAGE ExistentialQuantification, Rank2Types, PatternGuards #-} module Util where @@ -19,10 +19,7 @@ import Data.Data import Data.Generics.Uniplate.Operations import Language.Haskell.Exts.Extension--#if __GLASGOW_HASKELL__ >= 612 import GHC.IO.Handle(hDuplicate,hDuplicateTo)-#endif ---------------------------------------------------------------------@@ -147,7 +144,6 @@ -- so we fake them up, and then try mkTextEncoding last newEncoding :: String -> IO Encoding newEncoding "" = return defaultEncoding-#if __GLASGOW_HASKELL__ >= 612 newEncoding enc | Just e <- lookup (f enc) [(f a, b) | (as,b) <- encs, a <- as] = return $ wrap e | otherwise = do@@ -178,11 +174,6 @@ ,"UTF-32" * utf16 ,"UTF-32LE" * utf16le ,"UTF-32BE" * utf16be]-#else-newEncoding enc = do- putStrLn "Warning: Text encodings are not supported with HLint compiled by GHC 6.10"- return defaultEncoding-#endif exitMessage :: String -> a@@ -192,10 +183,7 @@ -- FIXME: This could use a lot more bracket calls!-captureOutput :: IO () -> IO (Maybe String)-#if __GLASGOW_HASKELL__ < 612-captureOutput act = return Nothing-#else+captureOutput :: IO () -> IO String captureOutput act = do tmp <- getTemporaryDirectory (f,h) <- openTempFile tmp "hlint"@@ -209,8 +197,7 @@ hDuplicateTo ste stderr res <- readFile' f removeFile f- return $ Just res-#endif+ return res -- FIXME: Should use strict ByteString