{-# LANGUAGE MultiParamTypeClasses, FlexibleInstances, TypeSynonymInstances #-}{- |
Module : Data.GraphViz.Types
Description : Haskell representation of Dot graphs.
Copyright : (c) Ivan Lazar Miljenovic
License : 3-Clause BSD-style
Maintainer : Ivan.Miljenovic@gmail.com
Four different representations of Dot graphs are available, all of
which are based loosely upon the specifications at:
<http://graphviz.org/doc/info/lang.html>. The 'DotRepr' class
provides a common interface for them (the 'PrintDotRepr',
'ParseDotRepr' and 'PPDotRepr' classes are used until class aliases
are implemented).
Every representation takes in a type parameter: this indicates the
node type (e.g. @DotGraph Int@ is a Dot graph with integer nodes).
Sum types are allowed, though care must be taken when specifying
their 'ParseDot' instances if there is the possibility of
overlapping definitions. The 'GraphID' type is an existing sum
type that allows textual and numeric values.
If you require using more than one Dot representation, you will
most likely need to import at least one of them qualified, as they
typically all use the same names.
As a comparison, all four representations provide how you would
define the following Dot graph (or at least one isomorphic to it)
(the original of which can be found at
<http://graphviz.org/content/cluster>). Note that in all the
examples, they are not necessarily done the best way (variables
rather than repeated constants, etc.); they are just there to
provide a comparison on the structure of each representation.
> digraph G {
>
> subgraph cluster_0 {
> style=filled;
> color=lightgrey;
> node [style=filled,color=white];
> a0 -> a1 -> a2 -> a3;
> label = "process #1";
> }
>
> subgraph cluster_1 {
> node [style=filled];
> b0 -> b1 -> b2 -> b3;
> label = "process #2";
> color=blue
> }
> start -> a0;
> start -> b0;
> a1 -> b3;
> b2 -> a3;
> a3 -> a0;
> a3 -> end;
> b3 -> end;
>
> start [shape=Mdiamond];
> end [shape=Msquare];
> }
Each representation is suited for different things:
["Data.GraphViz.Types.Canonical"] is ideal for converting other
graph-like data structures into Dot graphs (the "Data.GraphViz"
module provides some functions for this). It is a structured
representation of Dot code.
["Data.GraphViz.Types.Generalised"] matches the actual structure
of Dot code. As such, it is suited for parsing in existing Dot
code.
["Data.GraphViz.Types.Graph"] provides graph operations for
manipulating Dot graphs; this is suited when you want to edit
existing Dot code. It uses generalised Dot graphs for parsing and
canonical Dot graphs for printing.
["Data.GraphViz.Types.Monadic"] is a much easier representation to
use when defining relatively static Dot graphs in Haskell code,
and looks vaguely like actual Dot code if you squint a bit.
Please also read the limitations section at the end for advice on
how to properly use these Dot representations.
-}moduleData.GraphViz.Types(DotRepr(..),PrintDot(..),ParseDot(..),PrintDotRepr,ParseDotRepr,PPDotRepr-- * Common sub-types,GraphID(..),ToGraphID(..),textGraphID,GlobalAttributes(..),DotNode(..),DotEdge(..)-- * Helper types for looking up information within a @DotRepr@.,ClusterLookup,NodeLookup,Path-- * Obtaining the @DotNode@s and @DotEdges@.,graphNodes,graphEdges-- * Printing and parsing a @DotRepr@.,printDotGraph,parseDotGraph-- * Limitations and documentation-- $limitations)whereimportData.GraphViz.Types.Canonical(DotGraph(..),DotStatements(..),DotSubGraph(..))importData.GraphViz.Types.Common(GraphID(..),GlobalAttributes(..),DotNode(..),DotEdge(..),numericValue)importData.GraphViz.Types.StateimportData.GraphViz.Util(bool)importData.GraphViz.Parsing(ParseDot(..),runParser,checkValidParse,parse,adjustErr)importData.GraphViz.PreProcessing(preProcess)importData.GraphViz.Printing(PrintDot(..),printIt)importqualifiedData.Text.LazyasTimportData.Text.Lazy(Text)importControl.Arrow(first)importControl.Monad.Trans.State(get,put,modify,execState,evalState)-- ------------------------------------------------------------------------------- | This class is used to provide a common interface to different-- ways of representing a graph in /Dot/ form.---- You will most probably /not/ need to create your own instances of-- this class.---- The type variable represents the current node type of the Dot-- graph, and the 'Ord' restriction is there because in practice-- most implementations of some of these methods require it.class(Ordn)=>DotReprdgnwhere-- | Convert from a graph in canonical form. This is especially-- useful when using the functions from "Data.GraphViz.Algorithms".fromCanonical::DotGraphn->dgn-- | Return the ID of the graph.getID::dgn->MaybeGraphID-- | Set the ID of the graph.setID::GraphID->dgn->dgn-- | Is this graph directed?graphIsDirected::dgn->Bool-- | Set whether a graph is directed or not.setIsDirected::Bool->dgn->dgn-- | Is this graph strict? Strict graphs disallow multiple edges.graphIsStrict::dgn->Bool-- | A strict graph disallows multiple edges.setStrictness::Bool->dgn->dgn-- | Change the node values. This function is assumed to be-- /injective/, otherwise the resulting graph will not be-- identical to the original (modulo labels).mapDotGraph::(Ordn',DotReprdgn')=>(n->n')->dgn->dgn'-- | Return information on all the clusters contained within this-- 'DotRepr', as well as the top-level 'GraphAttrs' for the-- overall graph.graphStructureInformation::dgn->(GlobalAttributes,ClusterLookup)-- | Return information on the 'DotNode's contained within this-- 'DotRepr'. The 'Bool' parameter indicates if applicable-- 'NodeAttrs' should be included.nodeInformation::Bool->dgn->NodeLookupn-- | Return information on the 'DotEdge's contained within this-- 'DotRepr'. The 'Bool' parameter indicates if applicable-- 'EdgeAttrs' should be included.edgeInformation::Bool->dgn->[DotEdgen]-- | Give any anonymous sub-graphs or clusters a unique identifier-- (i.e. there will be no 'Nothing' key in the 'ClusterLookup'-- from 'graphStructureInformation').unAnonymise::dgn->dgn-- | This class exists just to make type signatures nicer; all-- instances of 'DotRepr' should also be an instance of-- 'PrintDotRepr'.class(DotReprdgn,PrintDot(dgn))=>PrintDotReprdgn-- | This class exists just to make type signatures nicer; all-- instances of 'DotRepr' should also be an instance of-- 'ParseDotRepr'.class(DotReprdgn,ParseDot(dgn))=>ParseDotReprdgn-- | This class exists just to make type signatures nicer; all-- instances of 'DotRepr' should also be an instance of-- 'PPDotRepr'.class(PrintDotReprdgn,ParseDotReprdgn)=>PPDotReprdgn-- | Returns all resultant 'DotNode's in the 'DotRepr' (not including-- 'NodeAttr's).graphNodes::(DotReprdgn)=>dgn->[DotNoden]graphNodes=toDotNodes.nodeInformationFalse-- | Returns all resultant 'DotEdge's in the 'DotRepr' (not including-- 'EdgeAttr's).graphEdges::(DotReprdgn)=>dgn->[DotEdgen]graphEdges=edgeInformationFalse-- | The actual /Dot/ code for an instance of 'DotRepr'. Note that it-- is expected that @'parseDotGraph' . 'printDotGraph' == 'id'@-- (this might not be true the other way around due to un-parseable-- components).printDotGraph::(PrintDotReprdgn)=>dgn->TextprintDotGraph=printIt-- | Parse a limited subset of the Dot language to form an instance of-- 'DotRepr'. Each instance may have its own limitations on what-- may or may not be parseable Dot code.---- Also removes any comments, etc. before parsing.parseDotGraph::(ParseDotReprdgn)=>Text->dgnparseDotGraph=fst.prs.preProcesswhereprs=firstcheckValidParse.runParserparse'parse'=parse`adjustErr`("Unable to parse the Dot graph; usually this is because of either:\n\
\ * Wrong choice of representation: try the Generalised one\n\
\ * Wrong choice of node type; try with `DotGraph String`.\n\
\\n\
\The actual parsing error was:\n\t"++)-- ------------------------------------------------------------------------------- Instance for Canonical graphs, to avoid cyclic modules.instance(Ordn)=>DotReprDotGraphnwherefromCanonical=idgetID=graphIDsetIDig=g{graphID=Justi}graphIsDirected=directedGraphsetIsDirecteddg=g{directedGraph=d}graphIsStrict=strictGraphsetStrictnesssg=g{strictGraph=s}mapDotGraph=fmapgraphStructureInformation=getGraphInfo.statementStructure.graphStatementsnodeInformationwGlobal=getNodeLookupwGlobal.statementNodes.graphStatementsedgeInformationwGlobal=getDotEdgeswGlobal.statementEdges.graphStatementsunAnonymise=renumberinstance(Ordn,PrintDotn)=>PrintDotReprDotGraphninstance(Ordn,ParseDotn)=>ParseDotReprDotGraphninstance(Ordn,PrintDotn,ParseDotn)=>PPDotReprDotGraphnstatementStructure::DotStatementsn->GraphState()statementStructurestmts=domapM_addGraphGlobals$attrStmtsstmtsmapM_(withSubGraphIDaddSubGraphstatementStructure)$subGraphsstmtsstatementNodes::(Ordn)=>DotStatementsn->NodeStaten()statementNodesstmts=domapM_addNodeGlobals$attrStmtsstmtsmapM_(withSubGraphIDrecursiveCallstatementNodes)$subGraphsstmtsmapM_addNode$nodeStmtsstmtsmapM_addEdgeNodes$edgeStmtsstmtsstatementEdges::DotStatementsn->EdgeStaten()statementEdgesstmts=domapM_addEdgeGlobals$attrStmtsstmtsmapM_(withSubGraphIDrecursiveCallstatementEdges)$subGraphsstmtsmapM_addEdge$edgeStmtsstmtswithSubGraphID::(Maybe(MaybeGraphID)->b->a)->(DotStatementsn->b)->DotSubGraphn->awithSubGraphIDfgsg=fmid.g$subGraphStmtssgwheremid=boolNothing(Just$subGraphIDsg)$isClustersgrenumber::DotGraphn->DotGraphnrenumberdg=dg{graphStatements=newStmts}wherestartN=succ$maxSGIntdgnewStmts=evalState(stRe$graphStatementsdg)startNstRest=dosgs'<-mapMsgRe$subGraphsstreturn$st{subGraphs=sgs'}sgResg=dosgid'<-casesubGraphIDsgofNothing->don<-getput$succnreturn.Just$Intnsgid->returnsgidstmts'<-stRe$subGraphStmtssgreturn$sg{subGraphID=sgid',subGraphStmts=stmts'}maxSGInt::DotGraphn->IntmaxSGIntdg=execState(stInt$graphStatementsdg).flipcheck0$graphIDdgwherecheck=maybeidmax.(numericValue=<<)stInt=mapM_sgInt.subGraphssgIntsg=domodify(check$subGraphIDsg)stInt$subGraphStmtssg-- ------------------------------------------------------------------------------- | A convenience class to make it easier to convert data types to-- 'GraphID' values, e.g. for cluster identifiers.---- In most cases, conversion would be via the 'Text' or 'String'-- instances (e.g. using 'show').classToGraphIDawheretoGraphID::a->GraphID-- | An alias for 'toGraphID' for use with the @OverloadedStrings@-- extension.textGraphID::Text->GraphIDtextGraphID=toGraphIDinstanceToGraphIDTextwheretoGraphID=StrinstanceToGraphIDStringwheretoGraphID=toGraphID.T.packinstanceToGraphIDCharwheretoGraphID=toGraphID.T.singletoninstanceToGraphIDIntwheretoGraphID=Int-- | This instance loses precision by going via 'Int'.instanceToGraphIDIntegerwheretoGraphID=Int.fromIntegerinstanceToGraphIDDoublewheretoGraphID=Dbl-- -----------------------------------------------------------------------------{- $limitations
Printing of /Dot/ code is done as strictly as possible, whilst
parsing is as permissive as possible. For example, if the types
allow it then @\"2\"@ will be parsed as an 'Int' value. Note that
quoting and escaping of textual values is done automagically.
A summary of known limitations\/differences:
* When creating 'GraphID' values for graphs and sub-graphs,
you should ensure that none of them have the same printed value
as one of the node identifiers values to avoid any possible problems.
* If you want any 'GlobalAttributes' in a sub-graph and want
them to only apply to that sub-graph, then you must ensure it
does indeed have a valid 'GraphID'.
* All sub-graphs which represent clusters should have unique
identifiers (well, only if you want them to be generated
sensibly).
* If eventually outputting to a format such as SVG, then you should
make sure to specify an identifier for the overall graph, as that is
used as the title of the resulting image.
* Whilst the graphs, etc. are polymorphic in their node type, you
should ensure that you use a relatively simple node type (that
is, it only covers a single line, etc.).
* Also, whilst Graphviz allows you to mix the types used for nodes,
this library requires\/assumes that they are all the same type (but
you /can/ use a sum-type).
* 'DotEdge' defines an edge @(a, b)@ (with an edge going from @a@
to @b@); in /Dot/ parlance the edge has a head at @a@ and a tail
at @b@. Care must be taken when using the related @Head*@ and
@Tail*@ 'Attribute's. See the differences section in
"Data.GraphViz.Attributes" for more information.
* It is common to see multiple edges defined on the one line in Dot
(e.g. @n1 -> n2 -> n3@ means to create a directed edge from @n1@
to @n2@ and from @n2@ to @n3@). These types of edge definitions
are parseable; however, they are converted to singleton edges.
* It is not yet possible to create or parse edges with
subgraphs\/clusters as one of the end points.
* The parser will strip out comments and pre-processor lines, join
together multiline statements and concatenate split strings together.
However, pre-processing within HTML-like labels is currently not
supported.
* Graphviz allows a node to be \"defined\" twice (e.g. the actual
node definition, and then in a subgraph with extra global attributes
applied to it). This actually represents the same node, but when
parsing they will be considered as separate 'DotNode's (such that
'graphNodes' will return both \"definitions\"). @canonicalise@ from
"Data.GraphViz.Algorithms" can be used to fix this.
See "Data.GraphViz.Attributes.Complete" for more limitations.
-}