├── .gitignore ├── .travis.yml ├── Analyse.hs ├── Analyse ├── Colors.hs ├── Everything.hs ├── GraphRepr.hs ├── Imports.hs ├── Module.hs ├── Utils.hs └── Visualise.hs ├── COPYRIGHT ├── CabalInfo.hs ├── ChangeLog ├── Main.hs ├── Parsing.hs ├── Parsing ├── ParseModule.hs ├── State.hs └── Types.hs ├── Setup.lhs ├── SourceGraph.cabal └── TODO /.gitignore: -------------------------------------------------------------------------------- 1 | dist 2 | cabal-dev 3 | *.o 4 | *.hi 5 | *.chi 6 | *.chs.h 7 | .virtualenv 8 | .hsenv 9 | .cabal-sandbox/ 10 | cabal.sandbox.config 11 | cabal.config 12 | TAGS 13 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | # This file has been generated -- see https://github.com/hvr/multi-ghc-travis 2 | language: c 3 | sudo: false 4 | 5 | cache: 6 | directories: 7 | - $HOME/.cabsnap 8 | - $HOME/.cabal/packages 9 | 10 | before_cache: 11 | - rm -fv $HOME/.cabal/packages/hackage.haskell.org/build-reports.log 12 | - rm -fv $HOME/.cabal/packages/hackage.haskell.org/00-index.tar 13 | 14 | matrix: 15 | include: 16 | - env: CABALVER=1.16 GHCVER=7.4.2 17 | compiler: ": #GHC 7.4.2" 18 | addons: {apt: {packages: [cabal-install-1.16,ghc-7.4.2,alex-3.1.4,happy-1.19.5], sources: [hvr-ghc]}} 19 | - env: CABALVER=1.16 GHCVER=7.6.3 20 | compiler: ": #GHC 7.6.3" 21 | addons: {apt: {packages: [cabal-install-1.16,ghc-7.6.3,alex-3.1.4,happy-1.19.5], sources: [hvr-ghc]}} 22 | - env: CABALVER=1.18 GHCVER=7.8.4 23 | compiler: ": #GHC 7.8.4" 24 | addons: {apt: {packages: [cabal-install-1.18,ghc-7.8.4,alex-3.1.4,happy-1.19.5], sources: [hvr-ghc]}} 25 | - env: CABALVER=1.22 GHCVER=7.10.2 26 | compiler: ": #GHC 7.10.2" 27 | addons: {apt: {packages: [cabal-install-1.22,ghc-7.10.2,alex-3.1.4,happy-1.19.5], sources: [hvr-ghc]}} 28 | - env: CABALVER=head GHCVER=head 29 | compiler: ": #GHC head" 30 | addons: {apt: {packages: [cabal-install-head,ghc-head,alex-3.1.4-3.14,happy-1.19.5], sources: [hvr-ghc]}} 31 | 32 | allow_failures: 33 | - env: CABALVER=head GHCVER=head 34 | 35 | before_install: 36 | - unset CC 37 | - export HAPPYVER=1.19.5 38 | - export ALEXVER=3.1.4 39 | - export PATH=/opt/ghc/$GHCVER/bin:/opt/cabal/$CABALVER/bin:/opt/happy/$HAPPYVER/bin:/opt/alex/$ALEXVER/bin:$PATH 40 | 41 | install: 42 | - cabal --version 43 | - echo "$(ghc --version) [$(ghc --print-project-git-commit-id 2> /dev/null || echo '?')]" 44 | - if [ -f $HOME/.cabal/packages/hackage.haskell.org/00-index.tar.gz ]; 45 | then 46 | zcat $HOME/.cabal/packages/hackage.haskell.org/00-index.tar.gz > 47 | $HOME/.cabal/packages/hackage.haskell.org/00-index.tar; 48 | fi 49 | - travis_retry cabal update -v 50 | - sed -i 's/^jobs:/-- jobs:/' ${HOME}/.cabal/config 51 | - cabal install --only-dependencies --enable-tests --enable-benchmarks --dry -v > installplan.txt 52 | - sed -i -e '1,/^Resolving /d' installplan.txt; cat installplan.txt 53 | 54 | # check whether current requested install-plan matches cached package-db snapshot 55 | - if diff -u installplan.txt $HOME/.cabsnap/installplan.txt; 56 | then 57 | echo "cabal build-cache HIT"; 58 | rm -rfv .ghc; 59 | cp -a $HOME/.cabsnap/ghc $HOME/.ghc; 60 | cp -a $HOME/.cabsnap/lib $HOME/.cabsnap/share $HOME/.cabsnap/bin $HOME/.cabal/; 61 | else 62 | echo "cabal build-cache MISS"; 63 | rm -rf $HOME/.cabsnap; 64 | mkdir -p $HOME/.ghc $HOME/.cabal/lib $HOME/.cabal/share $HOME/.cabal/bin; 65 | cabal install --only-dependencies --enable-tests --enable-benchmarks; 66 | fi 67 | 68 | # snapshot package-db on cache miss 69 | - if [ ! -d $HOME/.cabsnap ]; 70 | then 71 | echo "snapshotting package-db to build-cache"; 72 | mkdir $HOME/.cabsnap; 73 | cp -a $HOME/.ghc $HOME/.cabsnap/ghc; 74 | cp -a $HOME/.cabal/lib $HOME/.cabal/share $HOME/.cabal/bin installplan.txt $HOME/.cabsnap/; 75 | fi 76 | 77 | # Here starts the actual work to be performed for the package under test; 78 | # any command which exits with a non-zero exit code causes the build to fail. 79 | script: 80 | - if [ -f configure.ac ]; then autoreconf -i; fi 81 | - cabal configure --enable-tests --enable-benchmarks -v2 # -v2 provides useful information for debugging 82 | - cabal build # this builds all libraries and executables (including tests/benchmarks) 83 | - cabal test 84 | - cabal check 85 | - cabal sdist # tests that a source-distribution can be generated 86 | - cabal --version | grep --quiet 'cabal-install version 1.22'; 87 | if [ $? -eq 0 ]; then 88 | cabal install packdeps; 89 | find . -name '*.cabal' | xargs cabal exec packdeps; 90 | fi 91 | 92 | # Check that the resulting source distribution can be built & installed. 93 | # If there are no other `.tar.gz` files in `dist`, this can be even simpler: 94 | # `cabal install --force-reinstalls dist/*-*.tar.gz` 95 | - SRC_TGZ=$(cabal info . | awk '{print $2;exit}').tar.gz && 96 | (cd dist && cabal install --force-reinstalls "$SRC_TGZ") 97 | 98 | # EOF 99 | -------------------------------------------------------------------------------- /Analyse.hs: -------------------------------------------------------------------------------- 1 | {- 2 | Copyright (C) 2009 Ivan Lazar Miljenovic 3 | 4 | This file is part of SourceGraph. 5 | 6 | SourceGraph is free software; you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation; either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program; if not, write to the Free Software 18 | Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 19 | -} 20 | 21 | {- | 22 | Module : Analyse 23 | Description : Analyse Haskell software 24 | Copyright : (c) Ivan Lazar Miljenovic 2009 25 | License : GPL-3 or later. 26 | Maintainer : Ivan.Miljenovic@gmail.com 27 | 28 | Analyse Haskell software 29 | -} 30 | module Analyse(analyse, sgLegend) where 31 | 32 | import Analyse.Module 33 | import Analyse.Imports 34 | import Analyse.Everything 35 | import Analyse.Colors 36 | import Parsing.Types 37 | 38 | import Data.Graph.Analysis hiding (Bold) 39 | import qualified Data.Graph.Analysis.Reporting as R (DocInline(Bold)) 40 | import Data.GraphViz.Types.Canonical 41 | import Data.GraphViz.Attributes 42 | import Data.GraphViz.Attributes.Complete( Attribute(OutputOrder, FontSize) 43 | , OutputMode(EdgesFirst)) 44 | 45 | import System.Random(RandomGen) 46 | import Control.Arrow(first) 47 | 48 | -- | Analyse an entire Haskell project. Takes in a random seed, 49 | -- the list of exported modules and the parsed Haskell code in 50 | -- 'HaskellModules' form. 51 | analyse :: (RandomGen g) => g -> [ModName] -> ParsedModules 52 | -> [DocElement] 53 | analyse g exps hms = [ analyseEverything g exps hms 54 | , analyseImports exps hms 55 | , analyseModules hms 56 | ] 57 | 58 | sgLegend :: [(Either DocGraph DocInline, DocInline)] 59 | sgLegend = map (first Left) [ esCall 60 | , mods 61 | , esLoc 62 | , esData 63 | , esClass 64 | , esExp 65 | , callCats 66 | ] 67 | ++ [first Right edgeExplain] 68 | 69 | esCall, mods, esLoc, esData, esClass, esExp, callCats :: (DocGraph, DocInline) 70 | 71 | esCall = (dg', R.Bold txt) 72 | where 73 | dg' = DG "legend_call" (Text "Function Call") dg 74 | dg = mkLegendGraph ns es 75 | nAs = [shape BoxShape, fillColor defaultNodeColor] 76 | ns = [ (1, toLabel e1 : nAs) 77 | , (2, toLabel e2 : nAs) 78 | ] 79 | e1 = "f" 80 | e2 = "g" 81 | eAs = [color Black] 82 | es = [(1,2,eAs)] 83 | txt = Grouping [ Text "Two normal functions with" 84 | , Emphasis $ Text e1 85 | , Text "calling" 86 | , Emphasis $ Text e2 87 | , Text "." 88 | ] 89 | 90 | mods = (dg', R.Bold txt) 91 | where 92 | dg' = DG "legend_mods" (Text "Module Import") dg 93 | dg = mkLegendGraph ns es 94 | nAs = [shape Tab, fillColor defaultNodeColor] 95 | ns = [ (1, toLabel m1 : nAs) 96 | , (2, toLabel m2 : nAs) 97 | ] 98 | m1 = "Foo" 99 | m2 = "Bar" 100 | es = [(1,2,[])] 101 | txt = Grouping [ Text "Two modules with module" 102 | , Emphasis $ Text m1 103 | , Text "importing" 104 | , Emphasis $ Text m2 105 | , Text "." 106 | ] 107 | 108 | esLoc = (dg', R.Bold $ Text "Entities from different modules.") 109 | where 110 | dg' = DG "legend_loc" (Text "From module") dg 111 | dg = mkLegendGraph ns es 112 | nAs = [fillColor defaultNodeColor] 113 | ns = [ (1, toLabel "Current module" 114 | : style bold : nAs) 115 | , (2, toLabel "Other project module" 116 | : style solid : nAs) 117 | , (3, toLabel "Known external module" 118 | : style dashed : nAs) 119 | , (4, toLabel "Unknown external module" 120 | : style dotted : nAs) 121 | ] 122 | es = [] 123 | 124 | esData = (dg', R.Bold $ Text "Data type declaration.") 125 | where 126 | dg' = DG "legend_data" (Text "Data type declaration") dg 127 | dg = mkLegendGraph ns es 128 | nAs = [fillColor defaultNodeColor] 129 | ns = [ (1, toLabel "Constructor" 130 | : shape Box3D : nAs) 131 | , (2, toLabel "Record function" 132 | : shape Component : nAs) 133 | ] 134 | es = [(2,1,[ color Magenta, arrowFrom oDot, arrowTo vee])] 135 | 136 | esClass = (dg', R.Bold $ Text "Class and instance declarations.") 137 | where 138 | dg' = DG "legend_class" (Text "Class declaration") dg 139 | dg = mkLegendGraph ns es 140 | nAs = [fillColor defaultNodeColor] 141 | ns = [ (1, toLabel "Default instance" 142 | : shape Octagon : nAs) 143 | , (2, toLabel "Class function" 144 | : shape DoubleOctagon : nAs) 145 | , (3, toLabel "Instance for data type" 146 | : shape Octagon : nAs) 147 | ] 148 | eAs = [edgeEnds NoDir] 149 | es = [ (2,1, color Navy : eAs) 150 | , (2,3, color Turquoise : eAs) 151 | ] 152 | 153 | esExp = (dg', R.Bold $ Text "Entity location/accessibility classification.") 154 | where 155 | dg' = DG "legend_loc2" (Text "Entity Location") dg 156 | dg = mkLegendGraph ns es 157 | ns = zip [1..] 158 | [ [ toLabel "Inaccessible entity" 159 | , fillColor inaccessibleColor] 160 | , [ toLabel "Exported root entity" 161 | , fillColor exportedRootColor] 162 | , [ toLabel "Exported non-root entity" 163 | , fillColor exportedInnerColor] 164 | , [ toLabel "Implicitly exported entity" 165 | , fillColor implicitExportColor] 166 | , [ toLabel "Leaf entity" 167 | , fillColor leafColor] 168 | , [ toLabel "Normal entity" 169 | , fillColor defaultNodeColor] 170 | ] 171 | es = [] 172 | 173 | callCats = (dg', R.Bold $ Text "Edge classification.") 174 | where 175 | dg' = DG "legend_edges" (Text "Edge Classification") dg 176 | dg = mkLegendGraph ns es 177 | ns = map (flip (,) [toLabel "", shape PointShape]) [1..5] 178 | eA = edgeEnds NoDir 179 | es = [ (1,2, [eA, toLabel "Clique", color cliqueColor]) 180 | , (2,3, [eA, toLabel "Cycle", color cycleColor]) 181 | , (3,4, [eA, toLabel "Chain", color chainColor]) 182 | , (4,5, [eA, toLabel "Normal", color defaultEdgeColor]) 183 | ] 184 | 185 | 186 | mkLegendGraph :: [(Int,Attributes)] -> [(Int,Int,Attributes)] 187 | -> DotGraph Node 188 | mkLegendGraph ns es = DotGraph { strictGraph = False 189 | , directedGraph = True 190 | , graphID = Nothing 191 | , graphStatements 192 | = DotStmts { attrStmts = atts 193 | , subGraphs = [nSG] 194 | , nodeStmts = [] 195 | , edgeStmts = map mkE es 196 | } 197 | } 198 | where 199 | atts = [ GraphAttrs [OutputOrder EdgesFirst] 200 | , NodeAttrs [FontSize 10, style filled] 201 | ] 202 | sgAtts = [GraphAttrs [rank MinRank]] 203 | nSG = DotSG { isCluster = False 204 | , subGraphID = Nothing 205 | , subGraphStmts = DotStmts { attrStmts = sgAtts 206 | , subGraphs = [] 207 | , nodeStmts = map mkN ns 208 | , edgeStmts = [] 209 | } 210 | } 211 | mkN (n,as) = DotNode n as 212 | mkE (f,t,as) = DotEdge f t as 213 | 214 | edgeExplain :: (DocInline, DocInline) 215 | edgeExplain = (Grouping cntnt, R.Bold $ Text "Edge Widths") 216 | where 217 | cntnt = [ Text "The width of each edge is calculated by:" 218 | , BlankSpace 219 | , Emphasis $ Text 220 | "width = log (number of function calls) + 1" 221 | ] 222 | -------------------------------------------------------------------------------- /Analyse/Colors.hs: -------------------------------------------------------------------------------- 1 | {- 2 | Copyright (C) 2010 Ivan Lazar Miljenovic 3 | 4 | This file is part of SourceGraph. 5 | 6 | SourceGraph is free software; you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation; either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program; if not, write to the Free Software 18 | Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 19 | -} 20 | 21 | {- | 22 | Module : Analyse.Visualise 23 | Description : Visualisation functions. 24 | Copyright : (c) Ivan Lazar Miljenovic 2010 25 | License : GPL-3 or later. 26 | Maintainer : Ivan.Miljenovic@gmail.com 27 | 28 | Utility functions and types for analysis. 29 | -} 30 | module Analyse.Colors where 31 | 32 | import Data.GraphViz.Attributes 33 | 34 | inaccessibleColor :: X11Color 35 | inaccessibleColor = Crimson 36 | 37 | exportedRootColor :: X11Color 38 | exportedRootColor = Gold 39 | 40 | exportedInnerColor :: X11Color 41 | exportedInnerColor = Goldenrod 42 | 43 | implicitExportColor :: X11Color 44 | implicitExportColor = Khaki 45 | 46 | leafColor :: X11Color 47 | leafColor = Cyan 48 | 49 | defaultNodeColor :: X11Color 50 | defaultNodeColor = Bisque 51 | 52 | defaultEdgeColor :: X11Color 53 | defaultEdgeColor = Black 54 | 55 | cliqueColor :: X11Color 56 | cliqueColor = Orange 57 | 58 | cycleColor :: X11Color 59 | cycleColor = DarkOrchid 60 | 61 | chainColor :: X11Color 62 | chainColor = Chartreuse 63 | 64 | clusterBackground :: X11Color 65 | clusterBackground = Lavender 66 | 67 | noBackground :: X11Color 68 | noBackground = Snow 69 | -------------------------------------------------------------------------------- /Analyse/Everything.hs: -------------------------------------------------------------------------------- 1 | {- 2 | Copyright (C) 2009 Ivan Lazar Miljenovic 3 | 4 | This file is part of SourceGraph. 5 | 6 | SourceGraph is free software; you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation; either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program; if not, write to the Free Software 18 | Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 19 | -} 20 | 21 | {- | 22 | Module : Analyse.Software 23 | Description : Analyse Haskell software 24 | Copyright : (c) Ivan Lazar Miljenovic 2009 25 | License : GPL-3 or later. 26 | Maintainer : Ivan.Miljenovic@gmail.com 27 | 28 | Analysis of the entire overall piece of software. 29 | -} 30 | module Analyse.Everything(analyseEverything) where 31 | 32 | import Parsing.Types 33 | import Analyse.Utils 34 | import Analyse.GraphRepr 35 | import Analyse.Visualise 36 | 37 | import Data.Graph.Analysis 38 | 39 | import Data.List(nub) 40 | import Data.Maybe(mapMaybe) 41 | import qualified Data.Map as M 42 | import qualified Data.Set as S 43 | import qualified Data.MultiSet as MS 44 | import Text.Printf(printf) 45 | import System.Random(RandomGen) 46 | 47 | -- ----------------------------------------------------------------------------- 48 | 49 | -- | Performs analysis of the entire codebase. 50 | analyseEverything :: (RandomGen g) => g -> [ModName] -> ParsedModules 51 | -> DocElement 52 | analyseEverything g exps hm = Section sec elems 53 | where 54 | cd = codeToGraph exps hm 55 | sec = Text "Analysis of the entire codebase" 56 | elems = mapMaybe ($cd) [ graphOf 57 | , clustersOf g 58 | -- , collapseAnal 59 | , coreAnal 60 | , levelAnal 61 | , cycleCompAnal 62 | , rootAnal 63 | , componentAnal 64 | , cliqueAnal 65 | , cycleAnal 66 | , chainAnal 67 | ] 68 | 69 | 70 | codeToGraph :: [ModName] -> ParsedModules -> HData' 71 | codeToGraph exps pms = mkHData' vs $ importData params 72 | where 73 | pms' = M.elems pms 74 | exps' = S.toList . S.unions 75 | . map exports $ mapMaybe (flip M.lookup pms) exps 76 | ents = S.toList . S.unions 77 | $ map internalEnts pms' 78 | calls = MS.toList . MS.map callToRel . MS.unions 79 | $ map funcCalls pms' 80 | vs = S.filter (not . internalEntity) 81 | . S.unions $ map virtualEnts pms' 82 | params = ImpParams { dataPoints = ents 83 | , relationships = calls 84 | , roots = exps' 85 | , directed = True 86 | } 87 | 88 | graphOf :: HData' -> Maybe DocElement 89 | graphOf cd = Just $ Section sec [gc] 90 | where 91 | sec = Text "Visualisation of the entire software" 92 | gc = GraphImage $ DG "code" (Text lbl) (drawGraph lbl Nothing cd) 93 | lbl = "Entire Codebase" 94 | 95 | clustersOf :: (RandomGen g) => g -> HData' -> Maybe DocElement 96 | clustersOf g cd = Just $ Section sec [ text, gc, textAfter 97 | , blank, cwMsg, cw] -- , blank, rngMsg, rng] 98 | where 99 | blank = Paragraph [BlankSpace] 100 | sec = Text "Visualisation of overall function calls" 101 | gc = GraphImage $ DG "codeCluster" (Text lbl) (drawGraph' lbl cd) 102 | text = Paragraph 103 | [Text "Here is the current module grouping of functions:"] 104 | lbl = "Current module groupings" 105 | textAfter = Paragraph [Text "Here is a proposed alternate module grouping:"] 106 | -- [Text "Here are two proposed module groupings:"] 107 | cwMsg = Paragraph [Emphasis $ Text "Using the Chinese Whispers algorithm:"] 108 | cw = GraphImage $ DG "codeCW" (Text cwLbl) (drawClusters cwLbl (chineseWhispers g) cd) 109 | cwLbl = "Chinese Whispers module suggestions" 110 | {- 111 | rngMsg = Paragraph [Emphasis $ Text "Using the Relative Neighbourhood algorithm:"] 112 | rng = GraphImage $ DG "codeRNG" (Text rngLbl) (drawClusters lbl relNbrhd cd) 113 | -- Being naughty to avoid having to define drawClusters' 114 | relNbrhd = relativeNeighbourhood $ directedData cd 115 | rngLbl = "Relative Neighbourhood module suggestions" 116 | -} 117 | 118 | componentAnal :: HData' -> Maybe DocElement 119 | componentAnal cd 120 | | single comp = Nothing 121 | | otherwise = Just $ Section sec [Paragraph [Text text]] 122 | where 123 | -- Use compactData as the number of edges don't matter, just 124 | -- whether or not an edge exists. 125 | comp = applyAlg componentsOf . compactData $ collapsedHData cd 126 | len = length comp 127 | sec = Text "Function component analysis" 128 | text = printf "The functions are split up into %d components. \ 129 | \You may wish to consider splitting the code up \ 130 | \into multiple libraries." len 131 | 132 | cliqueAnal :: HData' -> Maybe DocElement 133 | cliqueAnal cd 134 | | null clqs = Nothing 135 | | otherwise = Just el 136 | where 137 | clqs = onlyCrossModule . applyAlg cliquesIn 138 | . onlyNormalCalls' . compactData $ collapsedHData cd 139 | clqs' = return . Itemized 140 | $ map (Paragraph . return . Text . showNodes' (fullName . snd)) clqs 141 | text = Text "The code has the following cross-module cliques:" 142 | el = Section sec $ Paragraph [text] : clqs' 143 | sec = Text "Overall clique analysis" 144 | 145 | cycleAnal :: HData' -> Maybe DocElement 146 | cycleAnal cd 147 | | null cycs = Nothing 148 | | otherwise = Just el 149 | where 150 | cycs = onlyCrossModule . applyAlg uniqueCycles 151 | . onlyNormalCalls' . compactData $ collapsedHData cd 152 | cycs' = return . Itemized 153 | $ map (Paragraph . return . Text . showCycle' (fullName . snd)) cycs 154 | text = Text "The code has the following cross-module non-clique cycles:" 155 | el = Section sec $ Paragraph [text] : cycs' 156 | sec = Text "Overall cycle analysis" 157 | 158 | chainAnal :: HData' -> Maybe DocElement 159 | chainAnal cd 160 | | null chns = Nothing 161 | | otherwise = Just el 162 | where 163 | chns = onlyCrossModule . interiorChains 164 | . onlyNormalCalls' . compactData $ collapsedHData cd 165 | chns' = return . Itemized 166 | $ map (Paragraph . return . Text . showPath' (fullName . snd)) chns 167 | text = Text "The code has the following cross-module chains:" 168 | textAfter = Text "These chains can all be compressed down to \ 169 | \a single function." 170 | el = Section sec $ 171 | [Paragraph [text]] ++ chns' ++ [Paragraph [textAfter]] 172 | sec = Text "Overall chain analysis" 173 | 174 | rootAnal :: HData' -> Maybe DocElement 175 | rootAnal cd 176 | | asExpected = Nothing 177 | | otherwise = Just $ Section sec inaccessible 178 | where 179 | cd' = compactData $ origHData cd 180 | ntWd = S.toList . inaccessibleNodes $ addImplicit (origVirts cd) cd' 181 | ntWd' = applyAlg getLabels cd' ntWd 182 | asExpected = null ntWd 183 | inaccessible = [ Paragraph [Text "These functions are those that are inaccessible:"] 184 | , Paragraph [Emphasis . Text $ showNodes' fullName ntWd'] 185 | ] 186 | sec = Text "Overall root analysis" 187 | 188 | 189 | cycleCompAnal :: HData' -> Maybe DocElement 190 | cycleCompAnal cd = Just $ Section sec pars 191 | where 192 | cc = cyclomaticComplexity . graphData $ collapsedHData cd 193 | sec = Text "Overall Cyclomatic Complexity" 194 | pars = [Paragraph [text], Paragraph [textAfter, link]] 195 | text = Text 196 | $ printf "The overall cyclomatic complexity is: %d" cc 197 | textAfter = Text "For more information on cyclomatic complexity, \ 198 | \please see: " 199 | link = DocLink (Text "Wikipedia: Cyclomatic Complexity") 200 | (Web "http://en.wikipedia.org/wiki/Cyclomatic_complexity") 201 | 202 | 203 | coreAnal :: HData' -> Maybe DocElement 204 | coreAnal = fmap mkDE . makeCore 205 | where 206 | mkDE cd' = Section sec [ hdr 207 | , GraphImage $ DG "codeCore" 208 | (Text lbl) 209 | (drawGraph lbl Nothing cd') 210 | ] 211 | lbl = "Overall core" 212 | hdr = coreDesc "software" 213 | sec = Text "Overall Core analysis" 214 | 215 | levelAnal :: HData' -> Maybe DocElement 216 | levelAnal cd = Just $ Section sec [hdr, lvls] 217 | where 218 | lvls = GraphImage $ DG p (Text lbl) (drawLevels lbl Nothing cd) 219 | p = "code_levels" 220 | lbl = unwords ["Levels within software"] 221 | sec = Grouping [Text "Visualisation of levels in the software"] 222 | hdr = Paragraph [Text "Visualises how far away from the exported root\ 223 | \ entities an entity is."] 224 | 225 | 226 | -- Comment out until can work out a way of dealing with [Entity] for 227 | -- the node-label type. 228 | {- 229 | collapseAnal :: HData' -> Maybe DocElement 230 | collapseAnal cd = if (trivialCollapse gc) 231 | then Nothing 232 | else Just $ Section sec [hdr, gr] 233 | where 234 | cd' = updateGraph collapseGraph cd 235 | gc = graph cd' 236 | lbl = "Collapsed view of the entire codebase" 237 | hdr = Paragraph [Text "The collapsed view of code collapses \ 238 | \down all cliques, cycles, chains, etc. to \ 239 | \make the graph tree-like." ] 240 | gr = GraphImage $ DG "codeCollapsed" (Text lbl) (drawGraph lbl Nothing cd') 241 | sec = Text "Collapsed view of the entire codebase" 242 | -} 243 | 244 | -- | Only use those values that are in more than one module. 245 | onlyCrossModule :: [LNGroup Entity] -> [LNGroup Entity] 246 | onlyCrossModule = filter crossModule 247 | where 248 | crossModule = not . single . nub . map (inModule . label) 249 | -------------------------------------------------------------------------------- /Analyse/GraphRepr.hs: -------------------------------------------------------------------------------- 1 | {-# LANGUAGE FlexibleContexts, TypeFamilies #-} 2 | 3 | {- 4 | Copyright (C) 2010 Ivan Lazar Miljenovic 5 | 6 | This file is part of SourceGraph. 7 | 8 | SourceGraph is free software; you can redistribute it and/or modify 9 | it under the terms of the GNU General Public License as published by 10 | the Free Software Foundation; either version 3 of the License, or 11 | (at your option) any later version. 12 | 13 | This program is distributed in the hope that it will be useful, 14 | but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | GNU General Public License for more details. 17 | 18 | You should have received a copy of the GNU General Public License 19 | along with this program; if not, write to the Free Software 20 | Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 21 | -} 22 | 23 | {- | 24 | Module : Analyse.GraphRepr 25 | Description : Interacting with GraphData 26 | Copyright : (c) Ivan Lazar Miljenovic 2009 27 | License : GPL-3 or later. 28 | Maintainer : Ivan.Miljenovic@gmail.com 29 | 30 | Interacting with GraphData from Graphalyze. 31 | -} 32 | module Analyse.GraphRepr 33 | ( -- * General stuff 34 | GData(..) 35 | , mapData 36 | , mapData' 37 | -- * Entity-based 38 | , HData' 39 | , mkHData' 40 | , origHData 41 | , origVirts 42 | , collapsedHData 43 | , collapsedVirts 44 | , updateOrig 45 | , updateCollapsed 46 | , makeCore 47 | , HData 48 | , mkHData 49 | , HSData 50 | , HSClustData 51 | , HSGraph 52 | , HSClustGraph 53 | -- ** Utility functions 54 | , addImplicit 55 | , implicitExports 56 | , onlyNormalCalls 57 | , onlyNormalCalls' 58 | -- * Import-based 59 | , MData 60 | , mkMData 61 | , ModData 62 | , ModGraph 63 | ) where 64 | 65 | import Analyse.Colors 66 | import Analyse.Utils 67 | import Parsing.Types 68 | 69 | import Data.Graph.Analysis 70 | import Data.Graph.Inductive 71 | import Data.GraphViz.Attributes (X11Color) 72 | 73 | import Control.Monad (liftM2) 74 | import Data.List (isPrefixOf) 75 | import Data.Map (Map) 76 | import qualified Data.Map as M 77 | import Data.Maybe (mapMaybe) 78 | import Data.Set (Set) 79 | import qualified Data.Set as S 80 | 81 | -- ----------------------------------------------------------------------------- 82 | 83 | data GData n e = GD { graphData :: GraphData n e 84 | , compactData :: GraphData n (Int, e) 85 | , nodeCols :: [(Set Node, X11Color)] 86 | , edgeCols :: [(Set Edge, X11Color)] 87 | } 88 | deriving (Eq, Show, Read) 89 | 90 | mkGData :: (Ord e) => (GraphData n e -> [(Set Node, X11Color)]) 91 | -> (GraphData n e -> [(Set Edge, X11Color)]) 92 | -> GraphData n e -> GData n e 93 | mkGData n e g = GD { graphData = g 94 | , compactData = updateGraph compactSame g 95 | , nodeCols = n g 96 | , edgeCols = e g 97 | } 98 | 99 | -- | Does not touch the 'nodeCols' values. Should only touch the labels. 100 | mapData :: (Ord e') => (GraphData n e -> GraphData n' e') 101 | -> GData n e -> GData n' e' 102 | mapData f gd = GD { graphData = gr' 103 | , compactData = updateGraph compactSame gr' 104 | , nodeCols = nodeCols gd 105 | , edgeCols = edgeCols gd 106 | } 107 | where 108 | gr = graphData gd 109 | gr' = f gr 110 | 111 | mapData' :: (Ord e') => (AGr n e -> AGr n' e') -> GData n e -> GData n' e' 112 | mapData' f = mapData (updateGraph f) 113 | 114 | commonColors :: GraphData n e -> [(Set Node, X11Color)] 115 | commonColors gd = [ (rs', exportedRootColor) 116 | , (es, exportedInnerColor) 117 | , (ls, leafColor) 118 | ] 119 | where 120 | rs' = S.intersection rs es 121 | rs = getRoots gd 122 | ls = getLeaves gd 123 | es = getWRoots gd 124 | 125 | getRoots :: GraphData a b -> Set Node 126 | getRoots = S.fromList . applyAlg rootsOf' 127 | 128 | getLeaves :: GraphData a b -> Set Node 129 | getLeaves = S.fromList . applyAlg leavesOf' 130 | 131 | getWRoots :: GraphData a b -> Set Node 132 | getWRoots = S.fromList . wantedRootNodes 133 | 134 | -- ----------------------------------------------------------------------------- 135 | 136 | data HData' = HD' { origHData :: HData 137 | , origVirts :: Set Entity 138 | , collapsedHData :: HData 139 | , collapsedVirts :: Set Entity 140 | } 141 | deriving (Eq, Show, Read) 142 | 143 | mkHData' :: Set Entity -> HSData -> HData' 144 | mkHData' vs hs = HD' { origHData = mkHData vs hs 145 | , origVirts = vs 146 | , collapsedHData = mkHData vs' hs' 147 | , collapsedVirts = vs' 148 | } 149 | where 150 | (hs', repLookup) = collapseStructures hs 151 | vs' = S.fromList 152 | . mapMaybe (flip M.lookup repLookup) 153 | $ S.toList vs 154 | 155 | -- | Doesn't touch origVirts 156 | updateOrig :: (HSGraph -> HSGraph) -> HData' -> HData' 157 | updateOrig f hd' = hd' { origHData = mapData' f $ origHData hd' } 158 | 159 | -- | Doesn't touch collapsedVirts 160 | updateCollapsed :: (HSGraph -> HSGraph) -> HData' -> HData' 161 | updateCollapsed f hd' = hd' { collapsedHData = mapData' f $ collapsedHData hd' } 162 | 163 | makeCore :: HData' -> Maybe HData' 164 | makeCore hd = bool Nothing (Just hd') $ isInteresting hd' 165 | where 166 | isInteresting = not . applyAlg (liftM2 (||) isEmpty unChanged) 167 | . graphData . origHData 168 | unChanged = applyAlg equal $ graphData (origHData hd) 169 | hd' = updateOrig coreOf hd 170 | 171 | type HData = GData Entity CallType 172 | 173 | mkHData :: Set Entity -> HSData -> HData 174 | mkHData vs = mkGData (entColors vs) (callColors . onlyNormalCalls) 175 | 176 | type HSData = GraphData Entity CallType 177 | type HSClustData = GraphData (GenCluster Entity) CallType 178 | type HSGraph = AGr Entity CallType 179 | type HSClustGraph = AGr (GenCluster Entity) CallType 180 | 181 | entColors :: Set Entity -> GraphData Entity e -> [(Set Node, X11Color)] 182 | entColors vs hd = (us, inaccessibleColor) 183 | : 184 | commonColors hd 185 | ++ 186 | -- Do this after in case there's an implicit export 187 | -- that is explicitly exported. 188 | [ (imps, implicitExportColor) 189 | ] 190 | where 191 | hd' = addImplicit vs hd 192 | us = inaccessibleNodes hd' 193 | imps = implicitExports vs hd 194 | 195 | callColors :: HSData -> [(Set Edge, X11Color)] 196 | callColors hd = [ (cliqueEdges clqs, cliqueColor) 197 | , (cycleEdges cycs, cycleColor) 198 | , (chainEdges chns, chainColor) 199 | ] 200 | where 201 | clqs = applyAlg cliquesIn' hd 202 | cycs = applyAlg uniqueCycles' hd 203 | chns = applyAlg chainsIn' hd 204 | 205 | -- ----------------------------------------------------------------------------- 206 | 207 | onlyNormalCalls :: HSData -> HSData 208 | onlyNormalCalls = updateGraph go 209 | where 210 | go = elfilter isNormalCall 211 | 212 | onlyNormalCalls' :: GraphData Entity (Int, CallType) 213 | -> GraphData Entity (Int, CallType) 214 | onlyNormalCalls' = updateGraph go 215 | where 216 | go = elfilter (isNormalCall . snd) 217 | 218 | isImplicitExport :: Set Entity -> LNode Entity -> Bool 219 | isImplicitExport vs = liftM2 (||) underscoredEntity (virtClass vs) . label 220 | 221 | -- | Various warnings about unused/unexported entities are suppressed 222 | -- if they start with an underscore: 223 | -- http://www.haskell.org/ghc/docs/latest/html/users_guide/options-sanity.html 224 | underscoredEntity :: Entity -> Bool 225 | underscoredEntity = isPrefixOf "_" . name 226 | 227 | virtClass :: Set Entity -> Entity -> Bool 228 | virtClass vs e = case eType e of 229 | ClassMethod{} -> isVirt 230 | CollapsedClass{} -> isVirt 231 | _ -> False 232 | where 233 | isVirt = e `S.member` vs 234 | 235 | addImplicit :: Set Entity -> GraphData Entity e -> GraphData Entity e 236 | addImplicit vs = addRootsBy (isImplicitExport vs) 237 | 238 | implicitExports :: Set Entity -> GraphData Entity e -> Set Node 239 | implicitExports vs = S.fromList 240 | . map node 241 | . applyAlg (filterNodes (const (isImplicitExport vs))) 242 | 243 | -- | Collapse items that must be kept together before clustering, etc. 244 | -- Also updates wantedRootNodes. 245 | collapseStructures :: HSData -> (HSData, Map Entity Entity) 246 | collapseStructures = collapseAndUpdate' collapseFuncs 247 | 248 | collapseFuncs :: [HSGraph -> [(NGroup, Entity)]] 249 | collapseFuncs = [ collapseDatas 250 | , collapseClasses 251 | , collapseInsts 252 | ] 253 | where 254 | collapseDatas = mkCollapseTp isData getDataType mkData 255 | mkData m d = Ent m ("Data: " ++ d) (CollapsedData d) 256 | collapseClasses = mkCollapseTp isClass getClassName mkClass 257 | mkClass m c = Ent m ("Class: " ++ c) (CollapsedClass c) 258 | collapseInsts = mkCollapseTp isInstance getInstance mkInst 259 | mkInst m (c,d) = Ent m ("Class: " ++ c ++ ", Data: " ++ d) 260 | (CollapsedInstance c d) 261 | 262 | mkCollapseTp :: (Ord a) => (EntityType -> Bool) -> (EntityType -> a) 263 | -> (ModName -> a -> Entity) -> HSGraph 264 | -> [(NGroup, Entity)] 265 | mkCollapseTp p v mkE g = map lng2ne lngs 266 | where 267 | lns = filter (p . eType . snd) $ labNodes g 268 | lnas = map addA lns 269 | lngs = groupSortBy snd lnas 270 | lng2ne lng = ( map (fst . fst) lng 271 | , mkEnt' $ head lng 272 | ) 273 | mkEnt' ((_,e),a) = mkE (inModule e) a 274 | addA ln@(_,l) = (ln, v $ eType l) 275 | 276 | -- ----------------------------------------------------------------------------- 277 | 278 | type MData = GData ModName () 279 | 280 | mkMData :: ModData -> MData 281 | mkMData = mkGData modColors modEdgeColors 282 | 283 | type ModData = GraphData ModName () 284 | type ModGraph = AGr ModName () 285 | 286 | modColors :: GraphData ModName e -> [(Set Node, X11Color)] 287 | modColors gd = (us, inaccessibleColor) : commonColors gd 288 | where 289 | us = inaccessibleNodes gd 290 | 291 | modEdgeColors :: (Eq e) => GraphData ModName e -> [(Set Edge, X11Color)] 292 | modEdgeColors gd = [ (cycleEdges cycs, cycleColor) 293 | , (chainEdges chns, chainColor) 294 | ] 295 | where 296 | cycs = applyAlg cyclesIn' gd 297 | chns = applyAlg chainsIn' gd 298 | 299 | 300 | -- ----------------------------------------------------------------------------- 301 | 302 | -------------------------------------------------------------------------------- /Analyse/Imports.hs: -------------------------------------------------------------------------------- 1 | {- 2 | Copyright (C) 2009 Ivan Lazar Miljenovic 3 | 4 | This file is part of SourceGraph. 5 | 6 | SourceGraph is free software; you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation; either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program; if not, write to the Free Software 18 | Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 19 | -} 20 | 21 | {- | 22 | Module : Analyse.Imports 23 | Description : Analyse module imports. 24 | Copyright : (c) Ivan Lazar Miljenovic 2009 25 | License : GPL-3 or later. 26 | Maintainer : Ivan.Miljenovic@gmail.com 27 | 28 | Analysis of Haskell module importing. 29 | -} 30 | module Analyse.Imports (analyseImports) where 31 | 32 | import Parsing.Types 33 | import Analyse.Utils 34 | import Analyse.GraphRepr 35 | import Analyse.Visualise 36 | 37 | import Data.Graph.Analysis 38 | 39 | import Data.Maybe(mapMaybe) 40 | import qualified Data.Map as M 41 | import qualified Data.Set as S 42 | import Text.Printf(printf) 43 | 44 | -- ----------------------------------------------------------------------------- 45 | 46 | -- | Analyse the imports present in the software. Takes in a random seed 47 | -- as well as a list of all modules exported. 48 | analyseImports :: [ModName] -> ParsedModules -> DocElement 49 | analyseImports exps hm = Section sec elems 50 | where 51 | imd = importsToGraph exps hm 52 | sec = Text "Analysis of module imports" 53 | elems = mapMaybe ($imd) [ graphOf 54 | , cycleCompAnal 55 | , rootAnal 56 | , componentAnal 57 | , cycleAnal 58 | , chainAnal 59 | ] 60 | 61 | importsToGraph :: [ModName] -> ParsedModules -> MData 62 | importsToGraph exps pms = mkMData $ importData params 63 | where 64 | params = ImpParams { dataPoints = M.keys pms 65 | , relationships = moduleImports pms 66 | , roots = exps 67 | , directed = True 68 | } 69 | 70 | moduleImports :: ParsedModules -> [Rel ModName ()] 71 | moduleImports = concatMap imps . M.elems 72 | where 73 | imps pm = map (toRel (moduleName pm)) 74 | . M.keys $ imports pm 75 | toRel m m' = (m,m',()) 76 | 77 | graphOf :: MData -> Maybe DocElement 78 | graphOf imd = Just $ Section sec [gi] 79 | where 80 | sec = Text "Visualisation of imports" 81 | gi = GraphImage $ DG "imports" (Text lbl) (drawModules lbl imd) 82 | lbl = "Import visualisation" 83 | 84 | componentAnal :: MData -> Maybe DocElement 85 | componentAnal imd 86 | | single comp = Nothing 87 | | otherwise = Just el 88 | where 89 | comp = applyAlg componentsOf $ graphData imd 90 | len = length comp 91 | el = Section sec [Paragraph [Text text]] 92 | sec = Text "Import component analysis" 93 | text = printf "The imports have %d components. \ 94 | \You may wish to consider splitting the code up." len 95 | 96 | cycleAnal :: MData -> Maybe DocElement 97 | cycleAnal imd 98 | | null cycs = Nothing 99 | | otherwise = Just el 100 | where 101 | cycs = applyAlg cyclesIn $ graphData imd 102 | cycs' = return . Itemized 103 | $ map (Paragraph . return . Text . showCycle' (nameOfModule' . snd)) cycs 104 | text = Text "The imports have the following cycles:" 105 | textAfter = Text "Whilst this is valid, it may make it difficult \ 106 | \to use in ghci, etc." 107 | el = Section sec 108 | $ Paragraph [text] : cycs' ++ [Paragraph [textAfter]] 109 | sec = Text "Cycle analysis of imports" 110 | 111 | chainAnal :: MData -> Maybe DocElement 112 | chainAnal imd 113 | | null chns = Nothing 114 | | otherwise = Just el 115 | where 116 | chns = interiorChains $ graphData imd 117 | chns' = return . Itemized 118 | $ map (Paragraph . return . Text . showPath' (nameOfModule . snd)) chns 119 | text = Text "The imports have the following chains:" 120 | textAfter = Text "These chains can all be compressed down to \ 121 | \a single module." 122 | el = Section sec $ 123 | [Paragraph [text]] ++ chns' ++ [Paragraph [textAfter]] 124 | sec = Text "Import chain analysis" 125 | 126 | rootAnal :: MData -> Maybe DocElement 127 | rootAnal imd 128 | | asExpected = Nothing 129 | | otherwise = Just $ Section sec inaccessible 130 | where 131 | imd' = graphData imd 132 | ntWd = S.toList . inaccessibleNodes $ imd' 133 | ntWd' = applyAlg getLabels imd' ntWd 134 | asExpected = null ntWd 135 | inaccessible = [ Paragraph [Text "These modules are those that are inaccessible:"] 136 | , Paragraph [Emphasis . Text $ showNodes' nameOfModule ntWd'] 137 | ] 138 | sec = Text "Import root analysis" 139 | 140 | cycleCompAnal :: MData -> Maybe DocElement 141 | cycleCompAnal imd = Just $ Section sec pars 142 | where 143 | cc = cyclomaticComplexity $ graphData imd 144 | sec = Text "Cyclomatic Complexity of imports" 145 | pars = [Paragraph [text], Paragraph [textAfter, link]] 146 | text = Text 147 | $ printf "The cyclomatic complexity of the imports is: %d" cc 148 | textAfter = Text "For more information on cyclomatic complexity, \ 149 | \please see: " 150 | link = DocLink (Text "Wikipedia: Cyclomatic Complexity") 151 | (Web "http://en.wikipedia.org/wiki/Cyclomatic_complexity") 152 | -------------------------------------------------------------------------------- /Analyse/Module.hs: -------------------------------------------------------------------------------- 1 | {- 2 | Copyright (C) 2009 Ivan Lazar Miljenovic 3 | 4 | This file is part of SourceGraph. 5 | 6 | SourceGraph is free software; you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation; either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program; if not, write to the Free Software 18 | Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 19 | -} 20 | 21 | {- | 22 | Module : Analyse.Module 23 | Description : Analyse modules. 24 | Copyright : (c) Ivan Lazar Miljenovic 2009 25 | License : GPL-3 or later. 26 | Maintainer : Ivan.Miljenovic@gmail.com 27 | 28 | Analysis of Haskell modules. 29 | -} 30 | module Analyse.Module(analyseModules) where 31 | 32 | import Parsing.Types 33 | import Analyse.Utils 34 | import Analyse.GraphRepr 35 | import Analyse.Visualise 36 | 37 | import Data.Graph.Analysis 38 | 39 | import Data.Maybe(mapMaybe) 40 | import qualified Data.Map as M 41 | import qualified Data.Set as S 42 | import qualified Data.MultiSet as MS 43 | import Text.Printf(printf) 44 | 45 | -- ----------------------------------------------------------------------------- 46 | 47 | -- Helper types 48 | 49 | -- | Shorthand type 50 | type ModuleData = (String, ModName, HData') 51 | 52 | -- ----------------------------------------------------------------------------- 53 | 54 | -- Analysing. 55 | 56 | -- | Performs analysis of all modules present in the 'ParsedModules' provided. 57 | analyseModules :: ParsedModules -> DocElement 58 | analyseModules = Section (Text "Analysis of each module") 59 | . mapMaybe analyseModule . M.elems 60 | 61 | -- | Performs analysis of the given 'ParsedModule'. 62 | analyseModule :: ParsedModule -> Maybe DocElement 63 | analyseModule hm = if n > 1 64 | then Just $ Section sec elems 65 | else Nothing 66 | where 67 | (n,fd@(m,_,_)) = moduleToGraph hm 68 | elems = mapMaybe ($fd) [ graphOf 69 | -- , collapseAnal 70 | , coreAnal 71 | , levelAnal 72 | , cycleCompAnal 73 | , rootAnal 74 | , componentAnal 75 | , cliqueAnal 76 | , cycleAnal 77 | , chainAnal 78 | ] 79 | sec = Grouping [ Text "Analysis of" 80 | , Emphasis (Text m)] 81 | 82 | -- | Convert the module to the /Graphalyze/ format. 83 | moduleToGraph :: ParsedModule -> (Int,ModuleData) 84 | moduleToGraph hm = (n,(nameOfModule mn, mn, mkHData' vs fd)) 85 | where 86 | mn = moduleName hm 87 | n = applyAlg noNodes fd 88 | fd = importData params 89 | vs = virtualEnts hm 90 | params = ImpParams { dataPoints = S.toList $ internalEnts hm 91 | , relationships = MS.toList . MS.map callToRel 92 | $ funcCalls hm 93 | , roots = S.toList $ exports hm 94 | , directed = True 95 | } 96 | 97 | graphOf :: ModuleData -> Maybe DocElement 98 | graphOf (n,m,fd) = Just $ Section sec [gi] 99 | where 100 | sec = Grouping [ Text "Visualisation of" 101 | , Emphasis $ Text n] 102 | gi = GraphImage $ DG n (Text lbl) (drawGraph lbl (Just m) fd) 103 | lbl = unwords ["Diagram of:", n] 104 | 105 | componentAnal :: ModuleData -> Maybe DocElement 106 | componentAnal (n,_,fd) 107 | | single comp = Nothing 108 | | otherwise = Just el 109 | where 110 | -- Use compactData as the number of edges don't matter, just 111 | -- whether or not an edge exists. 112 | comp = applyAlg componentsOf . compactData $ collapsedHData fd 113 | len = length comp 114 | el = Section sec [Paragraph [Text text]] 115 | sec = Grouping [ Text "Component analysis of" 116 | , Emphasis (Text n)] 117 | text = printf "The module %s has %d components. \ 118 | \You may wish to consider splitting it up." n len 119 | 120 | cliqueAnal :: ModuleData -> Maybe DocElement 121 | cliqueAnal (n,_,fd) 122 | | null clqs = Nothing 123 | | otherwise = Just el 124 | where 125 | clqs = applyAlg cliquesIn . onlyNormalCalls' . compactData 126 | $ collapsedHData fd 127 | clqs' = return . Itemized 128 | $ map (Paragraph . return . Text . showNodes' (name . snd)) clqs 129 | text = Text $ printf "The module %s has the following cliques:" n 130 | el = Section sec $ Paragraph [text] : clqs' 131 | sec = Grouping [ Text "Clique analysis of" 132 | , Emphasis (Text n)] 133 | 134 | cycleAnal :: ModuleData -> Maybe DocElement 135 | cycleAnal (n,_,fd) 136 | | null cycs = Nothing 137 | | otherwise = Just el 138 | where 139 | cycs = applyAlg uniqueCycles . onlyNormalCalls' . compactData 140 | $ collapsedHData fd 141 | cycs' = return . Itemized 142 | $ map (Paragraph . return . Text . showCycle' (name . snd)) cycs 143 | text = Text $ printf "The module %s has the following non-clique \ 144 | \cycles:" n 145 | el = Section sec $ Paragraph [text] : cycs' 146 | sec = Grouping [ Text "Cycle analysis of" 147 | , Emphasis (Text n)] 148 | 149 | chainAnal :: ModuleData -> Maybe DocElement 150 | chainAnal (n,_,fd) 151 | | null chns = Nothing 152 | | otherwise = Just el 153 | where 154 | chns = interiorChains . onlyNormalCalls' . compactData 155 | $ collapsedHData fd 156 | chns' = return . Itemized 157 | $ map (Paragraph . return . Text . showPath' (name . snd)) chns 158 | text = Text $ printf "The module %s has the following chains:" n 159 | textAfter = Text "These chains can all be compressed down to \ 160 | \a single function." 161 | el = Section sec 162 | $ [Paragraph [text]] ++ chns' ++ [Paragraph [textAfter]] 163 | sec = Grouping [ Text "Chain analysis of" 164 | , Emphasis (Text n)] 165 | 166 | rootAnal :: ModuleData -> Maybe DocElement 167 | rootAnal (n,_,fd) 168 | | asExpected = Nothing 169 | | otherwise = Just $ Section sec inaccessible 170 | where 171 | fd' = compactData $ origHData fd 172 | ntWd = S.toList . inaccessibleNodes $ addImplicit (origVirts fd) fd' 173 | ntWd' = applyAlg getLabels fd' ntWd 174 | asExpected = null ntWd 175 | inaccessible = [ Paragraph [Text "These functions are those that are inaccessible:"] 176 | , Paragraph [Emphasis . Text $ showNodes' name ntWd'] 177 | ] 178 | sec = Grouping [ Text "Root analysis of" 179 | , Emphasis (Text n)] 180 | 181 | coreAnal :: ModuleData -> Maybe DocElement 182 | coreAnal (n,m,fd) = fmap mkDE $ makeCore fd 183 | where 184 | mkDE fd' = Section sec [ hdr 185 | , GraphImage $ DG p 186 | (Text lbl) 187 | (drawGraph lbl (Just m) fd') 188 | ] 189 | p = n ++ "_core" 190 | lbl = unwords ["Core of", n] 191 | hdr = coreDesc "a module" 192 | sec = Grouping [ Text "Core analysis of" 193 | , Emphasis (Text n)] 194 | 195 | levelAnal :: ModuleData -> Maybe DocElement 196 | levelAnal (n,m,fd) = Just $ Section sec [hdr, lvls] 197 | where 198 | lvls = GraphImage $ DG p (Text lbl) (drawLevels lbl (Just m) fd) 199 | p = n ++ "_levels" 200 | lbl = unwords ["Levels within", n] 201 | sec = Grouping [ Text "Visualisation of levels in" 202 | , Emphasis (Text n) 203 | ] 204 | hdr = Paragraph [Text "Visualises how far away from the exported root\ 205 | \ entities an entity is."] 206 | 207 | -- Comment out until can work out a way of dealing with [Entity] for 208 | -- the node-label type. 209 | {- 210 | collapseAnal :: ModuleData -> Maybe DocElement 211 | collapseAnal (n,m,fd) = if (trivialCollapse gc) 212 | then Nothing 213 | else Just el 214 | where 215 | fd' = updateGraph collapseGraph fd 216 | gc = graph fd' 217 | p = n ++ "_collapsed" 218 | lbl = unwords ["Collapsed view of", n] 219 | hdr = Paragraph [Text "The collapsed view of a module collapses \ 220 | \down all cliques, cycles, chains, etc. to \ 221 | \make the graph tree-like." ] 222 | gr = GraphImage (p,Text lbl,drawGraph lbl (Just m) fd') 223 | el = Section sec [hdr, gr] 224 | sec = Grouping [ Text "Collapsed view of" 225 | , Emphasis (Text n)] 226 | -} 227 | 228 | cycleCompAnal :: ModuleData -> Maybe DocElement 229 | cycleCompAnal (n,_,fd) = Just $ Section sec pars 230 | where 231 | cc = cyclomaticComplexity . graphData $ collapsedHData fd 232 | sec = Grouping [ Text "Cyclomatic Complexity of" 233 | , Emphasis (Text n)] 234 | pars = [Paragraph [text], Paragraph [textAfter, link]] 235 | text = Text 236 | $ printf "The cyclomatic complexity of %s is: %d." n cc 237 | textAfter = Text "For more information on cyclomatic complexity, \ 238 | \please see: " 239 | link = DocLink (Text "Wikipedia: Cyclomatic Complexity") 240 | (Web "http://en.wikipedia.org/wiki/Cyclomatic_complexity") 241 | -------------------------------------------------------------------------------- /Analyse/Utils.hs: -------------------------------------------------------------------------------- 1 | {- 2 | Copyright (C) 2009 Ivan Lazar Miljenovic 3 | 4 | This file is part of SourceGraph. 5 | 6 | SourceGraph is free software; you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation; either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program; if not, write to the Free Software 18 | Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 19 | -} 20 | 21 | {- | 22 | Module : Analyse.Utils 23 | Description : Utility functions and types for analysis. 24 | Copyright : (c) Ivan Lazar Miljenovic 2009 25 | License : GPL-3 or later. 26 | Maintainer : Ivan.Miljenovic@gmail.com 27 | 28 | Utility functions and types for analysis. 29 | -} 30 | module Analyse.Utils where 31 | 32 | import Data.Graph.Analysis hiding (Bold) 33 | 34 | import Data.List(groupBy, sortBy) 35 | import Data.Function(on) 36 | import qualified Data.Set as S 37 | import Data.Set(Set) 38 | 39 | -- ----------------------------------------------------------------------------- 40 | 41 | -- | Cyclomatic complexity 42 | cyclomaticComplexity :: GraphData a b -> Int 43 | cyclomaticComplexity gd = e - n + 2*p 44 | where 45 | p = length $ applyAlg componentsOf gd 46 | n = applyAlg noNodes gd 47 | e = length $ applyAlg labEdges gd 48 | 49 | groupSortBy :: (Ord b) => (a -> b) -> [a] -> [[a]] 50 | groupSortBy f = groupBy ((==) `on` f) . sortBy (compare `on` f) 51 | 52 | 53 | bool :: a -> a -> Bool -> a 54 | bool f t b = if b then t else f 55 | 56 | chainEdges' :: NGroup -> Set Edge 57 | chainEdges' [] = S.empty 58 | chainEdges' ns = S.fromList $ zip ns (tail ns) 59 | 60 | chainEdges :: [NGroup] -> Set Edge 61 | chainEdges = S.unions . map chainEdges' 62 | 63 | cycleEdges' :: NGroup -> Set Edge 64 | cycleEdges' [] = S.empty 65 | cycleEdges' [_] = S.empty 66 | cycleEdges' ns@(n:ns') = (n, last ns') `S.insert` chainEdges' ns 67 | 68 | cycleEdges :: [NGroup] -> Set Edge 69 | cycleEdges = S.unions . map cycleEdges' 70 | 71 | cliqueEdges' :: NGroup -> Set Edge 72 | cliqueEdges' ns = S.fromList [(f,t) | f <- ns, t <- ns, f /= t] 73 | 74 | cliqueEdges :: [NGroup] -> Set Edge 75 | cliqueEdges = S.unions . map cliqueEdges' 76 | 77 | -- ----------------------------------------------------------------------------- 78 | 79 | -- For core 80 | 81 | coreDesc :: String -> DocElement 82 | coreDesc w = Paragraph [ Text "The core of" 83 | , BlankSpace 84 | , Text w 85 | , BlankSpace 86 | , Text "is calculated by recursively removing roots\ 87 | \ and leaves of the call graph; as such, it\ 88 | \ can be considered as the section where all\ 89 | \ the \"real work\" is done." 90 | ] 91 | -------------------------------------------------------------------------------- /Analyse/Visualise.hs: -------------------------------------------------------------------------------- 1 | {- 2 | Copyright (C) 2010 Ivan Lazar Miljenovic 3 | 4 | This file is part of SourceGraph. 5 | 6 | SourceGraph is free software; you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation; either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program; if not, write to the Free Software 18 | Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 19 | -} 20 | 21 | {- | 22 | Module : Analyse.Visualise 23 | Description : Visualisation functions. 24 | Copyright : (c) Ivan Lazar Miljenovic 2010 25 | License : GPL-3 or later. 26 | Maintainer : Ivan.Miljenovic@gmail.com 27 | 28 | Utility functions and types for analysis. 29 | -} 30 | module Analyse.Visualise where 31 | 32 | import Analyse.Colors 33 | import Analyse.GraphRepr 34 | import Analyse.Utils 35 | import Parsing.Types 36 | 37 | import Data.Graph.Analysis hiding (Bold) 38 | import Data.GraphViz 39 | import Data.GraphViz.Attributes.Complete (Attribute (Margin), DPoint (PVal), 40 | createPoint) 41 | 42 | import Data.List (find) 43 | import Data.Maybe (isNothing) 44 | import qualified Data.Set as S 45 | 46 | -- ----------------------------------------------------------------------------- 47 | 48 | -- | Create the nested 'DotGraph'. 49 | drawGraph :: String -> Maybe ModName -> HData' -> DotGraph Node 50 | drawGraph gid mm dg = setID (toGraphID gid) 51 | . graphviz params $ compactData dg' 52 | 53 | where 54 | params = Params True gAttrs toClust isClust ctypeID clustAttributes' nAttr eAttr 55 | dg' = origHData dg 56 | gAttrs = [nodeAttrs] -- [GraphAttrs [toLabel t]] 57 | -- Possible clustering problem 58 | toClust = clusterEntity -- bool clusterEntity clusterEntityM' $ isJust mm 59 | isClust = const True 60 | nAttr = entityAttributes dg' (isNothing mm) mm 61 | eAttr = callAttributes' dg' 62 | 63 | -- | One-module-per-cluster 'DotGraph'. 64 | drawGraph' :: String -> HData' -> DotGraph Node 65 | drawGraph' gid dg = setID (toGraphID gid) 66 | . graphvizClusters params $ compactData dg' 67 | where 68 | params = Params True gAttrs N undefined undefined modClustAttrs nAttr eAttr 69 | dg' = collapsedHData dg 70 | gAttrs = [nodeAttrs] -- [GraphAttrs [toLabel t]] 71 | nAttr = entityAttributes dg' False Nothing 72 | eAttr = callAttributes' dg' 73 | 74 | -- ----------------------------------------------------------------------------- 75 | 76 | -- | 'True' if add explicit module name to all entities, @'Just' m@ if 77 | -- only one module, @'Nothing'@ if all. 78 | entityAttributes :: GData n e -> Bool -> Maybe ModName 79 | -> LNode Entity -> Attributes 80 | entityAttributes hd a mm (n,Ent m nm t) 81 | = [ toLabel lbl 82 | , shape $ shapeFor t 83 | -- , Color ColorName cl 84 | , fillColor $ entCol hd n 85 | -- Have to re-set Filled because setting a new Style seems to 86 | -- override global Style. 87 | , styles [filled, styleFor mm m] 88 | ] 89 | where 90 | lbl = bool nm (nameOfModule m ++ "\\n" ++ nm) 91 | $ not sameMod || a 92 | sameMod = maybe True (m==) mm 93 | 94 | shapeFor :: EntityType -> Shape 95 | shapeFor Constructor{} = Box3D 96 | shapeFor RecordFunction{} = Component 97 | shapeFor ClassMethod{} = DoubleOctagon 98 | shapeFor DefaultInstance{} = Octagon 99 | shapeFor ClassInstance{} = Octagon 100 | shapeFor CollapsedData{} = Box3D 101 | shapeFor CollapsedClass{} = DoubleOctagon 102 | shapeFor CollapsedInstance{} = Octagon 103 | shapeFor NormalEntity = BoxShape 104 | 105 | styleFor :: Maybe ModName -> ModName -> Style 106 | styleFor mm m@LocalMod{} = bool solid bold $ maybe False (m==) mm 107 | styleFor _ ExtMod{} = dashed 108 | styleFor _ UnknownMod = dotted 109 | 110 | callAttributes :: GData n e -> Edge -> CallType 111 | -> Attributes 112 | callAttributes hd e NormalCall = [ color $ edgeCol hd e] 113 | callAttributes _ _ InstanceDeclaration = [ color Navy 114 | , edgeEnds NoDir 115 | ] 116 | callAttributes _ _ DefaultInstDeclaration = [ color Turquoise 117 | , edgeEnds NoDir 118 | ] 119 | callAttributes _ _ RecordConstructor = [ color Magenta 120 | , arrowFrom oDot 121 | , arrowTo vee 122 | ] 123 | 124 | callAttributes' :: GData n e -> LEdge (Int, CallType) 125 | -> Attributes 126 | callAttributes' hd (f,t,(n,ct)) = penWidth (log (fromIntegral n) + 1) 127 | : callAttributes hd (f,t) ct 128 | 129 | clustAttributes :: EntClustType -> Attributes 130 | clustAttributes (ClassDefn c) = [ toLabel $ "Class: " ++ c 131 | , styles [filled, rounded] 132 | , fillColor RosyBrown1 133 | ] 134 | clustAttributes (DataDefn d) = [ toLabel $ "Data: " ++ d 135 | , styles [filled, rounded] 136 | , fillColor PapayaWhip 137 | ] 138 | clustAttributes (ClassInst _ d) = [ toLabel $ "Instance for: " ++ d 139 | , styles [filled, rounded] 140 | , fillColor SlateGray1 141 | ] 142 | clustAttributes DefInst{} = [ toLabel $ "Default Instance" 143 | , styles [filled, rounded] 144 | , fillColor SlateGray1 145 | ] 146 | clustAttributes (ModPath p) = [ toLabel p ] 147 | 148 | clustAttributes' :: EntClustType -> [GlobalAttributes] 149 | clustAttributes' = return . GraphAttrs . clustAttributes 150 | 151 | modClustAttrs :: ModName -> [GlobalAttributes] 152 | modClustAttrs m = [GraphAttrs [ toLabel $ nameOfModule m 153 | , style filled 154 | , fillColor clusterBackground 155 | ] 156 | ] 157 | 158 | -- ----------------------------------------------------------------------------- 159 | 160 | -- | Create a 'DotGraph' using a clustering function. The clustering 161 | -- function shouldn't touch the the actual 'Node' values. 162 | drawClusters :: String -> (HSGraph -> HSClustGraph) 163 | -> HData' -> DotGraph Node 164 | drawClusters gid cf dg = setID (toGraphID gid) 165 | . graphvizClusters params $ compactData dg' 166 | where 167 | params = blankParams { globalAttributes = gAttrs 168 | , fmtCluster = const cAttr 169 | , fmtNode = nAttr 170 | , fmtEdge = eAttr 171 | } 172 | dg' = mapData' cf $ collapsedHData dg 173 | gAttrs = [nodeAttrs] -- [GraphAttrs [toLabel t]] 174 | cAttr = [GraphAttrs [ style filled 175 | , fillColor clusterBackground 176 | ] 177 | ] 178 | nAttr = entityAttributes dg' True Nothing 179 | eAttr = callAttributes' dg' 180 | 181 | drawLevels :: String -> Maybe ModName -> HData' -> DotGraph Node 182 | drawLevels gid mm hd = setID (toGraphID gid) 183 | $ graphvizClusters params dg' 184 | where 185 | params = blankParams { globalAttributes = gAttrs 186 | , fmtCluster = levelAttr 187 | , fmtNode = nAttr 188 | , fmtEdge = eAttr 189 | } 190 | hd' = collapsedHData hd 191 | vs = collapsedVirts hd 192 | dg = compactData hd' 193 | wrs = wantedRootNodes dg ++ S.toList (implicitExports vs dg) 194 | dg' = updateGraph (levelGraphFrom wrs) dg 195 | gAttrs = [nodeAttrs] -- [GraphAttrs [toLabel t]] 196 | nAttr = entityAttributes hd' (isNothing mm) mm 197 | eAttr = callAttributes' hd' 198 | 199 | levelAttr :: Int -> [GlobalAttributes] 200 | levelAttr l 201 | | l < minLevel = atts "Inaccessible entities" 202 | | l == minLevel = atts "Exported root entities" 203 | | otherwise = atts $ "Level = " ++ show l 204 | where 205 | atts t = [GraphAttrs [ toLabel t 206 | , style filled 207 | , fillColor clusterBackground 208 | ] 209 | ] 210 | 211 | -- ----------------------------------------------------------------------------- 212 | -- Dealing with inter-module imports, etc. 213 | 214 | drawModules :: String -> MData -> DotGraph Node 215 | drawModules gid md = setID (toGraphID gid) 216 | . graphviz params $ graphData md 217 | where 218 | params = Params True gAttrs clusteredModule isClust cID cAttr nAttr eAttr 219 | isClust = const True 220 | cID (_,s) = bool undefined (toGraphID s) $ (not . null) s 221 | gAttrs = [nodeAttrs] -- [GraphAttrs [toLabel t]] 222 | cAttr dp = [GraphAttrs $ directoryAttributes dp] 223 | nAttr (n,m) = [ toLabel m 224 | , fillColor $ entCol md n 225 | , shape Tab 226 | ] 227 | eAttr le = [color . edgeCol md $ edge le] 228 | 229 | directoryAttributes :: (Depth, String) -> Attributes 230 | directoryAttributes (d,n) = col : [ style filled 231 | , toLabel n 232 | ] 233 | where 234 | col = bool (fillColor noBackground) (fillColor clusterBackground) 235 | $ d `mod` 2 == 0 236 | 237 | -- ----------------------------------------------------------------------------- 238 | 239 | entCol :: GData n e -> Node -> X11Color 240 | entCol d n = maybe defaultNodeColor snd 241 | . find hasNode 242 | $ nodeCols d 243 | where 244 | hasNode = S.member n . fst 245 | 246 | nodeAttrs :: GlobalAttributes 247 | nodeAttrs = NodeAttrs [ Margin . PVal $ createPoint 0.4 0.1 248 | , style filled 249 | ] 250 | 251 | edgeCol :: GData n e -> Edge -> X11Color 252 | edgeCol d e = maybe defaultEdgeColor snd 253 | . find hasE 254 | $ edgeCols d 255 | where 256 | hasE = S.member e . fst 257 | -------------------------------------------------------------------------------- /COPYRIGHT: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /CabalInfo.hs: -------------------------------------------------------------------------------- 1 | {- 2 | Copyright (C) 2009 Ivan Lazar Miljenovic 3 | 4 | This file is part of SourceGraph. 5 | 6 | SourceGraph is free software; you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation; either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program; if not, write to the Free Software 18 | Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 19 | -} 20 | 21 | {- | 22 | Module : CabalInfo 23 | Description : Obtain information from a .cabal file. 24 | Copyright : (c) Ivan Lazar Miljenovic 2009 25 | License : GPL-3 or later. 26 | Maintainer : Ivan.Miljenovic@gmail.com 27 | 28 | Used to parse and obtain information from the provided Cabal file. 29 | -} 30 | module CabalInfo(parseCabal) where 31 | 32 | import Distribution.Compiler (CompilerInfo) 33 | import Distribution.ModuleName (toFilePath) 34 | import Distribution.Package 35 | import Distribution.PackageDescription hiding (author) 36 | import Distribution.PackageDescription.Configuration 37 | import Distribution.PackageDescription.Parse 38 | import Distribution.Simple.Compiler (compilerInfo) 39 | import Distribution.Simple.GHC (configure) 40 | import Distribution.Simple.Program (defaultProgramConfiguration) 41 | import Distribution.System (buildPlatform) 42 | import Distribution.Verbosity (silent) 43 | 44 | import Control.Exception (SomeException (..), try) 45 | import Control.Monad (liftM) 46 | import Data.List (nub) 47 | import Data.Maybe (fromJust, isJust) 48 | import System.FilePath (dropExtension) 49 | 50 | -- ----------------------------------------------------------------------------- 51 | 52 | ghcID :: IO CompilerInfo 53 | ghcID = liftM (compilerInfo . getCompiler) 54 | $ configure silent Nothing Nothing defaultProgramConfiguration 55 | where 56 | getCompiler (comp,_mplat,_progconfig) = comp 57 | 58 | parseCabal :: FilePath -> IO (Maybe (String, [FilePath])) 59 | parseCabal fp = do cID <- ghcID 60 | liftM (parseDesc cID) $ getDesc fp 61 | where 62 | -- Need to specify the Exception type 63 | getDesc :: FilePath -> IO (Either SomeException GenericPackageDescription) 64 | getDesc = try . readPackageDescription silent 65 | parseDesc cID = fmap parse . compactEithers . fmap (unGeneric cID) 66 | unGeneric cID = fmap fst 67 | . finalizePackageDescription [] -- flags, use later 68 | (const True) -- ignore 69 | -- deps 70 | buildPlatform 71 | cID 72 | [] 73 | parse pd = (nm, exps) 74 | where 75 | nm = pName . pkgName $ package pd 76 | pName (PackageName nm') = nm' 77 | exes = filter (buildable . buildInfo) $ executables pd 78 | lib = library pd 79 | moduleNames = map toFilePath 80 | exps | not $ null exes = nub $ map (dropExtension . modulePath) exes 81 | | isJust lib = moduleNames . exposedModules $ fromJust lib 82 | | otherwise = error "No exposed modules" 83 | 84 | compactEithers :: Either a (Either b c) -> Maybe c 85 | compactEithers (Right (Right c)) = Just c 86 | compactEithers _ = Nothing 87 | -------------------------------------------------------------------------------- /ChangeLog: -------------------------------------------------------------------------------- 1 | Changes in 0.6.1.1 2 | ================== 3 | 4 | * Update to take into account API changes of libraries. 5 | 6 | Changes in 0.6.1.0 7 | ================== 8 | 9 | * Only consider buildable executables for Cabal-based analyses. 10 | 11 | * Also buildable with haskell-src-exts-1.7.* 12 | 13 | Changes in 0.6.0.2 14 | ================== 15 | 16 | * Also buildable with haskell-src-exts-1.6.* 17 | 18 | Changes in 0.6.0.1 19 | ================== 20 | 21 | * Fix up background colours for nested directories in import visualisation. 22 | 23 | Changes in 0.6.0.0 24 | ================== 25 | 26 | * Now supports "implicitly exported" entities (as requested by Curt 27 | Sampson). This includes instantiated class methods from other 28 | modules and functions, etc. that start with an underscore (see 29 | http://www.haskell.org/ghc/docs/latest/html/users_guide/options-sanity.html 30 | for more information). 31 | 32 | * All inaccessible entities are now reported, not just those that were 33 | root nodes in the call graph. 34 | 35 | * Edges are now colour-coded based upon whether they are part of a 36 | clique, cycle or a chain. 37 | 38 | * Level-based analyses: visualise how deep an entity is from those 39 | exported entities. 40 | 41 | * The generated Dot code for the visualisations is also saved. 42 | 43 | Changes in 0.5.5.0 44 | ================== 45 | 46 | * Class instances now drawn correctly. 47 | 48 | * Better colour support. 49 | 50 | * Now has a legend. 51 | 52 | * Clean up printing of cliques, etc. 53 | 54 | Changes in 0.5.2.0 55 | ================== 56 | 57 | * Shift overall analysis to the top and per-module analysis to the 58 | end, as suggested by Duncan Coutts. 59 | 60 | * Graph drawing fixups: instances are now drawn correctly, and the 61 | module graph now has modules located in the correct directory. 62 | 63 | * Improve some graph drawing aspects (node margins, colours for module 64 | graphs, etc.). 65 | 66 | Changes in 0.5.1.0 67 | ================== 68 | 69 | * Add support for passing a single Haskell source file rather than a 70 | Cabal file as the argument, as requested by Curt Sampson. 71 | 72 | * Shade backgrounds of modules when clustering Entities. 73 | 74 | * RelativeNeighbourhood doesn't provide good alternate modules and 75 | takes up too much runtime, and so has been removed. 76 | 77 | Changes in 0.5.0.0 78 | ================== 79 | 80 | * Re-write of parsing. 81 | 82 | * Usage of new graphviz and Graphalyze features. 83 | 84 | * More abstraction into common routines into Analyse.Utils 85 | -------------------------------------------------------------------------------- /Main.hs: -------------------------------------------------------------------------------- 1 | {- 2 | Copyright (C) 2009 Ivan Lazar Miljenovic 3 | 4 | This program is free software; you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation; either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | This program is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | along with this program; if not, write to the Free Software 16 | Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 17 | -} 18 | 19 | {- | 20 | Module : Main 21 | Description : Analyse source code as a graph. 22 | Copyright : (c) Ivan Lazar Miljenovic 2009 23 | License : GPL-3 or later. 24 | Maintainer : Ivan.Miljenovic@gmail.com 25 | 26 | The executable file for the /SourceGraph/ programme. 27 | 28 | This was written as part of my mathematics honours thesis, 29 | /Graph-Theoretic Analysis of the Relationships in Discrete Data/. 30 | -} 31 | module Main where 32 | 33 | import CabalInfo 34 | import Parsing 35 | import Parsing.Types(nameOfModule) 36 | import Analyse 37 | 38 | import Data.Graph.Analysis 39 | import Data.Graph.Analysis.Reporting.Pandoc 40 | import Data.GraphViz.Commands(quitWithoutGraphviz) 41 | 42 | import Data.Char(toLower) 43 | import Data.Maybe(catMaybes) 44 | import qualified Data.Map as M 45 | import System.IO(hPutStrLn, stderr) 46 | import System.Directory( getCurrentDirectory 47 | , doesDirectoryExist 48 | , doesFileExist 49 | , getDirectoryContents) 50 | import System.FilePath( dropFileName 51 | , takeExtension 52 | , isPathSeparator 53 | , () 54 | , (<.>)) 55 | import System.Random(newStdGen) 56 | import System.Environment(getArgs) 57 | import Control.Arrow(second) 58 | import Control.Monad(liftM) 59 | import Control.Exception(SomeException(..), try) 60 | 61 | import Data.Version(showVersion) 62 | import qualified Paths_SourceGraph as Paths(version) 63 | 64 | -- ----------------------------------------------------------------------------- 65 | 66 | main :: IO () 67 | main = do quitWithoutGraphviz noGraphvizErr 68 | input <- getArgs 69 | mInfo <- getPkgInfo input 70 | case mInfo of 71 | Nothing -> putErrLn "No parseable package information found." 72 | Just (f,(nm,exps)) 73 | -> do let dir = dropFileName f 74 | dir' <- if null dir 75 | then getCurrentDirectory 76 | else return dir 77 | (failed,hms) <- parseFilesFrom dir' 78 | mapM_ (putErrLn . ("Could not parse source file "++)) failed 79 | analyseCode dir nm exps failed hms 80 | where 81 | noGraphvizErr = "ERROR:" ++ programmeName ++ " requires the tools from \ 82 | \http://graphviz.org to be installed." 83 | 84 | programmeName :: String 85 | programmeName = "SourceGraph" 86 | 87 | programmeVersion :: String 88 | programmeVersion = showVersion Paths.version 89 | 90 | putErrLn :: String -> IO () 91 | putErrLn = hPutStrLn stderr 92 | 93 | -- ----------------------------------------------------------------------------- 94 | 95 | getPkgInfo :: [String] -> IO (Maybe (FilePath, (String, [ModName]))) 96 | getPkgInfo [] = do putErrLn "Please provide either a Cabal file \ 97 | \or a Haskell source file as an argument." 98 | return Nothing 99 | getPkgInfo [f] 100 | | isCabalFile f = withF parseCabal' 101 | | isHaskellFile f = withF parseMain 102 | where 103 | withF func = do ex <- doesFileExist f 104 | if ex 105 | then addF $ func f 106 | else do putErrLn "The provided file does not exist." 107 | return Nothing 108 | addF = fmap (fmap ((,) f)) 109 | getPkgInfo _ = do putErrLn "Please provide a single Cabal \ 110 | \or Haskell source file as an argument." 111 | return Nothing 112 | 113 | parseCabal' :: FilePath -> IO (Maybe (String, [ModName])) 114 | parseCabal' = liftM (fmap (second (map fpToModule))) . parseCabal 115 | 116 | isCabalFile :: FilePath -> Bool 117 | isCabalFile = hasExt "cabal" 118 | 119 | parseMain :: FilePath -> IO (Maybe (String, [ModName])) 120 | parseMain fp = do (_,pms) <- parseHaskellFiles [fp] 121 | let mn = fst $ M.findMin pms 122 | return $ Just (nameOfModule mn, [mn]) 123 | 124 | -- | Determine if this is the path of a Haskell file. 125 | isHaskellFile :: FilePath -> Bool 126 | isHaskellFile fp = any (`hasExt` fp) haskellExtensions 127 | 128 | hasExt :: String -> FilePath -> Bool 129 | hasExt ext = (==) ext . drop 1 . takeExtension 130 | 131 | fpToModule :: FilePath -> ModName 132 | fpToModule = createModule . map pSep 133 | where 134 | pSep c 135 | | isPathSeparator c = moduleSep 136 | | otherwise = c 137 | 138 | -- ----------------------------------------------------------------------------- 139 | 140 | -- | Recursively parse all files from this directory 141 | parseFilesFrom :: FilePath -> IO ([FilePath],ParsedModules) 142 | parseFilesFrom fp = parseHaskellFiles =<< getHaskellFilesFrom fp 143 | 144 | parseHaskellFiles :: [FilePath] -> IO ([FilePath],ParsedModules) 145 | parseHaskellFiles = liftM parseHaskell . readFiles 146 | 147 | -- ----------------------------------------------------------------------------- 148 | 149 | -- Reading in the files. 150 | 151 | -- | Recursively find all Haskell source files from the current directory. 152 | getHaskellFilesFrom :: FilePath -> IO [FilePath] 153 | getHaskellFilesFrom fp 154 | = do isDir <- doesDirectoryExist fp -- Ensure it's a directory. 155 | if isDir 156 | then do r <- try getFilesIn -- Ensure we can read the directory. 157 | case r of 158 | (Right fs) -> return fs 159 | (Left SomeException{}) -> return [] 160 | else return [] 161 | where 162 | -- Filter out "." and ".." to stop infinite recursion. 163 | nonTrivialContents :: IO [FilePath] 164 | nonTrivialContents = do contents <- getDirectoryContents fp 165 | let contents' = filter (not . isTrivial) contents 166 | return $ map (fp ) contents' 167 | getFilesIn :: IO [FilePath] 168 | getFilesIn = do contents <- nonTrivialContents 169 | (dirs,files) <- partitionM doesDirectoryExist contents 170 | let hFiles = filter isHaskellFile files 171 | recursiveFiles <- concatMapM getHaskellFilesFrom dirs 172 | return (hFiles ++ recursiveFiles) 173 | 174 | haskellExtensions :: [FilePath] 175 | haskellExtensions = ["hs","lhs"] 176 | 177 | -- | Read in all the files that it can. 178 | readFiles :: [FilePath] -> IO [FileContents] 179 | readFiles = liftM catMaybes . mapM readFileContents 180 | 181 | -- | Try to read the given file. 182 | readFileContents :: FilePath -> IO (Maybe FileContents) 183 | readFileContents f = do cnts <- try $ readFile f 184 | case cnts of 185 | (Right str) -> return $ Just (f,str) 186 | (Left SomeException{}) -> return Nothing 187 | 188 | -- | A version of 'concatMap' for use in monads. 189 | concatMapM :: (Monad m) => (a -> m [b]) -> [a] -> m [b] 190 | concatMapM f = liftM concat . mapM f 191 | 192 | -- | A version of 'partition' for use in monads. 193 | partitionM :: (Monad m) => (a -> m Bool) -> [a] -> m ([a], [a]) 194 | partitionM _ [] = return ([],[]) 195 | partitionM p (x:xs) = do ~(ts,fs) <- partitionM p xs 196 | matches <- p x 197 | if matches 198 | then return (x:ts,fs) 199 | else return (ts,x:fs) 200 | 201 | -- | Trivial paths are the current directory, the parent directory and 202 | -- such directories 203 | isTrivial :: FilePath -> Bool 204 | isTrivial "." = True 205 | isTrivial ".." = True 206 | isTrivial "_darcs" = True 207 | isTrivial "dist" = True 208 | isTrivial "HLInt.hs" = True 209 | isTrivial f | isSetup f = True 210 | isTrivial _ = False 211 | 212 | lowerCase :: String -> String 213 | lowerCase = map toLower 214 | 215 | isSetup :: String -> Bool 216 | isSetup f = lowerCase f `elem` map ("setup" <.>) haskellExtensions 217 | 218 | -- ----------------------------------------------------------------------------- 219 | 220 | analyseCode :: FilePath -> String -> [ModName] 221 | -> [FilePath] -> ParsedModules -> IO () 222 | analyseCode fp nm exps fld hms = do d <- today 223 | g <- newStdGen 224 | let dc = doc d g 225 | docOut <- createDocument pandocHtml' dc 226 | case docOut of 227 | Just path -> success path 228 | Nothing -> failure 229 | where 230 | pandocHtml' = alsoSaveDot pandocHtml 231 | graphdir = "graphs" 232 | doc d g = Doc { rootDirectory = rt 233 | , fileFront = nm 234 | , graphDirectory = graphdir 235 | , title = t 236 | , author = a 237 | , date = d 238 | , legend = sgLegend 239 | , content = notes : c g 240 | } 241 | rt = fp programmeName 242 | sv s v = s ++ " (version " ++ v ++ ")" 243 | t = Grouping [Text "Analysis of", Text nm] 244 | a = unwords [ "Analysed by", sv programmeName programmeVersion 245 | , "using", sv "Graphalyze" version] 246 | c g = analyse g exps hms 247 | success fp' = putStrLn $ unwords ["Report generated at:",fp'] 248 | failure = putErrLn "Unable to generate report" 249 | notes = Section (Text "Notes") 250 | $ (if null fld then id else (++[failed])) 251 | [msg, implicitMsg, linkMsg] 252 | msg = Paragraph [ Text "Please note that the source-code analysis in this\ 253 | \ document is not necessarily perfect: " 254 | , Emphasis $ Text programmeName 255 | , Text " is " 256 | , Bold $ Text "not" 257 | , Text " a refactoring tool, and it's usage of Classes is\ 258 | \ still premature." 259 | ] 260 | implicitMsg = Paragraph [ Text "Implicitly exported entities refer to\ 261 | \ class methods that are instantiated\ 262 | \ but defined elsewhere, or" 263 | , BlankSpace 264 | , DocLink (Text "entities whose names start with\ 265 | \ an underscore") 266 | (Web "http://www.haskell.org/ghc/docs/latest/html/users_guide/options-sanity.html") 267 | , BlankSpace 268 | , Text ". Note that even for " 269 | , Emphasis $ Text "Main" 270 | , BlankSpace 271 | , Text "modules, these implicit exports are included." 272 | ] 273 | linkMsg = Paragraph [Text "All graph visualisations link to larger \ 274 | \SVG versions of the same graph."] 275 | failed = Section (Text "Parsing Failures") 276 | [ Paragraph [Text "The following source files were unable\ 277 | \ to be parsed; this may result in some\ 278 | \ analysis failures:"] 279 | , Itemized $ map (Paragraph . return . Text) fld 280 | ] 281 | -------------------------------------------------------------------------------- /Parsing.hs: -------------------------------------------------------------------------------- 1 | {- 2 | Copyright (C) 2009 Ivan Lazar Miljenovic 3 | 4 | This file is part of SourceGraph. 5 | 6 | SourceGraph is free software; you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation; either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program; if not, write to the Free Software 18 | Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 19 | -} 20 | 21 | {- | 22 | Module : Parsing 23 | Description : Parse the given Haskell modules. 24 | Copyright : (c) Ivan Lazar Miljenovic 2009 25 | License : GPL-3 or later. 26 | Maintainer : Ivan.Miljenovic@gmail.com 27 | 28 | Parse the given Haskell modules. 29 | -} 30 | module Parsing 31 | ( FileContents 32 | , ParsedModules 33 | , ModName 34 | , createModule 35 | , parseHaskell 36 | -- from Parsing.Types 37 | , moduleSep 38 | ) where 39 | 40 | import Parsing.Types 41 | import Parsing.ParseModule 42 | 43 | import Language.Haskell.Exts(parseFileContentsWithMode) 44 | import Language.Haskell.Exts.Parser( ParseMode(..) 45 | , ParseResult(..) 46 | , defaultParseMode) 47 | import Language.Haskell.Exts.Syntax(Module) 48 | 49 | import Data.Either(partitionEithers) 50 | 51 | type FileContents = (FilePath,String) 52 | 53 | -- | Parse all the files and return the map. 54 | -- This uses laziness to evaluate the 'HaskellModules' result 55 | -- whilst also using it to parse all the modules to create it. 56 | parseHaskell :: [FileContents] -> ([FilePath],ParsedModules) 57 | parseHaskell fc = (failed,hms) 58 | where 59 | (failed,ms) = parseFiles fc 60 | hms = createModuleMap hss 61 | hss = map (parseModule hms) ms 62 | 63 | -- | Attempt to parse an individual file. 64 | parseFile :: FileContents -> Either FilePath Module 65 | parseFile (p,f) = case (parseFileContentsWithMode mode f) of 66 | (ParseOk hs) -> Right hs 67 | _ -> Left p 68 | where 69 | mode = defaultParseMode { parseFilename = p 70 | , fixities = Nothing 71 | } 72 | 73 | -- | Parse all the files that you can. 74 | parseFiles :: [FileContents] -> ([FilePath],[Module]) 75 | parseFiles = partitionEithers . map parseFile 76 | -------------------------------------------------------------------------------- /Parsing/ParseModule.hs: -------------------------------------------------------------------------------- 1 | {-# LANGUAGE FlexibleInstances #-} 2 | 3 | {- 4 | Copyright (C) 2009 Ivan Lazar Miljenovic 5 | 6 | This file is part of SourceGraph. 7 | 8 | SourceGraph is free software; you can redistribute it and/or modify 9 | it under the terms of the GNU General Public License as published by 10 | the Free Software Foundation; either version 3 of the License, or 11 | (at your option) any later version. 12 | 13 | This program is distributed in the hope that it will be useful, 14 | but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | GNU General Public License for more details. 17 | 18 | You should have received a copy of the GNU General Public License 19 | along with this program; if not, write to the Free Software 20 | Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 21 | -} 22 | 23 | {- | 24 | Module : Parsing.ParseModule 25 | Description : Parse a Haskell module. 26 | Copyright : (c) Ivan Lazar Miljenovic 2009 27 | License : GPL-3 or later. 28 | Maintainer : Ivan.Miljenovic@gmail.com 29 | 30 | Parse a Haskell module. 31 | -} 32 | module Parsing.ParseModule(parseModule) where 33 | 34 | import Parsing.State 35 | import Parsing.Types 36 | 37 | import Language.Haskell.Exts.Pretty 38 | import Language.Haskell.Exts.Syntax 39 | 40 | import Control.Arrow (second, (***)) 41 | import Control.Monad (liftM, liftM2) 42 | import Data.Char (isUpper) 43 | import Data.Foldable (foldrM) 44 | import qualified Data.Map as M 45 | import Data.Maybe (catMaybes, fromJust, fromMaybe, maybeToList) 46 | import Data.MultiSet (MultiSet) 47 | import qualified Data.MultiSet as MS 48 | import Data.Set (Set) 49 | import qualified Data.Set as S 50 | 51 | -- ----------------------------------------------------------------------------- 52 | 53 | parseModule :: ParsedModules -> Module -> ParsedModule 54 | parseModule hms m = pm 55 | where 56 | mns = moduleNames hms 57 | pm = runPState hms mns blankPM $ parseInfo m 58 | 59 | -- ----------------------------------------------------------------------------- 60 | 61 | class ModuleItem a where 62 | parseInfo :: a -> PState () 63 | 64 | instance (ModuleItem a) => ModuleItem [a] where 65 | parseInfo = mapM_ parseInfo 66 | 67 | -- ----------------------------------------------------------------------------- 68 | -- Overall Module 69 | 70 | instance ModuleItem Module where 71 | parseInfo (Module _ nm _ _ es is ds) 72 | = do let mn = createModule' nm 73 | pm <- get 74 | put $ pm { moduleName = mn } 75 | parseInfo es 76 | parseInfo is 77 | parseInfo ds 78 | 79 | -- ----------------------------------------------------------------------------- 80 | -- Imports 81 | 82 | instance ModuleItem ImportDecl where 83 | parseInfo iDcl 84 | = do mns <- getModuleNames 85 | ms <- getModules 86 | pm <- get 87 | let nm = getModName mns . nameOf $ importModule iDcl 88 | md = M.lookup nm ms 89 | es = imported nm md 90 | im = mi nm es 91 | pm' = pm { imports = M.insert nm im (imports pm) } 92 | put pm' 93 | where 94 | mi nm es = I { fromModule = nm 95 | , importQuald = importQualified iDcl 96 | , importedAs = fmap nameOf $ importAs iDcl 97 | , importedEnts = es 98 | } 99 | 100 | imported nm Nothing 101 | = case importSpecs iDcl of 102 | Just (False,is) -> mkSet 103 | $ map (createEnt nm) is 104 | _ -> S.empty 105 | imported _ (Just ml) 106 | = case importSpecs iDcl of 107 | Nothing -> exprtd 108 | Just (False,is) -> lstd is 109 | Just (True, is) -> exprtd `S.difference` lstd is 110 | where 111 | exprtd = exports ml 112 | exLk = exportLookup ml 113 | lstd = mkSet . map (listedEnt ml exLk) 114 | 115 | -- | Guesstimate the correct 'Entity' designation for those from 116 | -- external modules. 117 | createEnt :: ModName -> ImportSpec -> [Entity] 118 | createEnt mn (IVar _ n) = [Ent mn (nameOf n) NormalEntity] 119 | createEnt mn (IThingWith n cs) = map (\c -> Ent mn c (eT c)) cs' 120 | where 121 | n' = nameOf n 122 | cs' = map nameOf cs 123 | isD = isUpper . head 124 | isDta = any (isUpper . head) cs' 125 | mkData c | isD c = Constructor n' 126 | | otherwise = RecordFunction n' -- Nothing 127 | mkClass _ = ClassMethod n' 128 | eT = if isDta then mkData else mkClass 129 | createEnt _ _ = [] 130 | 131 | -- | Determine the correct 'Entity' designation for the listed import item. 132 | listedEnt :: ParsedModule -> EntityLookup 133 | -> ImportSpec -> [Entity] 134 | listedEnt _ el (IVar _ n) = [lookupEntity' el $ nameOf n] 135 | listedEnt _ _ IAbs{} = [] 136 | listedEnt pm _ (IThingAll n) = esFrom dataDecls ++ esFrom classDecls 137 | -- one will be empty 138 | where 139 | esFrom f = maybe [] M.elems $ M.lookup (nameOf n) (f pm) 140 | listedEnt pm _ (IThingWith n cs) = esFrom dataDecls ++ esFrom classDecls 141 | where 142 | el f = M.lookup (nameOf n) $ f pm 143 | esFrom = maybe [] (\lk -> map (lookupEntity' lk . nameOf) cs) . el 144 | 145 | -- ----------------------------------------------------------------------------- 146 | -- Exports 147 | 148 | -- If the export list is unspecified but there is a function called 149 | -- "main" defined, then it is defined as the export list (otherwise 150 | -- all top-level items are exported). 151 | instance ModuleItem (Maybe [ExportSpec]) where 152 | parseInfo Nothing = do pm <- get 153 | fpm <- getFutureParsedModule 154 | el <- getLookup 155 | let mainFunc = M.lookup (Nothing,"main") el 156 | es = maybe (exportableEnts fpm) S.singleton mainFunc 157 | put $ pm { exports = es } 158 | parseInfo (Just eps) = do pm <- get 159 | fpm <- getFutureParsedModule 160 | let el = exportableLookup fpm 161 | es = mkSet $ map (listedExp fpm el) eps 162 | put $ pm { exports = es } 163 | 164 | -- Doesn't work on re-exported Class/Data specs. 165 | listedExp :: ParsedModule -> EntityLookup 166 | -> ExportSpec -> [Entity] 167 | listedExp _ el (EVar _ qn) = maybe [] (return . lookupEntity el) 168 | $ qName qn 169 | listedExp _ _ EAbs{} = [] 170 | listedExp pm _ (EThingAll qn) = esFrom dataDecls ++ esFrom classDecls 171 | -- one will be empty 172 | where 173 | esFrom f = fromMaybe [] 174 | $ do n <- liftM snd $ qName qn 175 | el <- M.lookup n $ f pm 176 | return $ M.elems el 177 | listedExp pm _ (EThingWith qn cs) = esFrom dataDecls ++ esFrom classDecls 178 | where 179 | esFrom f = fromMaybe [] $ do mn <- fmap snd $ qName qn 180 | el <- M.lookup mn $ f pm 181 | return $ map (lookupEntity' el . nameOf) cs 182 | listedExp pm _ (EModuleContents m) = fromMaybe [] 183 | . fmap (S.toList . importedEnts) 184 | . M.lookup (createModule' m) 185 | $ imports pm 186 | 187 | -- ----------------------------------------------------------------------------- 188 | -- Main part of the module 189 | 190 | instance ModuleItem Decl where 191 | -- Type alias 192 | parseInfo TypeDecl{} = return () 193 | -- Type Families: don't seem to have any entities. 194 | parseInfo TypeFamDecl{} = return () 195 | -- Data or Newtype 196 | parseInfo (DataDecl _ _ _ nm _ cs _) 197 | = do let d = nameOf nm 198 | els <- mapM (addConstructor d . unQConDecl) cs 199 | pm <- get 200 | let el = M.unions els 201 | dds' = M.insert d el $ dataDecls pm 202 | put $ pm { dataDecls = dds' } 203 | -- GADT-style Data or Newtype 204 | parseInfo (GDataDecl _ _ _ n _ _ gds _) 205 | = do m <- getModuleName 206 | pm <- get 207 | let d = nameOf n 208 | el = addGConstructors m d gds 209 | dds' = M.insert d el $ dataDecls pm 210 | put $ pm { dataDecls = dds' } 211 | -- Data Families: don't seem to have any entities 212 | parseInfo DataFamDecl{} = return () 213 | -- Type families are basically aliases... 214 | parseInfo TypeInsDecl{} = return () 215 | -- Data family instances are pretty much data declarations 216 | -- Don't add them yet, as can't necessarily go from Type -> Name 217 | -- todo 218 | parseInfo DataInsDecl{} = return () 219 | -- Same thing as above 220 | -- todo 221 | parseInfo GDataInsDecl{} = return () 222 | -- Defining a new class 223 | parseInfo (ClassDecl _ _ n _ _ cds) 224 | = do let c = nameOf n 225 | mels <- mapM (addClassDecl c) cds 226 | pm <- get 227 | let el = M.unions $ catMaybes mels 228 | cl' = M.insert c el $ classDecls pm 229 | put $ pm { classDecls = cl' } 230 | -- Instance of a class 231 | parseInfo (InstDecl _ _ _ _ n ts ids) 232 | = do let c = snd . fromJust $ qName n 233 | d = unwords $ map prettyPrint ts 234 | mapM_ (addInstDecl c d) ids 235 | -- Stand-alone deriving 236 | parseInfo DerivDecl{} = return () 237 | -- Fixity of infix operators 238 | parseInfo InfixDecl{} = return () 239 | -- Default types (Integer, etc.) 240 | parseInfo DefaultDecl{} = return () 241 | -- TH Splicing 242 | parseInfo SpliceDecl{} = return () 243 | -- Type sigs... use the actual function 244 | parseInfo TypeSig{} = return () 245 | -- Actual Function 246 | parseInfo (FunBind ms) = mapM_ addMatch ms 247 | -- Defining a variable, etc. 248 | parseInfo pb@PatBind{} 249 | = do mn <- getModuleName 250 | el <- getLookup 251 | pm <- get 252 | (d,c) <- getDecl pb -- Might as well use this 253 | -- We can have more than one definition from here, unlike 254 | -- for Matches. 255 | let vs = S.map snd d 256 | mkE v = Ent mn v NormalEntity 257 | es = S.map mkE vs 258 | es' = MS.fromList $ S.toList es 259 | mkFC e o = FC e (lookupEntity el o) NormalCall 260 | mkFCs o = MS.map (flip mkFC o) es' 261 | cs = MS.unions . map mkFCs $ MS.toList c 262 | pm' = pm { topEnts = topEnts pm `S.union` es 263 | , funcCalls = funcCalls pm `MS.union` cs 264 | } 265 | put pm' 266 | -- The rest are foreign import/export and pragmas 267 | parseInfo _ = return () 268 | 269 | -- ----------------------------------------------------------------------------- 270 | -- Constructors 271 | 272 | unQConDecl :: QualConDecl -> ConDecl 273 | unQConDecl (QualConDecl _ _ _ cd) = cd 274 | 275 | addConstructor :: DataType -> ConDecl -> PState EntityLookup 276 | addConstructor d (ConDecl n _) = do m <- getModuleName 277 | let n' = nameOf n 278 | e = Ent m n' (Constructor d) 279 | return $ M.singleton (Nothing,n') e 280 | addConstructor d (InfixConDecl _ n _) = do m <- getModuleName 281 | let n' = nameOf n 282 | e = Ent m n' (Constructor d) 283 | return $ M.singleton (Nothing,n') e 284 | addConstructor d (RecDecl n rbs) = do m <- getModuleName 285 | pm <- get 286 | let n' = nameOf n 287 | ce = Ent m n' (Constructor d) 288 | rs = map nameOf $ concatMap fst rbs 289 | res = map (mkRe m) rs 290 | es = ce : res 291 | fcs = MS.fromList $ map (mkFc ce) res 292 | put $ addFcs pm fcs 293 | return $ mkEl es 294 | where 295 | mkRe m r = Ent m r (RecordFunction d) 296 | mkFc c r = FC r c RecordConstructor 297 | addFcs pm fcs = pm { funcCalls = fcs `MS.union` funcCalls pm } 298 | 299 | -- ----------------------------------------------------------------------------- 300 | -- GADT constructors 301 | 302 | addGConstructors :: ModName -> DataType -> [GadtDecl] -> EntityLookup 303 | addGConstructors m d = mkEl . map addGConst 304 | where 305 | addGConst (GadtDecl _ n _ _) = Ent m (nameOf n) (Constructor d) 306 | 307 | -- ----------------------------------------------------------------------------- 308 | -- Class declaration 309 | 310 | addClassDecl :: ClassName -> ClassDecl 311 | -> PState (Maybe EntityLookup) 312 | addClassDecl c (ClsDecl d) = addCDecl c d 313 | addClassDecl _ _ = return Nothing 314 | 315 | addCDecl :: ClassName -> Decl -> PState (Maybe EntityLookup) 316 | addCDecl c (TypeSig _ ns _) = do m <- getModuleName 317 | let ns' = map nameOf ns 318 | eTp = ClassMethod c 319 | es = map (\n -> Ent m n eTp) ns' 320 | return $ Just (mkEl es) 321 | addCDecl c (FunBind ms) = mapM_ (addCMatch c) ms >> return Nothing 322 | 323 | addCDecl c pb@PatBind{} = do mn <- getModuleName 324 | el <- getLookup 325 | pm <- get 326 | (d,cs) <- getDecl pb 327 | let vs = S.map snd d 328 | -- Class-based entities 329 | mkI n = Ent mn n (DefaultInstance c) 330 | mkC n = Ent mn n (ClassMethod c) 331 | cis = S.map (\n -> (mkC n, mkI n)) vs 332 | -- Instance Decls 333 | iDcls = S.map snd cis `S.union` instDecls pm 334 | cis' = MS.fromList $ S.toList cis 335 | -- DefInst calls 336 | mkiCl (f,t) = FC f t DefaultInstDeclaration 337 | ciCls = MS.map mkiCl cis' 338 | -- Calls for that instance 339 | is = MS.map snd cis' 340 | mkFC i o = FC i (lookupEntity el o) NormalCall 341 | mkFCs o = MS.map (flip mkFC o) is 342 | cs' = MS.unions . map mkFCs $ MS.toList cs 343 | pm' = pm { instDecls = iDcls 344 | , funcCalls = funcCalls pm 345 | `MS.union` ciCls 346 | `MS.union` cs' 347 | } 348 | put pm' 349 | return Nothing 350 | -- Can't have anything else in classes 351 | addCDecl _ _ = return Nothing 352 | 353 | addCMatch :: ClassName -> Match -> PState () 354 | addCMatch c m = do el <- getLookup 355 | di <- addFuncCalls (DefaultInstance c) m 356 | pm <- get 357 | let cfn = name di 358 | cf = lookupEntity' el cfn 359 | dic = FC cf di DefaultInstDeclaration 360 | pm' = pm { instDecls = S.insert di $ instDecls pm 361 | , funcCalls = MS.insert dic $ funcCalls pm 362 | } 363 | put pm' 364 | 365 | -- ----------------------------------------------------------------------------- 366 | -- Instance Declaration 367 | 368 | addInstDecl :: ClassName -> DataType -> InstDecl -> PState () 369 | addInstDecl c d (InsDecl decl) = do cs <- addIDecl c d decl 370 | mn <- getModuleName 371 | pm <- get 372 | let fromThisMod = (==) mn . inModule 373 | cs' = S.filter (not . fromThisMod) cs 374 | pm' = pm { virtualEnts = virtualEnts pm 375 | `S.union` 376 | cs' 377 | } 378 | put pm' 379 | addInstDecl _ _ _ = return () 380 | 381 | addIDecl :: ClassName -> DataType -> Decl -> PState (Set Entity) 382 | addIDecl c d (FunBind ms) = liftM S.fromList $ mapM (addIMatch c d) ms 383 | addIDecl c d pb@PatBind{} = do mn <- getModuleName 384 | el <- getLookup 385 | pm <- get 386 | pmf <- getFutureParsedModule 387 | (df,cs) <- getDecl pb 388 | let vs = S.map snd df 389 | -- Class-based entities 390 | mkI n = Ent mn n (ClassInstance c d) 391 | mkC = classFuncLookup c pmf 392 | cis = S.map (\n -> (mkC n, mkI n)) vs 393 | -- Instance Decls 394 | iDcls = S.map snd cis `S.union` instDecls pm 395 | cis' = MS.fromList $ S.toList cis 396 | -- DefInst calls 397 | mkiCl (f,t) = FC f t InstanceDeclaration 398 | ciCls = MS.map mkiCl cis' 399 | -- Calls for that instance 400 | is = MS.map snd cis' 401 | mkFC i o = FC i (lookupEntity el o) NormalCall 402 | mkFCs o = MS.map (flip mkFC o) is 403 | cs' = MS.unions . map mkFCs $ MS.toList cs 404 | pm' = pm { instDecls = iDcls 405 | , funcCalls = funcCalls pm 406 | `MS.union` ciCls 407 | `MS.union` cs' 408 | } 409 | put pm' 410 | return $ S.map fst cis 411 | addIDecl _ _ _ = return S.empty 412 | 413 | addIMatch :: ClassName -> DataType -> Match -> PState Entity 414 | addIMatch c d m = do pmf <- getFutureParsedModule 415 | fi <- addFuncCalls (ClassInstance c d) m 416 | pm <- get 417 | let cfn = name fi 418 | cf = classFuncLookup c pmf cfn 419 | ic = FC cf fi InstanceDeclaration 420 | pm' = pm { instDecls = S.insert fi $ instDecls pm 421 | , funcCalls = MS.insert ic $ funcCalls pm 422 | } 423 | put pm' 424 | return cf 425 | 426 | -- Must use the future ParsedModule. Can't use internalLookup, since 427 | -- it includes the virtuals and results in infinite loops as it tries 428 | -- to lookup values that it creates... 429 | -- 430 | -- Note: we assume that if a class method is explicitly imported from 431 | -- an external module, then it will be obvious that it is a class 432 | -- method because otherwise the class won't be imported either. 433 | classFuncLookup :: ClassName -> ParsedModule -> EntityName -> Entity 434 | classFuncLookup c pmf n = case inModule e of 435 | UnknownMod -> e { eType = ClassMethod c } 436 | _ -> e 437 | where 438 | e = lookupEntity' knownMethods n 439 | knownMethods = localMethods `M.union` importMethods 440 | localMethods = fromMaybe M.empty $ c `M.lookup` classDecls pmf 441 | importMethods = M.filter (isMethod . eType) $ allImports pmf 442 | isMethod (ClassMethod c') = c == c' 443 | isMethod _ = False 444 | 445 | -- ----------------------------------------------------------------------------- 446 | -- For top-level functions 447 | 448 | addMatch :: Match -> PState () 449 | addMatch m = do e <- addFuncCalls NormalEntity m 450 | pm <- get 451 | put $ pm { topEnts = S.insert e $ topEnts pm } 452 | 453 | -- ----------------------------------------------------------------------------- 454 | 455 | -- Add the appropriate 'FunctionCall' values and return the created 456 | -- 'Entity'. The 'FunctionCall's have @callType = NormalCall@. 457 | addFuncCalls :: EntityType -> Match -> PState Entity 458 | addFuncCalls et m = do mn <- getModuleName 459 | el <- getLookup 460 | pm <- get 461 | (d,c) <- getMatch m 462 | let nm = snd $ S.findMin d 463 | f = Ent { inModule = mn 464 | , name = nm -- Assume non-qualified... 465 | , eType = et 466 | } 467 | cs = MS.map (mkFC el f) c 468 | pm' = pm { funcCalls = cs `MS.union` funcCalls pm } 469 | put pm' 470 | return f 471 | where 472 | mkFC el l qn = FC l (lookupEntity el qn) NormalCall 473 | 474 | -- ----------------------------------------------------------------------------- 475 | 476 | -- Pulling apart sub-components 477 | 478 | -- None of these really need PState... I thought they did mid-write, 479 | -- refactored them all to use it and then after I'd finished realised 480 | -- they didn't. Too late to change, so they can stay this way. 481 | 482 | type Defined = Set QEntityName 483 | type Called = MultiSet QEntityName 484 | type DefCalled = (Defined, Called) 485 | 486 | getMatch :: Match -> PState DefCalled 487 | getMatch (Match _ n ps _ rhs bs) = do (avs, afs) <- getPats ps 488 | rcs <- getRHS rhs 489 | (bds, bcs) <- getBindings bs 490 | let vs = avs `S.union` bds 491 | fs = MS.unions [afs, rcs, bcs] 492 | cs = defElsewhere fs vs 493 | return (S.singleton $ nameOf' n, cs) 494 | 495 | -- In a pattern, all variables are ones that have just been defined to 496 | -- use in that function, etc. 497 | getPat :: Pat -> PState DefCalled 498 | -- Variable 499 | getPat (PVar n) = return $ onlyVar n 500 | -- Literal value 501 | getPat PLit{} = return noEnts 502 | -- n + k pattern 503 | getPat (PNPlusK n _) = return $ onlyVar n 504 | -- e.g. a : as 505 | getPat (PInfixApp p1 c p2) = do (v1, c1) <- getPat p1 506 | (v2, c2) <- getPat p2 507 | return ( v1 `S.union` v2 508 | , insQName c $ c1 `MS.union` c2) 509 | -- Data constructor + args 510 | getPat (PApp qn ps) = liftM (second $ insQName qn) $ getPats ps 511 | -- Tuple 512 | getPat (PTuple _ ps) = getPats ps 513 | -- Explicit list 514 | getPat (PList ps) = getPats ps 515 | -- Parens around a Pat 516 | getPat (PParen p) = getPat p 517 | -- Record pattern 518 | getPat (PRec q ps) = liftM (second (insQName q) . sMsUnions) 519 | $ mapM getPField ps 520 | -- @-pattern 521 | getPat (PAsPat n p) = liftM (sMsMerge (onlyVar n)) $ getPat p 522 | -- _ 523 | getPat PWildCard = return noEnts 524 | -- ~pat 525 | getPat (PIrrPat p) = getPat p 526 | -- pattern with explicit type-sig 527 | getPat (PatTypeSig _ p _) = getPat p 528 | -- View pattern (function -> constructor) [this avoids an explicit 529 | -- case statement] 530 | getPat (PViewPat e p) = do ec <- getExp e 531 | (pd,pc) <- getPat p 532 | return (pd, ec `MS.union` pc) 533 | -- HaRP... no idea now to deal with this 534 | getPat PRPat{} = return noEnts 535 | -- !foo 536 | getPat (PBangPat p) = getPat p 537 | -- The rest are XML and TH patterns 538 | getPat _ = return noEnts 539 | 540 | getPats :: [Pat] -> PState DefCalled 541 | getPats = liftM sMsUnions . mapM getPat 542 | 543 | insQName :: QName -> Called -> Called 544 | insQName qn sq = maybe sq (flip MS.insert sq) $ qName qn 545 | 546 | onlyVar :: (Named n) => n -> DefCalled 547 | onlyVar n = (S.singleton $ nameOf' n, MS.empty) 548 | 549 | -- Punned fields: not registered as variables 550 | -- Record wildcards: nothing returned 551 | getPField :: PatField -> PState DefCalled 552 | getPField (PFieldPat qn p) = liftM (second $ insQName qn) $ getPat p 553 | getPField (PFieldPun n) = return (S.empty, MS.fromList . maybeToList $ qName n) 554 | getPField PFieldWildcard = return noEnts 555 | 556 | -- Still have to take care of function calls here somewhere... 557 | -- Nope: trying to get the overall list of functions called here... 558 | -- and _then_ create function calls to them! 559 | 560 | getBindings :: Binds -> PState DefCalled 561 | getBindings (BDecls ds) = liftM sMsUnions $ mapM getDecl ds 562 | getBindings (IPBinds is) = liftM sMsUnions $ mapM getIPBinds is 563 | 564 | getIPBinds :: IPBind -> PState DefCalled 565 | getIPBinds (IPBind _ _ e) = liftM noDefs $ getExp e 566 | 567 | getDecl :: Decl -> PState DefCalled 568 | getDecl (FunBind ms) = liftM sMsUnions $ mapM getMatch ms 569 | getDecl (PatBind _ p r bs) = do (pd,pc) <- getPat p 570 | rc <- getRHS r 571 | (bd,bc) <- getBindings bs 572 | let fs = MS.unions [pc, rc, bc] 573 | cs = defElsewhere fs bd 574 | return (pd, cs) 575 | getDecl _ = return noEnts 576 | 577 | 578 | getRHS :: Rhs -> PState Called 579 | getRHS (UnGuardedRhs e) = getExp e 580 | getRHS (GuardedRhss grs) = liftM MS.unions $ mapM getGRhs grs 581 | 582 | getGRhs :: GuardedRhs -> PState Called 583 | getGRhs (GuardedRhs _ ss e) = do (sf,sc) <- getStmts ss 584 | ec <- getExp e 585 | return $ defElsewhere' sf (sc `MS.union` ec) 586 | 587 | -- Gah, this might be wrong... 588 | 589 | getExp :: Exp -> PState Called 590 | getExp (Var qn) = return $ maybeEnt qn 591 | getExp IPVar{} = return MS.empty 592 | getExp (Con qn) = return $ maybeEnt qn 593 | getExp Lit{} = return MS.empty 594 | getExp (InfixApp e1 o e2) = do e1' <- getExp e1 595 | e2' <- getExp e2 596 | let o' = maybeEnt o 597 | return $ e1' `MS.union` e2' `MS.union` o' 598 | getExp (App ef vf) = liftM2 MS.union (getExp ef) (getExp vf) 599 | getExp (NegApp e) = getExp e 600 | getExp (Lambda _ ps e) = do (pd,pc) <- getPats ps 601 | e' <- getExp e 602 | return $ defElsewhere' pd 603 | $ MS.union pc e' 604 | getExp (Let bs e) = do (bd,bc) <- getBindings bs 605 | e' <- getExp e 606 | return $ defElsewhere' bd (MS.union bc e') 607 | getExp (If i t e) = getExps [i,t,e] 608 | getExp (Case e as) = do e' <- getExp e 609 | as' <- mapM getAlt as 610 | return $ MS.unions (e':as') 611 | getExp (Do ss) = chainedCalled $ map getStmt ss 612 | getExp (MDo ss) = liftM (uncurry defElsewhere') $ getStmts ss 613 | getExp (Tuple _ es) = getExps es 614 | getExp (TupleSection _ mes) = getExps $ catMaybes mes 615 | getExp (List es) = getExps es 616 | getExp (Paren e) = getExp e 617 | getExp (LeftSection e o) = liftM (MS.union (maybeEnt o)) $ getExp e 618 | getExp (RightSection o e) = liftM (MS.union (maybeEnt o)) $ getExp e 619 | getExp (RecConstr qn fus) = liftM (MS.union (maybeEnt qn)) $ getFUpdates fus 620 | getExp (RecUpdate e fus) = liftM2 MS.union (getExp e) (getFUpdates fus) 621 | getExp (EnumFrom e) = getExp e 622 | getExp (EnumFromTo e1 e2) = liftM2 MS.union (getExp e1) (getExp e2) 623 | getExp (EnumFromThen e1 e2) = liftM2 MS.union (getExp e1) (getExp e2) 624 | getExp (EnumFromThenTo e1 e2 e3) = liftM2 MS.union (getExp e1) 625 | $ liftM2 MS.union (getExp e2) (getExp e3) 626 | getExp (ListComp e qss) = liftM2 MS.union (getExp e) $ getQStmts qss 627 | getExp (ParComp e qsss) = liftM2 MS.union (getExp e) . liftM MS.unions 628 | $ mapM getQStmts qsss 629 | getExp (ExpTypeSig _ e _) = getExp e 630 | getExp (VarQuote qn) = return $ maybeEnt qn 631 | getExp (Proc _ p e) = do (pd,pc) <- getPat p 632 | c <- getExp e 633 | return $ pc `MS.union` defElsewhere c pd 634 | getExp (RightArrApp e1 e2) = liftM2 MS.union (getExp e1) (getExp e2) 635 | getExp (LeftArrApp e1 e2) = liftM2 MS.union (getExp e1) (getExp e2) 636 | getExp (RightArrHighApp e1 e2) = liftM2 MS.union (getExp e1) (getExp e2) 637 | getExp (LeftArrHighApp e1 e2) = liftM2 MS.union (getExp e1) (getExp e2) 638 | -- Everything else is TH, XML or Pragmas 639 | getExp _ = return MS.empty 640 | 641 | getExps :: [Exp] -> PState Called 642 | getExps = liftM MS.unions . mapM getExp 643 | 644 | chainedCalled :: [PState DefCalled] -> PState Called 645 | chainedCalled = foldrM go MS.empty 646 | where 647 | go s cs = liftM (rmVars cs) s 648 | rmVars cs (d,c) = defElsewhere cs d `MS.union` c 649 | 650 | getQStmt :: QualStmt -> PState DefCalled 651 | getQStmt (QualStmt s) = getStmt s 652 | getQStmt (ThenTrans e) = liftM noDefs $ getExp e 653 | getQStmt (ThenBy e1 e2) = liftM noDefs $ liftM2 MS.union (getExp e1) (getExp e2) 654 | getQStmt (GroupBy e) = liftM noDefs $ getExp e 655 | getQStmt (GroupUsing e) = liftM noDefs $ getExp e 656 | getQStmt (GroupByUsing e1 e2) = liftM noDefs 657 | $ liftM2 MS.union (getExp e1) (getExp e2) 658 | 659 | getQStmts :: [QualStmt] -> PState Called 660 | getQStmts = chainedCalled . map getQStmt 661 | 662 | getFUpdates :: [FieldUpdate] -> PState Called 663 | getFUpdates = liftM MS.unions . mapM getFUpdate 664 | 665 | getFUpdate :: FieldUpdate -> PState Called 666 | getFUpdate (FieldUpdate qn e) = liftM (MS.union (maybeEnt qn)) $ getExp e 667 | getFUpdate (FieldPun n) = return . MS.fromList . maybeToList $ qName n 668 | getFUpdate _ = return MS.empty 669 | 670 | getAlt :: Alt -> PState Called 671 | getAlt (Alt _ p gas bs) = do (pd,pc) <- getPat p 672 | gc <- getRHS gas 673 | (bd,bc) <- getBindings bs 674 | let d = pd `S.union` bd 675 | c = pc `MS.union` gc `MS.union` bc 676 | return $ defElsewhere c d 677 | 678 | getStmt :: Stmt -> PState DefCalled 679 | getStmt (Generator _ p e) = do (pf,pc) <- getPat p 680 | ec <- getExp e 681 | return (pf, defElsewhere' pf (MS.union pc ec)) 682 | getStmt (Qualifier e) = liftM noDefs $ getExp e 683 | getStmt (LetStmt bs) = getBindings bs 684 | getStmt (RecStmt ss) = getStmts ss 685 | 686 | getStmts :: [Stmt] -> PState DefCalled 687 | getStmts = liftM sMsUnions . mapM getStmt 688 | 689 | noDefs :: Called -> DefCalled 690 | noDefs = (,) S.empty 691 | 692 | maybeEnt :: (QNamed a) => a -> Called 693 | maybeEnt = maybe MS.empty MS.singleton . qName 694 | 695 | noEnts :: DefCalled 696 | noEnts = (S.empty, MS.empty) 697 | 698 | -- ----------------------------------------------------------------------------- 699 | 700 | class Named a where 701 | nameOf :: a -> String 702 | 703 | instance Named Name where 704 | nameOf (Ident n) = n 705 | nameOf (Symbol n) = n 706 | 707 | nameOf' :: (Named n) => n -> QEntityName 708 | nameOf' = (,) Nothing . nameOf 709 | 710 | instance Named CName where 711 | nameOf (VarName n) = nameOf n 712 | nameOf (ConName n) = nameOf n 713 | 714 | instance Named ModuleName where 715 | nameOf (ModuleName m) = m 716 | 717 | -- | Create the 'ModName'. 718 | createModule' :: ModuleName -> ModName 719 | createModule' = createModule . nameOf 720 | 721 | class QNamed a where 722 | qName :: a -> Maybe QEntityName 723 | 724 | instance QNamed QName where 725 | qName (Qual m n) = Just (Just $ nameOf m, nameOf n) 726 | qName (UnQual n) = Just (Nothing, nameOf n) 727 | qName Special{} = Nothing 728 | 729 | instance QNamed QOp where 730 | qName (QVarOp qn) = qName qn 731 | qName (QConOp qn) = qName qn 732 | 733 | sMsUnions :: (Ord a, Ord b) => [(Set a, MultiSet b)] -> (Set a, MultiSet b) 734 | sMsUnions = (S.unions *** MS.unions) . unzip 735 | 736 | sMsMerge :: (Ord a, Ord b) => (Set a, MultiSet b) 737 | -> (Set a, MultiSet b) -> (Set a, MultiSet b) 738 | sMsMerge (s1, ms1) = S.union s1 *** MS.union ms1 739 | 740 | defElsewhere :: Called -> Defined -> Called 741 | defElsewhere ms s = MS.fromMap $ fs `M.difference` ifs 742 | where 743 | fs = MS.toMap ms 744 | ifs = M.fromList . map (flip (,) () ) $ S.toList s 745 | 746 | defElsewhere' :: Defined -> Called -> Called 747 | defElsewhere' = flip defElsewhere 748 | 749 | -- ----------------------------------------------------------------------------- 750 | -------------------------------------------------------------------------------- /Parsing/State.hs: -------------------------------------------------------------------------------- 1 | {-# LANGUAGE CPP, GeneralizedNewtypeDeriving #-} 2 | 3 | {- 4 | Copyright (C) 2009 Ivan Lazar Miljenovic 5 | 6 | This file is part of SourceGraph. 7 | 8 | SourceGraph is free software; you can redistribute it and/or modify 9 | it under the terms of the GNU General Public License as published by 10 | the Free Software Foundation; either version 3 of the License, or 11 | (at your option) any later version. 12 | 13 | This program is distributed in the hope that it will be useful, 14 | but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | GNU General Public License for more details. 17 | 18 | You should have received a copy of the GNU General Public License 19 | along with this program; if not, write to the Free Software 20 | Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 21 | -} 22 | 23 | {- | 24 | Module : Parsing.State 25 | Description : State Monad for parsing. 26 | Copyright : (c) Ivan Lazar Miljenovic 2009 27 | License : GPL-3 or later. 28 | Maintainer : Ivan.Miljenovic@gmail.com 29 | 30 | Customised State Monad for parsing Haskell code. 31 | -} 32 | module Parsing.State 33 | ( PState 34 | , runPState 35 | , get 36 | , put 37 | , getModules 38 | , getModuleNames 39 | , getLookup 40 | , getFutureParsedModule 41 | , getModuleName 42 | ) where 43 | 44 | import Parsing.Types 45 | 46 | import Control.Monad.RWS 47 | 48 | #if !(MIN_VERSION_base (4,8,0)) 49 | import Control.Applicative (Applicative) 50 | #endif 51 | 52 | -- ----------------------------------------------------------------------------- 53 | 54 | runPState :: ParsedModules -> ModuleNames 55 | -> ParsedModule -> PState a -> ParsedModule 56 | runPState hms mns pm st = pm' 57 | where 58 | -- Tying the knot 59 | el = internalLookup pm' 60 | mp = MD hms mns el pm' 61 | (pm', _) = execRWS (runPS st) mp pm 62 | 63 | data ModuleData = MD { moduleLookup :: ParsedModules 64 | , modNmsLookup :: ModuleNames 65 | , entityLookup :: EntityLookup 66 | , futureParsedModule :: ParsedModule 67 | } 68 | 69 | type ModuleWrite = () 70 | 71 | newtype PState value 72 | = PS { runPS :: RWS ModuleData ModuleWrite ParsedModule value } 73 | -- Note: don't derive MonadReader, etc. as don't want anything 74 | -- outside this module to get the actual types used. 75 | deriving (Functor, Applicative, Monad, MonadState ParsedModule, MonadWriter ModuleWrite) 76 | 77 | asks' :: (ModuleData -> a) -> PState a 78 | asks' = PS . asks 79 | 80 | getModules :: PState ParsedModules 81 | getModules = asks' moduleLookup 82 | 83 | getModuleNames :: PState ModuleNames 84 | getModuleNames = asks' modNmsLookup 85 | 86 | getLookup :: PState EntityLookup 87 | getLookup = asks' entityLookup 88 | 89 | getFutureParsedModule :: PState ParsedModule 90 | getFutureParsedModule = asks' futureParsedModule 91 | 92 | getModuleName :: PState ModName 93 | getModuleName = gets moduleName 94 | -------------------------------------------------------------------------------- /Parsing/Types.hs: -------------------------------------------------------------------------------- 1 | {-# LANGUAGE TypeFamilies #-} 2 | 3 | {- 4 | Copyright (C) 2009 Ivan Lazar Miljenovic 5 | 6 | This file is part of SourceGraph. 7 | 8 | SourceGraph is free software; you can redistribute it and/or modify 9 | it under the terms of the GNU General Public License as published by 10 | the Free Software Foundation; either version 3 of the License, or 11 | (at your option) any later version. 12 | 13 | This program is distributed in the hope that it will be useful, 14 | but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | GNU General Public License for more details. 17 | 18 | You should have received a copy of the GNU General Public License 19 | along with this program; if not, write to the Free Software 20 | Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 21 | -} 22 | 23 | {- | 24 | Module : Parsing.Types 25 | Description : Types for parsing Haskell code. 26 | Copyright : (c) Ivan Lazar Miljenovic 2009 27 | License : GPL-3 or later. 28 | Maintainer : Ivan.Miljenovic@gmail.com 29 | 30 | Types for parsing Haskell modules. 31 | -} 32 | module Parsing.Types where 33 | 34 | import Data.Graph.Analysis.Types( ClusterLabel(..) 35 | , Rel) 36 | import Data.Graph.Analysis.Reporting(unDotPath) 37 | import Data.GraphViz(GraphID(..), ToGraphID(..), LNodeCluster, NodeCluster(..)) 38 | import Data.Graph.Inductive.Graph(LNode) 39 | 40 | import Data.Char(isLetter, isDigit) 41 | import Data.List(intercalate) 42 | import Data.Maybe(fromMaybe, isJust) 43 | import qualified Data.Map as M 44 | import Data.Map(Map) 45 | import qualified Data.Set as S 46 | import Data.Set(Set) 47 | import qualified Data.MultiSet as MS 48 | import Data.MultiSet(MultiSet) 49 | import qualified Data.Foldable as F 50 | 51 | -- ----------------------------------------------------------------------------- 52 | 53 | data ParsedModule = PM { moduleName :: ModName 54 | , imports :: ImpLookup 55 | , exports :: Set Entity 56 | , dataDecls :: DataDecs 57 | , classDecls :: ClassDecs 58 | -- These aren't real defined functions 59 | , instDecls :: Set Entity 60 | , topEnts :: Set Entity 61 | , virtualEnts :: Set Entity -- used for 62 | -- drawing 63 | -- this module 64 | , funcCalls :: MultiSet FunctionCall -- We want each 65 | -- function 66 | -- call made, 67 | -- including duplicates. 68 | } 69 | deriving (Eq, Ord, Show, Read) 70 | 71 | blankPM :: ParsedModule 72 | blankPM = PM { moduleName = UnknownMod 73 | , imports = M.empty 74 | , exports = S.empty 75 | , dataDecls = M.empty 76 | , classDecls = M.empty 77 | , instDecls = S.empty 78 | , topEnts = S.empty 79 | , virtualEnts = S.empty 80 | , funcCalls = MS.empty 81 | } 82 | 83 | -- | Creates an 'EntityLookup' for the purposes of determining which 84 | -- 'Entity's are exported from this module. 85 | exportLookup :: ParsedModule -> EntityLookup 86 | exportLookup = mkLookup' . exports 87 | 88 | -- ----------------------------------------------------------------------------- 89 | 90 | type EntityLookup = Map QEntityName Entity 91 | 92 | mkEl :: [Entity] -> EntityLookup 93 | mkEl = M.fromList . map (\e -> ((Nothing, name e), e)) 94 | 95 | -- | The 'EntityLookup' for use within a module; combines imports with 96 | -- what is defined in the module. 97 | internalLookup :: ParsedModule -> EntityLookup 98 | internalLookup pm = M.unions [imported, internal, virtuals] 99 | where 100 | imported = allImports pm 101 | internal = exportableLookup pm 102 | virtuals = mkLookup' $ virtualEnts pm 103 | 104 | -- | The defined stand-alone 'Entity's from this module. 105 | exportableLookup :: ParsedModule -> EntityLookup 106 | exportableLookup pm = M.unions [ decLookup 107 | , clLookup 108 | , defLookup 109 | ] 110 | where 111 | decLookup = getLookups dataDecls pm 112 | clLookup = getLookups classDecls pm 113 | defLookup = mkLookup' $ topEnts pm 114 | 115 | -- | Create an 'EntityLookup' from a particular part of a 'ParsedModule'. 116 | getLookups :: (ParsedModule -> Map String EntityLookup) 117 | -> ParsedModule -> EntityLookup 118 | getLookups f = M.unions . M.elems . f 119 | 120 | -- | Create an 'EntityLookup' using the given qualification for the 121 | -- 'Set' of 'Entity's. 122 | mkLookup :: EntQual -> Set Entity -> EntityLookup 123 | mkLookup al = mergeMaps . S.map (\e -> M.singleton (al, name e) e) 124 | 125 | mkLookup' :: Set Entity -> EntityLookup 126 | mkLookup' = mkLookup Nothing 127 | 128 | -- | Find the corresponding 'Entity' for the given name and qualification. 129 | lookupEntity :: EntityLookup -> QEntityName -> Entity 130 | lookupEntity el qn = fromMaybe unkn $ M.lookup qn el 131 | where 132 | unkn = Ent UnknownMod (snd qn) NormalEntity 133 | 134 | -- | Find the corresponding 'Entity' for the given name with no qualification. 135 | lookupEntity' :: EntityLookup -> EntityName -> Entity 136 | lookupEntity' el = lookupEntity el . (,) Nothing 137 | 138 | -- ----------------------------------------------------------------------------- 139 | 140 | 141 | -- | A lookup-map of 'HaskellModule's. 142 | type ParsedModules = Map ModName ParsedModule 143 | 144 | type ModuleNames = Map String ModName 145 | 146 | createModuleMap :: [ParsedModule] -> ParsedModules 147 | createModuleMap = M.fromList 148 | . map (\m -> (moduleName m, m)) 149 | 150 | {- 151 | removeMod :: ParsedModules -> ModName -> ParsedModules 152 | removeMod = flip M.delete 153 | -} 154 | modulesIn :: ParsedModules -> Set ModName 155 | modulesIn = S.fromList . M.keys 156 | 157 | moduleNames :: ParsedModules -> ModuleNames 158 | moduleNames = M.fromList . map (\m -> (nameOfModule m, m)) 159 | . M.keys 160 | 161 | getModName :: ModuleNames -> String -> ModName 162 | getModName mns nm = fromMaybe ext $ M.lookup nm mns 163 | where 164 | ext = ExtMod nm 165 | 166 | moduleRelationships :: Set ParsedModule -> Set (ModName, ModName) 167 | moduleRelationships = setUnion . S.map mkEdges 168 | where 169 | mkEdges pm = S.fromList 170 | . map ((,) (moduleName pm) . fromModule) 171 | . M.elems 172 | $ imports pm 173 | {- 174 | hModulesIn :: ParsedModules -> Set ParsedModule 175 | hModulesIn = S.fromList . M.elems 176 | -} 177 | 178 | {- 179 | getModule :: ParsedModules -> ModName -> Maybe ParsedModule 180 | getModule hm m = M.lookup m hm 181 | -} 182 | 183 | -- ----------------------------------------------------------------------------- 184 | 185 | -- | The name of a module. 186 | data ModName = LocalMod { modName :: String } 187 | | ExtMod { modName :: String } 188 | | UnknownMod 189 | deriving (Eq, Ord, Show, Read) 190 | 191 | internalEntity :: Entity -> Bool 192 | internalEntity e = case inModule e of 193 | LocalMod{} -> True 194 | _ -> False 195 | 196 | type Depth = Int 197 | 198 | clusteredModule :: LNode ModName -> NodeCluster (Depth, String) (LNode String) 199 | clusteredModule (n,m) = go 0 $ modulePathOf m 200 | where 201 | go _ [m'] = N (n,m') 202 | go d (p:ps) = C (d,p) $ go (succ d) ps 203 | go _ [] = error "Shouldn't be able to have an empty module name." 204 | 205 | instance ToGraphID ModName where 206 | toGraphID = toGraphID . unDotPath . nameOfModule 207 | 208 | instance ClusterLabel ModName where 209 | type Cluster ModName = String 210 | type NodeLabel ModName = String 211 | 212 | cluster = containingDir' 213 | nodeLabel = nameOfModule' 214 | 215 | nameOfModule :: ModName -> String 216 | nameOfModule UnknownMod = "Unknown Module" 217 | nameOfModule mn = modName mn 218 | 219 | nameOfModule' :: ModName -> String 220 | nameOfModule' = last . modulePathOf 221 | 222 | containingDir :: ModName -> String 223 | containingDir = intercalate [moduleSep] . dirPath 224 | 225 | containingDir' :: ModName -> String 226 | containingDir' m = case containingDir m of 227 | "" -> "Project Root" 228 | dir -> dir 229 | 230 | dirPath :: ModName -> [String] 231 | dirPath = init . modulePathOf 232 | 233 | modulePathOf :: ModName -> [String] 234 | modulePathOf = splitSects . nameOfModule 235 | where 236 | splitSects mp = case break ((==) moduleSep) mp of 237 | (p,"") -> [p] 238 | (p,dmp) -> p : splitSects (tail dmp) 239 | 240 | 241 | -- | The seperator between components of a module. 242 | moduleSep :: Char 243 | moduleSep = '.' 244 | 245 | -- | Create the 'ModName' from its 'String' representation. 246 | createModule :: String -> ModName 247 | createModule = LocalMod 248 | 249 | -- ----------------------------------------------------------------------------- 250 | 251 | type ImpLookup = Map ModName ModImport 252 | 253 | -- | The import list of a module. 254 | data ModImport = I { fromModule :: ModName 255 | , importQuald :: Bool 256 | -- | Any alias used to import it. Should be Just 257 | -- foo if importQuald is True. 258 | , importedAs :: Maybe String 259 | -- | The functions from this module that were imported. 260 | , importedEnts :: Set Entity 261 | } 262 | deriving (Eq, Ord, Show, Read) 263 | 264 | importsLookup :: [ModImport] -> EntityLookup 265 | importsLookup = M.unions . map importLookup 266 | 267 | allImports :: ParsedModule -> EntityLookup 268 | allImports = importsLookup . M.elems . imports 269 | 270 | importLookup :: ModImport -> EntityLookup 271 | importLookup hi 272 | | importQuald hi = with 273 | | isJust alias = M.union with without -- alias, no qual 274 | | otherwise = without 275 | where 276 | es = importedEnts hi 277 | alias = importedAs hi 278 | with = mkLookup alias es 279 | without = mkLookup Nothing es 280 | 281 | -- ----------------------------------------------------------------------------- 282 | 283 | data Entity = Ent { inModule :: ModName 284 | , name :: EntityName 285 | , eType :: EntityType 286 | } 287 | deriving (Eq, Ord, Show, Read) 288 | 289 | instance ClusterLabel Entity where 290 | type Cluster Entity = ModName 291 | type NodeLabel Entity = Entity 292 | 293 | cluster = inModule 294 | nodeLabel = id 295 | 296 | clusterEntityM :: LNode Entity -> LNodeCluster String Entity 297 | clusterEntityM ln = modPathClust id ln (N ln) 298 | 299 | modPathClust :: (String -> a) -> LNode Entity 300 | -> LNodeCluster a Entity -> LNodeCluster a Entity 301 | modPathClust f ln b = foldr ($) b $ map (C . f) p 302 | where 303 | p = modulePathOf . inModule $ snd ln 304 | 305 | clusterEntityM' :: LNode Entity -> LNodeCluster EntClustType Entity 306 | clusterEntityM' ln = modPathClust ModPath ln (clusterEntity ln) 307 | 308 | clusterEntity :: LNode Entity -> LNodeCluster EntClustType Entity 309 | clusterEntity ln@(_,e) = setClust $ N ln 310 | where 311 | setClust = case eType e of 312 | (Constructor d) -> C $ DataDefn d 313 | (RecordFunction d) -> C $ DataDefn d 314 | (ClassMethod c) -> C $ ClassDefn c 315 | (DefaultInstance c) -> C (ClassDefn c) . C (DefInst c) 316 | (ClassInstance c d) -> C (ClassDefn c) . C (ClassInst c d) 317 | _ -> id 318 | 319 | data EntClustType = ClassDefn ClassName 320 | | DataDefn DataType 321 | | ClassInst ClassName DataType 322 | | DefInst ClassName 323 | | ModPath String 324 | deriving (Eq, Ord, Show, Read) 325 | 326 | ctypeID :: EntClustType -> GraphID 327 | ctypeID (ClassDefn c) = toGraphID $ "Class_" ++ escID c 328 | ctypeID (DataDefn d) = toGraphID $ "Data_" ++ escID d 329 | ctypeID (ClassInst c d) = toGraphID $ "Class_" ++ escID c ++ "_Data_" ++ escID d 330 | ctypeID (DefInst c) = toGraphID $ "DefaultInstance_" ++ escID c 331 | ctypeID (ModPath p) = toGraphID $ "Directory_" ++ escID p 332 | 333 | escID :: String -> String 334 | escID = filter (\c -> isLetter c || isDigit c || c == '_') 335 | 336 | type EntityName = String 337 | 338 | type EntQual = Maybe String 339 | 340 | type QEntityName = (EntQual, EntityName) 341 | 342 | -- | All 'Entity's defined in this 'ParsedModule'. 343 | definedEnts :: ParsedModule -> Set Entity 344 | definedEnts pm = exportableEnts pm `S.union` instDecls pm 345 | 346 | exportableEnts :: ParsedModule -> Set Entity 347 | exportableEnts pm = S.unions [ decEnts 348 | , clEnts 349 | , defEnts 350 | ] 351 | where 352 | decEnts = getEnts dataDecls pm 353 | clEnts = getEnts classDecls pm 354 | defEnts = topEnts pm 355 | 356 | -- | All 'Entity's used internally within this 'ParsedModule'. 357 | internalEnts :: ParsedModule -> Set Entity 358 | internalEnts pm = S.union (definedEnts pm) (virtualEnts pm) 359 | 360 | getEnts :: (ParsedModule -> Map String EntityLookup) 361 | -> ParsedModule -> Set Entity 362 | getEnts f = mkSet 363 | . map M.elems 364 | . M.elems 365 | . f 366 | 367 | 368 | fullName :: Entity -> EntityName 369 | fullName e = nameOfModule (inModule e) ++ moduleSep : name e 370 | 371 | defEntity :: EntityName -> Entity 372 | defEntity nm = Ent { inModule = UnknownMod 373 | , name = nm 374 | , eType = NormalEntity 375 | } 376 | 377 | setEntModule :: ModName -> Entity -> Entity 378 | setEntModule m e = e { inModule = m } 379 | 380 | setEntModules :: ModName -> Set Entity -> Set Entity 381 | setEntModules = S.map . setEntModule 382 | 383 | -- ----------------------------------------------------------------------------- 384 | 385 | -- Extra type defns. 386 | 387 | type DataType = String 388 | 389 | type ClassName = String 390 | 391 | type DataDecs = Map DataType EntityLookup 392 | 393 | type ClassDecs = Map ClassName EntityLookup 394 | 395 | data FunctionCall = FC { fromEntity :: Entity 396 | , toEntity :: Entity 397 | , callType :: CallType 398 | } 399 | deriving (Eq, Ord, Show, Read) 400 | 401 | callToRel :: FunctionCall -> Rel Entity CallType 402 | callToRel (FC from to tp) = (from, to, tp) 403 | 404 | data CallType = NormalCall 405 | | InstanceDeclaration -- ClassName DataType EntityName 406 | | DefaultInstDeclaration -- ClassName EntityName 407 | | RecordConstructor 408 | deriving (Eq, Ord, Show, Read) 409 | 410 | isNormalCall :: CallType -> Bool 411 | isNormalCall NormalCall = True 412 | isNormalCall _ = False 413 | 414 | data EntityType = Constructor DataType 415 | | RecordFunction DataType -- (Maybe EntityName) 416 | -- same record function in 417 | -- multiple constructors 418 | | ClassMethod ClassName 419 | | DefaultInstance ClassName 420 | | ClassInstance ClassName DataType 421 | -- The following three are only for when collapsing. 422 | | CollapsedData DataType 423 | | CollapsedClass ClassName 424 | | CollapsedInstance ClassName DataType 425 | | NormalEntity -- A function or variable 426 | deriving (Eq, Ord, Show, Read) 427 | 428 | isData :: EntityType -> Bool 429 | isData Constructor{} = True 430 | isData RecordFunction{} = True 431 | isData _ = False 432 | 433 | getDataType :: EntityType -> DataType 434 | getDataType (Constructor d) = d 435 | getDataType (RecordFunction d) = d 436 | getDataType _ = error "Should not see this" 437 | 438 | isClass :: EntityType -> Bool 439 | isClass ClassMethod{} = True 440 | isClass DefaultInstance{} = True 441 | isClass _ = False 442 | 443 | getClassName :: EntityType -> ClassName 444 | getClassName (ClassMethod c) = c 445 | getClassName (DefaultInstance c) = c 446 | getClassName _ = error "Should not see this" 447 | 448 | isInstance :: EntityType -> Bool 449 | isInstance ClassInstance{} = True 450 | isInstance _ = False 451 | 452 | getInstance :: EntityType -> (ClassName, DataType) 453 | getInstance (ClassInstance c d) = (c,d) 454 | getInstance _ = error "Should not see this" 455 | 456 | -- ----------------------------------------------------------------------------- 457 | 458 | setUnion :: (Ord a) => Set (Set a) -> Set a 459 | setUnion = F.foldl' S.union S.empty 460 | 461 | mkSet :: (Ord a) => [[a]] -> Set a 462 | mkSet = S.fromList . concat -- or should this be S.unions . map 463 | -- S.fromList ? 464 | 465 | mergeMaps :: (Ord k) => Set (Map k a) -> Map k a 466 | mergeMaps = F.foldl' M.union M.empty 467 | 468 | -------------------------------------------------------------------------------- /Setup.lhs: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env runhaskell 2 | > import Distribution.Simple 3 | > main = defaultMain 4 | -------------------------------------------------------------------------------- /SourceGraph.cabal: -------------------------------------------------------------------------------- 1 | Name: SourceGraph 2 | Version: 0.7.0.7 3 | Synopsis: Static code analysis using graph-theoretic techniques. 4 | Description: { 5 | Statically analyse Haskell source code using graph-theoretic 6 | techniques. Sample reports can be found at: 7 | 8 | . 9 | To use SourceGraph, call it as either: 10 | . 11 | > SourceGraph path/to/Foo.cabal 12 | . 13 | Or, if your project doesn't use Cabal, then there is limited support 14 | for using an overall module from your program\/library: 15 | . 16 | > SourceGraph path/to/Foo.hs 17 | . 18 | Note that the Cabal method is preferred, as it is better able to 19 | determine the project name and exported modules (when passing a 20 | Haskell file to SourceGraph, it uses that module's name as the overall 21 | name of project and assumes that it is the only exported module; as 22 | such, it works better for programs than libraries). 23 | . 24 | Whichever way you run SourceGraph, it then creates a @SourceGraph@ 25 | subdirectory in the same directory as the file that was passed to it, 26 | and within that subdirectory creates the analysis report in 27 | @Foo.html@. 28 | . 29 | SourceGraph is still experimental in terms of its ability to parse and 30 | properly understand Haskell source code and in the types of analyses 31 | it performs. 32 | } 33 | 34 | Category: Development 35 | License: GPL 36 | License-file: COPYRIGHT 37 | Copyright: (c) Ivan Lazar Miljenovic 38 | Author: Ivan Lazar Miljenovic 39 | Maintainer: Ivan.Miljenovic@gmail.com 40 | Cabal-Version: >= 1.6 41 | Build-Type: Simple 42 | Extra-Source-Files: TODO 43 | ChangeLog 44 | 45 | Tested-With: GHC == 7.4.2, GHC == 7.6.3, GHC == 7.8.4, 46 | GHC == 7.10.2, GHC == 7.11.* 47 | 48 | Source-Repository head 49 | Type: git 50 | Location: https://github.com/ivan-m/SourceGraph 51 | 52 | 53 | Executable SourceGraph { 54 | 55 | Main-Is: Main.hs 56 | Other-Modules: CabalInfo, 57 | Parsing, 58 | Parsing.ParseModule, 59 | Parsing.State, 60 | Parsing.Types, 61 | Analyse, 62 | Analyse.Utils, 63 | Analyse.Colors, 64 | Analyse.GraphRepr, 65 | Analyse.Visualise, 66 | Analyse.Module, 67 | Analyse.Imports, 68 | Analyse.Everything, 69 | Paths_SourceGraph 70 | Ghc-Options: -Wall 71 | Ghc-Prof-Options: -prof 72 | 73 | Build-Depends: base == 4.*, 74 | containers, 75 | multiset, 76 | filepath, 77 | random, 78 | directory, 79 | mtl, 80 | fgl == 5.5.*, 81 | Graphalyze >= 0.14.1.0 && < 0.15, 82 | graphviz >= 2999.15.0.0 && < 2999.19, 83 | Cabal == 1.22.*, 84 | haskell-src-exts == 1.16.* 85 | } 86 | -------------------------------------------------------------------------------- /TODO: -------------------------------------------------------------------------------- 1 | IDs for class, etc. subgraphs should include the modules for cases 2 | like bytestring where two datatypes have the same name 3 | 4 | TODO for SourceGraph 5 | ==================== 6 | 7 | This is the list of planned improvements to the SourceGraph program. 8 | Please note that some of these improvements will actually take place 9 | in the [Graphalyze](http://hackage.haskell.org/package/Graphalyze) 10 | library. 11 | 12 | Parsing Improvements 13 | -------------------- 14 | 15 | SourceGraph uses 16 | [haskell-src-exts](http://hackage.haskell.org/package/haskell-src-exts) 17 | to parse Haskell code. As such, it is limited in terms of what it can 18 | parse first of all by what haskell-src-exts supports. 19 | 20 | * The following types of items are not yet recognised; either add 21 | support for them (e.g. using cpphs for CPP) or else log a message if 22 | there is no sane way of integrating them into the call graph: 23 | 24 | - Invalid code (these files will not even be readable by 25 | haskell-src-exts and as such a warning should be displayed). 26 | 27 | - Modules using the C Pre-Processor; adding support for this will 28 | depend on better Cabal file support and command line options. 29 | 30 | - [Haskell Regular 31 | Patterns](http://hackage.haskell.org/package/harp), [Haskell 32 | Source with XML](http://hackage.haskell.org/package/hsx) and the 33 | embedded XML syntax of [Haskell Server 34 | Pages](http://hackage.haskell.org/package/hsp) all utilise 35 | haskell-src-exts to extend Haskell syntax; as such, the parsing 36 | support is available but it is unknown how to convert them to 37 | entities in the call graph. 38 | 39 | - It is unknown how to add [Data 40 | Family](http://www.haskell.org/haskellwiki/GHC/Type_families) 41 | instances (both normal and GADT style) into the call graph. 42 | 43 | - It is probably not possible to integrate [Foreign Function 44 | Interface](http://www.haskell.org/haskellwiki/FFI) imports and 45 | exports into the call graph. 46 | 47 | - [Template 48 | Haskell](http://www.haskell.org/haskellwiki/Template_Haskell) is 49 | also not currently supported. 50 | 51 | * The following items have partial/incomplete/possibly wrong support 52 | for integration into the call graph: 53 | 54 | - Currently pragmas, LANGUAGE options, etc. are only supported if 55 | they are included in the top level of the module (as such, 56 | haskell-src-exts will use them for parsing purposes). 57 | 58 | - Entities explicitly imported from an external module are not 59 | always correctly categorised; to improve support for this, any 60 | class methods or datatype constructors/record functions should 61 | be explicitly imported [rather than using the `Foo(..)`] syntax; 62 | furthermore, a datatype import is only recognised as such if at 63 | least one constructor is imported (otherwise it is assumed to be 64 | a class). 65 | 66 | - When using record puns, it is not always possible to distinguish 67 | between the records and punned values. 68 | 69 | - When using record wildcards, not all records are completely 70 | listed/used as both record functions and variables (see the 71 | problem with record puns above). 72 | 73 | - Multi-param type classes may not be considered/formatted 74 | correctly. 75 | 76 | - Entities that are imported into a module and then re-exported 77 | (including re-exporting the entire imported module) may not be 78 | considered correctly. 79 | 80 | 81 | Analysis Improvements 82 | --------------------- 83 | 84 | * When considering levels, produce a plot of level size vs depth. 85 | 86 | - Similar plots may be useful for other analyses, such as the number 87 | of cycles of a given size. 88 | 89 | - Possibly also provide a characterisation of the "shape" of the plot. 90 | 91 | * Provide comparisons from other large-scale Haskell projects for 92 | analyses such as shape of the level graph, cyclomatic complexity. 93 | 94 | - To achieve this, possibly run a cut-down version of SourceGraph 95 | over all packages in 96 | [HackageDB](http://hackage.haskell.org/package/) to accumulate the 97 | comparison information. 98 | 99 | * Include more ways of analysing software from its Call Graph. 100 | 101 | Reporting Format 102 | ---------------- 103 | 104 | * Use CSS, etc. to improve the generated HTML files. 105 | 106 | * Produce multi-page HTML documents. 107 | 108 | * Improve formatting of entity listing (listing of cliques, etc.). 109 | 110 | * Report errors/warnings (from parsing, etc.). 111 | 112 | * Improve graph visualisation: 113 | 114 | - Having a lot of edges makes it difficult to "read" the 115 | visualisation (maybe when clustering have the edges go from 116 | cluster to cluster?). 117 | 118 | - Ensure node labels do not extend past the boundary of the node 119 | (note: for cluster labels, this seems to be a bug with Graphviz's 120 | SVG output). 121 | 122 | Project Integration 123 | ------------------- 124 | 125 | * Allow clearer differentiation between Cabal-based and source-based 126 | projects. 127 | 128 | - When basing it off files, allow the user to specify several files. 129 | 130 | * For Cabal: 131 | 132 | - When using Cabal, provide some way to choose which section is 133 | being analysed (i.e. library or an executable). 134 | + Probably also some way of reporting to the user which options are 135 | available. 136 | 137 | - Pass GHC, CPP, etc. flags through for when parsing the files. 138 | 139 | - Use the correct source directory and match modules to files. 140 | 141 | Program Usage 142 | ------------- 143 | 144 | * Provide command-line options to allow users to set the following: 145 | 146 | - Output directory. 147 | 148 | - Report format. 149 | 150 | - What output to generate, e.g.: 151 | + Brief analysis summary. 152 | + Only produce a call-graph (overall, imports and per-module). 153 | 154 | - What to analyse, that is one of the following: 155 | + Only one module (not when using Cabal mode). 156 | + Only files used in that project. 157 | + All files found (whether they are used in the project or not). 158 | 159 | * The ability to specify project flags (Cabal flags, CPP flags, etc.). 160 | 161 | * Write a README and supporting documentation. 162 | 163 | Future Plans 164 | ------------ 165 | 166 | * Write a proper website for SourceGraph. 167 | 168 | * Provide some way of making the analyses "interactive" (e.g. zooming, 169 | slicing, etc.). 170 | 171 | - Noam Lewis' proposed interactive graph editor may be a start 172 | towards providing this kind of functionality. 173 | 174 | * Integrate SourceGraph into 175 | [HackageDB](http://hackage.haskell.org/package/). 176 | --------------------------------------------------------------------------------