hlint (empty) → 1.0.0.0
raw patch · 18 files changed
+1764/−0 lines, 18 filesdep +basedep +containersdep +directorysetup-changed
Dependencies added: base, containers, directory, filepath, haskell-src-exts, mtl, syb, uniplate
Files
- LICENSE +340/−0
- Setup.hs +2/−0
- data/Hints.hs +120/−0
- data/hlint_ignore.txt +17/−0
- data/report.html +195/−0
- hlint.cabal +42/−0
- hlint.htm +165/−0
- src/CmdLine.hs +96/−0
- src/Hint/All.hs +33/−0
- src/Hint/Bracket.hs +60/−0
- src/Hint/Lambda.hs +90/−0
- src/Hint/List.hs +65/−0
- src/Hint/Match.hs +134/−0
- src/Hint/Monad.hs +46/−0
- src/Main.hs +83/−0
- src/Report.hs +44/−0
- src/Type.hs +32/−0
- src/Util.hs +200/−0
+ LICENSE view
@@ -0,0 +1,340 @@+ GNU GENERAL PUBLIC LICENSE+ Version 2, June 1991++ Copyright (C) 1989, 1991 Free Software Foundation, Inc.+ 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA+ Everyone is permitted to copy and distribute verbatim copies+ of this license document, but changing it is not allowed.++ Preamble++ The licenses for most software are designed to take away your+freedom to share and change it. By contrast, the GNU General Public+License is intended to guarantee your freedom to share and change free+software--to make sure the software is free for all its users. This+General Public License applies to most of the Free Software+Foundation's software and to any other program whose authors commit to+using it. (Some other Free Software Foundation software is covered by+the GNU Library General Public License instead.) You can apply it to+your programs, too.++ When we speak of free software, we are referring to freedom, not+price. Our General Public Licenses are designed to make sure that you+have the freedom to distribute copies of free software (and charge for+this service if you wish), that you receive source code or can get it+if you want it, that you can change the software or use pieces of it+in new free programs; and that you know you can do these things.++ To protect your rights, we need to make restrictions that forbid+anyone to deny you these rights or to ask you to surrender the rights.+These restrictions translate to certain responsibilities for you if you+distribute copies of the software, or if you modify it.++ For example, if you distribute copies of such a program, whether+gratis or for a fee, you must give the recipients all the rights that+you have. You must make sure that they, too, receive or can get the+source code. And you must show them these terms so they know their+rights.++ We protect your rights with two steps: (1) copyright the software, and+(2) offer you this license which gives you legal permission to copy,+distribute and/or modify the software.++ Also, for each author's protection and ours, we want to make certain+that everyone understands that there is no warranty for this free+software. If the software is modified by someone else and passed on, we+want its recipients to know that what they have is not the original, so+that any problems introduced by others will not reflect on the original+authors' reputations.++ Finally, any free program is threatened constantly by software+patents. We wish to avoid the danger that redistributors of a free+program will individually obtain patent licenses, in effect making the+program proprietary. To prevent this, we have made it clear that any+patent must be licensed for everyone's free use or not licensed at all.++ The precise terms and conditions for copying, distribution and+modification follow.++ GNU GENERAL PUBLIC LICENSE+ TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION++ 0. This License applies to any program or other work which contains+a notice placed by the copyright holder saying it may be distributed+under the terms of this General Public License. The "Program", below,+refers to any such program or work, and a "work based on the Program"+means either the Program or any derivative work under copyright law:+that is to say, a work containing the Program or a portion of it,+either verbatim or with modifications and/or translated into another+language. (Hereinafter, translation is included without limitation in+the term "modification".) Each licensee is addressed as "you".++Activities other than copying, distribution and modification are not+covered by this License; they are outside its scope. The act of+running the Program is not restricted, and the output from the Program+is covered only if its contents constitute a work based on the+Program (independent of having been made by running the Program).+Whether that is true depends on what the Program does.++ 1. You may copy and distribute verbatim copies of the Program's+source code as you receive it, in any medium, provided that you+conspicuously and appropriately publish on each copy an appropriate+copyright notice and disclaimer of warranty; keep intact all the+notices that refer to this License and to the absence of any warranty;+and give any other recipients of the Program a copy of this License+along with the Program.++You may charge a fee for the physical act of transferring a copy, and+you may at your option offer warranty protection in exchange for a fee.++ 2. You may modify your copy or copies of the Program or any portion+of it, thus forming a work based on the Program, and copy and+distribute such modifications or work under the terms of Section 1+above, provided that you also meet all of these conditions:++ a) You must cause the modified files to carry prominent notices+ stating that you changed the files and the date of any change.++ b) You must cause any work that you distribute or publish, that in+ whole or in part contains or is derived from the Program or any+ part thereof, to be licensed as a whole at no charge to all third+ parties under the terms of this License.++ c) If the modified program normally reads commands interactively+ when run, you must cause it, when started running for such+ interactive use in the most ordinary way, to print or display an+ announcement including an appropriate copyright notice and a+ notice that there is no warranty (or else, saying that you provide+ a warranty) and that users may redistribute the program under+ these conditions, and telling the user how to view a copy of this+ License. (Exception: if the Program itself is interactive but+ does not normally print such an announcement, your work based on+ the Program is not required to print an announcement.)++These requirements apply to the modified work as a whole. If+identifiable sections of that work are not derived from the Program,+and can be reasonably considered independent and separate works in+themselves, then this License, and its terms, do not apply to those+sections when you distribute them as separate works. But when you+distribute the same sections as part of a whole which is a work based+on the Program, the distribution of the whole must be on the terms of+this License, whose permissions for other licensees extend to the+entire whole, and thus to each and every part regardless of who wrote it.++Thus, it is not the intent of this section to claim rights or contest+your rights to work written entirely by you; rather, the intent is to+exercise the right to control the distribution of derivative or+collective works based on the Program.++In addition, mere aggregation of another work not based on the Program+with the Program (or with a work based on the Program) on a volume of+a storage or distribution medium does not bring the other work under+the scope of this License.++ 3. You may copy and distribute the Program (or a work based on it,+under Section 2) in object code or executable form under the terms of+Sections 1 and 2 above provided that you also do one of the following:++ a) Accompany it with the complete corresponding machine-readable+ source code, which must be distributed under the terms of Sections+ 1 and 2 above on a medium customarily used for software interchange; or,++ b) Accompany it with a written offer, valid for at least three+ years, to give any third party, for a charge no more than your+ cost of physically performing source distribution, a complete+ machine-readable copy of the corresponding source code, to be+ distributed under the terms of Sections 1 and 2 above on a medium+ customarily used for software interchange; or,++ c) Accompany it with the information you received as to the offer+ to distribute corresponding source code. (This alternative is+ allowed only for noncommercial distribution and only if you+ received the program in object code or executable form with such+ an offer, in accord with Subsection b above.)++The source code for a work means the preferred form of the work for+making modifications to it. For an executable work, complete source+code means all the source code for all modules it contains, plus any+associated interface definition files, plus the scripts used to+control compilation and installation of the executable. However, as a+special exception, the source code distributed need not include+anything that is normally distributed (in either source or binary+form) with the major components (compiler, kernel, and so on) of the+operating system on which the executable runs, unless that component+itself accompanies the executable.++If distribution of executable or object code is made by offering+access to copy from a designated place, then offering equivalent+access to copy the source code from the same place counts as+distribution of the source code, even though third parties are not+compelled to copy the source along with the object code.++ 4. You may not copy, modify, sublicense, or distribute the Program+except as expressly provided under this License. Any attempt+otherwise to copy, modify, sublicense or distribute the Program is+void, and will automatically terminate your rights under this License.+However, parties who have received copies, or rights, from you under+this License will not have their licenses terminated so long as such+parties remain in full compliance.++ 5. You are not required to accept this License, since you have not+signed it. However, nothing else grants you permission to modify or+distribute the Program or its derivative works. These actions are+prohibited by law if you do not accept this License. Therefore, by+modifying or distributing the Program (or any work based on the+Program), you indicate your acceptance of this License to do so, and+all its terms and conditions for copying, distributing or modifying+the Program or works based on it.++ 6. Each time you redistribute the Program (or any work based on the+Program), the recipient automatically receives a license from the+original licensor to copy, distribute or modify the Program subject to+these terms and conditions. You may not impose any further+restrictions on the recipients' exercise of the rights granted herein.+You are not responsible for enforcing compliance by third parties to+this License.++ 7. If, as a consequence of a court judgment or allegation of patent+infringement or for any other reason (not limited to patent issues),+conditions are imposed on you (whether by court order, agreement or+otherwise) that contradict the conditions of this License, they do not+excuse you from the conditions of this License. If you cannot+distribute so as to satisfy simultaneously your obligations under this+License and any other pertinent obligations, then as a consequence you+may not distribute the Program at all. For example, if a patent+license would not permit royalty-free redistribution of the Program by+all those who receive copies directly or indirectly through you, then+the only way you could satisfy both it and this License would be to+refrain entirely from distribution of the Program.++If any portion of this section is held invalid or unenforceable under+any particular circumstance, the balance of the section is intended to+apply and the section as a whole is intended to apply in other+circumstances.++It is not the purpose of this section to induce you to infringe any+patents or other property right claims or to contest validity of any+such claims; this section has the sole purpose of protecting the+integrity of the free software distribution system, which is+implemented by public license practices. Many people have made+generous contributions to the wide range of software distributed+through that system in reliance on consistent application of that+system; it is up to the author/donor to decide if he or she is willing+to distribute software through any other system and a licensee cannot+impose that choice.++This section is intended to make thoroughly clear what is believed to+be a consequence of the rest of this License.++ 8. If the distribution and/or use of the Program is restricted in+certain countries either by patents or by copyrighted interfaces, the+original copyright holder who places the Program under this License+may add an explicit geographical distribution limitation excluding+those countries, so that distribution is permitted only in or among+countries not thus excluded. In such case, this License incorporates+the limitation as if written in the body of this License.++ 9. The Free Software Foundation may publish revised and/or new versions+of the General Public License from time to time. Such new versions will+be similar in spirit to the present version, but may differ in detail to+address new problems or concerns.++Each version is given a distinguishing version number. If the Program+specifies a version number of this License which applies to it and "any+later version", you have the option of following the terms and conditions+either of that version or of any later version published by the Free+Software Foundation. If the Program does not specify a version number of+this License, you may choose any version ever published by the Free Software+Foundation.++ 10. If you wish to incorporate parts of the Program into other free+programs whose distribution conditions are different, write to the author+to ask for permission. For software which is copyrighted by the Free+Software Foundation, write to the Free Software Foundation; we sometimes+make exceptions for this. Our decision will be guided by the two goals+of preserving the free status of all derivatives of our free software and+of promoting the sharing and reuse of software generally.++ NO WARRANTY++ 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY+FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN+OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES+PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED+OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF+MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS+TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE+PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,+REPAIR OR CORRECTION.++ 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR+REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,+INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING+OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED+TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY+YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER+PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE+POSSIBILITY OF SUCH DAMAGES.++ END OF TERMS AND CONDITIONS++ How to Apply These Terms to Your New Programs++ If you develop a new program, and you want it to be of the greatest+possible use to the public, the best way to achieve this is to make it+free software which everyone can redistribute and change under these terms.++ To do so, attach the following notices to the program. It is safest+to attach them to the start of each source file to most effectively+convey the exclusion of warranty; and each file should have at least+the "copyright" line and a pointer to where the full notice is found.++ <one line to give the program's name and a brief idea of what it does.>+ Copyright (C) <year> <name of author>++ This program is free software; you can redistribute it and/or modify+ it under the terms of the GNU General Public License as published by+ the Free Software Foundation; either version 2 of the License, or+ (at your option) any later version.++ This program is distributed in the hope that it will be useful,+ but WITHOUT ANY WARRANTY; without even the implied warranty of+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ GNU General Public License for more details.++ You should have received a copy of the GNU General Public License+ along with this program; if not, write to the Free Software+ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA+++Also add information on how to contact you by electronic and paper mail.++If the program is interactive, make it output a short notice like this+when it starts in an interactive mode:++ Gnomovision version 69, Copyright (C) year name of author+ Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.+ This is free software, and you are welcome to redistribute it+ under certain conditions; type `show c' for details.++The hypothetical commands `show w' and `show c' should show the appropriate+parts of the General Public License. Of course, the commands you use may+be called something other than `show w' and `show c'; they could even be+mouse-clicks or menu items--whatever suits your program.++You should also get your employer (if you work as a programmer) or your+school, if any, to sign a "copyright disclaimer" for the program, if+necessary. Here is a sample; alter the names:++ Yoyodyne, Inc., hereby disclaims all copyright interest in the program+ `Gnomovision' (which makes passes at compilers) written by James Hacker.++ <signature of Ty Coon>, 1 April 1989+ Ty Coon, President of Vice++This General Public License does not permit incorporating your program into+proprietary programs. If your program is a subroutine library, you may+consider it more useful to permit linking proprietary applications with the+library. If this is what you want to do, use the GNU Library General+Public License instead of this License.
+ Setup.hs view
@@ -0,0 +1,2 @@+import Distribution.Simple+main = defaultMain
+ data/Hints.hs view
@@ -0,0 +1,120 @@+-- I/O++hint = putStrLn (show x) ==> print x++-- LIST++hint = concat (map f x) ==> concatMap f x+hint "Use one map" = map f (map g x) ==> map (f . g) x+hint = (x !! 0) ==> head x+hint = take n (repeat x) ==> replicate n x+hint = (x ++ concatMap (' ':) y) ==> unwords (x:y)+hint = concat (intersperse " " x) ==> unwords x+hint = head (reverse x) ==> last x+hint "Use index" = head (drop n x) ==> (x !! n)+hint = reverse (tail (reverse x)) ==> init x+hint = isPrefixOf (reverse x) (reverse y) ==> isSuffixOf x y++-- BOOL++hint = not (a == b) ==> (a /= b)+hint = not (a /= b) ==> (a == b)+hint "Redundant if" = (if a then True else False) ==> a+hint "Redundant if" = (if a then False else True) ==> not a+hint "Redundant if" = (if a then t else (if b then t else f)) ==> if a || b then t else f+hint "Redundant if" = (if a then (if b then t else f) else f) ==> if a && b then t else f+hint "Use if" = case a of {True -> t; False -> f} ==> if a then t else f+hint "Use if" = case a of {True -> t; _ -> f} ==> if a then t else f+hint "Use if" = case a of {False -> f; _ -> t} ==> if a then t else f++-- MONAD++hint = m >>= return . f ==> liftM f m+hint = (if x then y else return ()) ==> (when x $ y)++-- LIST COMP++hint "Use a list comprehension" = (if b then [x] else []) ==> [x | b]++-- SEQ++hint "The seq is redundant" = (x `seq` x) ==> x+hint "The $! is redundant" = (id $! x) ==> x++-- MAYBE++hint = maybe x id ==> fromMaybe x+hint = maybe False (const True) ==> isJust+hint = maybe True (const False) ==> isNothing++-- COMPLEX++hint "Use isPrefixOf, and then remove the (==) test" = (take i s == t) ==> ((i == length t) && (t `isPrefixOf` s))+ where _ = (isList t || isLit t) && isLit i+++{-+<TEST>+yes = concat . map f+yes = foo . bar . concat . map f . baz . bar+yes = map f (map g x)+yes = concat.map (\x->if x==e then l' else [x])+yes = f x where f x = concat . map head+yes = concat . map f . g+yes = concat $ map f x+yes = "test" ++ concatMap (' ':) ["of","this"]+yes = concat . intersperse " "+yes = if f a then True else False+yes = if f a then False else True+yes = not (a == b)+yes = not (a /= b)+yes = if a then 1 else if b then 1 else 2+no = if a then 1 else if b then 3 else 2+yes = a >>= return . id+yes = (x !! 0) + (x !! 2)+yes = if x == e then l2 ++ xs else [x] ++ check_elem xs+yes = if b < 42 then [a] else []+yes = take 5 (foo xs) == "hello"+no = take n (foo xs) == "hello"+yes = head (reverse xs)+yes = reverse xs `isPrefixOf` reverse ys+</TEST>+-}+++{-+-- TODO: Add RecMatch for things like map/foldr etc, with a similar entry in hints++-- more complicated, saved for later++-- map f x+redefined_map = mop+ where+ mop f (x:xs) = f x : mop f xs+ mop f [] = []++-- map<f> x+special_map f = mop+ where+ mop (x:xs) = f x : mop xs+ mop [] = []+++-- foldr f z x+special_foldr f z = fold+ where+ fold [] = z+ fold (x:xs) = f x (fold xs)++-- foldl f z x+special_foldl1 f = fold+ where+ fold acc [] = acc+ fold acc (x:xs) = fold (f x acc) xs++special_foldl2 f = fold+ where+ fold [] acc = acc+ fold (x:xs) acc = fold xs (f x acc)++-}
+ data/hlint_ignore.txt view
@@ -0,0 +1,17 @@+## This is a template file for ignoring hints from hlint+## Comments in this file start with a single # character++## To ignore all hints about eta reduction+# Eta reduce++## To ignore all hints about eta reduction in the module Data.List+# {Data.List} Eta reduce++## To ignore in both Data.List and Prelude+# {Data.List Prelude} Eta reduce++## To ignore in only one function+# {Data.List.map} Eta reduce++## To undo a previously ignored line+# !{Data.List.map} Eta reduce
+ data/report.html view
@@ -0,0 +1,195 @@+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">+<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">+<head>+<meta http-equiv="Content-Type" content="application/xhtml+xml; charset=UTF-8" />+<title>HLint report</title>+<script type='text/javascript'>+var hints = {};+var files = {};+var items = [];++var link_sel = 1;+var link_count = 0;++// <CONTENT>+idea("Eta reduce","Data/Binary/Defer/Class.hs",31,1,"get0 f = return f","get0 = return");+idea("Eta reduce","Data/Binary/Defer/Class.hs",41,1,"getFixed0 f = return f","getFixed0 = return");+idea("Eta reduce","Data/Binary/Defer/Class.hs",51,1,"put1 x1 = put x1","put1 = put");+idea("Use on","Data/Binary/Defer/Class.hs",52,1,"put2 x1 x2 = put x1 >> put x2","put2 = (>>) `on` put");+idea("Use on","Data/Binary/Defer/Link.hs",48,5,"a == b = linkKey a == linkKey b","(==) = (==) `on` linkKey");+idea("Use concatMap","General/Util.hs",71,1,"concat $ map (\\ a -> zipWith f (inits a) (tails a)) (permute xs)","concatMap (\\ a -> zipWith f (inits a) (tails a)) (permute xs)");+// </CONTENT>++function idea(name,file,line,col,old,suggest)+{+ hints[name] = value(0, hints[name]) + 1;+ files[file] = value(0, files[file]) + 1;+ items[items.length+1] = {name:name, file:file, line:line, col:col, old:old, suggest:suggest};+}++function sum(xs)+{+ var n = 0;+ for (var i in xs)+ n += xs[i];+ return n;+}++function value(def, x)+{+ if (x) return x; else return def;+}++function show_item(x)+{+ var s = "";+ s += x.file + ":" + x.line + ":" + x.col + ": " + x.name + "<br/>";+ s += "Found:<br/><pre>" + x.old + "</pre>";+ s += "Why not:<br/><pre>" + x.suggest + "</pre><hr/>";+ return s;+}++function show_items(f)+{+ var s = "";+ for (i in items)+ {+ var x = items[i];+ if (f(x)) s += show_item(x);+ }+ return s;+}++function pick_link(i)+{+ document.getElementById("link_" + link_sel).style.fontWeight = "normal";+ document.getElementById("link_" + i).style.fontWeight = "bold";+ link_sel = i;+}++function show_hints(i, match)+{+ pick_link(i);+ var s = "";+ for (var i in hints)+ {+ if (i == match || match == "")+ {+ function f(x){return x.name == i};+ s += "<h2>" + i + "</h2>"+ s += show_items(f);+ }+ }+ document.getElementById('content').innerHTML = s;+}++function show_files(i, match)+{+ pick_link(i);+ var s = "";+ for (var i in files)+ {+ if (i == match || match == "")+ {+ function f(x){return x.file == i};+ s += "<h2>" + i + "</h2>"+ s += show_items(f);+ }+ }+ document.getElementById('content').innerHTML = s;+}++function on_load()+{+ function f(name,file,line,col,old,suggest)+ {+ hints[name] = value(0, hints[name]) + 1;+ files[file] = value(0, files[file]) + 1;+ }++ function shows(text, xs)+ {+ var s;+ link_count++;+ s = "<p><a id='link_" + link_count + "' href='javascript:show_" + text + "(" + link_count + ",\"\")'>All " + text + " (" + sum(xs) + ")</a></p><ul>";+ for (var i in xs)+ {+ link_count++;+ s += "<li><a id='link_" + link_count + "' href='javascript:show_" + text + "(" + link_count + ",\"" + i + "\")'>" + i + " (" + xs[i] + ")</a></li>";+ }+ s += "</ul>";+ return s;+ }++ var s = shows("hints",hints) + shows("files",files);+ document.getElementById('leftbar').innerHTML = s;++ show_hints(1,"");+}+</script>+<style type="text/css">+/* See http://www.webreference.com/programming/css_frames/ */+body {+ margin:0;+ border:0;+ padding:0;+ height:100%;+ max-height:100%;+ font-family: sans-serif;+ font-size:76%;+ overflow: hidden;+}++h1 {+ position:absolute;+ top:0;+ left:0;+ width:100%;+ height:35px;+ overflow:auto;+ padding: 0;+ padding-left: 10px;+ margin: 0;+}++#leftbar {+ position:absolute;+ top:30px;+ left:0;+ width: 215px;+ bottom: 0px;+ overflow:auto;+ background:rgb(202,223,255);+ margin: 10px;+ padding-top: 0;+ padding-left: 7px;+ padding-right: 7px;+ -moz-border-radius: 5px;+}++#content {+ position:absolute;+ top:35px;+ left:250px;+ bottom:0;+ right:0;+ overflow:auto;+ padding-bottom: 15px;+}++#leftbar ul {margin-top: 0px; padding-left: 15px;}+#leftbar p {margin-bottom: 0px;}++pre{+ font-family: "lucida console", monospace;+}++</style>+</head>+<body onload='on_load()'>+<h1><a href="http://www.cs.york.ac.uk/~ndm/hlint/">HLint</a> report</h1>++<div id="leftbar" valign="top" style="min-width:200px">leftbar</div>+<div id="content" valign="top" width="100%">content</div>+</body>+</html>
+ hlint.cabal view
@@ -0,0 +1,42 @@+cabal-version: >= 1.2+build-type: Simple+name: hlint+version: 1.0.0.0+license: GPL+license-file: LICENSE+category: Development+author: Neil Mitchell <ndmitchell@gmail.com>+maintainer: Neil Mitchell <ndmitchell@gmail.com>+copyright: Neil Mitchell 2006-2008+synopsis: Source code suggestions+description:+ HLint gives suggestions on how to improve your source code.+homepage: http://www.cs.york.ac.uk/~ndm/hlint/+stability: Beta+data-dir: data+data-files:+ Hints.hs+ report.html+ hlint_ignore.txt+Extra-Source-Files:+ hlint.htm+++executable hlint+ build-depends: base == 4.0.*, syb, filepath, directory, haskell-src-exts == 0.4.6.*, uniplate == 1.2.* && >= 1.2.0.2, mtl, containers++ ghc-options: -fno-warn-overlapping-patterns+ main-is: Main.hs+ hs-source-dirs: src+ other-modules:+ CmdLine+ Main+ Report+ Type+ Util+ Hint.All+ Hint.Bracket+ Hint.Lambda+ Hint.List+ Hint.Match+ Hint.Monad
+ hlint.htm view
@@ -0,0 +1,165 @@+<!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://www.cs.york.ac.uk/~ndm/">Neil Mitchell</a>+</p>++<p>+ <a href="http://www.cs.york.ac.uk/~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>Installing and running HLint</li>+ <li>Adding additional hints</li>+ <li>Ignoring certain hints</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 useful improvements have been made by <a href="http://www.cs.chalmers.se/~d00nibro/">Niklas Broberg</a> in response to feature requests.+</p>++<h3>Bugs and limitations</h3>++<ul>+ <li>In some cases, the precedence of infix operators will be incorrect, leading to incorrect suggestions. It is hoped this will be fixed in a future version.</li>+ <li>Files requiring the C pre processor are not supported.</li>+</ul>+++<h2>Installing and running HLint</h2>++<p>+ Installation follows the standard pattern of any Haskell library or program, simply 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, simply run <tt>hlint <i>source</i></tt> where <i>source</i> is either a Haskell file or a directory containing some Haskell files. For example, running HLint over darcs would give:+</p>+<pre>++$ hlint darcs-2.1.2++darcs-2.1.2\src\CommandLine.lhs:94:1: Use concatMap+Found:+ concat $ map escapeC s+Why not:+ concatMap escapeC s++darcs-2.1.2\src\CommandLine.lhs:103:1: 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: 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, 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 class="rule">+ <b>Disclaimer:</b> While these hints are meant to be correct, they aren't guaranteed to be. Please report non equivalent code which doesn't involve incorrect parsing of infix operators (see Bugs above), and is incorrect without <tt>seq</tt>.+</p>++<h3>Reports</h3>++<p>+ HLint can generate a lot of information, and often searching for either the errors specific to a file, or a specific class of errors, is difficult. Using the <tt>--report</tt> flag HLint will produce a report file in HTML, which can be viewed interactively. It is recommended that if investigating more than a handlful of hints, a report is used.+</p>+++<h2>Adding additional hints</h2>++<p>+ The majority of hints are contained in a <tt>Hints.hs</tt> file which will be installed in the appropriate data directory by Cabal. This file may be freely edited, to add library specific knowledge, or to include hints that may have been missed. As an example of the contents of this file, the line specifying <tt>concatMap</tt> is:+</p>+<pre>+hint = 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>concat (map <i>f</i> <i>x</i>)</tt>. Anything with a 1-letter variable is treated as a substitution parameter. For examples of more complex hints see the supplied hints file.+</p><p>+ If you come up with interesting hints, please submit them. For example, some of the hints about <tt>last</tt> were supplied by Henning Thielemann.+</p>+++<h2>Ignoring certain hints</h2>++<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 are picked up from the <tt>hlint_ignore.txt</tt> file from the users data directory, along with any files specified with <tt>-I</tt> and any directives specified with <tt>-i</tt>. Some example directives are:+</p>+<ul>+ <li><tt>Eta reduce</tt> - supress all eta reduction suggestions.</li>+ <li><tt>{Data.List Prelude} Eta reduce</tt> - supress eta reduction hints in the Prelude and Data.List modules.</li>+ <li><tt>{Data.List.map}</tt> - don't give any hints in the function Data.List.map.</li>+ <li><tt>!{Data.List.map}</tt> - discard a previous ignore directive.</li>+</ul>+<p>+ In hint files, any lines which are blank or start with the <tt>#</tt> character are ignored.+</p>+++ </body>+</html>
+ src/CmdLine.hs view
@@ -0,0 +1,96 @@++module CmdLine(Mode(..), getMode) where++import Control.Monad+import Data.List+import Data.Maybe+import System.Console.GetOpt+import System.Directory+import System.Environment+import System.Exit+import System.FilePath+import Util++import Paths_hlint+import Data.Version+++data Mode = Mode+ {modeHints :: [FilePath] -- ^ which hint files to use+ ,modeFiles :: [FilePath] -- ^ which files to run it on+ ,modeTest :: Bool -- ^ run in test mode?+ ,modeReports :: [FilePath] -- ^ where to generate reports+ ,modeIgnoreFiles :: [FilePath] -- ^ where the ignore files are+ ,modeIgnore :: [String] -- ^ the ignore commands on the command line+ }+++data Opts = Help | HintFile FilePath | Test | Report FilePath | Ignore String | IgnoreFile FilePath+ deriving Eq++opts = [Option "?" ["help"] (NoArg Help) "Display help message"+ ,Option "h" ["hint"] (ReqArg HintFile "file") "Hint file to use"+ ,Option "t" ["test"] (NoArg Test) "Run in test mode"+ ,Option "r" ["report"] (OptArg (Report . fromMaybe "report.html") "file") "Generate a report in HTML"+ ,Option "i" ["ignore"] (ReqArg Ignore "message") "Ignore a particular hint"+ ,Option "I" ["ignore-file"] (ReqArg IgnoreFile "file") "A file of things to ignore"+ ]+++-- | Exit out if you need to display help info+getMode :: IO Mode+getMode = do+ args <- getArgs+ let (opt,files,err) = getOpt Permute opts args+ let test = Test `elem` opt+ when (not $ null err) $+ error $ unlines $ "Unrecognised arguments:" : err++ when (Help `elem` opt || (null files && not test)) $ do+ putStr $ unlines ["HLint v" ++ showVersion version ++ ", (C) Neil Mitchell 2006-2008, University of York"+ ,""+ ," hlint [files] [options]"+ ,usageInfo "" opts+ ,"HLint makes hints on how to improve some Haskell code."]+ exitWith ExitSuccess++ hints <- return [x | HintFile x <- opt]+ hints <- if null hints then getFile "Hints.hs" else return hints+ files <- liftM concat $ mapM getFile files++ dat <- getDataDir+ let stdIgnoreFile = dat </> "hlint_ignore.txt"+ hasIgnoreFile <- doesFileExist stdIgnoreFile++ return Mode{modeHints=hints, modeFiles=files, modeTest=test+ ,modeReports=[x | Report x <- opt]+ ,modeIgnore=[x | Ignore x <- opt]+ ,modeIgnoreFiles=[stdIgnoreFile | hasIgnoreFile] ++ [x | IgnoreFile x <- opt]+ }+++ifNull :: [a] -> [a] -> [a]+ifNull x y = if null x then y else x+++getFile :: FilePath -> IO [FilePath]+getFile file = do+ b <- doesDirectoryExist file+ if b then f file else do+ b <- doesFileExist file+ if b then return [file] else do+ dat <- getDataDir+ let s = dat </> file+ b <- doesFileExist s+ if b then return [s] else error $ "Couldn't find file: " ++ file+ where+ f file | takeExtension file `elem` [".hs",".lhs"] = return [file]+ f file = do+ b <- doesDirectoryExist file+ if not b then return [] else do+ s <- getDirectoryContents file+ liftM concat $ mapM (f . (</>) file) $ filter (not . isBadDir) s+++isBadDir :: FilePath -> Bool+isBadDir x = "." `isPrefixOf` x || "_" `isPrefixOf` x
+ src/Hint/All.hs view
@@ -0,0 +1,33 @@++module Hint.All(readHints, allHints) where++import Control.Monad+import Util+import Type+import Language.Haskell.Exts++import Hint.Match+import Hint.List+import Hint.Monad+import Hint.Lambda+import Hint.Bracket+++allHints :: [(String,Hint)]+allHints =+ let (*) = (,) in+ ["List" * listHint+ ,"Monad" * monadHint+ ,"Lambda" * lambdaHint+ ,"Bracket" * bracketHint+ ]+++readHints :: [FilePath] -> IO Hint+readHints = liftM (concatHints . concat) . mapM readHint+++readHint :: FilePath -> IO [Hint]+readHint file = do+ modu <- parseHsModule file+ return $ readMatch modu : map snd allHints
+ src/Hint/Bracket.hs view
@@ -0,0 +1,60 @@+{-# LANGUAGE PatternGuards #-}++{-+<TEST>+yes = (f x) x+no = f (x x)+yes = (f x) ||| y+yes = if (f x) then y else z+yes = if x then (f y) else z+</TEST>+-}+++module Hint.Bracket where++import Control.Monad+import Control.Monad.State+import Data.Generics+import Data.Maybe+import Type+import Util+import Language.Haskell.Exts+++bracketHint :: Hint+bracketHint = concatMap bracketExp . universeExp nullSrcLoc++bracketExp :: (SrcLoc,Exp) -> [Idea]+bracketExp (loc,x) = [idea "Use fewer brackets" loc x y | Just y <- [f x]]+ where+ f :: Exp -> Maybe Exp+ f (Paren x) | atom x = Just x+ f x = if cs /= [] && b then Just r else Nothing+ where+ (r,(b,[])) = runState (gmapM g x) (False, cs)+ cs = snd $ precedence x+ + g :: Data a => a -> State (Bool,[Int]) a+ g x | Just y <- cast x = do+ (b,c:cs) <- get+ liftM (fromJust . cast) $ case y of+ Paren z | fst (precedence z) < c -> put (True, cs) >> return z+ _ -> put (b, cs) >> return y+ g x = return x+++-- return my precedence, and the precedence of my children+-- higher precedence means no brackets+-- if the object in a position has a lower priority, the brackets are unnecessary+precedence :: Exp -> (Int,[Int])+precedence x = case x of+ If{} -> block * [block,block,block]+ Let{} -> block * [block]+ Case{} -> block * [block]+ InfixApp{} -> op * [op,op]+ App{} -> appL * [appR,appL]+ _ -> top * []+ where+ (*) = (,)+ appL:appR:op:block:top:_ = [1..]
+ src/Hint/Lambda.hs view
@@ -0,0 +1,90 @@+{-# LANGUAGE ViewPatterns, PatternGuards #-}++{-+ Find and match:++ foo a = \x -> y (provided no where's outside the lambda)+ \x -> y (use const, if the variable x does not occur in y, and it doesn't need bracketing)+ foo x = y x (eta reduce)+ foo x = f $ g x (eta reduce, convert to .)+ foo x y = f (g x) (g y) ==> f `on` g+ -- Never offer to eta reduce if the variable is named mr and is the only one (Monomorphism Restriction)+ -- don't eta reduce func a b c = .... (g b) (g c) to (g b) . g, looks ugly++<TEST>+yes1 a = \x -> x + x+yes2 a = foo (\x -> True) -- const True+no1 = foo (\x -> map f [])+yes3 x = y x -- eta reduce+no2 mr = y mr+yes4 x = g $ f $ map head x+no3 z x y = f (g x) (g y)+yes5 x y = f (g x) (g y)+</TEST>+-}+++module Hint.Lambda where++import Util+import Type+import Control.Monad+import Language.Haskell.Exts+import Data.Generics.PlateData+import Data.Maybe+++lambdaHint :: Hint+lambdaHint x = concatMap lambdaExp (universeBi x) ++ concatMap lambdaDecl (universe x)+++lambdaExp :: Exp -> [Idea]+lambdaExp o@(Lambda loc [v] y) | atom y, Just x <- f v, x `notElem` universeBi y =+ [idea "Use const" loc o res]+ where+ f (PVar x) = Just x+ f PWildCard = Just $ Ident "_"+ f _ = Nothing+ res = App (toVar "const") (hsParen y)+lambdaExp _ = []+++lambdaDecl :: Decl -> [Idea]+lambdaDecl (PatBind loc (PVar x) rhs bind) = lambdaDef $ Match loc x [] rhs bind+lambdaDecl (FunBind [x]) = lambdaDef x --only apply to 1-def, because arities must be the same+lambdaDecl _ = []+++lambdaDef :: Match -> [Idea]+lambdaDef o@(Match loc name pats (UnGuardedRhs bod) (BDecls []))+ | Lambda loc vs y <- bod = [idea "Lambda shift" loc o $ reform (pats++vs) y]+ | pats /= [], PVar p <- last pats, Ident _ <- name, p /= Ident "mr", Just y <- etaReduce p bod =+ [idea "Eta reduce" loc o $ reform (init pats) y]+ | [PVar x, PVar y] <- pats, Just (f,g) <- useOn x y bod =+ [idea "Use on" loc o $ reform [] (remParen $ InfixApp (addParen f) (QVarOp $ UnQual $ Ident "on") (addParen g))]+ where reform pats2 bod2 = Match loc name pats2 (UnGuardedRhs bod2) (BDecls [])+lambdaDef _ = []+++-- given x y, f (g x) (g y) = Just (f, g)+useOn :: Name -> Name -> Exp -> Maybe (Exp, Exp)+useOn x1 y1 (view -> App2 f (view -> App1 g1 x2) (view -> App1 g2 y2))+ | g1 == g2, map (Var . UnQual) [x1,y1] == [x2,y2] = Just (f,g1)+useOn _ _ _ = Nothing+++etaReduce :: Name -> Exp -> Maybe Exp+etaReduce x (App y (Var (UnQual z))) | x == z && x `notElem` universeBi y = Just y+etaReduce x (App y z) | not (uglyEta y z) && x `notElem` universeBi y = do+ z2 <- etaReduce x z+ return $ InfixApp y (QVarOp $ UnQual $ Symbol ".") z2+etaReduce x (view -> App2 dollar y z) | dollar ~= "$" = etaReduce x (App y z)+etaReduce x y | isParen y = etaReduce x (fromParen y)+etaReduce x _ = Nothing+++-- (f (g x)) (h y), ugly if g == h+uglyEta :: Exp -> Exp -> Bool+uglyEta (fromParen -> App f (fromParen -> App g x)) (fromParen -> App h y) = g == h+uglyEta _ _ = False+
+ src/Hint/List.hs view
@@ -0,0 +1,65 @@+{-# LANGUAGE ViewPatterns, PatternGuards #-}++{-+ Find and match:++<TEST>+yes = 1:2:[] -- [1,2]+yes = ['h','e','l','l','o'] -- "hello"++-- [a]++b -> a : b, but only if not in a chain of ++'s+yes = [x] ++ xs+yes = "x" ++ xs+no = [x] ++ xs ++ ys+no = xs ++ [x] ++ ys+</TEST>+-}+++module Hint.List where++import Util+import Type+import Language.Haskell.Exts+++listHint :: Hint+listHint = listDecl++listDecl :: Decl -> [Idea]+listDecl = concatMap (listExp False) . children0Exp nullSrcLoc++-- boolean = are you in a ++ chain+listExp :: Bool -> (SrcLoc,Exp) -> [Idea]+listExp b (loc,x) =+ if null res then concatMap (listExp $ isAppend x) $ children1Exp loc x else [head res]+ where+ res = [idea name loc x x2 | (name,f) <- checks, Just x2 <- [f b x]]+++isAppend (view -> App2 op _ _) = op ~= "++"+isAppend _ = False+++checks = let (*) = (,) in+ ["Use a string literal" * useString+ ,"Use a list literal" * useList+ ,"Use (:)" * useCons+ ]+++useString b (List xs) | not (null xs) && all isCharExp xs = Just $ Lit $ String [x | Lit (Char x) <- xs]+useString b _ = Nothing++useList b = fmap List . 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 _ = Nothing++useCons False (view -> App2 op x y) | op ~= "++", Just x2 <- f x = Just $ InfixApp x2 (QConOp list_cons_name) y+ where+ f (Lit (String [x])) = Just $ Lit $ Char x+ f (List [x]) = Just x+ f _ = Nothing+useCons _ _ = Nothing
+ src/Hint/Match.hs view
@@ -0,0 +1,134 @@+{-# LANGUAGE PatternGuards, ViewPatterns #-}++module Hint.Match(readMatch) where++import Language.Haskell.Exts+import Data.Char+import Data.Generics.PlateData+import Data.List+import Data.Maybe+import Type+import Util+import Control.Monad+import Data.Function+++data Mat = Mat {message :: String, lhs :: Exp, rhs :: Exp, side :: Maybe Exp}++instance Show Mat where+ show (Mat x y z q) = unlines $ ("Match " ++ show x) :+ map (\x -> " " ++ prettyPrint x) ([y,z] ++ maybeToList q)++ showList = showString . concatMap show++-- Any 1-letter variable names are assumed to be unification variables+isFreeVar :: String -> Bool+isFreeVar [x] = x == '?' || isAlpha x+isFreeVar _ = False+++---------------------------------------------------------------------+-- READ THE MATCHES++readMatch :: Module -> Hint+readMatch = findIdeas . concatMap readOne . childrenBi++++readOne :: Decl -> [Mat]+readOne (FunBind [Match src (Ident "hint") [PLit (String msg)]+ (UnGuardedRhs (InfixApp lhs (QVarOp (UnQual (Symbol "==>"))) rhs)) (BDecls bind)]) =+ [Mat (if null msg then pickName lhs rhs else msg) (fromParen lhs) (fromParen rhs) (readSide bind)]++readOne (PatBind src (PVar name) bod bind) = readOne $ FunBind [Match src name [PLit (String "")] bod bind]++readOne (FunBind xs) | length xs /= 1 = concatMap (readOne . FunBind . (:[])) xs++readOne x = error $ "Failed to read hint " ++ maybe "" showSrcLoc (getSrcLoc x) ++ "\n" ++ prettyPrint x+++readSide :: [Decl] -> Maybe Exp+readSide [] = Nothing+readSide [PatBind src PWildCard (UnGuardedRhs bod) (BDecls [])] = Just bod+readSide (x:_) = error $ "Failed to read side condition " ++ maybe "" showSrcLoc (getSrcLoc x) ++ "\n" ++ prettyPrint x+++pickName :: Exp -> Exp -> String+pickName lhs rhs | null names = "Unnamed suggestion"+ | otherwise = "Use " ++ head names+ where+ names = filter (not . isFreeVar) $ map f (childrenBi rhs) \\ map f (childrenBi lhs) + f (Ident x) = x+ f (Symbol x) = x+++---------------------------------------------------------------------+-- PERFORM MATCHING++findIdeas :: [Mat] -> Decl -> [Idea]+findIdeas matches decl =+ [ idea (message m) loc x y+ | (loc, x) <- universeExp nullSrcLoc decl, not $ isParen x+ , m <- matches, Just y <- [matchIdea m x]]+++matchIdea :: Mat -> Exp -> Maybe Exp+matchIdea Mat{lhs=lhs,rhs=rhs,side=side} x = do+ u <- unify lhs x+ u <- check u+ if checkSide side u+ then return $ remParen $ dotContract $ subst u rhs+ else Nothing+++-- unify a b = c, a[c] = b+unify :: Exp -> Exp -> Maybe [(String,Exp)]+unify x y | isParen x || isParen y = unify (fromParen x) (fromParen y)+unify x y | Just v <- fromVar x, isFreeVar v = Just [(v,addParen y)]+unify x y | ((==) `on` descend (const $ toVar "_")) x y = liftM concat $ zipWithM unify (children x) (children y)+unify x o@(view -> App2 op y1 y2)+ | op ~= "$" = unify x $ addParen y1 `App` addParen y2+ | op ~= "." = unify x $ dotExpand o+unify x (InfixApp lhs op rhs) = unify x (opExp op `App` lhs `App` rhs)+unify _ _ = Nothing+++-- check the unification is valid+check :: [(String,Exp)] -> Maybe [(String,Exp)]+check = mapM f . groupBy ((==) `on` fst) . sortBy (compare `on` fst)+ where f xs = if length (nub xs) == 1 then Just (head xs) else Nothing+++checkSide :: Maybe Exp -> [(String,Exp)] -> Bool+checkSide Nothing bind = True+checkSide (Just x) bind = f x+ where+ f (InfixApp x op y)+ | opExp op ~= "&&" = f x && f y+ | opExp op ~= "||" = f x || f y+ f x | isParen x = f $ fromParen x+ f (App x y)+ | Just ('i':'s':typ) <- fromVar x, Just v <- fromVar y, Just e <- lookup v bind+ = head (words $ show e) == typ+ f x = error $ "Hint.Match.checkSide, unknown side condition: " ++ prettyPrint x+++-- perform a substitution+subst :: [(String,Exp)] -> Exp -> Exp+subst bind x | Just v <- fromVar x, isFreeVar v, Just y <- lookup v bind = y+ | otherwise = descend (subst bind) x+++dotExpand :: Exp -> Exp+dotExpand (view -> App2 op x1 x2) | op ~= "." = App (addParen x1) (addParen $ dotExpand x2)+dotExpand x = addParen x `App` toVar "?"+++-- simplify, removing any introduced ? vars, from expanding (.)+dotContract :: Exp -> Exp+dotContract x = fromMaybe x (f x)+ where+ f x | isParen x = f $ fromParen x+ f (App x y) | Just "?" <- fromVar y = Just x+ | Just z <- f y = Just $ InfixApp x (QVarOp $ UnQual $ Symbol ".") z+ f _ = Nothing
+ src/Hint/Monad.hs view
@@ -0,0 +1,46 @@+{-# LANGUAGE ViewPatterns, PatternGuards #-}++{-+ Find and match:++ mapM, foldM, forM, replicateM, sequence, zipWithM+ not at the last line of a do statement, or to the left of >>++<TEST>+yes = do mapM print a; return b+no = mapM print a+</TEST>+-}+++module Hint.Monad where++import Control.Monad+import Util+import Type+import Language.Haskell.Exts+++badFuncs = ["mapM","foldM","forM","replicateM","sequence","zipWithM"]+++monadHint :: Hint+monadHint = concatMap monadExp . universeExp nullSrcLoc++monadExp :: (SrcLoc,Exp) -> [Idea]+monadExp (loc,x) = case x of+ (view -> App2 op x1 x2) | op ~= ">>" -> f x1+ Do xs -> concat [f x | Qualifier x <- init xs]+ MDo xs -> monadExp (loc, Do xs)+ _ -> []+ where+ f x = [idea "Use a more efficient monadic variant" loc x y+ |Just y <- [monadCall x]]+++-- see through Paren and down if/case etc+monadCall :: Exp -> Maybe Exp+monadCall (Paren x) = liftM Paren $ monadCall x+monadCall (App x y) = liftM (`App` y) $ monadCall x+monadCall x | x:_ <- filter (x ~=) badFuncs = Just $ toVar (x ++ "_")+monadCall _ = Nothing
+ src/Main.hs view
@@ -0,0 +1,83 @@++module Main where++import Control.Arrow+import Control.Monad+import Data.List+import Language.Haskell.Exts+import System.Directory+import Data.Generics.PlateData++import CmdLine+import Report+import Type+import Ignore+import Util+import Hint.All+++main = do+ mode <- getMode+ if modeTest mode then do+ hints <- mapM (readHints . (:[])) (modeHints mode)+ src <- doesDirectoryExist "src/Hint"+ (fail,total) <- liftM ((sum *** sum) . unzip) $ sequence $+ zipWith runTest hints (modeHints mode) +++ [runTest h ("src/Hint/" ++ name ++ ".hs") | (name,h) <- allHints, src]+ when (not src) $ putStrLn "Warning, couldn't find source code, so non-hint tests skipped"+ if fail == 0+ then putStrLn $ "Tests passed (" ++ show total ++ ")"+ else putStrLn $ "Tests failed (" ++ show fail ++ " of " ++ show total ++ ")"+ else do+ hints <- readHints $ modeHints mode+ ignore <- ignore (modeIgnoreFiles mode) (modeIgnore mode)+ ideas <- liftM concat $ mapM (runFile ignore hints) (modeFiles mode)+ let n = length ideas+ if n == 0 then do+ when (not $ null $ modeReports mode) $ putStrLn "Skipping writing reports"+ putStrLn "No relevant suggestions"+ else do+ flip mapM_ (modeReports mode) $ \x -> do+ putStrLn $ "Writing report to " ++ x ++ " ..."+ writeReport x ideas+ putStrLn $ "Found " ++ show n ++ " suggestions"+++-- return the number of hints given+runFile :: (Idea -> Bool) -> Hint -> FilePath -> IO [Idea]+runFile ignore hint file = do+ src <- parseHsModule file+ let ideas = filter (not . ignore) $ applyHint hint src+ mapM_ print ideas+ return ideas++++-- return the number of fails/total+runTest :: Hint -> FilePath -> IO (Int,Int)+runTest hint file = do+ tests <- parseTestFile file+ let failures = concatMap f tests+ mapM_ putStrLn failures+ return (length failures, length tests)+ where+ f o | ("no" `isPrefixOf` name) == null ideas && length ideas <= 1 = []+ | otherwise = ["Test failed in " ++ name ++ concatMap ((++) " | " . show) ideas]+ where+ ideas = hint o+ name = declName o+++parseTestFile :: FilePath -> IO [Decl]+parseTestFile file = do+ src <- readFile file+ src <- return $ unlines $ f $ lines src+ case parseFileContents src of+ ParseOk x -> return $ childrenBi $ operatorPrec x+ _ -> error $ "Parse failure in test block of " ++ file ++ "\n" ++ src+ where+ open = isPrefixOf "<TEST>"+ shut = isPrefixOf "</TEST>"+ f [] = []+ f xs = inner ++ f (drop 1 test)+ where (inner,test) = break shut $ drop 1 $ dropWhile (not . open) xs
+ src/Report.hs view
@@ -0,0 +1,44 @@++module Report(writeReport) where++import Type+import Language.Haskell.Exts+import Data.List+import System.FilePath+import Paths_hlint+++writeReport :: FilePath -> [Idea] -> IO ()+writeReport file ideas = do+ dat <- getDataDir+ src <- readFile (dat </> "report.html")+ writeFile file $ unlines $ repContent content $ lines src+ where+ content = map f ideas+ drp = filePrefix $ map (srcFilename . loc) ideas+ f x = "idea(" ++ concat (intersperse "," args) ++ ");"+ where args = [show $ text x+ ,show $ drp $ srcFilename $ loc x, show $ srcLine $ loc x, show $ srcColumn $ loc x+ ,show $ from x, show $ to x]+++repContent :: [String] -> [String] -> [String]+repContent content xs = pre ++ take 1 mid ++ content ++ post+ where+ (pre,mid) = break (isInfixOf_ "<CONTENT>") xs+ post = dropWhile (not . isInfixOf_ "</CONTENT>") mid+++-- from GHC 6.10 is in the real libraries+isInfixOf_ find = any (isPrefixOf find) . tails+++filePrefix :: [FilePath] -> (FilePath -> FilePath)+filePrefix xs | null xs = flipSlash+ | otherwise = flipSlash . drop n2+ where+ (mn,mx) = (minimum xs, maximum xs)+ n = length $ takeWhile id $ zipWith (==) mn mx+ n2 = length $ dropWhile (`notElem` "\\/") $ reverse $ take n mn++ flipSlash = map (\x -> if x == '\\' then '/' else x)
+ src/Type.hs view
@@ -0,0 +1,32 @@++module Type where++import Language.Haskell.Exts+import Util+++-- Key is Data.List.split, for example+data Idea = Idea {key :: String, text :: String, loc :: SrcLoc, from :: String, to :: String}+ deriving Eq++idea s loc from to = Idea "" s loc (prettyPrint from) (prettyPrint to)+++instance Show Idea where+ show x = unlines $+ [showSrcLoc (loc x) ++ " " ++ text x] ++ f "Found" from ++ f "Why not" to+ where f msg sel = (msg ++ ":") : map (" "++) (lines $ sel x)++++type Hint = Decl -> [Idea]+++concatHints :: [Hint] -> Hint+concatHints hs x = concatMap ($x) hs+++applyHint :: Hint -> Module -> [Idea]+applyHint h m = [i{key = name ++ ['.'|name/=""] ++ declName d}+ | d <- moduleDecls m, i <- h d]+ where name = moduleName m
+ src/Util.hs view
@@ -0,0 +1,200 @@+{-# LANGUAGE PatternGuards, ViewPatterns, MultiParamTypeClasses #-}++module Util where++import Data.Generics+import Data.Generics.PlateData+import Data.List+import Data.Maybe+import Language.Haskell.Exts+++headDef :: a -> [a] -> a+headDef x [] = x+headDef x (y:ys) = y+++declName :: Decl -> String+declName (TypeDecl _ name _ _) = fromName name+declName (DataDecl _ _ _ name _ _ _) = fromName name+declName (GDataDecl _ _ _ name _ _ _ _) = fromName name+declName (TypeFamDecl _ name _ _) = fromName name+declName (DataFamDecl _ _ name _ _) = fromName name+declName (ClassDecl _ _ name _ _ _) = fromName name+declName (PatBind _ (PVar name) _ _) = fromName name+declName (FunBind (Match _ name _ _ _ : _)) = fromName name+declName (ForImp _ _ _ _ name _) = fromName name+declName (ForExp _ _ _ name _) = fromName name+declName _ = ""+++fromName :: Name -> String+fromName (Ident x) = x+fromName (Symbol x) = x+++opExp :: QOp -> Exp+opExp (QVarOp op) = Var op+opExp (QConOp op) = Con op+++parseHsModule :: FilePath -> IO Module+parseHsModule file = do+ res <- parseFile file+ case res of+ ParseOk x -> return $ operatorPrec x+ ParseFailed src msg -> do+ putStrLn $ showSrcLoc src ++ " Parse failure, " ++ limit 50 msg+ return $ Module nullSrcLoc (ModuleName "") [] Nothing Nothing [] []++moduleDecls :: Module -> [Decl]+moduleDecls (Module _ _ _ _ _ _ xs) = xs++moduleName :: Module -> String+moduleName (Module _ (ModuleName x) _ _ _ _ _) = x++++limit :: Int -> String -> String+limit n s = if null post then s else pre ++ "..."+ where (pre,post) = splitAt n s+++-- "f $ g $ x" is parsed as "(f $ g) $ x", but should be "f $ (g $ x)"+-- ditto for (.)+-- this function rotates the ($) and (.), provided there are no explicit Parens+operatorPrec :: Module -> Module+operatorPrec = descendBi (transform f)+ where+ f (InfixApp (InfixApp x op2 y) op1 z) + | op <- opExp op1, op1 == op2, op ~= "." || op ~= "$" = f $ InfixApp x op1 (f $ InfixApp y op1 z)+ f x = x+++---------------------------------------------------------------------+-- SRCLOC FUNCTIONS++nullSrcLoc :: SrcLoc+nullSrcLoc = SrcLoc "" 0 0++showSrcLoc :: SrcLoc -> String+showSrcLoc (SrcLoc file line col) = file ++ ":" ++ show line ++ ":" ++ show col ++ ":"++getSrcLoc :: Data a => a -> Maybe SrcLoc+getSrcLoc = headDef Nothing . gmapQ cast+++---------------------------------------------------------------------+-- UNIPLATE STYLE FUNCTIONS++-- children on Exp, but with SrcLoc's+children1Exp :: Data a => SrcLoc -> a -> [(SrcLoc, Exp)]+children1Exp src x = concat $ gmapQ (children0Exp src2) x+ where src2 = fromMaybe src (getSrcLoc x)++children0Exp :: Data a => SrcLoc -> a -> [(SrcLoc, Exp)]+children0Exp src x | Just y <- cast x = [(src, y)]+ | otherwise = children1Exp src x++universeExp :: Data a => SrcLoc -> a -> [(SrcLoc, Exp)]+universeExp src x = concatMap f (children0Exp src x)+ where f (src,x) = (src,x) : concatMap f (children1Exp src x)+++---------------------------------------------------------------------+-- VARIABLE MANIPULATION++-- pick a variable that is not being used+freeVar :: Data a => a -> String+freeVar x = head $ allVars \\ concat [[y, drop 1 y] | Ident y <- universeBi x]+ where allVars = [letter : number | number <- "" : map show [1..], letter <- ['a'..'z']]+++fromVar :: Exp -> Maybe String+fromVar (Var (UnQual (Ident x))) = Just x+fromVar (Var (UnQual (Symbol x))) = Just x+fromVar _ = Nothing++toVar :: String -> Exp+toVar = Var . UnQual . Ident++isVar :: Exp -> Bool+isVar = isJust . fromVar+++isCharExp :: Exp -> Bool+isCharExp (Lit (Char _)) = True+isCharExp _ = False+++----------------------------------------------------------------------+-- BRACKETS++addParen, hsParen :: Exp -> Exp+addParen x = if atom x then x else XExpTag x+hsParen x = if atom x then x else Paren x++remParen :: Exp -> Exp+remParen = transform g . transform f+ where+ g (XExpTag x) = Paren x+ g x = x+ + f (XExpTag x) | atom x = x+ f (InfixApp a b c) = InfixApp (f2 a) b (f2 c)+ f x = x+ + f2 (XExpTag (App a b)) = App a b+ f2 x = x++isParen :: Exp -> Bool+isParen (Paren _) = True+isParen (XExpTag _) = True+isParen _ = False++fromParen :: Exp -> Exp+fromParen (Paren x) = fromParen x+fromParen (XExpTag x) = fromParen x+fromParen x = x++atom x = case x of+ XExpTag _ -> True -- because pretending to be Paren+ Paren _ -> True+ Var _ -> True+ Con _ -> True+ Lit _ -> True+ Tuple _ -> True+ List _ -> True+ LeftSection _ _ -> True+ RightSection _ _ -> True+ RecConstr _ _ -> True+ ListComp _ _ -> True+ _ -> False+++---------------------------------------------------------------------+-- PATTERN MATCHING++class View a b where+ view :: a -> b+++data App2 = NoApp2 | App2 Exp Exp Exp deriving Show++instance View Exp App2 where+ view (fromParen -> InfixApp lhs op rhs) = view $ opExp op `App` lhs `App` rhs+ view (fromParen -> (fromParen -> f `App` x) `App` y) = App2 f x y+ view _ = NoApp2+++data App1 = NoApp1 | App1 Exp Exp deriving Show++instance View Exp App1 where+ view (fromParen -> f `App` x) = App1 f x+ view _ = NoApp1+++(~=) :: Exp -> String -> Bool+(Con (Special Cons)) ~= ":" = True+(List []) ~= "[]" = True+x ~= y = fromVar x == Just y