packages feed

SourceGraph (empty) → 0.1

raw patch · 12 files changed

+2277/−0 lines, 12 filesdep +Cabaldep +Graphalyzedep +basesetup-changed

Dependencies added: Cabal, Graphalyze, base, containers, directory, fgl, filepath, graphviz, haskell-src-exts, random

Files

+ Analyse.hs view
@@ -0,0 +1,50 @@+{-+Copyright (C) 2008 Ivan Lazar Miljenovic <Ivan.Miljenovic@gmail.com>++This file is part of SourceGraph.++SourceGraph is free software; you can redistribute it and/or modify+it under the terms of the GNU General Public License as published by+the Free Software Foundation; either version 3 of the License, or+(at your option) any later version.++This program is distributed in the hope that it will be useful,+but WITHOUT ANY WARRANTY; without even the implied warranty of+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the+GNU General Public License for more details.++You should have received a copy of the GNU General Public License+along with this program; if not, write to the Free Software+Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA+-}++{- |+   Module      : Analyse+   Description : Analyse Haskell software+   Copyright   : (c) Ivan Lazar Miljenovic 2008+   License     : GPL-3 or later.+   Maintainer  : Ivan.Miljenovic@gmail.com++   Analyse Haskell software+ -}+module Analyse where++import Analyse.Utils+import Analyse.Module+import Analyse.Imports+import Analyse.Everything+import Parsing.Types++import Data.Graph.Analysis++import System.Random++-- | Analyse an entire Haskell project.  Takes in a random seed,+--   the list of exported modules and the parsed Haskell code in+--   'HaskellModules' form.+analyse            :: (RandomGen g) => g -> [ModuleName] -> HaskellModules+                   -> [DocElement]+analyse g exps hms = [ analyseModules hms+                     , analyseImports g exps hms+                     , analyseEverything g exps hms+                     ]
+ Analyse/Everything.hs view
@@ -0,0 +1,213 @@+{-+Copyright (C) 2008 Ivan Lazar Miljenovic <Ivan.Miljenovic@gmail.com>++This file is part of SourceGraph.++SourceGraph is free software; you can redistribute it and/or modify+it under the terms of the GNU General Public License as published by+the Free Software Foundation; either version 3 of the License, or+(at your option) any later version.++This program is distributed in the hope that it will be useful,+but WITHOUT ANY WARRANTY; without even the implied warranty of+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the+GNU General Public License for more details.++You should have received a copy of the GNU General Public License+along with this program; if not, write to the Free Software+Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA+-}++{- |+   Module      : Analyse.Software+   Description : Analyse Haskell software+   Copyright   : (c) Ivan Lazar Miljenovic 2008+   License     : GPL-3 or later.+   Maintainer  : Ivan.Miljenovic@gmail.com++   Analysis of the entire overall piece of software.+ -}+module Analyse.Everything where++import Parsing.Types+import Analyse.Utils++import Data.Graph.Analysis++import Data.Maybe+import Text.Printf+import System.Random++type CodeData = GraphData Function+++-- | Performs analysis of the entire codebase.+analyseEverything :: (RandomGen g) => g -> [ModuleName] -> HaskellModules+                  -> DocElement+analyseEverything g exps hm = Section title elems+    where+      cd = codeToGraph exps hm+      title = Text "Analysis of the entire codebase"+      elems = catMaybes+              $ map ($cd) [ graphOf+                          , clustersOf g+                          , collapseAnal+                          , coreAnal+                          , cycleCompAnal+                          , rootAnal+                          , componentAnal+                          , cliqueAnal+                          , cycleAnal+                          , chainAnal+                          ]+++codeToGraph          :: [ModuleName] -> HaskellModules -> CodeData+codeToGraph exps hms = importData params+    where+      exps' = concat . catMaybes $ map (fmap exports . getModule hms) exps+      fl = combineCalls .map functions $ hModulesIn hms+      params = Params { dataPoints    = functionsIn fl+                      , relationships = functionEdges fl+                      , roots         = exps'+                      , directed      = True+                      }++graphOf    :: CodeData -> Maybe DocElement+graphOf cd = Just $ Section title [gc]+    where+      title = Text "Visualisation of the entire software"+      gc = GraphImage $ applyAlg dg cd+      dg g = toGraph "code" label g+      label = "Software visualisation"++clustersOf      :: (RandomGen g) => g -> CodeData -> Maybe DocElement+clustersOf g cd = Just $ Section title [text, gc, textAfter, cw, rng]+    where+      title = Text "Visualisation of overall function calls"+      gc = GraphImage $ applyAlg dg cd+      text = Paragraph+             [Text "Here is the current module grouping of functions:"]+      dg gr = toClusters "codeCluster" label gr+      label = "Module groupings"+      textAfter = Paragraph [Text "Here are two proposed module groupings:"]+      cw = GraphImage+           . toClusters "codeCW" "Chinese Whispers module suggestions"+           $ applyAlg (chineseWhispers g) cd+      rng = GraphImage+            . toClusters "codeRNG" "Relative Neighbourhood module suggestions"+            $ applyAlg relativeNeighbourhood cd++componentAnal :: CodeData -> Maybe DocElement+componentAnal cd+    | single comp = Nothing+    | otherwise   = Just elem+    where+      comp = applyAlg componentsOf cd+      len = length comp+      elem = Section title [Paragraph [Text text]]+      title = Text "Function component analysis"+      text = printf "The functions are split up into %d components.  \+                     \You may wish to consider splitting the code up \+                     \into multiple libraries." len++cliqueAnal :: CodeData -> Maybe DocElement+cliqueAnal cd+    | null clqs = Nothing+    | otherwise = Just elem+    where+      clqs = applyAlg cliquesIn cd+      clqs' = map (Paragraph . return . Text . showNodes) clqs+      text = Text "The code has the following cliques:"+      elem = Section title $ (Paragraph [text]) : clqs'+      title = Text "Overall clique analysis"++cycleAnal :: CodeData -> Maybe DocElement+cycleAnal cd+    | null cycs = Nothing+    | otherwise = Just elem+    where+      cycs = applyAlg uniqueCycles cd+      cycs' = map (Paragraph . return . Text . showCycle) cycs+      text = Text "The code has the following non-clique cycles:"+      elem = Section title $ (Paragraph [text]) : cycs'+      title = Text "Overall cycle analysis"++chainAnal :: CodeData -> Maybe DocElement+chainAnal cd+    | null chns = Nothing+    | otherwise = Just elem+    where+      chns = applyAlg chainsIn cd+      chns' = map (Paragraph .return . Text . showPath) chns+      text = Text "The functions have the following chains:"+      textAfter = Text "These chains can all be compressed down to \+                       \a single function."+      elem = Section title $+             [Paragraph [text]] ++ chns' ++ [Paragraph [textAfter]]+      title = Text "Overall chain analysis"++rootAnal :: CodeData -> Maybe DocElement+rootAnal cd+    | asExpected = Nothing+    | otherwise  = Just elem+    where+      (wntd, ntRs, ntWd) = classifyRoots cd+      asExpected = (null ntRs) && (null ntWd)+      rpt (s,ns) = if (null ns)+                   then Nothing+                   else Just [ Paragraph+                               [Text+                                $ concat ["These functions are those that are "+                                         , s, ":"]]+                             , Paragraph [Text $ showNodes ns]]+      ps = concat . catMaybes+           $ map rpt [ ("available for use and roots",wntd)+                     , ("available for use but not roots",ntWd)+                     , ("not available for use but roots",ntRs)]+      elem = Section title ps+      title = Text "Import root analysis"+++cycleCompAnal    :: CodeData -> Maybe DocElement+cycleCompAnal cd = Just $ Section title [par]+    where+      cc = cyclomaticComplexity cd+      title = Text "Overall Cyclomatic Complexity"+      par = Paragraph [text, textAfter, link]+      text = Text+             $ printf "The overall cyclomatic complexity is: %d" cc+      textAfter = Text "For more information on cyclomatic complexity, \+                       \please see:"+      link = DocLink (Text "Wikipedia: Cyclomatic Complexity")+                     (URL "http://en.wikipedia.org/wiki/Cyclomatic_complexity")+++coreAnal    :: CodeData -> Maybe DocElement+coreAnal cd = Just elem+    where+      core = applyAlg coreOf cd+      p = "codeCore"+      label = "Overall core"+      hdr = Paragraph [Text "The core of software can be thought of as \+                             \the part where all the work is actually done."]+      empMsg = Paragraph [Text "The code is a tree."]+      anal = if (isEmpty core)+             then empMsg+             else GraphImage (toGraph p label core)+      elem = Section title [hdr, anal]+      title = Text "Overall Core analysis"+++collapseAnal    :: CodeData -> Maybe DocElement+collapseAnal cd = Just elem+    where+      gc = applyAlg collapseGraph cd+      p = "codeCollapsed"+      label = "Collapsed view of the entire codebase"+      hdr = Paragraph [Text "The collapsed view of code collapses \+                            \down all cliques, cycles, chains, etc. to \+                            \make the graph tree-like." ]+      gr = GraphImage (toGraph p label gc)+      elem = Section title [hdr, gr]+      title = Text "Collapsed view of the entire codebase"
+ Analyse/Imports.hs view
@@ -0,0 +1,166 @@+{-+Copyright (C) 2008 Ivan Lazar Miljenovic <Ivan.Miljenovic@gmail.com>++This file is part of SourceGraph.++SourceGraph is free software; you can redistribute it and/or modify+it under the terms of the GNU General Public License as published by+the Free Software Foundation; either version 3 of the License, or+(at your option) any later version.++This program is distributed in the hope that it will be useful,+but WITHOUT ANY WARRANTY; without even the implied warranty of+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the+GNU General Public License for more details.++You should have received a copy of the GNU General Public License+along with this program; if not, write to the Free Software+Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA+-}++{- |+   Module      : Analyse.Imports+   Description : Analyse module imports.+   Copyright   : (c) Ivan Lazar Miljenovic 2008+   License     : GPL-3 or later.+   Maintainer  : Ivan.Miljenovic@gmail.com++   Analysis of Haskell module importing.+ -}+module Analyse.Imports (analyseImports) where++import Parsing.Types+import Analyse.Utils++import Data.Graph.Analysis++import Data.Maybe+import Text.Printf+import System.Random++type ImportData = GraphData ModuleName++-- | Analyse the imports present in the software.  Takes in a random seed+--   as well as a list of all modules exported.+analyseImports :: (RandomGen g) => g -> [ModuleName] -> HaskellModules+               -> DocElement+analyseImports g exps hm = Section title elems+    where+      id = importsToGraph exps hm+      title = Text "Analysis of module imports"+      elems = catMaybes+              $ map ($id) [ graphOf+                          , clustersOf g+                          , cycleCompAnal+                          , rootAnal+                          , componentAnal+                          , cycleAnal+                          , chainAnal+                          ]++importsToGraph          :: [ModuleName] -> HaskellModules -> ImportData+importsToGraph exps hms = importData params+    where+      params = Params { dataPoints    = modulesIn hms+                      , relationships = moduleImports hms+                      , roots         = exps+                      , directed      = True+                      }++graphOf    :: ImportData -> Maybe DocElement+graphOf id = Just $ Section title [gi]+    where+      title = Text "Visualisation of imports"+      gi = GraphImage $ applyAlg dg id+      dg g = toGraph "imports" label g+      label = "Import visualisation"++clustersOf      :: (RandomGen g) => g -> ImportData -> Maybe DocElement+clustersOf g id = Just $ Section title [text, gi, textAfter, cw, rng]+    where+      title = Text "Visualisation of module groupings"+      gi = GraphImage $ applyAlg dg id+      text = Paragraph [Text "Here is the current module groupings:"]+      dg gr = toClusters "importCluster" label gr+      label = "Module groupings"+      textAfter = Paragraph [Text "Here are two proposed module groupings:"]+      cw = GraphImage+           . toClusters "importCW" "Chinese Whispers module groupings"+           $ applyAlg (chineseWhispers g) id+      rng = GraphImage+            . toClusters "importRNG" "Relative Neighbourhood module groupings"+            $ applyAlg relativeNeighbourhood id++componentAnal :: ImportData -> Maybe DocElement+componentAnal id+    | single comp = Nothing+    | otherwise   = Just elem+    where+      comp = applyAlg componentsOf id+      len = length comp+      elem = Section title [Paragraph [Text text]]+      title = Text "Import component analysis"+      text = printf "The imports have %d components.  \+                     \You may wish to consider splitting the code up." len++cycleAnal :: ImportData -> Maybe DocElement+cycleAnal id+    | null cycs = Nothing+    | otherwise = Just elem+    where+      cycs = applyAlg cyclesIn id+      cycs' = map (Paragraph .return . Text . showCycle) cycs+      text = Text "The imports have the following cycles:"+      textAfter = Text "Whilst this is valid, it may make it difficult \+                       \to use in ghci, etc."+      elem = Section title+             $ (Paragraph [text]) : cycs' ++ [Paragraph [textAfter]]+      title = Text "Cycle analysis of imports"++chainAnal :: ImportData -> Maybe DocElement+chainAnal id+    | null chns = Nothing+    | otherwise = Just elem+    where+      chns = applyAlg chainsIn id+      chns' = map (Paragraph .return . Text . showPath) chns+      text = Text "The imports have the following chains:"+      textAfter = Text "These chains can all be compressed down to \+                       \a single module."+      elem = Section title $+             [Paragraph [text]] ++ chns' ++ [Paragraph [textAfter]]+      title = Text "Import chain analysis"++rootAnal :: ImportData -> Maybe DocElement+rootAnal id+    | asExpected = Nothing+    | otherwise  = Just elem+    where+      (wntd, ntRs, ntWd) = classifyRoots id+      asExpected = (null ntRs) && (null ntWd)+      rpt (s,ns) = if (null ns)+                   then Nothing+                   else Just [ Paragraph+                               [Text+                                $ concat ["These modules are those that are "+                                         , s, ":"]]+                             , Paragraph [Text $ showNodes ns]]+      ps = concat . catMaybes+           $ map rpt [ ("in the export list and roots",wntd)+                     , ("in the export list but not roots",ntWd)+                     , ("not in the export list but roots",ntRs)]+      elem = Section title ps+      title = Text "Import root analysis"++cycleCompAnal    :: ImportData -> Maybe DocElement+cycleCompAnal id = Just $ Section title [par]+    where+      cc = cyclomaticComplexity id+      title = Text "Cyclomatic Complexity of imports"+      par = Paragraph [text, textAfter, link]+      text = Text+             $ printf "The cyclomatic complexity of the imports is: %d" cc+      textAfter = Text "For more information on cyclomatic complexity, \+                       \please see:"+      link = DocLink (Text "Wikipedia: Cyclomatic Complexity")+                     (URL "http://en.wikipedia.org/wiki/Cyclomatic_complexity")
+ Analyse/Module.hs view
@@ -0,0 +1,216 @@+{-+Copyright (C) 2008 Ivan Lazar Miljenovic <Ivan.Miljenovic@gmail.com>++This file is part of SourceGraph.++SourceGraph is free software; you can redistribute it and/or modify+it under the terms of the GNU General Public License as published by+the Free Software Foundation; either version 3 of the License, or+(at your option) any later version.++This program is distributed in the hope that it will be useful,+but WITHOUT ANY WARRANTY; without even the implied warranty of+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the+GNU General Public License for more details.++You should have received a copy of the GNU General Public License+along with this program; if not, write to the Free Software+Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA+-}++{- |+   Module      : Analyse.Module+   Description : Analyse modules.+   Copyright   : (c) Ivan Lazar Miljenovic 2008+   License     : GPL-3 or later.+   Maintainer  : Ivan.Miljenovic@gmail.com++   Analysis of Haskell modules.+ -}+module Analyse.Module(analyseModules) where++import Parsing.Types+import Analyse.Utils++import Data.Graph.Analysis++import Data.Maybe+import Text.Printf++-- -----------------------------------------------------------------------------++-- Helper types++-- | Shorthand type+type FunctionData = (String, GraphData AString)++-- -----------------------------------------------------------------------------++-- Analysing.++-- | Performs analysis of all modules present in the 'HaskellModules' provided.+analyseModules :: HaskellModules -> DocElement+analyseModules = Section (Text "Analysis of each module")+                 . map analyseModule . hModulesIn++-- | Performs analysis of the given 'HaskellModule'.+analyseModule    :: HaskellModule -> DocElement+analyseModule hm = Section title elems+    where+      m = show $ moduleName hm+      fd = moduleToGraph hm+      elems = catMaybes+              $ map ($fd) [ graphOf+                          , collapseAnal+                          , coreAnal+                          , cycleCompAnal+                          , rootAnal+                          , componentAnal+                          , cliqueAnal+                          , cycleAnal+                          , chainAnal+                          ]+      title = Grouping [ Text "Analysis of"+                       , Emphasis (Text m)]++-- | Convert the module to the /Graphalyze/ format.+moduleToGraph    :: HaskellModule -> FunctionData+moduleToGraph hm = (show $ moduleName hm, fd')+    where+      fd' = manipulateNodes (AS . name) fd+      fd = importData params+      funcs = functions hm+      params = Params { dataPoints    = functionsIn funcs+                      , relationships = functionEdges funcs+                      , roots         = exports hm+                      , directed      = True+                      }++graphOf        :: FunctionData -> Maybe DocElement+graphOf (m,fd) = Just $ Section title [gi]+    where+      title = Grouping [ Text "Visualisation of"+                       , Emphasis (Text m)]+      gi = GraphImage $ applyAlg dg fd+      dg g = toGraph m label g+      label = unwords ["Diagram of:", m]++componentAnal :: FunctionData -> Maybe DocElement+componentAnal (m,fd)+    | single comp = Nothing+    | otherwise   = Just elem+    where+      comp = applyAlg componentsOf fd+      len = length comp+      elem = Section title [Paragraph [Text text]]+      title = Grouping [ Text "Component analysis of"+                       , Emphasis (Text m)]+      text = printf "The module %s has %d components.  \+                     \You may wish to consider splitting it up." m len++cliqueAnal :: FunctionData -> Maybe DocElement+cliqueAnal (m,fd)+    | null clqs = Nothing+    | otherwise = Just elem+    where+      clqs = applyAlg cliquesIn fd+      clqs' = map (Paragraph . return . Text . showNodes) clqs+      text = Text $ printf "The module %s has the following cliques:" m+      elem = Section title $ (Paragraph [text]) : clqs'+      title = Grouping [ Text "Clique analysis of"+                       , Emphasis (Text m)]++cycleAnal :: FunctionData -> Maybe DocElement+cycleAnal (m,fd)+    | null cycs = Nothing+    | otherwise = Just elem+    where+      cycs = applyAlg uniqueCycles fd+      cycs' = map (Paragraph . return . Text . showCycle) cycs+      text = Text $ printf "The module %s has the following non-clique \+                            \cycles:" m+      elem = Section title $ (Paragraph [text]) : cycs'+      title = Grouping [ Text "Cycle analysis of"+                       , Emphasis (Text m)]++chainAnal :: FunctionData -> Maybe DocElement+chainAnal (m,fd)+    | null chns = Nothing+    | otherwise = Just elem+    where+      chns = applyAlg chainsIn fd+      chns' = map (Paragraph . return . Text . showPath) chns+      text = Text $ printf "The module %s has the following chains:" m+      textAfter = Text "These chains can all be compressed down to \+                       \a single function."+      elem = Section title+             $ [Paragraph [text]] ++ chns' ++ [Paragraph [textAfter]]+      title = Grouping [ Text "Chain analysis of"+                       , Emphasis (Text m)]++rootAnal :: FunctionData -> Maybe DocElement+rootAnal (m,fd)+    | asExpected = Nothing+    | otherwise  = Just elem+    where+      (wntd, ntRs, ntWd) = classifyRoots fd+      asExpected = (null ntRs) && (null ntWd)+      rpt (s,ns) = if (null ns)+                   then Nothing+                   else Just [ Paragraph+                               [Text+                                $ concat ["These nodes are those that are "+                                         , s, ":"]]+                             , Paragraph [Text $ showNodes ns]]+      ps = concat . catMaybes+           $ map rpt [ ("in the export list and roots",wntd)+                     , ("in the export list but not roots",ntWd)+                     , ("not in the export list but roots",ntRs)]+      elem = Section title ps+      title = Grouping [ Text "Root analysis of"+                       , Emphasis (Text m)]++coreAnal        :: FunctionData -> Maybe DocElement+coreAnal (m,fd) = Just elem+    where+      core = applyAlg coreOf fd+      p = m ++ "_core"+      label = unwords ["Core of", m]+      hdr = Paragraph [Text "The core of a module can be thought of as \+                             \the part where all the work is actually done."]+      empMsg = Paragraph [Text $ printf "The module %s is a tree." m]+      anal = if (isEmpty core)+             then empMsg+             else GraphImage (toGraph p label core)+      elem = Section title [hdr, anal]+      title = Grouping [ Text "Core analysis of"+                       , Emphasis (Text m)]++collapseAnal :: FunctionData -> Maybe DocElement+collapseAnal (m,fd) = Just elem+    where+      gc = applyAlg collapseGraph fd+      p = m ++ "_collapsed"+      label = unwords ["Collapsed view of", m]+      hdr = Paragraph [Text "The collapsed view of a module collapses \+                            \down all cliques, cycles, chains, etc. to \+                            \make the graph tree-like." ]+      gr = GraphImage (toGraph p label gc)+      elem = Section title [hdr, gr]+      title = Grouping [ Text "Collapsed view of"+                       , Emphasis (Text m)]+++cycleCompAnal        :: FunctionData -> Maybe DocElement+cycleCompAnal (m,fd) = Just $ Section title pars+    where+      cc = cyclomaticComplexity fd+      title = Grouping [ Text "Cyclomatic Complexity of"+                       , Emphasis (Text m)]+      pars = [Paragraph [text], Paragraph [textAfter, link]]+      text = Text+             $ printf "The cyclomatic complexity of %s is: %d." m cc+      textAfter = Text "For more information on cyclomatic complexity, \+                       \please see: "+      link = DocLink (Text "Wikipedia: Cyclomatic Complexity")+                     (URL "http://en.wikipedia.org/wiki/Cyclomatic_complexity")
+ Analyse/Utils.hs view
@@ -0,0 +1,63 @@+{-+Copyright (C) 2008 Ivan Lazar Miljenovic <Ivan.Miljenovic@gmail.com>++This file is part of SourceGraph.++SourceGraph is free software; you can redistribute it and/or modify+it under the terms of the GNU General Public License as published by+the Free Software Foundation; either version 3 of the License, or+(at your option) any later version.++This program is distributed in the hope that it will be useful,+but WITHOUT ANY WARRANTY; without even the implied warranty of+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the+GNU General Public License for more details.++You should have received a copy of the GNU General Public License+along with this program; if not, write to the Free Software+Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA+-}++{- |+   Module      : Analyse.Utils+   Description : Utility functions and types for analysis.+   Copyright   : (c) Ivan Lazar Miljenovic 2008+   License     : GPL-3 or later.+   Maintainer  : Ivan.Miljenovic@gmail.com++   Utility functions and types for analysis.+ -}+module Analyse.Utils where++import Data.Graph.Analysis+import Data.GraphViz+import Data.Graph.Inductive hiding (graphviz)+++-- | Defining a wrapper around String to define a sensible 'show' definition.+newtype AString = AS String+    deriving (Eq, Ord)++instance Show AString where+    show (AS f) = f++-- | Create a graph in the 'DocGraph' format.+--   Takes in the filepath, title and the graph to be drawn.+toGraph       :: (Show a) => FilePath -> String -> AGr a -> DocGraph+toGraph p t g = (p,Text t,dg)+    where+      dg = graphviz t g++toClusters       :: (Show c, ClusterLabel a c) => FilePath -> String+                 -> AGr a -> DocGraph+toClusters p t g = (p, Text t, dg)+    where+      dg = graphvizClusters t g++-- | Cyclomatic complexity+cyclomaticComplexity    :: GraphData a -> Int+cyclomaticComplexity gd = e - n + 2*p+    where+      p = length $ applyAlg componentsOf gd+      n = applyAlg noNodes gd+      e = length $ applyAlg labEdges gd
@@ -0,0 +1,674 @@+                    GNU GENERAL PUBLIC LICENSE+                       Version 3, 29 June 2007++ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>+ Everyone is permitted to copy and distribute verbatim copies+ of this license document, but changing it is not allowed.++                            Preamble++  The GNU General Public License is a free, copyleft license for+software and other kinds of works.++  The licenses for most software and other practical works are designed+to take away your freedom to share and change the works.  By contrast,+the GNU General Public License is intended to guarantee your freedom to+share and change all versions of a program--to make sure it remains free+software for all its users.  We, the Free Software Foundation, use the+GNU General Public License for most of our software; it applies also to+any other work released this way by its authors.  You can apply it to+your programs, too.++  When we speak of free software, we are referring to freedom, not+price.  Our General Public Licenses are designed to make sure that you+have the freedom to distribute copies of free software (and charge for+them if you wish), that you receive source code or can get it if you+want it, that you can change the software or use pieces of it in new+free programs, and that you know you can do these things.++  To protect your rights, we need to prevent others from denying you+these rights or asking you to surrender the rights.  Therefore, you have+certain responsibilities if you distribute copies of the software, or if+you modify it: responsibilities to respect the freedom of others.++  For example, if you distribute copies of such a program, whether+gratis or for a fee, you must pass on to the recipients the same+freedoms that you received.  You must make sure that they, too, receive+or can get the source code.  And you must show them these terms so they+know their rights.++  Developers that use the GNU GPL protect your rights with two steps:+(1) assert copyright on the software, and (2) offer you this License+giving you legal permission to copy, distribute and/or modify it.++  For the developers' and authors' protection, the GPL clearly explains+that there is no warranty for this free software.  For both users' and+authors' sake, the GPL requires that modified versions be marked as+changed, so that their problems will not be attributed erroneously to+authors of previous versions.++  Some devices are designed to deny users access to install or run+modified versions of the software inside them, although the manufacturer+can do so.  This is fundamentally incompatible with the aim of+protecting users' freedom to change the software.  The systematic+pattern of such abuse occurs in the area of products for individuals to+use, which is precisely where it is most unacceptable.  Therefore, we+have designed this version of the GPL to prohibit the practice for those+products.  If such problems arise substantially in other domains, we+stand ready to extend this provision to those domains in future versions+of the GPL, as needed to protect the freedom of users.++  Finally, every program is threatened constantly by software patents.+States should not allow patents to restrict development and use of+software on general-purpose computers, but in those that do, we wish to+avoid the special danger that patents applied to a free program could+make it effectively proprietary.  To prevent this, the GPL assures that+patents cannot be used to render the program non-free.++  The precise terms and conditions for copying, distribution and+modification follow.++                       TERMS AND CONDITIONS++  0. Definitions.++  "This License" refers to version 3 of the GNU General Public License.++  "Copyright" also means copyright-like laws that apply to other kinds of+works, such as semiconductor masks.++  "The Program" refers to any copyrightable work licensed under this+License.  Each licensee is addressed as "you".  "Licensees" and+"recipients" may be individuals or organizations.++  To "modify" a work means to copy from or adapt all or part of the work+in a fashion requiring copyright permission, other than the making of an+exact copy.  The resulting work is called a "modified version" of the+earlier work or a work "based on" the earlier work.++  A "covered work" means either the unmodified Program or a work based+on the Program.++  To "propagate" a work means to do anything with it that, without+permission, would make you directly or secondarily liable for+infringement under applicable copyright law, except executing it on a+computer or modifying a private copy.  Propagation includes copying,+distribution (with or without modification), making available to the+public, and in some countries other activities as well.++  To "convey" a work means any kind of propagation that enables other+parties to make or receive copies.  Mere interaction with a user through+a computer network, with no transfer of a copy, is not conveying.++  An interactive user interface displays "Appropriate Legal Notices"+to the extent that it includes a convenient and prominently visible+feature that (1) displays an appropriate copyright notice, and (2)+tells the user that there is no warranty for the work (except to the+extent that warranties are provided), that licensees may convey the+work under this License, and how to view a copy of this License.  If+the interface presents a list of user commands or options, such as a+menu, a prominent item in the list meets this criterion.++  1. Source Code.++  The "source code" for a work means the preferred form of the work+for making modifications to it.  "Object code" means any non-source+form of a work.++  A "Standard Interface" means an interface that either is an official+standard defined by a recognized standards body, or, in the case of+interfaces specified for a particular programming language, one that+is widely used among developers working in that language.++  The "System Libraries" of an executable work include anything, other+than the work as a whole, that (a) is included in the normal form of+packaging a Major Component, but which is not part of that Major+Component, and (b) serves only to enable use of the work with that+Major Component, or to implement a Standard Interface for which an+implementation is available to the public in source code form.  A+"Major Component", in this context, means a major essential component+(kernel, window system, and so on) of the specific operating system+(if any) on which the executable work runs, or a compiler used to+produce the work, or an object code interpreter used to run it.++  The "Corresponding Source" for a work in object code form means all+the source code needed to generate, install, and (for an executable+work) run the object code and to modify the work, including scripts to+control those activities.  However, it does not include the work's+System Libraries, or general-purpose tools or generally available free+programs which are used unmodified in performing those activities but+which are not part of the work.  For example, Corresponding Source+includes interface definition files associated with source files for+the work, and the source code for shared libraries and dynamically+linked subprograms that the work is specifically designed to require,+such as by intimate data communication or control flow between those+subprograms and other parts of the work.++  The Corresponding Source need not include anything that users+can regenerate automatically from other parts of the Corresponding+Source.++  The Corresponding Source for a work in source code form is that+same work.++  2. Basic Permissions.++  All rights granted under this License are granted for the term of+copyright on the Program, and are irrevocable provided the stated+conditions are met.  This License explicitly affirms your unlimited+permission to run the unmodified Program.  The output from running a+covered work is covered by this License only if the output, given its+content, constitutes a covered work.  This License acknowledges your+rights of fair use or other equivalent, as provided by copyright law.++  You may make, run and propagate covered works that you do not+convey, without conditions so long as your license otherwise remains+in force.  You may convey covered works to others for the sole purpose+of having them make modifications exclusively for you, or provide you+with facilities for running those works, provided that you comply with+the terms of this License in conveying all material for which you do+not control copyright.  Those thus making or running the covered works+for you must do so exclusively on your behalf, under your direction+and control, on terms that prohibit them from making any copies of+your copyrighted material outside their relationship with you.++  Conveying under any other circumstances is permitted solely under+the conditions stated below.  Sublicensing is not allowed; section 10+makes it unnecessary.++  3. Protecting Users' Legal Rights From Anti-Circumvention Law.++  No covered work shall be deemed part of an effective technological+measure under any applicable law fulfilling obligations under article+11 of the WIPO copyright treaty adopted on 20 December 1996, or+similar laws prohibiting or restricting circumvention of such+measures.++  When you convey a covered work, you waive any legal power to forbid+circumvention of technological measures to the extent such circumvention+is effected by exercising rights under this License with respect to+the covered work, and you disclaim any intention to limit operation or+modification of the work as a means of enforcing, against the work's+users, your or third parties' legal rights to forbid circumvention of+technological measures.++  4. Conveying Verbatim Copies.++  You may convey verbatim copies of the Program's source code as you+receive it, in any medium, provided that you conspicuously and+appropriately publish on each copy an appropriate copyright notice;+keep intact all notices stating that this License and any+non-permissive terms added in accord with section 7 apply to the code;+keep intact all notices of the absence of any warranty; and give all+recipients a copy of this License along with the Program.++  You may charge any price or no price for each copy that you convey,+and you may offer support or warranty protection for a fee.++  5. Conveying Modified Source Versions.++  You may convey a work based on the Program, or the modifications to+produce it from the Program, in the form of source code under the+terms of section 4, provided that you also meet all of these conditions:++    a) The work must carry prominent notices stating that you modified+    it, and giving a relevant date.++    b) The work must carry prominent notices stating that it is+    released under this License and any conditions added under section+    7.  This requirement modifies the requirement in section 4 to+    "keep intact all notices".++    c) You must license the entire work, as a whole, under this+    License to anyone who comes into possession of a copy.  This+    License will therefore apply, along with any applicable section 7+    additional terms, to the whole of the work, and all its parts,+    regardless of how they are packaged.  This License gives no+    permission to license the work in any other way, but it does not+    invalidate such permission if you have separately received it.++    d) If the work has interactive user interfaces, each must display+    Appropriate Legal Notices; however, if the Program has interactive+    interfaces that do not display Appropriate Legal Notices, your+    work need not make them do so.++  A compilation of a covered work with other separate and independent+works, which are not by their nature extensions of the covered work,+and which are not combined with it such as to form a larger program,+in or on a volume of a storage or distribution medium, is called an+"aggregate" if the compilation and its resulting copyright are not+used to limit the access or legal rights of the compilation's users+beyond what the individual works permit.  Inclusion of a covered work+in an aggregate does not cause this License to apply to the other+parts of the aggregate.++  6. Conveying Non-Source Forms.++  You may convey a covered work in object code form under the terms+of sections 4 and 5, provided that you also convey the+machine-readable Corresponding Source under the terms of this License,+in one of these ways:++    a) Convey the object code in, or embodied in, a physical product+    (including a physical distribution medium), accompanied by the+    Corresponding Source fixed on a durable physical medium+    customarily used for software interchange.++    b) Convey the object code in, or embodied in, a physical product+    (including a physical distribution medium), accompanied by a+    written offer, valid for at least three years and valid for as+    long as you offer spare parts or customer support for that product+    model, to give anyone who possesses the object code either (1) a+    copy of the Corresponding Source for all the software in the+    product that is covered by this License, on a durable physical+    medium customarily used for software interchange, for a price no+    more than your reasonable cost of physically performing this+    conveying of source, or (2) access to copy the+    Corresponding Source from a network server at no charge.++    c) Convey individual copies of the object code with a copy of the+    written offer to provide the Corresponding Source.  This+    alternative is allowed only occasionally and noncommercially, and+    only if you received the object code with such an offer, in accord+    with subsection 6b.++    d) Convey the object code by offering access from a designated+    place (gratis or for a charge), and offer equivalent access to the+    Corresponding Source in the same way through the same place at no+    further charge.  You need not require recipients to copy the+    Corresponding Source along with the object code.  If the place to+    copy the object code is a network server, the Corresponding Source+    may be on a different server (operated by you or a third party)+    that supports equivalent copying facilities, provided you maintain+    clear directions next to the object code saying where to find the+    Corresponding Source.  Regardless of what server hosts the+    Corresponding Source, you remain obligated to ensure that it is+    available for as long as needed to satisfy these requirements.++    e) Convey the object code using peer-to-peer transmission, provided+    you inform other peers where the object code and Corresponding+    Source of the work are being offered to the general public at no+    charge under subsection 6d.++  A separable portion of the object code, whose source code is excluded+from the Corresponding Source as a System Library, need not be+included in conveying the object code work.++  A "User Product" is either (1) a "consumer product", which means any+tangible personal property which is normally used for personal, family,+or household purposes, or (2) anything designed or sold for incorporation+into a dwelling.  In determining whether a product is a consumer product,+doubtful cases shall be resolved in favor of coverage.  For a particular+product received by a particular user, "normally used" refers to a+typical or common use of that class of product, regardless of the status+of the particular user or of the way in which the particular user+actually uses, or expects or is expected to use, the product.  A product+is a consumer product regardless of whether the product has substantial+commercial, industrial or non-consumer uses, unless such uses represent+the only significant mode of use of the product.++  "Installation Information" for a User Product means any methods,+procedures, authorization keys, or other information required to install+and execute modified versions of a covered work in that User Product from+a modified version of its Corresponding Source.  The information must+suffice to ensure that the continued functioning of the modified object+code is in no case prevented or interfered with solely because+modification has been made.++  If you convey an object code work under this section in, or with, or+specifically for use in, a User Product, and the conveying occurs as+part of a transaction in which the right of possession and use of the+User Product is transferred to the recipient in perpetuity or for a+fixed term (regardless of how the transaction is characterized), the+Corresponding Source conveyed under this section must be accompanied+by the Installation Information.  But this requirement does not apply+if neither you nor any third party retains the ability to install+modified object code on the User Product (for example, the work has+been installed in ROM).++  The requirement to provide Installation Information does not include a+requirement to continue to provide support service, warranty, or updates+for a work that has been modified or installed by the recipient, or for+the User Product in which it has been modified or installed.  Access to a+network may be denied when the modification itself materially and+adversely affects the operation of the network or violates the rules and+protocols for communication across the network.++  Corresponding Source conveyed, and Installation Information provided,+in accord with this section must be in a format that is publicly+documented (and with an implementation available to the public in+source code form), and must require no special password or key for+unpacking, reading or copying.++  7. Additional Terms.++  "Additional permissions" are terms that supplement the terms of this+License by making exceptions from one or more of its conditions.+Additional permissions that are applicable to the entire Program shall+be treated as though they were included in this License, to the extent+that they are valid under applicable law.  If additional permissions+apply only to part of the Program, that part may be used separately+under those permissions, but the entire Program remains governed by+this License without regard to the additional permissions.++  When you convey a copy of a covered work, you may at your option+remove any additional permissions from that copy, or from any part of+it.  (Additional permissions may be written to require their own+removal in certain cases when you modify the work.)  You may place+additional permissions on material, added by you to a covered work,+for which you have or can give appropriate copyright permission.++  Notwithstanding any other provision of this License, for material you+add to a covered work, you may (if authorized by the copyright holders of+that material) supplement the terms of this License with terms:++    a) Disclaiming warranty or limiting liability differently from the+    terms of sections 15 and 16 of this License; or++    b) Requiring preservation of specified reasonable legal notices or+    author attributions in that material or in the Appropriate Legal+    Notices displayed by works containing it; or++    c) Prohibiting misrepresentation of the origin of that material, or+    requiring that modified versions of such material be marked in+    reasonable ways as different from the original version; or++    d) Limiting the use for publicity purposes of names of licensors or+    authors of the material; or++    e) Declining to grant rights under trademark law for use of some+    trade names, trademarks, or service marks; or++    f) Requiring indemnification of licensors and authors of that+    material by anyone who conveys the material (or modified versions of+    it) with contractual assumptions of liability to the recipient, for+    any liability that these contractual assumptions directly impose on+    those licensors and authors.++  All other non-permissive additional terms are considered "further+restrictions" within the meaning of section 10.  If the Program as you+received it, or any part of it, contains a notice stating that it is+governed by this License along with a term that is a further+restriction, you may remove that term.  If a license document contains+a further restriction but permits relicensing or conveying under this+License, you may add to a covered work material governed by the terms+of that license document, provided that the further restriction does+not survive such relicensing or conveying.++  If you add terms to a covered work in accord with this section, you+must place, in the relevant source files, a statement of the+additional terms that apply to those files, or a notice indicating+where to find the applicable terms.++  Additional terms, permissive or non-permissive, may be stated in the+form of a separately written license, or stated as exceptions;+the above requirements apply either way.++  8. Termination.++  You may not propagate or modify a covered work except as expressly+provided under this License.  Any attempt otherwise to propagate or+modify it is void, and will automatically terminate your rights under+this License (including any patent licenses granted under the third+paragraph of section 11).++  However, if you cease all violation of this License, then your+license from a particular copyright holder is reinstated (a)+provisionally, unless and until the copyright holder explicitly and+finally terminates your license, and (b) permanently, if the copyright+holder fails to notify you of the violation by some reasonable means+prior to 60 days after the cessation.++  Moreover, your license from a particular copyright holder is+reinstated permanently if the copyright holder notifies you of the+violation by some reasonable means, this is the first time you have+received notice of violation of this License (for any work) from that+copyright holder, and you cure the violation prior to 30 days after+your receipt of the notice.++  Termination of your rights under this section does not terminate the+licenses of parties who have received copies or rights from you under+this License.  If your rights have been terminated and not permanently+reinstated, you do not qualify to receive new licenses for the same+material under section 10.++  9. Acceptance Not Required for Having Copies.++  You are not required to accept this License in order to receive or+run a copy of the Program.  Ancillary propagation of a covered work+occurring solely as a consequence of using peer-to-peer transmission+to receive a copy likewise does not require acceptance.  However,+nothing other than this License grants you permission to propagate or+modify any covered work.  These actions infringe copyright if you do+not accept this License.  Therefore, by modifying or propagating a+covered work, you indicate your acceptance of this License to do so.++  10. Automatic Licensing of Downstream Recipients.++  Each time you convey a covered work, the recipient automatically+receives a license from the original licensors, to run, modify and+propagate that work, subject to this License.  You are not responsible+for enforcing compliance by third parties with this License.++  An "entity transaction" is a transaction transferring control of an+organization, or substantially all assets of one, or subdividing an+organization, or merging organizations.  If propagation of a covered+work results from an entity transaction, each party to that+transaction who receives a copy of the work also receives whatever+licenses to the work the party's predecessor in interest had or could+give under the previous paragraph, plus a right to possession of the+Corresponding Source of the work from the predecessor in interest, if+the predecessor has it or can get it with reasonable efforts.++  You may not impose any further restrictions on the exercise of the+rights granted or affirmed under this License.  For example, you may+not impose a license fee, royalty, or other charge for exercise of+rights granted under this License, and you may not initiate litigation+(including a cross-claim or counterclaim in a lawsuit) alleging that+any patent claim is infringed by making, using, selling, offering for+sale, or importing the Program or any portion of it.++  11. Patents.++  A "contributor" is a copyright holder who authorizes use under this+License of the Program or a work on which the Program is based.  The+work thus licensed is called the contributor's "contributor version".++  A contributor's "essential patent claims" are all patent claims+owned or controlled by the contributor, whether already acquired or+hereafter acquired, that would be infringed by some manner, permitted+by this License, of making, using, or selling its contributor version,+but do not include claims that would be infringed only as a+consequence of further modification of the contributor version.  For+purposes of this definition, "control" includes the right to grant+patent sublicenses in a manner consistent with the requirements of+this License.++  Each contributor grants you a non-exclusive, worldwide, royalty-free+patent license under the contributor's essential patent claims, to+make, use, sell, offer for sale, import and otherwise run, modify and+propagate the contents of its contributor version.++  In the following three paragraphs, a "patent license" is any express+agreement or commitment, however denominated, not to enforce a patent+(such as an express permission to practice a patent or covenant not to+sue for patent infringement).  To "grant" such a patent license to a+party means to make such an agreement or commitment not to enforce a+patent against the party.++  If you convey a covered work, knowingly relying on a patent license,+and the Corresponding Source of the work is not available for anyone+to copy, free of charge and under the terms of this License, through a+publicly available network server or other readily accessible means,+then you must either (1) cause the Corresponding Source to be so+available, or (2) arrange to deprive yourself of the benefit of the+patent license for this particular work, or (3) arrange, in a manner+consistent with the requirements of this License, to extend the patent+license to downstream recipients.  "Knowingly relying" means you have+actual knowledge that, but for the patent license, your conveying the+covered work in a country, or your recipient's use of the covered work+in a country, would infringe one or more identifiable patents in that+country that you have reason to believe are valid.++  If, pursuant to or in connection with a single transaction or+arrangement, you convey, or propagate by procuring conveyance of, a+covered work, and grant a patent license to some of the parties+receiving the covered work authorizing them to use, propagate, modify+or convey a specific copy of the covered work, then the patent license+you grant is automatically extended to all recipients of the covered+work and works based on it.++  A patent license is "discriminatory" if it does not include within+the scope of its coverage, prohibits the exercise of, or is+conditioned on the non-exercise of one or more of the rights that are+specifically granted under this License.  You may not convey a covered+work if you are a party to an arrangement with a third party that is+in the business of distributing software, under which you make payment+to the third party based on the extent of your activity of conveying+the work, and under which the third party grants, to any of the+parties who would receive the covered work from you, a discriminatory+patent license (a) in connection with copies of the covered work+conveyed by you (or copies made from those copies), or (b) primarily+for and in connection with specific products or compilations that+contain the covered work, unless you entered into that arrangement,+or that patent license was granted, prior to 28 March 2007.++  Nothing in this License shall be construed as excluding or limiting+any implied license or other defenses to infringement that may+otherwise be available to you under applicable patent law.++  12. No Surrender of Others' Freedom.++  If conditions are imposed on you (whether by court order, agreement or+otherwise) that contradict the conditions of this License, they do not+excuse you from the conditions of this License.  If you cannot convey a+covered work so as to satisfy simultaneously your obligations under this+License and any other pertinent obligations, then as a consequence you may+not convey it at all.  For example, if you agree to terms that obligate you+to collect a royalty for further conveying from those to whom you convey+the Program, the only way you could satisfy both those terms and this+License would be to refrain entirely from conveying the Program.++  13. Use with the GNU Affero General Public License.++  Notwithstanding any other provision of this License, you have+permission to link or combine any covered work with a work licensed+under version 3 of the GNU Affero General Public License into a single+combined work, and to convey the resulting work.  The terms of this+License will continue to apply to the part which is the covered work,+but the special requirements of the GNU Affero General Public License,+section 13, concerning interaction through a network will apply to the+combination as such.++  14. Revised Versions of this License.++  The Free Software Foundation may publish revised and/or new versions of+the GNU General Public License from time to time.  Such new versions will+be similar in spirit to the present version, but may differ in detail to+address new problems or concerns.++  Each version is given a distinguishing version number.  If the+Program specifies that a certain numbered version of the GNU General+Public License "or any later version" applies to it, you have the+option of following the terms and conditions either of that numbered+version or of any later version published by the Free Software+Foundation.  If the Program does not specify a version number of the+GNU General Public License, you may choose any version ever published+by the Free Software Foundation.++  If the Program specifies that a proxy can decide which future+versions of the GNU General Public License can be used, that proxy's+public statement of acceptance of a version permanently authorizes you+to choose that version for the Program.++  Later license versions may give you additional or different+permissions.  However, no additional obligations are imposed on any+author or copyright holder as a result of your choosing to follow a+later version.++  15. Disclaimer of Warranty.++  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY+APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR+PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM+IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.++  16. Limitation of Liability.++  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF+SUCH DAMAGES.++  17. Interpretation of Sections 15 and 16.++  If the disclaimer of warranty and limitation of liability provided+above cannot be given local legal effect according to their terms,+reviewing courts shall apply local law that most closely approximates+an absolute waiver of all civil liability in connection with the+Program, unless a warranty or assumption of liability accompanies a+copy of the Program in return for a fee.++                     END OF TERMS AND CONDITIONS++            How to Apply These Terms to Your New Programs++  If you develop a new program, and you want it to be of the greatest+possible use to the public, the best way to achieve this is to make it+free software which everyone can redistribute and change under these terms.++  To do so, attach the following notices to the program.  It is safest+to attach them to the start of each source file to most effectively+state the exclusion of warranty; and each file should have at least+the "copyright" line and a pointer to where the full notice is found.++    <one line to give the program's name and a brief idea of what it does.>+    Copyright (C) <year>  <name of author>++    This program is free software: you can redistribute it and/or modify+    it under the terms of the GNU General Public License as published by+    the Free Software Foundation, either version 3 of the License, or+    (at your option) any later version.++    This program is distributed in the hope that it will be useful,+    but WITHOUT ANY WARRANTY; without even the implied warranty of+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the+    GNU General Public License for more details.++    You should have received a copy of the GNU General Public License+    along with this program.  If not, see <http://www.gnu.org/licenses/>.++Also add information on how to contact you by electronic and paper mail.++  If the program does terminal interaction, make it output a short+notice like this when it starts in an interactive mode:++    <program>  Copyright (C) <year>  <name of author>+    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.+    This is free software, and you are welcome to redistribute it+    under certain conditions; type `show c' for details.++The hypothetical commands `show w' and `show c' should show the appropriate+parts of the General Public License.  Of course, your program's commands+might be different; for a GUI interface, you would use an "about box".++  You should also get your employer (if you work as a programmer) or school,+if any, to sign a "copyright disclaimer" for the program, if necessary.+For more information on this, and how to apply and follow the GNU GPL, see+<http://www.gnu.org/licenses/>.++  The GNU General Public License does not permit incorporating your program+into proprietary programs.  If your program is a subroutine library, you+may consider it more useful to permit linking proprietary applications with+the library.  If this is what you want to do, use the GNU Lesser General+Public License instead of this License.  But first, please read+<http://www.gnu.org/philosophy/why-not-lgpl.html>.
+ Main.hs view
@@ -0,0 +1,208 @@+{-+Copyright (C) 2008 Ivan Lazar Miljenovic <Ivan.Miljenovic@gmail.com>++This program is free software; you can redistribute it and/or modify+it under the terms of the GNU General Public License as published by+the Free Software Foundation; either version 3 of the License, or+(at your option) any later version.++This program is distributed in the hope that it will be useful,+but WITHOUT ANY WARRANTY; without even the implied warranty of+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the+GNU General Public License for more details.++You should have received a copy of the GNU General Public License+along with this program; if not, write to the Free Software+Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA+-}++{- |+   Module      : Main+   Description : Analyse source code as a graph.+   Copyright   : (c) Ivan Lazar Miljenovic 2008+   License     : GPL-3 or later.+   Maintainer  : Ivan.Miljenovic@gmail.com++   The executable file for the /SourceGraph/ programme.++   This was written as part of my mathematics honours thesis,+   /Graph-Theoretic Analysis of the Relationships in Discrete Data/.+ -}+module Main where++import Parsing+import Analyse++import Data.Graph.Analysis+import Data.Graph.Analysis.Reporting.Pandoc++import Distribution.Package+import Distribution.PackageDescription hiding (author)+import Distribution.Verbosity++import Data.List+import Data.Maybe+import System.IO+import System.Directory+import System.FilePath+import System.Random+import System.Environment+import Control.Monad+import Control.Exception++main :: IO ()+main = do input <- getArgs+          let mcbl = getCabalFile input+          case mcbl of+            Nothing+                -> putErrLn "Please pass in a .cabal file"+            Just cbl+                -> do pcbl <- parseCabal cbl+                      case pcbl of+                        Nothing+                            -> putErrLn $ unwords [cbl,"is unparseable"]+                        Just (nm,exps)+                            -> do let dir = dropFileName cbl+                                  dir' <- if null dir+                                            then getCurrentDirectory+                                            else return dir+                                  hms <- parseFilesFrom dir'+                                  analyseCode dir nm exps hms++programName :: String+programName = "SourceGraph"++programVersion :: String+programVersion = "0.1"++putErrLn :: String -> IO ()+putErrLn = hPutStrLn stderr++-- -----------------------------------------------------------------------------++parseCabal    :: FilePath -> IO (Maybe (String, [ModuleName]))+parseCabal fp = do gpd <- try $ readPackageDescription silent fp+                   case gpd of+                     (Right gpd') -> return (Just $ parse gpd')+                     (Left _)     -> return Nothing+    where+      parse pd = (nm, exp')+          where+            cbl = packageDescription pd+            nm = pkgName $ package cbl+            cexes :: [Executable]+            cexes = map (condTreeData .snd) $ condExecutables pd+            exes = executables cbl+            clib = condLibrary pd+            lib = library cbl+            exp | not $ null cexes = nub $ map (dropExtension . modulePath) cexes+                | not $ null exes  = nub . map dropExtension $ exeModules cbl+                | isJust clib      = exposedModules . condTreeData+                                     $ fromJust clib+                | isJust lib       = exposedModules $ fromJust lib+                | otherwise        = error "No exposed modules"+            exp' = map createModule exp++getCabalFile :: [FilePath] -> Maybe FilePath+getCabalFile = listToMaybe . filter isCabalFile+    where+      isCabalFile f  = (takeExtension f) == (extSeparator : "cabal")++-- -----------------------------------------------------------------------------++-- | Recursively parse all files from this directory+parseFilesFrom    :: FilePath -> IO HaskellModules+parseFilesFrom fp = do files <- getHaskellFilesFrom fp+                       cnts <- readFiles files+                       return $ parseHaskell cnts++-- -----------------------------------------------------------------------------++-- Reading in the files.++-- | Recursively find all Haskell source files from the current directory.+getHaskellFilesFrom :: FilePath -> IO [FilePath]+getHaskellFilesFrom fp+    = do isDir <- doesDirectoryExist fp -- Ensure it's a directory.+         if isDir+            then do r <- try getFilesIn -- Ensure we can read the directory.+                    case r of+                      (Right fs) -> return fs+                      (Left _)   -> return []+            else return []+    where+      -- Filter out "." and ".." to stop infinite recursion.+      nonTrivialContents :: IO [FilePath]+      nonTrivialContents = do contents <- getDirectoryContents fp+                              let contents' = filter (not . isTrivial) contents+                              return $ map (fp </>) contents'+      getFilesIn :: IO [FilePath]+      getFilesIn = do contents <- nonTrivialContents+                      (dirs,files) <- partitionM doesDirectoryExist contents+                      let hFiles = filter isHaskellFile files+                      recursiveFiles <- concatMapM getHaskellFilesFrom dirs+                      return (hFiles ++ recursiveFiles)++-- | Determine if this is the path of a Haskell file.+isHaskellFile   :: FilePath -> Bool+isHaskellFile f = (takeExtension f) `elem` haskellExtensions+    where+      haskellExtensions = map (extSeparator :) ["hs","lhs"]++-- | Read in all the files that it can.+readFiles :: [FilePath] -> IO [FileContents]+readFiles = liftM catMaybes . mapM readFileContents++-- | Try to read the given file.+readFileContents   :: FilePath -> IO (Maybe FileContents)+readFileContents f = do cnts <- try $ readFile f+                        case cnts of+                          (Right str) -> return $ Just (f,str)+                          (Left _)    -> return Nothing++-- | A version of 'concatMap' for use in monads.+concatMapM   :: (Monad m) => (a -> m [b]) -> [a] -> m [b]+concatMapM f = liftM concat . mapM f++-- | A version of 'partition' for use in monads.+partitionM      :: (Monad m) => (a -> m Bool) -> [a] -> m ([a], [a])+partitionM _ [] = return ([],[])+partitionM p (x:xs) = do ~(ts,fs) <- partitionM p xs+                         matches <- p x+                         if matches+                            then return (x:ts,fs)+                            else return (ts,x:fs)++-- | Trivial paths are the current directory and the parent directory.+isTrivial      :: FilePath -> Bool+isTrivial "."  = True+isTrivial ".." = True+isTrivial _    = False++-- -----------------------------------------------------------------------------++analyseCode                :: FilePath -> String -> [ModuleName]+                           -> HaskellModules -> IO ()+analyseCode fp nm exps hms = do d <- today+                                g <- newStdGen+                                let dc = doc d g+                                out <- createDocument pandocHtml dc+                                case out of+                                  Just fp -> success fp+                                  Nothing -> failure+    where+      doc d g = Doc { rootDirectory = rt+                    , fileFront     = nm+                    , title         = t+                    , author        = a+                    , date          = d+                    , content       = c g+                    }+      rt = fp </> programName+      sv s v = s ++ " (version " ++ v ++ ")"+      t = Grouping [Text "Analysis of", Emphasis $ Text nm]+      a = unwords [ "Analysed by", sv programName programVersion+                  , "using", sv "Graphalyze" version]+      c g = analyse g exps hms+      success fp = putStrLn $ unwords ["Report generated at:",fp]+      failure = putErrLn "Unable to generate report"
+ Parsing.hs view
@@ -0,0 +1,68 @@+{-+Copyright (C) 2008 Ivan Lazar Miljenovic <Ivan.Miljenovic@gmail.com>++This file is part of SourceGraph.++SourceGraph is free software; you can redistribute it and/or modify+it under the terms of the GNU General Public License as published by+the Free Software Foundation; either version 3 of the License, or+(at your option) any later version.++This program is distributed in the hope that it will be useful,+but WITHOUT ANY WARRANTY; without even the implied warranty of+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the+GNU General Public License for more details.++You should have received a copy of the GNU General Public License+along with this program; if not, write to the Free Software+Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA+-}++{- |+   Module      : Parsing+   Description : Parse the given Haskell modules.+   Copyright   : (c) Ivan Lazar Miljenovic 2008+   License     : GPL-3 or later.+   Maintainer  : Ivan.Miljenovic@gmail.com++   Parse the given Haskell modules.+ -}+module Parsing+    ( FileContents+    , HaskellModules+    , ModuleName+    , createModule+    , parseHaskell+    ) where++import Parsing.Types+import Parsing.ParseModule++import Language.Haskell.Exts.Parser hiding (parseModule)+import Language.Haskell.Exts.Syntax(HsModule)++import Data.Maybe++type FileContents = (FilePath,String)++-- | Parse all the files and return the map.+--   This uses laziness to evaluate the 'HaskellModules' result+--   whilst also using it to parse all the modules to create it.+parseHaskell    :: [FileContents] -> HaskellModules+parseHaskell fc = hms+    where+      ms = parseFiles fc+      hms = createModuleMap hss+      hss = map (parseModule hms) ms++-- | Attempt to parse an individual file.+parseFile       :: FileContents -> Maybe HsModule+parseFile (p,f) = case (parseModuleWithMode mode f) of+                    (ParseOk hs) -> Just hs+                    _            -> Nothing+    where+      mode = ParseMode p++-- | Parse all the files that you can.+parseFiles :: [FileContents] -> [HsModule]+parseFiles = catMaybes . map parseFile
+ Parsing/ParseModule.hs view
@@ -0,0 +1,389 @@+{-+Copyright (C) 2008 Ivan Lazar Miljenovic <Ivan.Miljenovic@gmail.com>++This file is part of SourceGraph.++SourceGraph is free software; you can redistribute it and/or modify+it under the terms of the GNU General Public License as published by+the Free Software Foundation; either version 3 of the License, or+(at your option) any later version.++This program is distributed in the hope that it will be useful,+but WITHOUT ANY WARRANTY; without even the implied warranty of+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the+GNU General Public License for more details.++You should have received a copy of the GNU General Public License+along with this program; if not, write to the Free Software+Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA+-}++{- |+   Module      : Parsing.ParseModule+   Description : Parse a Haskell module.+   Copyright   : (c) Ivan Lazar Miljenovic 2008+   License     : GPL-3 or later.+   Maintainer  : Ivan.Miljenovic@gmail.com++   Parse a Haskell module.+ -}+module Parsing.ParseModule (parseModule) where++import Parsing.Types++import Language.Haskell.Exts.Syntax++import Data.List+import Data.Maybe+import qualified Data.Map as M++-- -----------------------------------------------------------------------------++{- |+   Parses a Haskell Module in 'HsModule' format into the internal+   'HaskellModule' format.  The 'HaskellModules' parameter is used+   to look up the export lists of all imported functions.++   The resulting 'HaskellModule'\'s 'functions' field is a 'Map' that+   maps all functions defined in this module to those functions+   accessible to them from modules in the first parameter.++   At the moment, parsing works only on stand-alone functions, i.e. no+   data structures, class declarations or instance declarations.+ -}+parseModule :: HaskellModules -> HsModule -> HaskellModule+parseModule hm (HsModule _ md exps imp decls) = Hs { moduleName = m+                                                   , imports    = imps'+                                                   , exports    = exps'+                                                   , functions  = fs+                                                   }+    where+      m = createModule' md+      (imps,fl) = parseImports hm imp+      imps' = map fromModule imps+      -- If there isn't an export list, export everything.+      -- The exception is if there isn't an export list but there is a+      -- /main/ function, in which case only export that.+      exps' | isJust exps = parseExports m $ fromJust exps+            | hasMain     = [mainFunc]+            | otherwise   = defFuncs+      mainFunc = F m (nameOf main_name) Nothing+      hasMain = elem mainFunc defFuncs+      fs = M.fromList funcs+      -- We utilise "Tying-the-knot" here to simultaneously update the+      -- lookup map as well as utilise that lookup map.+      funcs = functionCalls m fl' decls+      defFuncs = map fst funcs+      flInternal = createLookup defFuncs+      fl' = M.union fl flInternal++-- | Create the 'ModuleName'.+createModule' :: Module -> ModuleName+createModule' = createModule . modName++-- | Parse all import declarations, and create the 'FunctionLookup' map+--   on the imports.+parseImports       :: HaskellModules -> [HsImportDecl]+                   -> ([HsImport],FunctionLookup)+parseImports hm is = (is', flookup)+    where+      is' = catMaybes $ map (parseImport hm) is+      flookup = createLookup $ concatMap importList is'++-- | Convert the import declaration.  Assumes that all functions imported+--   are indeed valid.+parseImport :: HaskellModules -> HsImportDecl -> Maybe HsImport+parseImport hm im+    | not (M.member m hm) = Nothing -- This module isn't available.+    | otherwise           = Just $ I m qual imps+    where+      mn = importModule im+      m = createModule' mn+      -- Determine if this module has been imported with an /as/ prefix.+      -- If not, it has the entire name as its prefix.+      qual = fmap modName (importAs im)+      qual' = fromMaybe (modName mn) qual+      -- Try and get the functions that this module exports.+      mExport = exports $ hm M.! m+      mImport = case (importSpecs im) of+                  -- Everything was imported+                  Nothing -> mExport+                  -- Only specific items were imported.+                  Just (True, ims) -> getFunctions m ims+                  -- These items were hidden.+                  Just (False, hd) -> mExport \\ (getFunctions m hd)+      qImport = map (addQual qual') mImport+      imps = if (importQualified im)+             then qImport+             else mImport ++ qImport+      getFunctions m = map (setModule m) . getItems+      setModule m f = F m f Nothing+      getItems = catMaybes . map getImport+      -- We only care about functions, variables, etc.+      getImport (HsIVar nm) = Just (nameOf nm)+      getImport _           = Nothing++++-- | Parsing the export list.+parseExports   :: ModuleName -> [HsExportSpec] -> [Function]+parseExports m = catMaybes . map (parseExport m)+    where+      -- We only care about exported functions.+      parseExport m (HsEVar qn) = fmap (setFuncModule m) $ hsName qn+      parseExport _ _           = Nothing++-- | Parse the contents of the module.  For each stand-alone function,+--   return it along with all other known functions that it calls.+functionCalls         :: ModuleName -> FunctionLookup -> [HsDecl]+                      -> [(Function, [Function])]+functionCalls m fl ds = catMaybes $ map (functionCall m fl) ds++-- | Parse an individual 'HsDecl'.  We only parse 'HsFunBind' and 'HsPatBind'+--   declarations, as they're the only ones that define stand-alone functions.+functionCall :: ModuleName -> FunctionLookup -> HsDecl+             -> Maybe (Function, [Function])+functionCall m fl d@(HsFunBind {}) = fmap (flip (,) calls) nm+    where+      nm = listToMaybe . setFuncModules m $ functionNames d+      calls = lookupFunctions fl $ hsNames d+functionCall m fl d@(HsPatBind {}) = fmap (flip (,) calls) nm+    where+      nm = listToMaybe . setFuncModules m $ functionNames d+      calls = lookupFunctions fl $ hsNames d+functionCall _ _ _ = Nothing++-- -----------------------------------------------------------------------------++-- Utility functions.++-- | Extract the actual name of the 'Module'.+modName            :: Module -> String+modName (Module m) = m++-- | A true list-difference function.  The default '\\\\' function only deletes+--   the first instance of each value, this deletes /all/ of them.+diff       :: (Eq a) => [a] -> [a] -> [a]+diff xs ys = filter (not . flip elem ys) xs++-- | Specify the qualification that this function was imported with.+addQual     :: String -> Function -> Function+addQual q f = f { qualdBy = Just q }++-- -----------------------------------------------------------------------------++-- | Parsing of names, identifiers, etc.++nameOf              :: HsName -> String+nameOf (HsIdent  i) = i+nameOf (HsSymbol s) = s++-- The class of parsed items which represent a single element.+class HsItem f where+    hsName :: f -> Maybe Function++instance HsItem HsName where+    hsName nm = Just $ defFunc (nameOf nm)++-- Implicit parameters+instance HsItem HsIPName where+    hsName (HsIPDup v) = Just $ defFunc v+    hsName (HsIPLin v) = Just $ defFunc v++-- Qualified variables and constructors+instance HsItem HsQName where+    hsName (Qual mod name) = fmap (addQual (modName mod)) (hsName name)+    hsName (UnQual name)   = hsName name+    -- inbuilt special syntax, e.g. [], (,), etc.+    hsName (Special _)     = Nothing++-- Infix operators.+instance HsItem HsQOp where+    hsName (HsQVarOp qn) = hsName qn+    hsName (HsQConOp qn) = hsName qn++-- Operators in infix declarations+instance HsItem HsOp where+    hsName (HsVarOp nm) = hsName nm+    hsName (HsConOp nm) = hsName nm++-- Items in import statements+instance HsItem HsCName where+    hsName (HsVarName nm) = hsName nm+    hsName (HsConName nm) = hsName nm++-- We don't care about literals+instance HsItem HsLiteral where+    hsName _ = Nothing++-------------------------------------------------------------------------------++-- | Functions, blocks, etc.++class HsItemList vs where+    hsNames :: vs -> [Function]++-- | A \"compatibility\" function to pseudo-convert an instance of 'HsItem'+--   into one that acts like one from 'HsItemList'+hsName'        :: (HsItem i) => i -> [Function]+hsName' i = maybeToList (hsName i)++-- A list of 'HsItemList' instances can be treated as a single instance.+instance (HsItemList vs) => HsItemList [vs] where+    hsNames vss = concatMap hsNames vss++instance HsItemList HsPat where+    hsNames (HsPVar var)              = hsName' var+    hsNames (HsPLit _)                = []+    hsNames (HsPNeg pat)              = hsNames pat+    hsNames (HsPInfixApp pat1 _ pat2) = (hsNames pat1)+                                        ++ (hsNames pat2)+    hsNames (HsPApp _ pats)           = hsNames pats+    hsNames (HsPTuple pats)           = hsNames pats+    hsNames (HsPList pats)            = hsNames pats+    hsNames (HsPParen pat)            = hsNames pat+    hsNames (HsPRec _ pfields)        = hsNames pfields+    hsNames (HsPAsPat name pat)       = hsName' name+                                        ++ hsNames pat+    hsNames HsPWildCard               = []+    hsNames (HsPIrrPat pat)           = hsNames pat+    -- Ignore HaRP and Hsx extensions for now+    hsNames _                         = []++instance HsItemList HsPatField where+    hsNames (HsPFieldPat _ pat) = hsNames pat++instance HsItemList HsBinds where+    hsNames (HsBDecls dcls) = hsNames dcls+    hsNames (HsIPBinds ibs) = hsNames ibs++instance HsItemList HsExp where+    hsNames (HsVar qn)                = hsName' qn+    hsNames (HsIPVar ip)              = hsName' ip+    hsNames (HsCon _)                 = []+    hsNames (HsLit _)                 = []+    hsNames (HsInfixApp e1 q e2)      = hsName' q+                                        ++ hsNames e1 ++ hsNames e2+    hsNames (HsApp e1 e2)             = hsNames e1 ++ hsNames e2+    hsNames (HsNegApp e)              = hsNames e+    hsNames (HsLambda _ ps e)         = (hsNames e) `diff` (hsNames ps)+    hsNames (HsLet bs e)              = (hsNames bs ++ hsNames e)+                                        `diff` (functionNames bs)+    hsNames (HsDLet ips e)            = (hsNames ips ++ hsNames e)+                                        `diff` (functionNames ips)+    hsNames (HsWith e ips)            = (hsNames ips ++ hsNames e)+                                        `diff` (functionNames ips)+    hsNames (HsIf i t e)              = hsNames [i,t,e]+    hsNames (HsCase e as)             = hsNames e ++ hsNames as+    hsNames (HsDo stmts)              = hsNames stmts+    hsNames (HsMDo stmts)             = hsNames stmts+    hsNames (HsTuple es)              = hsNames es+    hsNames (HsList es)               = hsNames es+    hsNames (HsParen e)               = hsNames e+    hsNames (HsLeftSection e qop)     = hsNames e ++ hsName' qop+    hsNames (HsRightSection qop e)    = hsNames e ++ hsName' qop+    hsNames (HsRecConstr _ flds)      = hsNames flds+    hsNames (HsRecUpdate e flds)      = hsNames e ++ hsNames flds+    hsNames (HsEnumFrom f)            = hsNames f+    hsNames (HsEnumFromTo f t)        = hsNames [f,t]+    hsNames (HsEnumFromThen f th)     = hsNames [f,th]+    hsNames (HsEnumFromThenTo f th t) = hsNames [f,th,t]+    hsNames (HsListComp e stmts)      = let svars = functionNames stmts+                                            e' = hsNames e ++ hsNames stmts+                                        in e' `diff` svars+    hsNames (HsExpTypeSig _ e _)      = hsNames e+    hsNames (HsAsPat _ _)             = [] -- something for FunctionNames?+    hsNames (HsIrrPat _)              = []+    -- For now, ignore HaRP, TH and Hsx stuff+    hsNames _                         = []++instance HsItemList HsFieldUpdate where+    hsNames (HsFieldUpdate _ e) = hsNames e++instance HsItemList HsAlt where+    hsNames (HsAlt _ pats rhs bnds) = (rhs' ++ bnds')+                                      `diff` (lhs ++ bndNames)+        where+          lhs = hsNames pats+          bndNames = functionNames bnds+          bnds' = hsNames bnds+          rhs' = hsNames rhs++instance HsItemList HsGuardedAlts where+    hsNames (HsUnGuardedAlt e) = hsNames e+    hsNames (HsGuardedAlts gas) = hsNames gas++instance HsItemList HsGuardedAlt where+    hsNames (HsGuardedAlt _ stmts e) = e' `diff` svars+        where+          svars = functionNames stmts+          e' = hsNames e ++ hsNames stmts++instance HsItemList HsDecl where+    hsNames (HsFunBind ms)          = hsNames ms+    hsNames (HsPatBind _ _ rhs bds) = (bds' ++ rhs') `diff` rNames+        where+          rNames = functionNames bds+          bds' = hsNames bds+          rhs' = hsNames rhs+    hsNames _                       = []+++instance HsItemList HsMatch where+    hsNames (HsMatch _ _ pats rhs bnds) = (rhs' ++ bnds')+                                          `diff` (lhs ++ bndNames)+        where+          lhs = hsNames pats+          bndNames = functionNames bnds+          bnds' = hsNames bnds+          rhs' = hsNames rhs++instance HsItemList HsRhs where+    hsNames (HsUnGuardedRhs e) = hsNames e+    hsNames (HsGuardedRhss rs) = hsNames rs++instance HsItemList HsGuardedRhs where+    hsNames (HsGuardedRhs _ stmts e) = e' `diff` svars+        where+          svars = functionNames stmts+          e' = hsNames e ++ hsNames stmts++instance HsItemList HsStmt where+    hsNames (HsGenerator _ _ e) = hsNames e+    hsNames (HsQualifier e)     = hsNames e+    hsNames (HsLetStmt bnds)    = hsNames bnds++instance HsItemList HsIPBind where+    hsNames (HsIPBind _ ip e) = e' `diff` ip'+        where+          ip' = hsName' ip+          e' = hsNames e++-- -----------------------------------------------------------------------------++-- | Those parsed elements that represent a function.+class FunctionNames fn where+    functionNames :: fn -> [Function]++instance (FunctionNames fn) => FunctionNames [fn] where+    functionNames = concatMap functionNames++instance FunctionNames HsStmt where+    functionNames (HsGenerator _ p _) = hsNames p+    functionNames (HsQualifier _)     = []+    functionNames (HsLetStmt bnds)    = functionNames bnds++instance FunctionNames HsMatch where+    functionNames (HsMatch _ nm _ _ _) = hsName' nm++instance FunctionNames HsDecl where+    functionNames (HsFunBind ms)      = functionNames ms+    functionNames (HsPatBind _ p _ _) = hsNames p+    functionNames _                   = []++instance FunctionNames HsBinds where+    functionNames (HsBDecls decls) = functionNames decls+    functionNames (HsIPBinds bnds) = functionNames bnds++instance FunctionNames HsIPBind where+    functionNames (HsIPBind _ ipn _) = hsName' ipn
+ Parsing/Types.hs view
@@ -0,0 +1,191 @@+{-# LANGUAGE MultiParamTypeClasses+            , TypeSynonymInstances+ #-}++{-+Copyright (C) 2008 Ivan Lazar Miljenovic <Ivan.Miljenovic@gmail.com>++This file is part of SourceGraph.++SourceGraph is free software; you can redistribute it and/or modify+it under the terms of the GNU General Public License as published by+the Free Software Foundation; either version 3 of the License, or+(at your option) any later version.++This program is distributed in the hope that it will be useful,+but WITHOUT ANY WARRANTY; without even the implied warranty of+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the+GNU General Public License for more details.++You should have received a copy of the GNU General Public License+along with this program; if not, write to the Free Software+Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA+-}++{- |+   Module      : Parsing.Types+   Description : Types for parsing Haskell code.+   Copyright   : (c) Ivan Lazar Miljenovic 2008+   License     : GPL-3 or later.+   Maintainer  : Ivan.Miljenovic@gmail.com++   Types for parsing Haskell modules.+ -}+module Parsing.Types where++import Data.Graph.Analysis.Types++import Data.Maybe+import qualified Data.Map as M+import Data.Map(Map)+import Control.Arrow(first)++-- -----------------------------------------------------------------------------++-- | A high-level viewpoint of a Haskell module.+data HaskellModule = Hs { moduleName :: ModuleName+                        , imports    :: [ModuleName]+                        , exports    :: [Function]+                        , functions  :: FunctionCalls+                        }++-- | A lookup-map of 'HaskellModule's.+type HaskellModules = Map ModuleName HaskellModule++-- | Create the 'HaskellModules' lookup map from a list of 'HaskellModule's.+createModuleMap :: [HaskellModule] -> HaskellModules+createModuleMap = M.fromList . map (\m -> (moduleName m, m))++modulesIn :: HaskellModules -> [ModuleName]+modulesIn = M.keys++moduleImports :: HaskellModules -> [(ModuleName,ModuleName)]+moduleImports = concatMap mkEdges . M.assocs+    where+      mkEdges (m,hm) = map ((,) m) $ imports hm++hModulesIn :: HaskellModules -> [HaskellModule]+hModulesIn = M.elems++getModule      :: HaskellModules -> ModuleName -> Maybe HaskellModule+getModule hm m = M.lookup m hm++-- -----------------------------------------------------------------------------++-- | The name of a module.  The 'Maybe' component refers to the possible path+--   of this module.+data ModuleName = M (Maybe String) String+                  deriving (Eq, Ord)++instance ClusterLabel ModuleName String where+    cluster (M p _) = fromMaybe "" p+    nodelabel (M _ m) = m++-- | The seperator between components of a module.+moduleSep :: Char+moduleSep = '.'++-- | Split the module string into a path string and a name string.+splitMod   :: String -> (String,String)+splitMod m = case (break (moduleSep ==) m) of+               (m',"")  -> ("",m')+               (p,_:m') -> first (addPath p) $ splitMod m'++-- | Add two path components together.+addPath       :: String -> String -> String+addPath "" m  = m+addPath p  "" = p+addPath p  m  = p ++ (moduleSep : m)++instance Show ModuleName where+    show (M Nothing m)    = m+    show (M (Just dir) m) = addPath dir m++-- | Create the 'ModuleName' from its 'String' representation.+createModule :: String -> ModuleName+createModule m = case (splitMod m) of+                   (m',"") -> M Nothing m'+                   (d,m')  -> M (Just d) m'++-- | A default module, used for when you haven't specified which module+--   something belongs to yet.+unknownModule :: ModuleName+unknownModule = M Nothing "Module Not Found"++-- -----------------------------------------------------------------------------++-- | The import list of a module.+data HsImport = I { fromModule :: ModuleName+                  -- | How the module was imported, if it actually was.+                  , qualAs     :: Maybe String+                  -- | The functions from this module that were imported.+                  , importList :: [Function]+                  }++-- -----------------------------------------------------------------------------++-- | Defines a function.+data Function = F { inModule :: ModuleName+                  , name     :: String+                  , qualdBy  :: Maybe String+                  }+                deriving (Eq, Ord)++instance Show Function where+    show f = addPath (show $ inModule f) (name f)++instance ClusterLabel Function ModuleName where+    cluster = inModule+    nodelabel = name++-- | Create a default function with using 'unknownModule'.+defFunc   :: String -> Function+defFunc f = F unknownModule f Nothing++-- | Set the module of this function.+setFuncModule     :: ModuleName -> Function -> Function+setFuncModule m f = f { inModule = m }++-- | Set the module of these functions.+setFuncModules :: ModuleName -> [Function] -> [Function]+setFuncModules m = map (setFuncModule m)++-- | Defines a lookup map between the used qualifier and function name,+--   and the actual /unqualified/ function.+type FunctionLookup = Map (Maybe String,String) Function++-- | Create a 'FunctionLookup' map using the given functions.+createLookup :: [Function] -> FunctionLookup+createLookup = M.fromList . map addKey+    where+      addKey f = ((qualdBy f, name f), f)++-- | Try to lookup the given function.+functionLookup      :: FunctionLookup -> Function -> Maybe Function+functionLookup fl f = M.lookup k fl+    where+      k = (qualdBy f, name f)++-- | Lookup the given functions, returning only those that are in the+--   'FunctionLookup' map.+lookupFunctions    :: FunctionLookup -> [Function] -> [Function]+lookupFunctions fl = catMaybes . map (functionLookup fl)++type FunctionCalls = Map Function [Function]++-- | Get every function call as a pair.+functionEdges :: FunctionCalls -> [(Function,Function)]+functionEdges = concatMap mkEdges . M.assocs+    where+      mkEdges (f,fs) = map ((,) f) fs++-- The next two functions are defined to avoid having to import+-- Data.Map in modules that use this one.++-- | Gets the functions+functionsIn :: FunctionCalls -> [Function]+functionsIn = M.keys++-- | Combine multiple function calls+combineCalls :: [FunctionCalls] -> FunctionCalls+combineCalls = M.unions
+ Setup.lhs view
@@ -0,0 +1,3 @@+#!/usr/bin/env runhaskell+> import Distribution.Simple+> main = defaultMain
+ SourceGraph.cabal view
@@ -0,0 +1,36 @@+Name:                SourceGraph+Version:             0.1+Synopsis:            Use graph-theory to analyse your code+Description:         SourceGraph uses the Graphalyze library to analyse+                     Cabalized Haskell code.+Category:            Development+License:             GPL+License-file:        COPYRIGHT+Copyright:           (c) Ivan Lazar Miljenovic+Author:              Ivan Lazar Miljenovic+Maintainer:          Ivan.Miljenovic@gmail.com+Cabal-Version:       >= 1.2+Build-Type:          Simple+Tested-With:         GHC==6.8.3+build-Depends:       base++Flag small_base+  description: Choose the new smaller, split-up base package.++Executable SourceGraph {++    Main-Is:            Main.hs+    Other-Modules:      Parsing, Parsing.Types, Parsing.ParseModule,+                        Analyse, Analyse.Utils, Analyse.Module,+                                 Analyse.Imports, Analyse.Everything+    Ghc-Options:        -Wall+    Ghc-Prof-Options:   -auto-all++    if flag(small_base)+       Build-Depends:   base >= 3, containers, filepath, random, directory+    else+       Build-Depends:   base < 3++    Build-Depends:      fgl, Graphalyze >= 0.3, graphviz >= 2008.9.20,+                        Cabal < 1.5, haskell-src-exts+}